diff --git a/packages/core/tests/component-registration.test.ts b/packages/core/tests/component-registration.test.ts index b8f067576..db9322e2b 100644 --- a/packages/core/tests/component-registration.test.ts +++ b/packages/core/tests/component-registration.test.ts @@ -8,7 +8,12 @@ import { useComponentModuleLoader } from "@executablemd/test-support/host"; * cases go through `execute()` so what they assert is what a document gets. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, resource, scoped, spawn, until } from "effection"; import type { Operation } from "effection"; @@ -37,9 +42,11 @@ import type { Json as CoreJson, } from "../src/types.ts"; +const OWNER = "packages/core/tests/component-registration.test.ts"; const NO_PROPS = { type: "object", properties: {}, additionalProperties: false }; /** A directory for one test's files, removed when the test scope closes. */ + function useFixture(): Operation { return resource(function* (provide) { const dir = yield* until(mkdtemp(join(tmpdir(), "cr-test-"))); @@ -113,14 +120,16 @@ function* thrown(body: () => Operation): Operation { } } -function run(dir: string, includes: string[] = [dir]): Operation { +function run( + dir: string, + includes: string[] = [dir], + stream = new InMemoryStream(), +): Operation { return scoped(function* () { // `API.Files` has no host default, and `` is one of the components // these cases resolve. yield* useHostFiles(); - return yield* collect( - yield* execute({ path: join(dir, "doc.md"), stream: new InMemoryStream(), includes }), - ); + return yield* collect(yield* execute({ path: join(dir, "doc.md"), stream, includes })); }); } @@ -513,16 +522,19 @@ describe("Tier CR — installation order never decides", () => { }); describe("Tier CR — what a document gets", () => { + beforeEach(journalBeforeEach(OWNER)); it("CR22: a repository component replaces one of core's, end to end", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); yield* writeTextFile(join(dir, "doc.md"), "ignored\n"); yield* writeTextFile(join(dir, "Parse.md"), "MINE\n"); - expect(String(yield* run(dir))).toContain("MINE"); + expect(String(yield* run(dir, undefined, stream))).toContain("MINE"); }); it("CR22b: a repository Json.md replaces core's serializer, `as` and all", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); // `as` is the engine's, so the override takes it the way every text // component does: what it rendered is captured and read back later. yield* writeTextFile( @@ -541,7 +553,7 @@ describe("Tier CR — what a document gets", () => { // The override's own rendering keeps the line structure a Markdown // component produces, so the marker and the word are matched together // rather than spelled as one literal. - const rendered = String(yield* run(dir)); + const rendered = String(yield* run(dir, undefined, stream)); expect(rendered).toMatch(/CAPTURED:\s*MINE/); expect(rendered).not.toContain("serialized"); }); @@ -551,6 +563,7 @@ describe("Tier CR — what a document gets", () => { // prop JSON boundary exactly as any other component's would. it("CR22c: an override crosses the ordinary prop boundary, absence and all", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); yield* writeTextFile(join(dir, "doc.md"), "\n"); // `required` is what makes this discriminating: on the ordinary boundary // this operand is an absence, so the required check is what answers it. A @@ -573,7 +586,7 @@ describe("Tier CR — what a document gets", () => { // capture is handed the authored `undefined`. The override is handed the // ordinary reading of the same text, where `undefined` means the prop is // not there — the behavior every non-capturing component has (§6.5). - const rendered = yield* reportOf(() => run(dir)); + const rendered = yield* reportOf(() => run(dir, undefined, stream)); expect(rendered).toContain("value"); expect(rendered).toContain("required"); expect(rendered).not.toContain("no JSON text"); @@ -582,6 +595,7 @@ describe("Tier CR — what a document gets", () => { it("CR22d: a repository CodeBlock.md replaces core's fence, end to end", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); yield* writeTextFile(join(dir, "doc.md"), '\n'); // `value` is an ordinary prop on both sides, so the override receives the // same string core's registration would have been handed. Nothing about @@ -595,38 +609,45 @@ describe("Tier CR — what a document gets", () => { // Core's own would have wrapped the string in a fence; the override writes // it bare, so the output says which one ran and what it was given. - const rendered = String(yield* run(dir)); + const rendered = String(yield* run(dir, undefined, stream)); expect(rendered).toContain("OVERRIDE:fenced"); expect(rendered).not.toContain("```"); }); - it("CR23: a broken local component fails instead of falling back to core's", function* () { + const brokenLocal = "CR23: a broken local component fails instead of falling back to core's"; + it(brokenLocal, function* () { const dir = yield* useFixture(); - // Core's renders its content, so a fall-through would succeed - // visibly. That is what makes the failure below meaningful. - yield* writeTextFile(join(dir, "doc.md"), "VISIBLE\n"); - yield* writeTextFile(join(dir, "TempDir.md"), "unbroken\n"); - expect(String(yield* run(dir))).toContain("unbroken"); - - // Present, and unusable: the schema is not a schema. - yield* writeTextFile( - join(dir, "TempDir.md"), - ["---", "props:", " type: object", " properties: 7", "---", "", "unbroken"].join("\n"), - ); + const testCase = { owner: OWNER, name: brokenLocal }; + yield* captureTestJournal(testCase, join(dir, "doc.md"), function* (stream) { + // Core's renders its content, so a fall-through would succeed + // visibly. That is what makes the failure below meaningful. + yield* writeTextFile(join(dir, "doc.md"), "VISIBLE\n"); + yield* writeTextFile(join(dir, "TempDir.md"), "unbroken\n"); + expect(String(yield* run(dir, undefined, stream))).toContain("unbroken"); + + // Present, and unusable: the schema is not a schema. + yield* writeTextFile( + join(dir, "TempDir.md"), + ["---", "props:", " type: object", " properties: 7", "---", "", "unbroken"].join("\n"), + ); - const output = yield* reportOf(() => run(dir)); - expect(output).toContain("properties"); - // Neither the broken component's body nor core's component ran. - expect(output).not.toContain("unbroken"); - expect(output).not.toContain("VISIBLE"); + yield* captureTestJournal(testCase, join(dir, "doc.md"), function* (secondStream) { + const output = yield* reportOf(() => run(dir, undefined, secondStream)); + expect(output).toContain("properties"); + // Neither the broken component's body nor core's component ran. + expect(output).not.toContain("unbroken"); + expect(output).not.toContain("VISIBLE"); + }); + }); }); it("CR24: a structural name is not satisfied by a file named after it", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); yield* writeTextFile(join(dir, "doc.md"), "\n"); yield* writeTextFile(join(dir, "Content.md"), "SHOULD NOT RENDER\n"); - const output = yield* reportOf(() => run(dir)); + const output = yield* reportOf(() => run(dir, undefined, stream)); expect(output).not.toContain("SHOULD NOT RENDER"); expect(output).toContain("reserved"); }); @@ -637,6 +658,7 @@ describe("Tier CR — what a document gets", () => { // which is what no syntax or validation row can show. it("CR24c: a repository Terminal.Grid.md and Terminal.md each run their own body", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); yield* writeTextFile( join(dir, "doc.md"), '\n\n\n', @@ -660,7 +682,7 @@ describe("Tier CR — what a document gets", () => { ["---", "props:", " title: { type: string }", "---", "", "PANE:{props.title}"].join("\n"), ); - const rendered = String(yield* run(dir)); + const rendered = String(yield* run(dir, undefined, stream)); // Each definition's own body, with its own props: the grid laid nothing // out and the pane opened nothing — they are Markdown components. expect(rendered).toContain("GRID:2"); @@ -669,6 +691,7 @@ describe("Tier CR — what a document gets", () => { it("CR24d: a registration may claim both names, and its own fn answers", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); yield* writeTextFile(join(dir, "doc.md"), "\n\n\n"); const rendered = yield* scoped(function* () { @@ -681,7 +704,7 @@ describe("Tier CR — what a document gets", () => { yield* collect( yield* execute({ path: join(dir, "doc.md"), - stream: new InMemoryStream(), + stream, includes: [dir], }), ), @@ -701,20 +724,29 @@ describe("Tier CR — what a document gets", () => { // The search path has to be *relative* for this to bite: an absolute one is // used verbatim and never consults a working directory at all, which is why // the fixture lives under the process's own directory. - it("CR24b: a relative repository component loads inside a rebound cwd", function* () { - yield* useComponentModuleLoader(); - const dir = yield* useLocalFixture(); - yield* writeTextFile(join(dir, "doc.md"), "\n\n\n"); - yield* writeTextFile( - join(dir, "Widget.ts"), - [ - "export const props = { type: 'object', properties: {}, additionalProperties: false };", - "export default function*() { return 'LOADED'; }", - ].join("\n"), - ); - - expect(String(yield* run(dir))).toContain("LOADED"); - }); + { + const caseName = "CR24b: a relative repository component loads inside a rebound cwd"; + it(caseName, function* () { + yield* useComponentModuleLoader(); + const dir = yield* useLocalFixture(); + yield* captureTestJournal( + { owner: OWNER, name: caseName }, + join(dir, "doc.md"), + function* (stream) { + yield* writeTextFile(join(dir, "doc.md"), "\n\n\n"); + yield* writeTextFile( + join(dir, "Widget.ts"), + [ + "export const props = { type: 'object', properties: {}, additionalProperties: false };", + "export default function*() { return 'LOADED'; }", + ].join("\n"), + ); + + expect(String(yield* run(dir, undefined, stream))).toContain("LOADED"); + }, + ); + }); + } }); describe("Tier CR — inspection describes without running", () => { diff --git a/packages/core/tests/component-returns.test.ts b/packages/core/tests/component-returns.test.ts index ce09933d8..29d836593 100644 --- a/packages/core/tests/component-returns.test.ts +++ b/packages/core/tests/component-returns.test.ts @@ -7,7 +7,8 @@ import { useComponentModuleLoader } from "@executablemd/test-support/host"; * roots, and deterministic replay. */ -import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; +import { beforeAll, beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, scoped, spawn, until, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -34,6 +35,13 @@ import { import type { Json } from "../src/types.ts"; import { asText } from "./helpers.ts"; +const OWNER = "packages/core/tests/component-returns.test.ts"; +function* useReturnsFixture(): Operation<{ directory: string; stream: InMemoryStream }> { + const directory = path.join(os.tmpdir(), `returns-test-${randomUUID()}`); + const stream = yield* useJournalStream(path.join(directory, "doc.md")); + return { directory, stream }; +} + const ROOT = fileURLToPath(new URL("../../../", import.meta.url)); interface Run { @@ -82,6 +90,7 @@ function* runExecution(options: { * comment in the body, so a case about what a rejection says reads it here. A * successful run's text is unchanged. */ + function said(run: Run): string { return run.error ?? asText(run.value ?? ""); } @@ -103,9 +112,12 @@ function run(files: Record, stream?: DurableStream): Operation): Operation { +function runFixture( + files: Record, + stream = new InMemoryStream(), + dir = path.join(os.tmpdir(), `returns-test-${randomUUID()}`), +): Operation { return scoped(function* () { - const dir = path.join(os.tmpdir(), `returns-test-${randomUUID()}`); yield* ensureDir(dir); // Removing the directory removes the symlink with it, and registering the // cleanup first means a failure during setup still takes the fixture away. @@ -120,7 +132,7 @@ function runFixture(files: Record): Operation { return yield* runExecution({ path: path.join(dir, "doc.md"), - stream: new InMemoryStream(), + stream, includes: [dir], commands: [], }); @@ -167,6 +179,7 @@ function* raised(operation: () => Operation): Operation { } describe("Tier RV — component return values", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); describe("value kinds", () => { @@ -186,42 +199,60 @@ describe("Tier RV — component return values", () => { for (const [label, declaration, expression, expected] of kinds) { it(`binds ${label} through as`, function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": valueComponent(declaration, expression), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": valueComponent(declaration, expression), + }, + stream, + ); expect(result.error).toBeUndefined(); expect(said(result)).toContain(`captured: ${JSON.stringify(expected)}`); }); } it("emits no segments of its own", function* () { - const result = yield* run({ - "doc.md": 'before\n\n\n\nafter\n', - "Verdict.md": valueComponent("returns:\n passed: { type: boolean }", "({ passed: true })"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": 'before\n\n\n\nafter\n', + "Verdict.md": valueComponent( + "returns:\n passed: { type: boolean }", + "({ passed: true })", + ), + }, + stream, + ); expect(said(result)).not.toContain("passed"); }); it("drives caller control flow from the captured value", function* () { - const result = yield* run({ - "doc.md": [ - '', - "", - "", - "", - "REVIEW PASSED", - "", - "", - "", - "REVIEW FAILED", - "", - "", - "", - "", - ].join("\n"), - "Verdict.md": valueComponent("returns:\n passed: { type: boolean }", "({ passed: true })"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + '', + "", + "", + "", + "REVIEW PASSED", + "", + "", + "", + "REVIEW FAILED", + "", + "", + "", + "", + ].join("\n"), + "Verdict.md": valueComponent( + "returns:\n passed: { type: boolean }", + "({ passed: true })", + ), + }, + stream, + ); expect(said(result)).toContain("REVIEW PASSED"); expect(said(result)).not.toContain("REVIEW FAILED"); }); @@ -229,53 +260,69 @@ describe("Tier RV — component return values", () => { describe("declaration forms", () => { it("requires every property of the object shorthand", function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": valueComponent( - "returns:\n passed: { type: boolean }\n summary: { type: string }", - "({ passed: true })", - ), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": valueComponent( + "returns:\n passed: { type: boolean }\n summary: { type: string }", + "({ passed: true })", + ), + }, + stream, + ); const output = said(result); expect(output).toContain("Return validation failed for "); expect(output).toContain("summary"); }); it("rejects a property the object shorthand does not declare", function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": valueComponent( - "returns:\n passed: { type: boolean }", - "({ passed: true, extra: 1 })", - ), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": valueComponent( + "returns:\n passed: { type: boolean }", + "({ passed: true, extra: 1 })", + ), + }, + stream, + ); expect(said(result)).toContain("Return validation failed for "); }); it("accepts a full schema with an optional property", function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": valueComponent( - [ - "returns:", - " type: object", - " properties:", - " passed: { type: boolean }", - " summary: { type: string }", - " required: [passed]", - " additionalProperties: false", - ].join("\n"), - "({ passed: true })", - ), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": valueComponent( + [ + "returns:", + " type: object", + " properties:", + " passed: { type: boolean }", + " summary: { type: string }", + " required: [passed]", + " additionalProperties: false", + ].join("\n"), + "({ passed: true })", + ), + }, + stream, + ); expect(said(result)).toContain('captured: {"passed":true}'); }); it("rejects a non-object returns declaration", function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": "---\nreturns: text\n---\n\nbody\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": "---\nreturns: text\n---\n\nbody\n", + }, + stream, + ); expect(said(result)).toContain('"returns" must declare a JSON Schema object'); }); @@ -291,8 +338,9 @@ describe("Tier RV — component return values", () => { }); it("rejects an invalid return schema in execution and inspection alike", function* () { + const stream = yield* useJournalStream("doc.md"); const source = "---\nreturns:\n type: nonsense\n---\n\n\n"; - const result = yield* run({ "doc.md": CAPTURING_ROOT, "Verdict.md": source }); + const result = yield* run({ "doc.md": CAPTURING_ROOT, "Verdict.md": source }, stream); expect(said(result)).toContain("invalid return schema"); yield* useStubFs({ "Verdict.md": source }); @@ -316,20 +364,24 @@ describe("Tier RV — component return values", () => { for (const [label, expression] of rejected) { it(`rejects ${label} before binding`, function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - // The value is produced in the expression itself: an eval - // block cannot even export some of these. - "Verdict.md": [ - "---", - "returns:", - " type: object", - "---", - "", - ``, - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + // The value is produced in the expression itself: an eval + // block cannot even export some of these. + "Verdict.md": [ + "---", + "returns:", + " type: object", + "---", + "", + ``, + "", + ].join("\n"), + }, + stream, + ); const output = said(result); expect(output).toContain("Return validation failed for "); expect(output).toContain("is not JSON"); @@ -342,29 +394,33 @@ describe("Tier RV — component return values", () => { } it("fills defaults into the returned value without mutating the producer's object", function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": [ - "---", - "returns:", - " type: object", - " properties:", - " passed: { type: boolean }", - " severity: { type: string, default: low }", - " required: [passed]", - " additionalProperties: false", - "---", - "", - "```js eval", - "const produced = { passed: true };", - "```", - "", - "", - "", - "produced stays: {produced}", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": [ + "---", + "returns:", + " type: object", + " properties:", + " passed: { type: boolean }", + " severity: { type: string, default: low }", + " required: [passed]", + " additionalProperties: false", + "---", + "", + "```js eval", + "const produced = { passed: true };", + "```", + "", + "", + "", + "produced stays: {produced}", + "", + ].join("\n"), + }, + stream, + ); const output = said(result); expect(output).toContain('"severity":"low"'); expect(output).not.toContain("produced stays"); @@ -373,26 +429,38 @@ describe("Tier RV — component return values", () => { describe("text mode compatibility", () => { it("renders and captures a string when no returns is declared", function* () { - const result = yield* run({ - "doc.md": '\n\ncaptured: {note}\n', - "Note.md": "NOTE BODY\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n\ncaptured: {note}\n', + "Note.md": "NOTE BODY\n", + }, + stream, + ); expect(said(result)).toContain("captured: NOTE BODY"); }); it("treats an explicit string schema as value mode", function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": valueComponent("returns:\n type: string", '"shipped"'), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": valueComponent("returns:\n type: string", '"shipped"'), + }, + stream, + ); expect(said(result)).toContain('captured: "shipped"'); }); it("keeps selection working for a text component", function* () { - const result = yield* run({ - "doc.md": "\n", - "Note.md": "DOCUMENTATION\n\n\n\nSELECTED\n\n\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": "\n", + "Note.md": "DOCUMENTATION\n\n\n\nSELECTED\n\n\n", + }, + stream, + ); const output = said(result); expect(output).toContain("SELECTED"); expect(output).not.toContain("DOCUMENTATION"); @@ -421,68 +489,84 @@ describe("Tier RV — component return values", () => { for (const owned of OWNED) { it(`RV11a: <${owned.name}> keeps the value body that owns it`, function* () { - const result = yield* run({ - "doc.md": '\n\nGot {v}\n', - "Verdict.md": ["---", "returns:", " type: string", "---", "", ...owned.body, ""].join( - "\n", - ), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n\nGot {v}\n', + "Verdict.md": ["---", "returns:", " type: string", "---", "", ...owned.body, ""].join( + "\n", + ), + }, + stream, + ); expect(said(result)).toContain("Got picked"); }); } it("RV11a: an unselected reaches the component's missing-return diagnostic", function* () { - const result = yield* run({ - "doc.md": '\n', - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - "", - '', - "", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n', + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + "", + '', + "", + "", + ].join("\n"), + }, + stream, + ); expect(said(result)).toContain(" declares `returns` but produced no "); }); it("RV11b: a caller's selects through a Markdown wrapper", function* () { + const stream = yield* useJournalStream("doc.md"); // The wrapper declares nothing. The return is the caller's text, so it // satisfies the caller's declaration wherever the wrapper renders it. - const result = yield* run({ - "doc.md": [ - "---", - "returns:", - " type: string", - "---", - "", - "", - '', - "", - "", - ].join("\n"), - "Wrap.md": "Wrapping \n", - }); + const result = yield* run( + { + "doc.md": [ + "---", + "returns:", + " type: string", + "---", + "", + "", + '', + "", + "", + ].join("\n"), + "Wrap.md": "Wrapping \n", + }, + stream, + ); expect(result.value).toBe("through the wrapper"); }); it("RV11c: a an invoked body writes never satisfies its caller", function* () { - const result = yield* run({ - "doc.md": [ - "---", - "returns:", - " type: string", - "---", - "", - "", - '', - "", - ].join("\n"), - "Foreign.md": '\n', - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "---", + "returns:", + " type: string", + "---", + "", + "", + '', + "", + ].join("\n"), + "Foreign.md": '\n', + }, + stream, + ); // The foreign body declares no `returns`, so its own text-body preflight // refuses the element — it never reaches the caller's frame. expect(said(result)).toContain(" requires a document or component"); @@ -490,52 +574,61 @@ describe("Tier RV — component return values", () => { }); it("RV11b: a caller's selects through a function component's content()", function* () { - const result = yield* runFixture({ - "doc.md": [ - "---", - "returns:", - " type: string", - "---", - "", - "", - '', - "", - "", - ].join("\n"), - "Wrap.ts": [ - 'import { content } from "@executablemd/core";', - "export default function*() {", - " const rendered = yield* content();", - " return `wrapped ${rendered}`;", - "}", - "", - ].join("\n"), - }); + const { directory, stream } = yield* useReturnsFixture(); + const result = yield* runFixture( + { + "doc.md": [ + "---", + "returns:", + " type: string", + "---", + "", + "", + '', + "", + "", + ].join("\n"), + "Wrap.ts": [ + 'import { content } from "@executablemd/core";', + "export default function*() {", + " const rendered = yield* content();", + " return `wrapped ${rendered}`;", + "}", + "", + ].join("\n"), + }, + stream, + directory, + ); expect(result.value).toBe("through content()"); }); it("RV11c: a render() generates stays reserved beneath a value body", function* () { + const stream = yield* useJournalStream("doc.md"); // `render()` runs inside , whose own value frame is active — // so this proves dynamic markdown is refused on its own terms rather than // for want of an owner to claim. - const result = yield* run({ - "doc.md": '\n', - "Dynamic.md": [ - "---", - "returns:", - " type: string", - "---", - "", - "```js eval", - "const generated = yield* render(\'\');", - "```", - "", - "{generated}", - "", - '', - "", - ].join("\n"), - }); + const result = yield* run( + { + "doc.md": '\n', + "Dynamic.md": [ + "---", + "returns:", + " type: string", + "---", + "", + "```js eval", + "const generated = yield* render(\'\');", + "```", + "", + "{generated}", + "", + '', + "", + ].join("\n"), + }, + stream, + ); // Diagnosed where it was generated, and no component named Return was // resolved to answer it. expect(said(result)).toContain(" is reserved"); @@ -545,42 +638,47 @@ describe("Tier RV — component return values", () => { }); it("RV10c: two concurrent projections claim once and evaluate once", function* () { + const { directory, stream } = yield* useReturnsFixture(); // Both projections of one authored are started before either is // awaited, so the second reaches the body while the first is in flight. // The claim is taken synchronously, before the claiming return evaluates // anything, so exactly one expression is ever evaluated. - const result = yield* runFixture({ - "doc.md": [ - "---", - "returns:", - " type: string", - "---", - "", - "```js eval", - "globalThis.__rv10c = 0;", - "const mark = () => {", - " globalThis.__rv10c += 1;", - ' return "evaluated";', - "};", - "```", - "", - "", - "", - "", - "", - ].join("\n"), - "Both.ts": [ - 'import { content } from "@executablemd/core";', - 'import { all, spawn } from "effection";', - "export default function*() {", - " const first = yield* spawn(() => content());", - " const second = yield* spawn(() => content());", - " yield* all([first, second]);", - ' return "both";', - "}", - "", - ].join("\n"), - }); + const result = yield* runFixture( + { + "doc.md": [ + "---", + "returns:", + " type: string", + "---", + "", + "```js eval", + "globalThis.__rv10c = 0;", + "const mark = () => {", + " globalThis.__rv10c += 1;", + ' return "evaluated";', + "};", + "```", + "", + "", + "", + "", + "", + ].join("\n"), + "Both.ts": [ + 'import { content } from "@executablemd/core";', + 'import { all, spawn } from "effection";', + "export default function*() {", + " const first = yield* spawn(() => content());", + " const second = yield* spawn(() => content());", + " yield* all([first, second]);", + ' return "both";', + "}", + "", + ].join("\n"), + }, + stream, + directory, + ); expect(said(result)).toContain( "The root document declares `returns` but executed more than one .", @@ -592,30 +690,35 @@ describe("Tier RV — component return values", () => { }); it("RV12: a teardown failure after selection wins over the selected value", function* () { - const result = yield* runFixture({ - "doc.md": [ - "---", - "returns:", - " type: string", - "---", - "", - '', - "", - '', - "", - ].join("\n"), - // The body completes; teardown is what fails, after the value was - // already selected. - "Failing.ts": [ - 'import { ensure } from "effection";', - "export const returns = { type: 'string' };", - "export default function*() {", - ' yield* ensure(function* () { throw new Error("TEARDOWN_FAILED"); });', - ' return "body finished";', - "}", - "", - ].join("\n"), - }); + const { directory, stream } = yield* useReturnsFixture(); + const result = yield* runFixture( + { + "doc.md": [ + "---", + "returns:", + " type: string", + "---", + "", + '', + "", + '', + "", + ].join("\n"), + // The body completes; teardown is what fails, after the value was + // already selected. + "Failing.ts": [ + 'import { ensure } from "effection";', + "export const returns = { type: 'string' };", + "export default function*() {", + ' yield* ensure(function* () { throw new Error("TEARDOWN_FAILED"); });', + ' return "body finished";', + "}", + "", + ].join("\n"), + }, + stream, + directory, + ); expect(said(result)).toContain("TEARDOWN_FAILED"); expect(result.value).toBeUndefined(); @@ -637,12 +740,14 @@ describe("Tier RV — component return values", () => { const dir = path.join(os.tmpdir(), `returns-halt-${randomUUID()}`); yield* ensureDir(dir); yield* ensure(() => rm(dir, { recursive: true, force: true })); + const documentPath = path.join(dir, "doc.md"); + const stream = yield* useJournalStream(documentPath); yield* writeTextFile(path.join(dir, "package.json"), JSON.stringify({ type: "module" })); yield* until( symlink(path.join(ROOT, "node_modules"), path.join(dir, "node_modules"), "dir"), ); yield* writeTextFile( - path.join(dir, "doc.md"), + documentPath, [ "---", "returns:", @@ -675,8 +780,8 @@ describe("Tier RV — component return values", () => { const outcome: string[] = []; const task = yield* spawn(function* () { const execution = yield* execute({ - path: path.join(dir, "doc.md"), - stream: new InMemoryStream(), + path: documentPath, + stream, includes: [dir], }); const result = yield* execution; @@ -780,39 +885,43 @@ describe("Tier RV — component return values", () => { }); it("RV10e: a component cannot select a value through the named return context", function* () { + const stream = yield* useJournalStream("doc.md"); // The same attack the value root faces, run from inside a Markdown value // component's own body: read the carrier the engine published, write to // it, clear its claim, then replace the context with a fully-formed // forgery. The component's one authored is unselected, so // anything it selected would be a value nothing validated. - const result = yield* run({ - "doc.md": '\n\nGot {v}\n', - "Verdict.md": [ - "---", - "returns:", - " type: number", - "---", - "", - "```js eval", - 'import { createContext } from "effection";', - 'const ctx = createContext("expand.return");', - "const carrier = yield* ctx.get();", - 'try { carrier.selected = { value: "schema-bypassed" }; } catch (error) {}', - "try { carrier.claimed = false; } catch (error) {}", - "yield* ctx.set({", - ' owner: "Verdict",', - ' returns: { type: "string" },', - " claimed: true,", - ' selected: { value: "schema-bypassed" },', - "});", - "```", - "", - "", - "", - "", - "", - ].join("\n"), - }); + const result = yield* run( + { + "doc.md": '\n\nGot {v}\n', + "Verdict.md": [ + "---", + "returns:", + " type: number", + "---", + "", + "```js eval", + 'import { createContext } from "effection";', + 'const ctx = createContext("expand.return");', + "const carrier = yield* ctx.get();", + 'try { carrier.selected = { value: "schema-bypassed" }; } catch (error) {}', + "try { carrier.claimed = false; } catch (error) {}", + "yield* ctx.set({", + ' owner: "Verdict",', + ' returns: { type: "string" },', + " claimed: true,", + ' selected: { value: "schema-bypassed" },', + "});", + "```", + "", + "", + "", + "", + "", + ].join("\n"), + }, + stream, + ); expect(said(result)).toContain(" declares `returns` but produced no "); expect(said(result)).not.toContain("schema-bypassed"); @@ -822,39 +931,44 @@ describe("Tier RV — component return values", () => { }); it("RV10e: importing the internal return module selects nothing", function* () { + const { directory, stream } = yield* useReturnsFixture(); // An eval block's imports are hoisted and resolved like any module's, so // a document can import the engine's own source by file URL. It gains // nothing: the body a value root is settling from is a local of that // expansion, handed down as a parameter, and no export takes someone // else's. Whatever the document builds here is a body of its own. const internal = new URL("../src/return-flow.ts", import.meta.url).href; - const result = yield* runFixture({ - "doc.md": [ - "---", - "returns:", - " type: number", - "---", - "", - "```js eval", - 'import { createContext } from "effection";', - `import * as flow from ${JSON.stringify(internal)};`, - 'const surface = Object.keys(flow).sort().join(",");', - "// Whatever this module still exports, aimed at this run.", - 'const own = flow.createReturnBody("__root__", { type: "string" });', - "own.claim();", - 'own.select("schema-bypassed");', - 'const stolen = yield* createContext("expand.return").get();', - 'const reached = stolen === undefined ? "nothing" : "something";', - "```", - "", - "surface: {surface} reached: {reached}", - "", - "", - "", - "", - "", - ].join("\n"), - }); + const result = yield* runFixture( + { + "doc.md": [ + "---", + "returns:", + " type: number", + "---", + "", + "```js eval", + 'import { createContext } from "effection";', + `import * as flow from ${JSON.stringify(internal)};`, + 'const surface = Object.keys(flow).sort().join(",");', + "// Whatever this module still exports, aimed at this run.", + 'const own = flow.createReturnBody("__root__", { type: "string" });', + "own.claim();", + 'own.select("schema-bypassed");', + 'const stolen = yield* createContext("expand.return").get();', + 'const reached = stolen === undefined ? "nothing" : "something";', + "```", + "", + "surface: {surface} reached: {reached}", + "", + "", + "", + "", + "", + ].join("\n"), + }, + stream, + directory, + ); // The run fails exactly as a value root that executed no return does. expect(said(result)).toContain( @@ -873,47 +987,55 @@ describe("Tier RV — component return values", () => { }); it("RV14: a nested value body owns a separate declaration", function* () { - const result = yield* run({ - "doc.md": '\n\nGot {o}\n', - "Outer.md": [ - "---", - "returns:", - " type: string", - "---", - "", - '', - "", - "", - ].join("\n"), - "Inner.md": [ - "---", - "returns:", - " type: string", - "---", - "", - '', - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n\nGot {o}\n', + "Outer.md": [ + "---", + "returns:", + " type: string", + "---", + "", + '', + "", + "", + ].join("\n"), + "Inner.md": [ + "---", + "returns:", + " type: string", + "---", + "", + '', + "", + ].join("\n"), + }, + stream, + ); // Two executions, neither a duplicate: each claimed its own body. expect(said(result)).toContain("Got outer saw inner"); }); it("RV10d: projecting one authored twice is a duplicate", function* () { - const result = yield* run({ - "doc.md": [ - "---", - "returns:", - " type: string", - "---", - "", - "", - '', - "", - "", - ].join("\n"), - "Twice.md": "\n\n\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "---", + "returns:", + " type: string", + "---", + "", + "", + '', + "", + "", + ].join("\n"), + "Twice.md": "\n\n\n", + }, + stream, + ); expect(said(result)).toContain( "The root document declares `returns` but executed more than one .", ); @@ -922,24 +1044,33 @@ describe("Tier RV — component return values", () => { describe("structure, before body effects", () => { it("refuses in a text component", function* () { - const result = yield* run({ - "doc.md": "\n", - "Note.md": `${BODY_EFFECT}\n\n\n`, - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": "\n", + "Note.md": `${BODY_EFFECT}\n\n\n`, + }, + stream, + ); expect(said(result)).toContain(" requires a document or component"); expect(result.commands).toEqual([]); }); it("RV10a: requires a statically authored when returns is declared", function* () { - const result = yield* run({ - "doc.md": '\n', - "Verdict.md": `---\nreturns:\n type: string\n---\n\n${BODY_EFFECT}\n`, - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n', + "Verdict.md": `---\nreturns:\n type: string\n---\n\n${BODY_EFFECT}\n`, + }, + stream, + ); expect(said(result)).toContain("no "); expect(result.commands).toEqual([]); }); it("RV10a: a caller's does not satisfy the callee's declaration", function* () { + const stream = yield* useJournalStream("doc.md"); // Preflight reads the callee's own source, before is // substituted, so content the caller offers can neither introduce nor // satisfy a declaration. @@ -947,66 +1078,77 @@ describe("Tier RV — component return values", () => { // where it is written. Offering it to the callee still declares nothing: // preflight reads the callee's own source, before is // substituted. - const result = yield* run({ - "doc.md": [ - "---", - "returns:", - " type: string", - "---", - "", - '', - '', - "", - "", - ].join("\n"), - "Verdict.md": `---\nreturns:\n type: string\n---\n\n${BODY_EFFECT}\n\n`, - }); + const result = yield* run( + { + "doc.md": [ + "---", + "returns:", + " type: string", + "---", + "", + '', + '', + "", + "", + ].join("\n"), + "Verdict.md": `---\nreturns:\n type: string\n---\n\n${BODY_EFFECT}\n\n`, + }, + stream, + ); expect(said(result)).toContain("no "); expect(result.commands).toEqual([]); }); it("RV10b: a nested is statically valid and reaches runtime", function* () { - const result = yield* run({ - "doc.md": '\n\nGot {v}\n', - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - BODY_EFFECT, - "", - "", - '', - "", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n\nGot {v}\n', + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + BODY_EFFECT, + "", + "", + '', + "", + "", + ].join("\n"), + }, + stream, + ); expect(said(result)).toContain("Got one"); // Preflight did not reject the shape, so the body's effect ran. expect(result.commands.length).toBe(1); }); it("RV10d: two executed s fail the body after the first effect", function* () { - const result = yield* run({ - "doc.md": '\n\nGot {v}\n', - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - BODY_EFFECT, - "", - '', - "", - // Evaluating this expression at all would throw a different, louder - // error, so the duplicate diagnostic below is proof it was never - // evaluated. - "", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n\nGot {v}\n', + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + BODY_EFFECT, + "", + '', + "", + // Evaluating this expression at all would throw a different, louder + // error, so the duplicate diagnostic below is proof it was never + // evaluated. + "", + "", + ].join("\n"), + }, + stream, + ); expect(said(result)).toContain(" declares `returns` but executed more than one"); expect(said(result)).not.toContain("missingBinding"); // The first selected value is discarded rather than bound: the caller's @@ -1018,43 +1160,51 @@ describe("Tier RV — component return values", () => { }); it("refuses alongside returns", function* () { - const result = yield* run({ - "doc.md": '\n', - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - BODY_EFFECT, - "", - "", - "text", - "", - "", - '', - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n', + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + BODY_EFFECT, + "", + "", + "text", + "", + "", + '', + "", + ].join("\n"), + }, + stream, + ); expect(said(result)).toContain(" and `returns` are exclusive"); expect(result.commands).toEqual([]); }); it("refuses with children, extra props, or no value", function* () { - const result = yield* run({ - "doc.md": '\n', - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - BODY_EFFECT, - "", - 'body', - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n', + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + BODY_EFFECT, + "", + 'body', + "", + ].join("\n"), + }, + stream, + ); const output = said(result); expect(output).toContain('accepts only a "value" prop'); expect(output).toContain('requires a "value" prop'); @@ -1063,20 +1213,24 @@ describe("Tier RV — component return values", () => { }); it("refuses a value component invoked without as", function* () { - const result = yield* run({ - "doc.md": "\n", - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - BODY_EFFECT, - "", - '', - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": "\n", + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + BODY_EFFECT, + "", + '', + "", + ].join("\n"), + }, + stream, + ); expect(said(result)).toContain("must be invoked with `as`"); expect(result.commands).toEqual([]); }); @@ -1084,29 +1238,37 @@ describe("Tier RV — component return values", () => { describe(" is reserved", () => { it("diagnoses caller content that declares ", function* () { - const result = yield* run({ - "doc.md": "\n\n\n", - "Wrapper.md": "\n", - "Return.md": "A COMPONENT NAMED RETURN\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": "\n\n\n", + "Wrapper.md": "\n", + "Return.md": "A COMPONENT NAMED RETURN\n", + }, + stream, + ); const output = said(result); expect(output).toContain(" requires a document or component"); expect(output).not.toContain("A COMPONENT NAMED RETURN"); }); it("diagnoses a produced by render(markdown)", function* () { - const result = yield* run({ - "doc.md": "\n", - "Dynamic.md": [ - "```js eval", - 'const rendered = yield* render("");', - "```", - "", - "{rendered}", - "", - ].join("\n"), - "Return.md": "A COMPONENT NAMED RETURN\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": "\n", + "Dynamic.md": [ + "```js eval", + 'const rendered = yield* render("");', + "```", + "", + "{rendered}", + "", + ].join("\n"), + "Return.md": "A COMPONENT NAMED RETURN\n", + }, + stream, + ); const output = said(result); expect(output).toContain(" is reserved"); expect(output).not.toContain("A COMPONENT NAMED RETURN"); @@ -1115,49 +1277,57 @@ describe("Tier RV — component return values", () => { describe("execution order", () => { it("runs documentation after and evaluates the value in place", function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - "```js eval", - 'const before = "early";', - "```", - "", - "", - "", - "```sh exec", - "echo AFTER_RETURN", - "```", - "", - "```js eval", - 'const after = "late";', - "```", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + "```js eval", + 'const before = "early";', + "```", + "", + "", + "", + "```sh exec", + "echo AFTER_RETURN", + "```", + "", + "```js eval", + 'const after = "late";', + "```", + "", + ].join("\n"), + }, + stream, + ); expect(said(result)).toContain('captured: "early"'); expect(result.commands).toEqual(["echo AFTER_RETURN"]); }); it("fails the caller when documentation after fails", function* () { - const result = yield* run({ - "doc.md": '\n', - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - '', - "", - "", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": '\n', + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + '', + "", + "", + "", + ].join("\n"), + }, + stream, + ); expect(result.error).toContain("Missing"); }); }); @@ -1172,26 +1342,41 @@ describe("Tier RV — component return values", () => { ].join("\n"); it("validates and captures a declared return value", function* () { - const result = yield* runFixture({ "doc.md": CAPTURING_ROOT, "Verdict.ts": valueFunction }); + const { directory, stream } = yield* useReturnsFixture(); + const result = yield* runFixture( + { "doc.md": CAPTURING_ROOT, "Verdict.ts": valueFunction }, + stream, + directory, + ); expect(said(result)).toContain('captured: {"passed":true}'); }); it("refuses a value function component invoked without as", function* () { - const result = yield* runFixture({ "doc.md": "\n", "Verdict.ts": valueFunction }); + const { directory, stream } = yield* useReturnsFixture(); + const result = yield* runFixture( + { "doc.md": "\n", "Verdict.ts": valueFunction }, + stream, + directory, + ); expect(said(result)).toContain("must be invoked with `as`"); }); it("reports a value that fails its schema", function* () { - const result = yield* runFixture({ - "doc.md": CAPTURING_ROOT, - "Verdict.ts": [ - "export const returns = { passed: { type: 'boolean' } };", - "export default function*() {", - " return { passed: 'yes' };", - "}", - "", - ].join("\n"), - }); + const { directory, stream } = yield* useReturnsFixture(); + const result = yield* runFixture( + { + "doc.md": CAPTURING_ROOT, + "Verdict.ts": [ + "export const returns = { passed: { type: 'boolean' } };", + "export default function*() {", + " return { passed: 'yes' };", + "}", + "", + ].join("\n"), + }, + stream, + directory, + ); expect(said(result)).toContain("Return validation failed for "); }); @@ -1199,12 +1384,20 @@ describe("Tier RV — component return values", () => { // return value — it simply has nowhere to go without `as`, and renders // nothing rather than being stringified into the document or diagnosed. it("renders nothing for a component that returns a non-string", function* () { - const result = yield* runFixture({ - "doc.md": "before\n\n\n\nafter\n", - "Verdict.ts": ["export default function*() {", " return { passed: true };", "};", ""].join( - "\n", - ), - }); + const { directory, stream } = yield* useReturnsFixture(); + const result = yield* runFixture( + { + "doc.md": "before\n\n\n\nafter\n", + "Verdict.ts": [ + "export default function*() {", + " return { passed: true };", + "};", + "", + ].join("\n"), + }, + stream, + directory, + ); const rendered = said(result); expect(rendered).not.toContain("non-string"); expect(rendered).not.toContain("passed"); @@ -1215,38 +1408,49 @@ describe("Tier RV — component return values", () => { describe("composition", () => { it("captures a value component invoked inside another component's body", function* () { - const result = yield* run({ - "doc.md": "\n", - "Report.md": [ - '', - "", - "", - "", - "REPORT PASSED", - "", - "", - "", - ].join("\n"), - "Verdict.md": valueComponent("returns:\n passed: { type: boolean }", "({ passed: true })"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": "\n", + "Report.md": [ + '', + "", + "", + "", + "REPORT PASSED", + "", + "", + "", + ].join("\n"), + "Verdict.md": valueComponent( + "returns:\n passed: { type: boolean }", + "({ passed: true })", + ), + }, + stream, + ); expect(said(result)).toContain("REPORT PASSED"); }); it("does not leak the value into the component's own environment", function* () { - const result = yield* run({ - "doc.md": CAPTURING_ROOT, - "Verdict.md": [ - "---", - "returns:", - " type: string", - "---", - "", - '', - "", - "self: {verdict}", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": CAPTURING_ROOT, + "Verdict.md": [ + "---", + "returns:", + " type: string", + "---", + "", + '', + "", + "self: {verdict}", + "", + ].join("\n"), + }, + stream, + ); const output = said(result); expect(output).toContain('captured: "one"'); expect(output).not.toContain("self:"); @@ -1271,7 +1475,8 @@ describe("Tier RV — component return values", () => { ].join("\n"); it("returns its validated value and keeps body text observable", function* () { - const result = yield* run({ "doc.md": valueRoot }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run({ "doc.md": valueRoot }, stream); expect(result.value).toEqual({ passed: true }); expect(result.output).toContain("BODY TEXT"); }); @@ -1296,50 +1501,63 @@ describe("Tier RV — component return values", () => { }); it("fails as a whole when its structure is invalid", function* () { - const result = yield* run({ - "doc.md": ["---", "returns:", " type: string", "---", "", BODY_EFFECT, ""].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": ["---", "returns:", " type: string", "---", "", BODY_EFFECT, ""].join("\n"), + }, + stream, + ); expect(result.value).toBeUndefined(); expect(result.error).toContain("no "); expect(result.commands).toEqual([]); }); it("fails as a whole when its value violates the schema", function* () { - const result = yield* run({ - "doc.md": [ - "---", - "returns:", - " passed: { type: boolean }", - "---", - "", - '', - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "---", + "returns:", + " passed: { type: boolean }", + "---", + "", + '', + "", + ].join("\n"), + }, + stream, + ); expect(result.value).toBeUndefined(); expect(result.error).toContain("Return validation failed for <__root__ />"); }); it("fails as a whole when its body fails after ", function* () { - const result = yield* run({ - "doc.md": [ - "---", - "returns:", - " type: string", - "---", - "", - '', - "", - "", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "---", + "returns:", + " type: string", + "---", + "", + '', + "", + "", + "", + ].join("\n"), + }, + stream, + ); expect(result.value).toBeUndefined(); expect(result.error).toContain("Missing"); }); it("keeps a text root's completion and rendering unchanged", function* () { - const result = yield* run({ "doc.md": "# Title\n" }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run({ "doc.md": "# Title\n" }, stream); expect(said(result)).toContain("# Title"); expect(result.output).toContain("# Title"); }); @@ -1413,6 +1631,7 @@ describe("Tier RV — component return values", () => { }); describe("993 value invocation privacy", () => { + beforeEach(journalBeforeEach(OWNER)); it("W5: a value body requesting caller text does not select the outer source", function* () { const result = yield* run({ "doc.md": 'docsprivate', @@ -1422,9 +1641,13 @@ describe("993 value invocation privacy", () => { expect(result.output).toBe(""); }); it("W5: a value root refuses nested declarations before its first effect", function* () { - const result = yield* run({ - "doc.md": `---\nreturns: { type: string }\n---\n${BODY_EFFECT}\n`, - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": `---\nreturns: { type: string }\n---\n${BODY_EFFECT}\n`, + }, + stream, + ); expect(said(result)).toContain("exclusive"); expect(result.commands).toEqual([]); }); diff --git a/packages/core/tests/file-component.test.ts b/packages/core/tests/file-component.test.ts index 0ffb06802..caa82aa25 100644 --- a/packages/core/tests/file-component.test.ts +++ b/packages/core/tests/file-component.test.ts @@ -12,7 +12,9 @@ * fixture unlinks its symlinks rather than following them. */ -import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; +import { captureTestJournal } from "../../test-support/failure-journal.ts"; +import { beforeAll, beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, race, resource, scoped, sleep, suspend, until } from "effection"; import type { Operation } from "effection"; @@ -47,6 +49,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import process from "node:process"; +const OWNER = "packages/core/tests/file-component.test.ts"; + /** * A workspace and a directory beside it that is deliberately out of reach. * @@ -489,16 +493,18 @@ const BOUNDARIES: Array<{ ]; describe("Tier FL — File", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); // FL1: the ordinary round trip, in relative paths against the contextual // directory — the position every other test starts from. it("FL1: a relative write is readable at the same relative path", function* () { const fixture = yield* useFixture(); - - const output = yield* run( + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); + const output = yield* runWith( fixture, ['Request content', ''].join("\n"), + stream, ); expect(yield* read(fixture, "request.md")).toBe("Request content"); @@ -509,8 +515,12 @@ describe("Tier FL — File", () => { // path, so a document cannot accidentally leak where it wrote. it("FL2: the write form renders nothing", function* () { const fixture = yield* useFixture(); - - const output = yield* run(fixture, 'Request content'); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); + const output = yield* runWith( + fixture, + 'Request content', + stream, + ); expect(text(output).trim()).toBe(""); expect(yield* read(fixture, "request.md")).toBe("Request content"); @@ -519,8 +529,8 @@ describe("Tier FL — File", () => { // FL3: a path names where the file goes, not a directory that must exist. it("FL3: a write creates the parent directories its path names", function* () { const fixture = yield* useFixture(); - - yield* run(fixture, 'nested'); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); + yield* runWith(fixture, 'nested', stream); expect(yield* read(fixture, "fixtures/nested/request.md")).toBe("nested"); }); @@ -529,14 +539,15 @@ describe("Tier FL — File", () => { // same content again leaves the same file rather than appending. it("FL4: a second write replaces the content", function* () { const fixture = yield* useFixture(); - - yield* run( + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); + yield* runWith( fixture, [ 'first', 'second', 'second', ].join("\n"), + stream, ); expect(yield* read(fixture, "notes.md")).toBe("second"); @@ -546,8 +557,10 @@ describe("Tier FL — File", () => { // after it still runs. it("FL5: reading a missing path fails as a printed error", function* () { const fixture = yield* useFixture(); - - const output = text(yield* run(fixture, ['', "", "after"].join("\n"))); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); + const output = text( + yield* runWith(fixture, ['', "", "after"].join("\n"), stream), + ); expect(output).toContain('cannot read "absent.md": no such file.'); expect(output).toContain("after"); @@ -557,11 +570,12 @@ describe("Tier FL — File", () => { // reading one produces on a given platform. it("FL6: reading a directory fails naming what it is", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const output = text( - yield* run( + yield* runWith( fixture, ['inner', ''].join("\n"), + stream, ), ); @@ -602,6 +616,7 @@ describe("Tier FL — File", () => { // back through either name agree. it("FL9: an internal symlink is followed for both reads and writes", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* until(mkdir(join(fixture.workspace, "real"))); yield* writeTextFile(join(fixture.workspace, "real/target.txt"), "original"); yield* until( @@ -609,9 +624,10 @@ describe("Tier FL — File", () => { ); const output = text( - yield* run( + yield* runWith( fixture, ['', 'replaced'].join("\n"), + stream, ), ); @@ -657,12 +673,12 @@ describe("Tier FL — File", () => { // The invocation fails rather than writing, and carries the reason out. it("FL12: a failing child leaves an existing file untouched", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); // `` reports what it did not write, and the checked failure inside it // is still the run's: no write, no replacement, and nothing after it (#441). let failure = ""; try { - yield* run( + yield* runWith( fixture, [ 'first', @@ -676,6 +692,7 @@ describe("Tier FL — File", () => { `touch ${join(fixture.workspace, "sibling-ran.txt")}`, "```", ].join("\n"), + stream, ); } catch (error) { failure = error instanceof Error ? error.message : String(error); @@ -761,32 +778,43 @@ describe("Tier FL — File", () => { // FL13: the write itself failing is the other half. The replacement is a // rename over a temporary, so a directory that refuses new files stops it // before the previous content is disturbed. - it("FL13: a failed replacement leaves the previous content in place", function* () { - // Root ignores directory permissions, so there would be no failure to - // observe and the assertion below would measure nothing. - if (process.getuid?.() === 0) { - return; - } - - const fixture = yield* useFixture(); - const locked = join(fixture.workspace, "locked"); - yield* until(mkdir(locked)); - yield* writeTextFile(join(locked, "notes.md"), "first"); - yield* until(chmod(locked, 0o555)); - yield* ensure(() => until(chmod(locked, 0o755))); - - const output = text(yield* run(fixture, 'second')); + { + const caseName = "FL13: a failed replacement leaves the previous content in place"; + it(caseName, function* () { + // Root ignores directory permissions, so there would be no failure to + // observe and the assertion below would measure nothing. + if (process.getuid?.() === 0) { + return; + } - expect(output).toContain("Function component File error:"); - expect(yield* read(fixture, "locked/notes.md")).toBe("first"); - }); + const fixture = yield* useFixture(); + yield* captureTestJournal( + { owner: OWNER, name: caseName }, + join(fixture.workspace, "doc.md"), + function* (stream) { + const locked = join(fixture.workspace, "locked"); + yield* until(mkdir(locked)); + yield* writeTextFile(join(locked, "notes.md"), "first"); + yield* until(chmod(locked, 0o555)); + yield* ensure(() => until(chmod(locked, 0o755))); + + const output = text( + yield* runWith(fixture, 'second', stream), + ); + + expect(output).toContain("Function component File error:"); + expect(yield* read(fixture, "locked/notes.md")).toBe("first"); + }, + ); + }); + } // FL14: the temporary the replacement goes through is an implementation // detail, and it must not become a document's problem. it("FL14: a successful write leaves no temporary file behind", function* () { const fixture = yield* useFixture(); - - yield* run(fixture, 'content'); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); + yield* runWith(fixture, 'content', stream); expect(yield* entries(fixture.workspace)).toEqual(["notes.md"]); }); @@ -871,15 +899,16 @@ describe("Tier FL — File", () => { // would refuse an ordinary file whose name happens to start with two dots. it("FL17: a name beginning with dots is an ordinary file", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const output = text( - yield* run( + yield* runWith( fixture, [ 'dotted', 'nested', '', ].join("\n"), + stream, ), ); @@ -1360,6 +1389,7 @@ function* useFileCalls(calls: string[]): Operation { } describe("Tier FL — the authored form decides the effect", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); const LYING: Array<[string, readonly boolean[]]> = [ diff --git a/packages/core/tests/files-fatal.test.ts b/packages/core/tests/files-fatal.test.ts index fe925ac4e..4323861ec 100644 --- a/packages/core/tests/files-fatal.test.ts +++ b/packages/core/tests/files-fatal.test.ts @@ -15,7 +15,9 @@ * that misbehave in exactly one way each. */ -import { describe, it, beforeAll } from "@executablemd/test-support/bdd"; +import { captureTestJournal } from "../../test-support/failure-journal.ts"; +import { beforeAll, beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, Err, Ok, resource, scoped, spawn, suspend, until, withResolvers } from "effection"; import type { Operation, Result } from "effection"; @@ -52,6 +54,7 @@ import { mkdtemp, realpath } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +const OWNER = "packages/core/tests/files-fatal.test.ts"; function useFixture(): Operation { return resource(function* (provide) { const dir = yield* until(mkdtemp(join(tmpdir(), "ff-test-"))); @@ -74,7 +77,12 @@ interface Outcome { * error precisely by leaving nothing in the output, and by stopping what comes * after it. */ -function run(dir: string, source: string, install?: () => Operation): Operation { +function run( + dir: string, + source: string, + install?: () => Operation, + stream = new InMemoryStream(), +): Operation { return scoped(function* () { yield* writeTextFile(join(dir, "doc.md"), source); yield* API.Env.around( @@ -93,7 +101,7 @@ function run(dir: string, source: string, install?: () => Operation): Oper const result = yield* scoped(function* () { const execution = yield* execute({ path: join(dir, "doc.md"), - stream: new InMemoryStream(), + stream, includes: [dir], }); try { @@ -223,6 +231,7 @@ function writeDocument(dir: string): string { } describe("Tier FF — Files infrastructure failure", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); // FF1: no provider at all. The check a write performs before its children is @@ -230,20 +239,26 @@ describe("Tier FF — Files infrastructure failure", () => { // children — and nothing after the component runs either. it("FF1: an absent provider fails the execution before children or siblings", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); const touched: string[] = []; - const outcome = yield* run(dir, writeDocument(dir), function* () { - yield* API.Fs.around({ - *writeTextFile([path, content], next) { - touched.push(path); - return yield* next(path, content); - }, - *rename([from, to], next) { - touched.push(from); - return yield* next(from, to); - }, - }); - }); + const outcome = yield* run( + dir, + writeDocument(dir), + function* () { + yield* API.Fs.around({ + *writeTextFile([path, content], next) { + touched.push(path); + return yield* next(path, content); + }, + *rename([from, to], next) { + touched.push(from); + return yield* next(from, to); + }, + }); + }, + stream, + ); expect(outcome.ok).toBe(false); expect(parseFilesFatal(fatalCause(outcome.error))).toEqual({ @@ -322,16 +337,21 @@ describe("Tier FF — Files infrastructure failure", () => { // the run does not own. it("FF3: a refused operation is fatal, with its own fixed diagnostic", function* () { const dir = yield* useFixture(); - - const outcome = yield* run(dir, "INSIDE\n\nAFTER", function* () { - yield* useHostFiles(); - yield* useFiles({ - // deno-lint-ignore require-yield - *temporaryDirectory(): Operation> { - throw new FilesOperationDeniedError("temporary-directory"); - }, - }); - }); + const stream = yield* useJournalStream(join(dir, "doc.md")); + const outcome = yield* run( + dir, + "INSIDE\n\nAFTER", + function* () { + yield* useHostFiles(); + yield* useFiles({ + // deno-lint-ignore require-yield + *temporaryDirectory(): Operation> { + throw new FilesOperationDeniedError("temporary-directory"); + }, + }); + }, + stream, + ); expect(outcome.ok).toBe(false); expect(parseFilesFatal(fatalCause(outcome.error))).toEqual({ @@ -349,31 +369,37 @@ describe("Tier FF — Files infrastructure failure", () => { // provider-level statement of FL18b and FL18c. it("FF4: a refused check expands no children and makes no later provider call", function* () { const dir = yield* useFixture(); + const stream = yield* useJournalStream(join(dir, "doc.md")); const calls: string[] = []; - const outcome = yield* run(dir, writeDocument(dir), function* () { - yield* useFiles({ - // deno-lint-ignore require-yield - *checkFilePath(): Operation> { - calls.push("checkFilePath"); - return Err( - new FilesError( - Object.freeze({ - type: FILES_ERROR, - operation: "check-file-path", - phase: "lexical", - reason: "lexical-escape", - }), - ), - ); - }, - // deno-lint-ignore require-yield - *writeTextFile(): Operation> { - calls.push("writeTextFile"); - throw new Error("the write must never be reached"); - }, - }); - }); + const outcome = yield* run( + dir, + writeDocument(dir), + function* () { + yield* useFiles({ + // deno-lint-ignore require-yield + *checkFilePath(): Operation> { + calls.push("checkFilePath"); + return Err( + new FilesError( + Object.freeze({ + type: FILES_ERROR, + operation: "check-file-path", + phase: "lexical", + reason: "lexical-escape", + }), + ), + ); + }, + // deno-lint-ignore require-yield + *writeTextFile(): Operation> { + calls.push("writeTextFile"); + throw new Error("the write must never be reached"); + }, + }); + }, + stream, + ); expect(calls).toEqual(["checkFilePath"]); // An ordinary refusal, so the document reads it and carries on. @@ -1286,10 +1312,15 @@ describe("Tier FF — Files infrastructure failure", () => { // wrong beneath one. it("FF10: an ordinary provider failure stays a printed error", function* () { const dir = yield* useFixture(); - - const outcome = yield* run(dir, '\n\nAFTER', function* () { - yield* useHostFiles(); - }); + const stream = yield* useJournalStream(join(dir, "doc.md")); + const outcome = yield* run( + dir, + '\n\nAFTER', + function* () { + yield* useHostFiles(); + }, + stream, + ); expect(outcome.ok).toBe(true); expect(outcome.output).toContain('cannot read "absent.md": no such file.'); diff --git a/packages/core/tests/fixed-filesystem-components.test.ts b/packages/core/tests/fixed-filesystem-components.test.ts index 86bcb37b0..026a52a23 100644 --- a/packages/core/tests/fixed-filesystem-components.test.ts +++ b/packages/core/tests/fixed-filesystem-components.test.ts @@ -30,7 +30,9 @@ * copy of core, which is Deno-only and lives in `syntax-loaded-copy.test.ts`. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { captureTestJournal } from "../../test-support/failure-journal.ts"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { Ok, ensure, resource, scoped, spawn, suspend, until, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -53,7 +55,10 @@ import { mkdtemp, readdir, realpath } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +const OWNER = "packages/core/tests/fixed-filesystem-components.test.ts"; + /** The registry visible in the current scope. */ + function currentRegistry(): Operation { return Component.operations.registry; } @@ -131,6 +136,7 @@ function* useWorkspaceCwd(fixture: Fixture): Operation { * before any later installation exists. */ function observeEnclosingCwd( + stream: InMemoryStream, fixture: Fixture, source: string, ): Operation<{ failure: string; enclosing: string }> { @@ -140,9 +146,7 @@ function observeEnclosingCwd( yield* useWorkspaceCwd(fixture); let failure = ""; try { - yield* collect( - yield* execute({ path, stream: new InMemoryStream(), includes: [fixture.workspace] }), - ); + yield* collect(yield* execute({ path, stream, includes: [fixture.workspace] })); } catch (error) { failure = error instanceof Error ? error.message : String(error); } @@ -153,7 +157,12 @@ function observeEnclosingCwd( }); } -function run(fixture: Fixture, source: string, install?: () => Operation): Operation { +function run( + fixture: Fixture, + source: string, + install?: () => Operation, + stream = new InMemoryStream(), +): Operation { return scoped(function* () { const path = join(fixture.workspace, "doc.md"); yield* writeTextFile(path, source); @@ -162,7 +171,7 @@ function run(fixture: Fixture, source: string, install?: () => Operation): yield* install(); } const output: Json = yield* collect( - yield* execute({ path, stream: new InMemoryStream(), includes: [fixture.workspace] }), + yield* execute({ path, stream, includes: [fixture.workspace] }), ); return String(output); }); @@ -217,8 +226,10 @@ function answerImport( } describe("Tier FX — the complete journey, with no repository vocabulary", () => { + beforeEach(journalBeforeEach(OWNER)); it("FX1: core and a Files provider enter, write, read and delete; markers never run", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* writeMarkers(fixture); const output = yield* run( @@ -231,6 +242,8 @@ describe("Tier FX — the complete journey, with no repository vocabulary", () = '', "", ].join("\n"), + undefined, + stream, ); // The read text, and none of the three markers: selection answered with @@ -246,7 +259,7 @@ describe("Tier FX — the complete journey, with no repository vocabulary", () = it("FX1b: Files middleware transforms the write, and the later read returns it", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const output = yield* run( fixture, [ @@ -263,6 +276,7 @@ describe("Tier FX — the complete journey, with no repository vocabulary", () = }, }); }, + stream, ); // A fixed name is not a fixed provider. The body still performs its write @@ -276,7 +290,7 @@ describe("Tier FX — the complete journey, with no repository vocabulary", () = it("FX1c: the enclosing working directory is restored for a later sibling", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const output = yield* run( fixture, [ @@ -287,6 +301,8 @@ describe("Tier FX — the complete journey, with no repository vocabulary", () = '', "{seen}", ].join("\n"), + undefined, + stream, ); expect(output).toContain("out"); @@ -297,6 +313,7 @@ describe("Tier FX — the complete journey, with no repository vocabulary", () = }); describe("Tier FX — nothing else may claim the names", () => { + beforeEach(journalBeforeEach(OWNER)); it("FX2: a registration and a reserved registration are both refused", function* () { for (const name of FIXED) { const refused = yield* raised(() => @@ -387,7 +404,7 @@ describe("Tier FX — nothing else may claim the names", () => { it("FX2c: a same-name local implementation is never loaded, and open names still win", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); // A candidate that would be fatal if it were ever imported. Selection // refuses it by name, so its top level never runs — which is the difference // between losing selection and being loaded and then ignored. @@ -398,7 +415,12 @@ describe("Tier FX — nothing else may claim the names", () => { // An open name beside it, to show the include itself is live. yield* writeTextFile(join(fixture.workspace, "Kept.md"), "kept by the repository\n"); - const output = yield* run(fixture, ['', "", ""].join("\n")); + const output = yield* run( + fixture, + ['', "", ""].join("\n"), + undefined, + stream, + ); expect(output).toContain("kept by the repository"); expect(yield* exists(join(fixture.workspace, "notes"))).toBe(true); @@ -406,8 +428,10 @@ describe("Tier FX — nothing else may claim the names", () => { }); describe("Tier FX — the final import answer is verified", () => { + beforeEach(journalBeforeEach(OWNER)); it("FX3: middleware may observe and delegate every fixed import", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const seen: string[] = []; const output = yield* run( @@ -426,6 +450,7 @@ describe("Tier FX — the final import answer is verified", () => { }, }); }, + stream, ); expect(output).not.toContain("MARKER"); @@ -434,162 +459,183 @@ describe("Tier FX — the final import answer is verified", () => { } }); - it("FX3b: a replacement is refused before the body or any provider call", function* () { + const replacedDefinition = "FX3b: a replacement is refused before the body or any provider call"; + it(replacedDefinition, function* () { for (const name of FIXED) { const fixture = yield* useFixture(); - const reached: string[] = []; - - const refused = yield* raised(() => - run( - fixture, - [ - '', - 'first', - '', - "", - ].join("\n"), - function* () { - yield* Files.around({ - *ensureDirectory([input], next) { - reached.push("ensureDirectory"); - return yield* next(input); - }, - *writeTextFile([input], next) { - reached.push("writeTextFile"); - return yield* next(input); - }, - *deleteFile([input], next) { - reached.push("deleteFile"); - return yield* next(input); + yield* captureTestJournal( + { owner: OWNER, name: replacedDefinition }, + join(fixture.workspace, "doc.md"), + function* (stream) { + const reached: string[] = []; + + const refused = yield* raised(() => + run( + fixture, + [ + '', + 'first', + '', + "", + ].join("\n"), + function* () { + yield* Files.around({ + *ensureDirectory([input], next) { + reached.push("ensureDirectory"); + return yield* next(input); + }, + *writeTextFile([input], next) { + reached.push("writeTextFile"); + return yield* next(input); + }, + *deleteFile([input], next) { + reached.push("deleteFile"); + return yield* next(input); + }, + }); + yield* answerImport(name, () => ({ + kind: "function", + name, + props: { type: "object", properties: {}, additionalProperties: false }, + // deno-lint-ignore require-yield + *fn(): Operation { + reached.push("replacement"); + return "replaced"; + }, + }))(); }, - }); - yield* answerImport(name, () => ({ - kind: "function", - name, - props: { type: "object", properties: {}, additionalProperties: false }, - // deno-lint-ignore require-yield - *fn(): Operation { - reached.push("replacement"); - return "replaced"; - }, - }))(); - }, - ), - ); + stream, + ), + ); - expect(refused).toContain("canonical execution did not produce"); - expect(reached).not.toContain("replacement"); - // `` is refused at the first element, so nothing inside it runs. The - // other two are refused after the directory exists, which is the element - // before them succeeding rather than this one partly succeeding. - if (name === "Dir") { - expect(reached).toEqual([]); - } + expect(refused).toContain("canonical execution did not produce"); + expect(reached).not.toContain("replacement"); + // `` is refused at the first element, so nothing inside it runs. The + // other two are refused after the directory exists, which is the element + // before them succeeding rather than this one partly succeeding. + if (name === "Dir") { + expect(reached).toEqual([]); + } + }, + ); } }); - it("FX3c: an in-place change to a fixed definition cannot run, now or later", function* () { + const immutableDefinition = + "FX3c: an in-place change to a fixed definition cannot run, now or later"; + it(immutableDefinition, function* () { const fixture = yield* useFixture(); - const definition = fixedFilesystemDefinition("File"); - if (definition === undefined) { - throw new Error("core supplies no File definition"); - } - const original = definition.fn; - const originalPathType = pathType(definition.props); - expect(originalPathType).toBe("string"); - - let attempts = 0; - const accepted: boolean[] = []; - let replacementCalls = 0; - - // The dangerous shape is not a replacement object — it is a change to the - // object canonical execution handed out, which every execution in the - // process shares. Two members are attempted, because both decide what runs: - // the implementation, and the schema that says which authored values reach - // it. - const output = yield* run( - fixture, - [ - "", - "", - 'one', - "", - 'two', - "", - '', - "", - "LATER {two}", - "", - "", - ].join("\n"), - function* () { - yield* Component.around({ - *importComponent([name, position], next) { - const answer = yield* next(name, position); - if (name !== "File" || attempts > 0) { + const testCase = { owner: OWNER, name: immutableDefinition }; + yield* captureTestJournal(testCase, join(fixture.workspace, "doc.md"), function* (stream) { + const definition = fixedFilesystemDefinition("File"); + if (definition === undefined) { + throw new Error("core supplies no File definition"); + } + const original = definition.fn; + const originalPathType = pathType(definition.props); + expect(originalPathType).toBe("string"); + + let attempts = 0; + const accepted: boolean[] = []; + let replacementCalls = 0; + + // The dangerous shape is not a replacement object — it is a change to the + // object canonical execution handed out, which every execution in the + // process shares. Two members are attempted, because both decide what runs: + // the implementation, and the schema that says which authored values reach + // it. + const output = yield* run( + fixture, + [ + "", + "", + 'one', + "", + 'two', + "", + '', + "", + "LATER {two}", + "", + "", + ].join("\n"), + function* () { + yield* Component.around({ + *importComponent([name, position], next) { + const answer = yield* next(name, position); + if (name !== "File" || attempts > 0) { + return answer; + } + attempts += 1; + accepted.push( + Reflect.set(answer, "fn", function* (): Operation { + replacementCalls += 1; + return "POISONED-FILE-BODY"; + }), + ); + const path = pathSchema(answer.props); + if (path !== undefined) { + accepted.push(Reflect.set(path, "type", "number")); + } return answer; - } - attempts += 1; - accepted.push( - Reflect.set(answer, "fn", function* (): Operation { - replacementCalls += 1; - return "POISONED-FILE-BODY"; - }), - ); - const path = pathSchema(answer.props); - if (path !== undefined) { - accepted.push(Reflect.set(path, "type", "number")); - } - return answer; - }, - }); - }, - ); + }, + }); + }, + stream, + ); - // Both attempts were made and both were rejected where they were made, - // rather than the handler quietly doing nothing. - expect(attempts).toBe(1); - expect(accepted).toEqual([false, false]); - - // No replacement body and no replacement I/O, on this import or any later - // one: the writes are the document's own text and the read returns it. - expect(replacementCalls).toBe(0); - expect(output).not.toContain("POISONED"); - expect(output).toContain("LATER two"); - expect(yield* readTextFile(join(fixture.workspace, "one.md"))).toBe("one"); - expect(yield* readTextFile(join(fixture.workspace, "two.md"))).toBe("two"); - - // The owning definition and its whole schema are what they were. - expect(fixedFilesystemDefinition("File")?.fn).toBe(original); - expect(pathType(fixedFilesystemDefinition("File")?.props)).toBe("string"); - - // And the contract a *fresh* execution validates against is unchanged. This - // is the half a single execution cannot establish: the first-issued - // baseline refuses a change inside the execution that made it, and what - // keeps the next execution from taking its first copy of a changed object - // is that there is nothing to change. - const later = yield* useFixture(); - const second = yield* run( - later, - [ - 'still a string path', - '', - "{seen}", - ].join("\n"), - ); - expect(second).toContain("still a string path"); - expect(yield* readTextFile(join(later.workspace, "valid.md"))).toBe("still a string path"); + // Both attempts were made and both were rejected where they were made, + // rather than the handler quietly doing nothing. + expect(attempts).toBe(1); + expect(accepted).toEqual([false, false]); + + // No replacement body and no replacement I/O, on this import or any later + // one: the writes are the document's own text and the read returns it. + expect(replacementCalls).toBe(0); + expect(output).not.toContain("POISONED"); + expect(output).toContain("LATER two"); + expect(yield* readTextFile(join(fixture.workspace, "one.md"))).toBe("one"); + expect(yield* readTextFile(join(fixture.workspace, "two.md"))).toBe("two"); + + // The owning definition and its whole schema are what they were. + expect(fixedFilesystemDefinition("File")?.fn).toBe(original); + expect(pathType(fixedFilesystemDefinition("File")?.props)).toBe("string"); + + // And the contract a *fresh* execution validates against is unchanged. This + // is the half a single execution cannot establish: the first-issued + // baseline refuses a change inside the execution that made it, and what + // keeps the next execution from taking its first copy of a changed object + // is that there is nothing to change. + const later = yield* useFixture(); + yield* captureTestJournal( + testCase, + join(later.workspace, "doc.md"), + function* (secondStream) { + const second = yield* run( + later, + [ + 'still a string path', + '', + "{seen}", + ].join("\n"), + undefined, + secondStream, + ); + expect(second).toContain("still a string path"); + expect(yield* readTextFile(join(later.workspace, "valid.md"))).toBe( + "still a string path", + ); + }, + ); + }); }); it("FX3c2: another name's issued definition is refused", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const swapped = yield* raised(() => run( fixture, - // `` first, so its definition has been issued by the time the - // `` import is answered with it. An answer holding a definition - // this execution never issued is the other refusal, below. 'x\n\nfirst\n', function* () { const other = fixedFilesystemDefinition("File"); @@ -598,6 +644,7 @@ describe("Tier FX — the final import answer is verified", () => { } yield* answerImport("Dir", () => other)(); }, + stream, ), ); expect(swapped).toContain("produced for another component"); @@ -605,7 +652,7 @@ describe("Tier FX — the final import answer is verified", () => { it("FX3d: a rebuilt definition is refused, however exactly it matches", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); // A dispatcher built from the same declaration, so every field matches and // the function is not the one this execution retained. A definition from an // actual second loaded copy of core is the same class of answer and is @@ -623,6 +670,7 @@ describe("Tier FX — the final import answer is verified", () => { fixture, 'first', answerImport("File", () => rebuilt), + stream, ), ); @@ -632,18 +680,23 @@ describe("Tier FX — the final import answer is verified", () => { it("FX3e: middleware may still refuse a fixed import by throwing", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const refused = yield* raised(() => - run(fixture, 'first', function* () { - yield* Component.around({ - *importComponent([name, position], next) { - if (name === "File") { - throw new Error("this host refuses File"); - } - return yield* next(name, position); - }, - }); - }), + run( + fixture, + 'first', + function* () { + yield* Component.around({ + *importComponent([name, position], next) { + if (name === "File") { + throw new Error("this host refuses File"); + } + return yield* next(name, position); + }, + }); + }, + stream, + ), ); expect(refused).toContain("this host refuses File"); @@ -684,9 +737,11 @@ describe("Tier FX — the dispatcher authenticates its own invocation", () => { }); describe("Tier FX — Dir's ordering, ownership and cancellation", () => { + beforeEach(journalBeforeEach(OWNER)); for (const tag of ["Dir", "InDirectory"]) { it(`FX5: ${tag} restores the enclosing directory in its owner after failure`, function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* writeTextFile(join(fixture.workspace, "outside.md"), "outside"); yield* writeTextFile(join(fixture.workspace, "InDirectory.md"), DIRECTORY_WRAPPER); @@ -694,6 +749,7 @@ describe("Tier FX — Dir's ordering, ownership and cancellation", () => { // error this component owns, and what this case is about is the directory // ownership surviving a body that ends the run. const { failure, enclosing } = yield* observeEnclosingCwd( + stream, fixture, [ `<${tag} path="notes">`, @@ -716,6 +772,7 @@ describe("Tier FX — Dir's ordering, ownership and cancellation", () => { it("FX5b: a refused ensure begins no content and binds no directory", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); // A file where the directory would go, so the ensure is refused rather than // failing for a reason of the test's own making. yield* writeTextFile(join(fixture.workspace, "notes"), "not a directory\n"); @@ -733,6 +790,7 @@ describe("Tier FX — Dir's ordering, ownership and cancellation", () => { }, }); }, + stream, ), ); @@ -743,12 +801,15 @@ describe("Tier FX — Dir's ordering, ownership and cancellation", () => { it("FX5c: a directory that is already there keeps what is in it", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* ensureDir(join(fixture.workspace, "notes")); yield* writeTextFile(join(fixture.workspace, "notes", "kept.md"), "kept\n"); yield* run( fixture, ['', 'added', ""].join("\n"), + undefined, + stream, ); expect(yield* entries(join(fixture.workspace, "notes"))).toEqual(["added.md", "kept.md"]); @@ -758,6 +819,7 @@ describe("Tier FX — Dir's ordering, ownership and cancellation", () => { for (const tag of ["Dir", "InDirectory"]) { it(`FX5d: ${tag} restores the directory after joined cancellation`, function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* writeTextFile(join(fixture.workspace, "outside.md"), "outside"); yield* writeTextFile(join(fixture.workspace, "InDirectory.md"), DIRECTORY_WRAPPER); const inside = withResolvers(); @@ -785,7 +847,7 @@ describe("Tier FX — Dir's ordering, ownership and cancellation", () => { const task = yield* spawn(function* () { const output = yield* collect( - yield* execute({ path, stream: new InMemoryStream(), includes: [fixture.workspace] }), + yield* execute({ path, stream, includes: [fixture.workspace] }), ); outcome.push(String(output)); }); diff --git a/packages/core/tests/invocation-identity.test.ts b/packages/core/tests/invocation-identity.test.ts index c3d88ecac..2a57c16c3 100644 --- a/packages/core/tests/invocation-identity.test.ts +++ b/packages/core/tests/invocation-identity.test.ts @@ -1,3 +1,4 @@ +import { captureTestJournal } from "../../test-support/failure-journal.ts"; import { useComponentModuleLoader } from "@executablemd/test-support/host"; /** * Tier CIV — the identity a trusted host's component names its work after @@ -20,7 +21,8 @@ import { useComponentModuleLoader } from "@executablemd/test-support/host"; * running at that moment. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { createContext, race, scoped, sleep, spawn, useScope, withResolvers } from "effection"; import type { Context, Operation } from "effection"; @@ -51,6 +53,7 @@ import { InMemoryStream } from "@executablemd/durable-streams"; import { readTextFile } from "@effectionx/fs"; import { fileURLToPath } from "node:url"; +const OWNER = "packages/core/tests/invocation-identity.test.ts"; /** * The engine's expansion context, addressed by the name it publishes under. * @@ -176,6 +179,7 @@ function run( components: readonly IdentityComponent[], install?: () => Operation, includes: readonly string[] = [], + stream = new InMemoryStream(), ): Operation { return scoped(function* () { const installation: ExecutionInstallation = { @@ -186,7 +190,7 @@ function run( yield* executeInstalled( { ...inlineSource(source), - stream: new InMemoryStream(), + stream, includes: [...includes], }, [installation], @@ -200,13 +204,14 @@ function rendered( source: string, components: readonly IdentityComponent[], includes: readonly string[] = [], + stream = new InMemoryStream(), ): Operation { return scoped(function* () { const settled = yield* collect( yield* executeInstalled( { ...inlineSource(source), - stream: new InMemoryStream(), + stream, includes: [...includes], }, [{ components }], @@ -268,9 +273,11 @@ function* seam(): Operation<{ claim: IdentityClaimant; domain: IdentityDomain }> } describe("Tier CIV — the identity a host's component names its work after", () => { + beforeEach(journalBeforeEach(OWNER)); it("CIV1: two sites are handed two identities", function* () { + const stream = yield* useJournalStream(""); const seen = record(); - yield* run("\n\n\n", [probe(seen)], nothing); + yield* run("\n\n\n", [probe(seen)], nothing, undefined, stream); expect(seen.taken).toHaveLength(2); expect(new Set(seen.taken).size).toBe(2); // The engine's own identity for that invocation, which is what @@ -279,17 +286,24 @@ describe("Tier CIV — the identity a host's component names its work after", () }); it("CIV2: a contextual Api answer is replaceable, so a durable name may not come from one", function* () { + const stream = yield* useJournalStream(""); const seen = record(); // `hasContent()` stands for every Component Api answer: a handler installed // outside the invocation answers ahead of the engine's own. - yield* run("\n", [probe(seen)], function* () { - yield* Component.around({ - // deno-lint-ignore require-yield - *hasContent(_args, _next) { - return true; - }, - }); - }); + yield* run( + "\n", + [probe(seen)], + function* () { + yield* Component.around({ + // deno-lint-ignore require-yield + *hasContent(_args, _next) { + return true; + }, + }); + }, + undefined, + stream, + ); expect(seen.api).toEqual([true]); expect(seen.taken).toHaveLength(1); expect(seen.taken[0]).not.toBe(FORGED); @@ -306,32 +320,39 @@ describe("Tier CIV — the identity a host's component names its work after", () }); it("CIV4: middleware cannot build an invocation the claimant will answer for", function* () { + const stream = yield* useJournalStream(""); const seen = record(); - yield* run("\n\n\n", [probe(seen)], function* () { - yield* Component.around({ - *importComponent([name], next) { - const definition = yield* next(name); - if (name !== "Probe" || definition.kind !== "function") { - return definition; - } - const original = definition.fn; - if (typeof original !== "function") { - return definition; - } - return { - ...definition, - *fn(props: Record, _invocation: ComponentInvocation) { - // A structural stand-in, which is what a wrapper would mint to - // give both sites one durable name. It answers the authored form - // too — implementing the whole public shape is exactly what a - // forger would do, and identity is the private field rather than - // the shape. - return yield* original(props, { hasContent: () => false }); - }, - }; - }, - }); - }); + yield* run( + "\n\n\n", + [probe(seen)], + function* () { + yield* Component.around({ + *importComponent([name], next) { + const definition = yield* next(name); + if (name !== "Probe" || definition.kind !== "function") { + return definition; + } + const original = definition.fn; + if (typeof original !== "function") { + return definition; + } + return { + ...definition, + *fn(props: Record, _invocation: ComponentInvocation) { + // A structural stand-in, which is what a wrapper would mint to + // give both sites one durable name. It answers the authored form + // too — implementing the whole public shape is exactly what a + // forger would do, and identity is the private field rather than + // the shape. + return yield* original(props, { hasContent: () => false }); + }, + }; + }, + }); + }, + undefined, + stream, + ); expect(seen.taken).toEqual([]); expect(seen.refusals).toHaveLength(2); @@ -341,28 +362,35 @@ describe("Tier CIV — the identity a host's component names its work after", () }); it("CIV5: middleware may forward the genuine issuance, and each site keeps its own", function* () { + const stream = yield* useJournalStream(""); const seen = record(); - yield* run("\n\n\n", [probe(seen)], function* () { - yield* Component.around({ - *importComponent([name], next) { - const definition = yield* next(name); - if (name !== "Probe" || definition.kind !== "function") { - return definition; - } - const original = definition.fn; - if (typeof original !== "function") { - return definition; - } - return { - ...definition, - *fn(props: Record, invocation: ComponentInvocation) { - // Ordinary delegation, and it stays supported. - return yield* original(props, invocation); - }, - }; - }, - }); - }); + yield* run( + "\n\n\n", + [probe(seen)], + function* () { + yield* Component.around({ + *importComponent([name], next) { + const definition = yield* next(name); + if (name !== "Probe" || definition.kind !== "function") { + return definition; + } + const original = definition.fn; + if (typeof original !== "function") { + return definition; + } + return { + ...definition, + *fn(props: Record, invocation: ComponentInvocation) { + // Ordinary delegation, and it stays supported. + return yield* original(props, invocation); + }, + }; + }, + }); + }, + undefined, + stream, + ); expect(seen.refusals).toEqual([]); expect(seen.taken).toHaveLength(2); @@ -370,34 +398,41 @@ describe("Tier CIV — the identity a host's component names its work after", () }); it("CIV6: a live ancestor's issuance cannot be spent inside its content", function* () { + const stream = yield* useJournalStream(""); const seen = record(); let parent: ComponentInvocation | undefined; // One `` inside another: the same component, the same domain, so the // projection is the only thing that can refuse the nested claim. - yield* run("\n\n\n", [probe(seen)], function* () { - yield* Component.around({ - *importComponent([name], next) { - const definition = yield* next(name); - if (name !== "Probe" || definition.kind !== "function") { - return definition; - } - const original = definition.fn; - if (typeof original !== "function") { - return definition; - } - return { - ...definition, - *fn(props: Record, invocation: ComponentInvocation) { - if (parent === undefined) { - parent = invocation; - return yield* original(props, invocation); - } - return yield* original(props, parent); - }, - }; - }, - }); - }); + yield* run( + "\n\n\n", + [probe(seen)], + function* () { + yield* Component.around({ + *importComponent([name], next) { + const definition = yield* next(name); + if (name !== "Probe" || definition.kind !== "function") { + return definition; + } + const original = definition.fn; + if (typeof original !== "function") { + return definition; + } + return { + ...definition, + *fn(props: Record, invocation: ComponentInvocation) { + if (parent === undefined) { + parent = invocation; + return yield* original(props, invocation); + } + return yield* original(props, parent); + }, + }; + }, + }); + }, + undefined, + stream, + ); // The outer element named itself before it projected. The nested claim was // refused rather than answered with the ancestor's identity. @@ -407,33 +442,40 @@ describe("Tier CIV — the identity a host's component names its work after", () }); it("CIV7: an issuance kept from the first site cannot be spent at the second", function* () { + const stream = yield* useJournalStream(""); const seen = record(); let kept: ComponentInvocation | undefined; - yield* run("\n\n\n", [probe(seen)], function* () { - yield* Component.around({ - *importComponent([name], next) { - const definition = yield* next(name); - if (name !== "Probe" || definition.kind !== "function") { - return definition; - } - const original = definition.fn; - if (typeof original !== "function") { - return definition; - } - return { - ...definition, - *fn(props: Record, invocation: ComponentInvocation) { - if (kept === undefined) { - kept = invocation; - return yield* original(props, invocation); - } - // The first site's issuance, routed at the second. - return yield* original(props, kept); - }, - }; - }, - }); - }); + yield* run( + "\n\n\n", + [probe(seen)], + function* () { + yield* Component.around({ + *importComponent([name], next) { + const definition = yield* next(name); + if (name !== "Probe" || definition.kind !== "function") { + return definition; + } + const original = definition.fn; + if (typeof original !== "function") { + return definition; + } + return { + ...definition, + *fn(props: Record, invocation: ComponentInvocation) { + if (kept === undefined) { + kept = invocation; + return yield* original(props, invocation); + } + // The first site's issuance, routed at the second. + return yield* original(props, kept); + }, + }; + }, + }); + }, + undefined, + stream, + ); expect(seen.taken).toHaveLength(1); expect(seen.refusals).toHaveLength(1); @@ -441,6 +483,7 @@ describe("Tier CIV — the identity a host's component names its work after", () }); it("CIV8: an implementation kept from one component names nothing at another", function* () { + const stream = yield* useJournalStream(""); const seen = record(); let kept: unknown; // Two components, each declared with a domain of its own, so a refusal here @@ -478,6 +521,8 @@ describe("Tier CIV — the identity a host's component names its work after", () }, }); }, + undefined, + stream, ); // `` named itself; `` refused rather than admitting @@ -606,6 +651,7 @@ describe("Tier CIV — the identity a host's component names its work after", () }); it("CIV11: a nested registration of the same name borrows nothing", function* () { + const stream = yield* useJournalStream(""); const seen = record(); let kept: unknown; let shadowed: RegistryEntry | undefined; @@ -621,63 +667,69 @@ describe("Tier CIV — the identity a host's component names its work after", () new URL("./fixtures/invocation-identity/nested-registration.md", import.meta.url), ), ); - yield* run(source, [probe(seen)], function* () { - yield* registerComponents([ - { - name: "Nest", - origin: "test://nest", - props: NO_PROPS, - *fn(): Operation { - return yield* content(); + yield* run( + source, + [probe(seen)], + function* () { + yield* registerComponents([ + { + name: "Nest", + origin: "test://nest", + props: NO_PROPS, + *fn(): Operation { + return yield* content(); + }, }, - }, - ]); - yield* Component.around({ - // The nested registration, once the declared implementation is in hand. - registry: (_args, next): ComponentRegistry => { - const answer = next(); - return shadowed === undefined ? answer : new Map([...answer, ["Probe", shadowed]]); - }, - *importComponent([name], next) { - const definition = yield* next(name); - if (name !== "Probe" || definition.kind !== "function") { - return definition; - } - if (kept === undefined) { - kept = definition.fn; - // Registered again under the same name, so canonical resolution - // stops selecting the execution's own component for it. - shadowed = { - default: { - definition: { - kind: "function", - name: "Probe", - props: NO_PROPS, - // deno-lint-ignore require-yield - *fn(): Operation { - nested.push("the nested registration ran"); - return ""; + ]); + yield* Component.around({ + // The nested registration, once the declared implementation is in hand. + registry: (_args, next): ComponentRegistry => { + const answer = next(); + return shadowed === undefined ? answer : new Map([...answer, ["Probe", shadowed]]); + }, + *importComponent([name], next) { + const definition = yield* next(name); + if (name !== "Probe" || definition.kind !== "function") { + return definition; + } + if (kept === undefined) { + kept = definition.fn; + // Registered again under the same name, so canonical resolution + // stops selecting the execution's own component for it. + shadowed = { + default: { + definition: { + kind: "function", + name: "Probe", + props: NO_PROPS, + // deno-lint-ignore require-yield + *fn(): Operation { + nested.push("the nested registration ran"); + return ""; + }, }, + origin: "test://nested-probe", }, - origin: "test://nested-probe", + }; + return definition; + } + return { + ...definition, + *fn(props: Record, invocation: ComponentInvocation) { + const borrowed = kept; + if (typeof borrowed !== "function") { + nested.push("nothing retained"); + return ""; + } + return yield* borrowed(props, invocation); }, }; - return definition; - } - return { - ...definition, - *fn(props: Record, invocation: ComponentInvocation) { - const borrowed = kept; - if (typeof borrowed !== "function") { - nested.push("nothing retained"); - return ""; - } - return yield* borrowed(props, invocation); - }, - }; - }, - }); - }); + }, + }); + }, + undefined, + stream, + ); // The declared site named itself. The nested site ran the retained // implementation with its own genuine invocation and named nothing: @@ -847,6 +899,7 @@ describe("Tier CIV — the identity a host's component names its work after", () }); it("CIV13: a refused registration leaves a claimant that answers for nothing", function* () { + const stream = yield* useJournalStream(""); const seen = record(); let refusal: string | undefined; // `as` is the engine's own prop, so declaring it as a capture is refused @@ -857,7 +910,7 @@ describe("Tier CIV — the identity a host's component names its work after", () captures: ["as"], }; try { - yield* run("\n", [invalid], nothing); + yield* run("\n", [invalid], nothing, undefined, stream); } catch (error) { refusal = error instanceof Error ? error.message : String(error); } @@ -879,6 +932,7 @@ describe("Tier CIV — the identity a host's component names its work after", () * reading it costs nothing, and that it cannot be recovered from anywhere else. */ describe("Tier CIV — the import's own terminal is the association", () => { + beforeEach(journalBeforeEach(OWNER)); it("CIV26: a handler that delegates through a descendant scope keeps the identity", function* () { // Ordinary middleware, delegating the same name once — in a scope of its // own, which the Api allows and which nothing about an import forbids. The @@ -908,46 +962,69 @@ describe("Tier CIV — the import's own terminal is the association", () => { }); it("CIV26: nested imports shadow and restore, each through its own terminal", function* () { + const stream = yield* useJournalStream(""); // The outer probe expands a body that imports the inner one, so two imports // are open at once in one scope. Each dispatch owns its terminal, so neither // needs a stack to find its own frame. const seen = record(); - yield* run("\n\n\n", [probe(seen, "Outer"), probe(seen, "Probe")]); + yield* run( + "\n\n\n", + [probe(seen, "Outer"), probe(seen, "Probe")], + undefined, + undefined, + stream, + ); expect(seen.refusals).toEqual([]); expect(seen.taken).toHaveLength(2); expect(new Set(seen.taken).size).toBe(2); }); - it("CIV26: delegating twice, or delegating another name, names nothing", function* () { + const multipleDelegations = "CIV26: delegating twice, or delegating another name, names nothing"; + it(multipleDelegations, function* () { // Each of these reaches this import's terminal — that is not the failure. // What fails is what the frame then holds: two selections, or one for a // component the element never wrote. const ways: readonly ("twice" | "another name")[] = ["twice", "another name"]; for (const what of ways) { - const seen = record(); - yield* run("\n", [probe(seen), probe(seen, "Other")], function* () { - yield* Component.around( - { - *importComponent([name, position], next) { - // Only the element's own import. The root is imported through the - // same operation, and redirecting that is a different mistake. - if (name !== "Probe") { - return yield* next(name, position); - } - if (what === "twice") { - yield* next(name, position); - return yield* next(name, position); - } - return yield* next("Other", position); + yield* captureTestJournal( + { owner: OWNER, name: multipleDelegations }, + "", + function* (stream) { + const seen = record(); + yield* run( + "\n", + [probe(seen), probe(seen, "Other")], + function* () { + yield* Component.around( + { + *importComponent([name, position], next) { + // Only the element's own import. The root is imported through the + // same operation, and redirecting that is a different mistake. + if (name !== "Probe") { + return yield* next(name, position); + } + if (what === "twice") { + yield* next(name, position); + return yield* next(name, position); + } + return yield* next("Other", position); + }, + }, + { at: "max" }, + ); }, - }, - { at: "max" }, - ); - }); + undefined, + stream, + ); - expect([what, seen.taken]).toEqual([what, []]); - expect([what, seen.refusals]).toHaveLength(2); + expect([what, seen.taken]).toEqual([what, []]); + expect([what, seen.refusals.length]).toEqual([what, 1]); + if (what === "another name") { + expect(seen.refusals[0]).toContain("this claimant answers for "); + } + }, + ); } }); @@ -1022,6 +1099,7 @@ describe("Tier CIV — the import's own terminal is the association", () => { for (const { what, report, says } of NOT_THIS_CALL) { it(`CIV29: ${what} is somebody else's failure`, function* () { + const stream = yield* useJournalStream(""); // The same arrangement, with the foreign terminal raising something that // carries the mark without being this call's report of it. Ordinary // resolution answers imports nothing answered, not unrelated failures, so @@ -1030,26 +1108,32 @@ describe("Tier CIV — the import's own terminal is the association", () => { const seen = record(); let failure = ""; try { - yield* run("\n", [probe(seen), probe(seen, "Other")], function* () { - yield* Component.around( - { - *importComponent([name, position], next) { - if (name !== "Probe") { - return yield* next(name, position); - } - return yield* importThroughTerminal( - "Other", - position, - // deno-lint-ignore require-yield - function* (asked: string) { - throw report(asked); - }, - ); + yield* run( + "\n", + [probe(seen), probe(seen, "Other")], + function* () { + yield* Component.around( + { + *importComponent([name, position], next) { + if (name !== "Probe") { + return yield* next(name, position); + } + return yield* importThroughTerminal( + "Other", + position, + // deno-lint-ignore require-yield + function* (asked: string) { + throw report(asked); + }, + ); + }, }, - }, - { at: "max" }, - ); - }); + { at: "max" }, + ); + }, + undefined, + stream, + ); } catch (error) { failure = error instanceof Error ? error.message : String(error); } @@ -1160,6 +1244,7 @@ function* environmentDeclaration(): Operation { } describe("Tier CIV — where the execution's import resolution lives", () => { + beforeEach(journalBeforeEach(OWNER)); it("CIV30: the environment boundary carries no import terminal", function* () { const declared = yield* environmentDeclaration(); // Read as members rather than as text, so this is about what the interface @@ -1206,6 +1291,7 @@ describe("Tier CIV — where the execution's import resolution lives", () => { }); describe("Tier CIV — two canonical imports live at the same time", () => { + beforeEach(journalBeforeEach(OWNER)); const CONCURRENT = [ "", "", @@ -1343,6 +1429,7 @@ describe("Tier CIV — two canonical imports live at the same time", () => { }); describe("Tier CIV — the authored form on the invocation", () => { + beforeEach(journalBeforeEach(OWNER)); const FORMS: Array<[string, string, boolean]> = [ ["self-closing", "\n", false], ["paired", "written\n", true], @@ -1351,8 +1438,9 @@ describe("Tier CIV — the authored form on the invocation", () => { for (const [what, source, expected] of FORMS) { it(`CIV19: a ${what} element reports its own form`, function* () { + const stream = yield* useJournalStream(""); const seen = record(); - yield* run(source, [probe(seen)]); + yield* run(source, [probe(seen)], undefined, undefined, stream); expect(seen.authored).toEqual([expected]); // The engine's two accounts of the same element agree while nothing is @@ -1363,6 +1451,7 @@ describe("Tier CIV — the authored form on the invocation", () => { } it("CIV19: asking the form projects nothing and suspends on nothing", function* () { + const stream = yield* useJournalStream(""); const ran: string[] = []; const seen = record(); // A component that reads the form and returns without projecting. The @@ -1383,20 +1472,26 @@ describe("Tier CIV — the authored form on the invocation", () => { }, }; - yield* run("\n\n\n", [asking], function* () { - yield* registerComponents([ - { - name: "Canary", - origin: "test://canary", - props: NO_PROPS, - // deno-lint-ignore require-yield - *fn(): Operation { - ran.push("canary"); - return ""; + yield* run( + "\n\n\n", + [asking], + function* () { + yield* registerComponents([ + { + name: "Canary", + origin: "test://canary", + props: NO_PROPS, + // deno-lint-ignore require-yield + *fn(): Operation { + ran.push("canary"); + return ""; + }, }, - }, - ]); - }); + ]); + }, + undefined, + stream, + ); // Read twice, answered twice, and the content it was written with never // expanded: the query is a fact about the element, not a projection of it. @@ -1405,6 +1500,7 @@ describe("Tier CIV — the authored form on the invocation", () => { }); it("CIV20: reading the form leaves the durable identity unspent", function* () { + const stream = yield* useJournalStream(""); const seen = record(); const taking: IdentityComponent = { name: "Taking", @@ -1428,7 +1524,7 @@ describe("Tier CIV — the authored form on the invocation", () => { }, }; - yield* run("\n", [taking]); + yield* run("\n", [taking], undefined, undefined, stream); expect(seen.authored).toEqual([false, false]); expect(seen.refusals).toEqual([]); @@ -1436,6 +1532,7 @@ describe("Tier CIV — the authored form on the invocation", () => { }); it("CIV21: a component that imports nothing still reads the canonical form", function* () { + const stream = yield* useJournalStream(""); yield* useComponentModuleLoader(); const directory = fileURLToPath(new URL("./fixtures/invocation-identity/", import.meta.url)); @@ -1446,6 +1543,7 @@ describe("Tier CIV — the authored form on the invocation", () => { "\n\nwritten\n", [], [directory], + stream, ); expect(both).toContain("loaded:false"); @@ -1453,23 +1551,30 @@ describe("Tier CIV — the authored form on the invocation", () => { }); it("CIV21: the form is on the invocation and nowhere a name reaches", function* () { + const stream = yield* useJournalStream(""); const seen = record(); let reachable: string[] = []; - yield* run("\n", [probe(seen)], function* () { - yield* Component.around({ - *importComponent([name, position], next) { - const definition = yield* next(name, position); - if (name === "Probe") { - // What a handler holding the definition can see of the fact: the - // definition carries none of it, because it is not a property of - // the component. - reachable = Reflect.ownKeys(definition).map(String); - } - return definition; - }, - }); - }); + yield* run( + "\n", + [probe(seen)], + function* () { + yield* Component.around({ + *importComponent([name, position], next) { + const definition = yield* next(name, position); + if (name === "Probe") { + // What a handler holding the definition can see of the fact: the + // definition carries none of it, because it is not a property of + // the component. + reachable = Reflect.ownKeys(definition).map(String); + } + return definition; + }, + }); + }, + undefined, + stream, + ); expect(seen.authored).toEqual([false]); expect(reachable).not.toContain("hasContent"); @@ -1579,12 +1684,16 @@ describe("Tier CIV — the authored form on the invocation", () => { * and CIV28 below. */ describe("Tier PA10b — concurrent capability-backed identity", () => { + beforeEach(journalBeforeEach(OWNER)); it("PA10b: two concurrent sites each claim their own identity, exactly once", function* () { + const stream = yield* useJournalStream(""); const seen = record(); yield* run( ["", "", "", ""].join("\n"), [probe(seen)], nothing, + undefined, + stream, ); // Both claimed, neither refused, and neither received the other's. @@ -1597,6 +1706,7 @@ describe("Tier PA10b — concurrent capability-backed identity", () => { }); it("PA10b: a nested inside a spawn claims its own identities too", function* () { + const stream = yield* useJournalStream(""); const seen = record(); yield* run( [ @@ -1612,6 +1722,8 @@ describe("Tier PA10b — concurrent capability-backed identity", () => { ].join("\n"), [probe(seen)], nothing, + undefined, + stream, ); // Three sites, three identities, no refusal: a spawn nested inside a diff --git a/packages/core/tests/output-error-mode.test.ts b/packages/core/tests/output-error-mode.test.ts index 64b8977eb..4ba8bd676 100644 --- a/packages/core/tests/output-error-mode.test.ts +++ b/packages/core/tests/output-error-mode.test.ts @@ -12,7 +12,8 @@ * either way. */ -import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; +import { beforeAll, beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { createContext, ensure, Ok, scoped } from "effection"; import type { Operation } from "effection"; @@ -35,6 +36,7 @@ import { renderSegments } from "../src/render.ts"; import { useTempFileCompiler } from "../src/temp-file-compiler.ts"; import type { ErrorSegment, FunctionComponentDefinition, Json, Segment } from "../src/types.ts"; +const OWNER = "packages/core/tests/output-error-mode.test.ts"; interface Run { /** Chunks in the order consumers received them. */ chunks: string[]; @@ -48,6 +50,7 @@ interface Run { } /** The command each exec block ran, in order — what actually started. */ + function commands(events: DurableEvent[]): string[] { return events.flatMap((event) => event.type === "yield" && event.description.type === "exec" @@ -307,26 +310,31 @@ const PRINTING: FunctionComponentDefinition = { }; describe("Tier OM — a failing keeps what it rendered", () => { + beforeEach(journalBeforeEach(OWNER)); it("OM1: emits the partial selection, fails, and runs no later sibling", function* () { - const result = yield* run({ - "doc.md": [ - "", - "", - "```bash exec", - "echo BEFORE", - "```", - "", - "```bash exec", - "FAIL", - "```", - "", - "```bash exec", - "echo LATER", - "```", - "", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "", + "", + "```bash exec", + "echo BEFORE", + "```", + "", + "```bash exec", + "FAIL", + "```", + "", + "```bash exec", + "echo LATER", + "```", + "", + "", + ].join("\n"), + }, + stream, + ); expect(result.displayed).toContain("BEFORE"); expect(result.ok).toBe(false); @@ -335,22 +343,26 @@ describe("Tier OM — a failing keeps what it rendered", () => { }); it("OM2: keeps a component region's partial selection and fails the document", function* () { - const result = yield* run({ - "components/Stage.md": [ - "", - "", - "```bash exec", - "echo BEFORE", - "```", - "", - "```bash exec", - "FAIL", - "```", - "", - "", - ].join("\n"), - "doc.md": "\n\n```bash exec\necho LATER\n```\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Stage.md": [ + "", + "", + "```bash exec", + "echo BEFORE", + "```", + "", + "```bash exec", + "FAIL", + "```", + "", + "", + ].join("\n"), + "doc.md": "\n\n```bash exec\necho LATER\n```\n", + }, + stream, + ); expect(result.displayed).toContain("BEFORE"); expect(result.ok).toBe(false); @@ -360,21 +372,25 @@ describe("Tier OM — a failing keeps what it rendered", () => { // The integration pin with #307/#310: a command that printed before it failed // is a failure, its stdout stays visible, and nothing after it runs. it("OM3: keeps the stdout of a non-zero command and stops the document there", function* () { - const result = yield* run({ - "doc.md": [ - "", - "", - "```bash exec", - "FAIL", - "```", - "", - "```bash exec", - "echo LATER", - "```", - "", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "", + "", + "```bash exec", + "FAIL", + "```", + "", + "```bash exec", + "echo LATER", + "```", + "", + "", + ].join("\n"), + }, + stream, + ); expect(result.displayed).toContain("PREVIEW"); expect(result.ok).toBe(false); @@ -382,33 +398,37 @@ describe("Tier OM — a failing keeps what it rendered", () => { }); it("OM4: preserves an earlier region and runs neither the documentation nor the region after it", function* () { - const result = yield* run({ - "doc.md": [ - "", - "", - "```bash exec", - "echo FIRST", - "```", - "", - "```bash exec", - "FAIL", - "```", - "", - "", - "", - "```bash exec", - "echo DOCUMENTATION", - "```", - "", - "", - "", - "```bash exec", - "echo SECOND", - "```", - "", - "", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "", + "", + "```bash exec", + "echo FIRST", + "```", + "", + "```bash exec", + "FAIL", + "```", + "", + "", + "", + "```bash exec", + "echo DOCUMENTATION", + "```", + "", + "", + "", + "```bash exec", + "echo SECOND", + "```", + "", + "", + ].join("\n"), + }, + stream, + ); expect(result.displayed).toContain("FIRST"); expect(result.ok).toBe(false); @@ -420,6 +440,7 @@ describe("Tier OM — a failing keeps what it rendered", () => { }); describe("Tier OM — is how a region prints instead", () => { + beforeEach(journalBeforeEach(OWNER)); it("OM5a: prints the error once and lets the region continue", function* () { const expanded = yield* expandUnder( "output", @@ -444,24 +465,28 @@ describe("Tier OM — is how a region prints instead", () => { }); it("OM5c: completes a document whose region printed its failure", function* () { - const result = yield* run({ - "components/Stage.md": [ - "", - "", - "", - "", - "```bash exec", - "FAIL", - "```", - "", - "", - "", - "MARKER", - "", - "", - ].join("\n"), - "doc.md": "", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Stage.md": [ + "", + "", + "", + "", + "```bash exec", + "FAIL", + "```", + "", + "", + "", + "MARKER", + "", + "", + ].join("\n"), + "doc.md": "", + }, + stream, + ); expect(result.ok).toBe(true); expect(result.output).toContain("MARKER"); @@ -504,25 +529,29 @@ describe("Tier OM — is how a region prints instead", () => { * which is what makes this an attack instead of a demonstration. */ it("OM5g: a counterfeit printsCheckedFailures context cannot keep the run", function* () { + const stream = yield* useJournalStream("doc.md"); const Counterfeit = createContext("component.printsCheckedFailures", false); const result = yield* scoped(function* () { yield* Counterfeit.set(true); // It really is set for everything the run does. expect(yield* Counterfeit.get()).toBe(true); - return yield* run({ - "doc.md": [ - "```bash exec", - "FAIL", - "```", - "", - "MARKER", - "", - "```bash exec", - "echo LATER", - "```", - ].join("\n"), - }); + return yield* run( + { + "doc.md": [ + "```bash exec", + "FAIL", + "```", + "", + "MARKER", + "", + "```bash exec", + "echo LATER", + "```", + ].join("\n"), + }, + stream, + ); }); // The document contains no error-handling construct, so it fails. @@ -541,23 +570,27 @@ describe("Tier OM — is how a region prints instead", () => { * work, and a real `` element around it. */ it("OM5h: a real region prints the checked failure and continues", function* () { - const result = yield* run({ - "doc.md": [ - "", - "", - "```bash exec", - "FAIL", - "```", - "", - "", - "", - "MARKER", - "", - "```bash exec", - "echo LATER", - "```", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "", + "", + "```bash exec", + "FAIL", + "```", + "", + "", + "", + "MARKER", + "", + "```bash exec", + "echo LATER", + "```", + ].join("\n"), + }, + stream, + ); expect(result.ok).toBe(true); // Printed where the document asked for it, and the run went on. @@ -573,27 +606,31 @@ describe("Tier OM — is how a region prints instead", () => { * runs it. */ it("OM5i: covers a checked failure inside an in the region", function* () { - const result = yield* run({ - "doc.md": [ - "", - "", - '', - "", - "```bash exec", - "FAIL", - "```", - "", - "", - "", - "", - "", - "MARKER", - "", - "```bash exec", - "echo LATER", - "```", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "", + "", + '', + "", + "```bash exec", + "FAIL", + "```", + "", + "", + "", + "", + "", + "MARKER", + "", + "```bash exec", + "echo LATER", + "```", + ].join("\n"), + }, + stream, + ); expect(result.ok).toBe(true); expect(result.output).toContain("Command failed"); @@ -607,62 +644,70 @@ describe("Tier OM — is how a region prints instead", () => { * invocation is only how it is placed. */ it("OM5j: covers caller content projected through a component in the region", function* () { - const result = yield* run({ - "components/Frame.md": "\n", - "doc.md": [ - "", - "", - "", - "", - "```bash exec", - "FAIL", - "```", - "", - "", - "", - "", - "", - "MARKER", - "", - "```bash exec", - "echo LATER", - "```", - ].join("\n"), - }); - - expect(result.ok).toBe(true); - expect(result.output).toContain("Command failed"); - expect(result.output).toContain("MARKER"); - expect(commands(result.events).some((name) => name.includes("LATER"))).toBe(true); - }); - - /** - * The other edge of the same boundary: recovery ends with the region. A - * failing command written after `` is an ordinary checked - * failure, and the region before it changes nothing about that. - */ - it("OM5k: does not cover a checked failure after the region closes", function* () { - const result = yield* run({ - "doc.md": [ - "", - "", - "```bash exec", - "FAIL", - "```", - "", - "", - "", - "```bash exec", - "FAIL", - "```", - "", - "MARKER", - "", - "```bash exec", - "echo LATER", - "```", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Frame.md": "\n", + "doc.md": [ + "", + "", + "", + "", + "```bash exec", + "FAIL", + "```", + "", + "", + "", + "", + "", + "MARKER", + "", + "```bash exec", + "echo LATER", + "```", + ].join("\n"), + }, + stream, + ); + + expect(result.ok).toBe(true); + expect(result.output).toContain("Command failed"); + expect(result.output).toContain("MARKER"); + expect(commands(result.events).some((name) => name.includes("LATER"))).toBe(true); + }); + + /** + * The other edge of the same boundary: recovery ends with the region. A + * failing command written after `` is an ordinary checked + * failure, and the region before it changes nothing about that. + */ + it("OM5k: does not cover a checked failure after the region closes", function* () { + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + "", + "", + "```bash exec", + "FAIL", + "```", + "", + "", + "", + "```bash exec", + "FAIL", + "```", + "", + "MARKER", + "", + "```bash exec", + "echo LATER", + "```", + ].join("\n"), + }, + stream, + ); expect(result.ok).toBe(false); expect(String((result.error as Error).message)).toContain("Command failed"); @@ -676,6 +721,7 @@ describe("Tier OM — is how a region prints instead", () => { * decide that a command which exited nonzero left the run intact. */ it("OM5l: a component catching ContentError cannot accept a checked failure", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* runRegistered( { "doc.md": [ @@ -695,6 +741,7 @@ describe("Tier OM — is how a region prints instead", () => { ].join("\n"), }, { Catching: CATCHING }, + stream, ); // The recovery return is not accepted as the run's outcome. @@ -712,11 +759,13 @@ describe("Tier OM — is how a region prints instead", () => { * component's own rather than a command's. */ it("OM5m: an ordinary content failure takes the same path it always did", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* runRegistered( { "doc.md": ["", "", "", "", "", "", "MARKER"].join("\n"), }, { Catching: CATCHING, Broken: BROKEN }, + stream, ); // Unchanged: the projected content's failure is the caller's, and it is @@ -735,6 +784,7 @@ describe("Tier OM — is how a region prints instead", () => { * delegating reaches nothing either. */ it("OM5n: counterfeit options cannot contain a component's checked failure", function* () { + const stream = yield* useJournalStream("doc.md"); const counterfeit: { containCheckedFailures: unknown[] } = { containCheckedFailures: [] }; let delegated = false; @@ -764,6 +814,7 @@ describe("Tier OM — is how a region prints instead", () => { ].join("\n"), }, { Catching: CATCHING }, + stream, ); }); @@ -784,6 +835,7 @@ describe("Tier OM — is how a region prints instead", () => { * ``, does contain. */ it("OM5p: a registered Test of the same name and origin contains nothing", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* scoped(function* () { yield* registerComponents([ { @@ -793,7 +845,7 @@ describe("Tier OM — is how a region prints instead", () => { fn: expandingBody, }, ]); - return yield* run({ "doc.md": CONTAINMENT_DOC }); + return yield* run({ "doc.md": CONTAINMENT_DOC }, stream); }); // The command's nonzero exit is the run's, so the document stops there. @@ -811,6 +863,7 @@ describe("Tier OM — is how a region prints instead", () => { * contains the failure is core's own ``. */ it("OM5q: supplied behavior reaches core's Test, which contains the failure", function* () { + const stream = yield* useJournalStream("doc.md"); const Behavior = createApi<{ test(props: Record): Operation }>( "TestBehavior", { @@ -827,7 +880,7 @@ describe("Tier OM — is how a region prints instead", () => { return yield* expandingBody(); }, }); - return yield* run({ "doc.md": CONTAINMENT_DOC }); + return yield* run({ "doc.md": CONTAINMENT_DOC }, stream); }); // Contained: the failure ended that invocation, the run's own record stayed @@ -892,6 +945,7 @@ describe("Tier OM — is how a region prints instead", () => { * exit something the run survived. */ it("OM5o: an output region whose component replaces the failure still fails", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* runRegistered( { "doc.md": [ @@ -911,6 +965,7 @@ describe("Tier OM — is how a region prints instead", () => { ].join("\n"), }, { Catching: CATCHING }, + stream, ); expect(result.ok).toBe(false); @@ -920,9 +975,15 @@ describe("Tier OM — is how a region prints instead", () => { }); it("OM5f: a checked command failure fails a root without ", function* () { - const result = yield* run({ - "doc.md": ["```bash exec", "FAIL", "```", "", "```bash exec", "echo LATER", "```"].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": ["```bash exec", "FAIL", "```", "", "```bash exec", "echo LATER", "```"].join( + "\n", + ), + }, + stream, + ); expect(result.ok).toBe(false); expect(String((result.error as Error).message)).toContain("Command failed"); @@ -932,7 +993,9 @@ describe("Tier OM — is how a region prints instead", () => { }); describe("Tier OM — the failed document is a determined outcome", () => { + beforeEach(journalBeforeEach(OWNER)); it("OM6: reports the original failure object on a live run", function* () { + const stream = yield* useJournalStream("doc.md"); const thrown = new Error("the component's own failure"); const failing: FunctionComponentDefinition = { kind: "function", @@ -945,7 +1008,7 @@ describe("Tier OM — the failed document is a determined outcome", () => { }; // A plain root, because settlement is the root's and not a region's: the // failure a run reports is the object the component threw either way. - const result = yield* runRegistered({ "doc.md": "" }, { Failing: failing }); + const result = yield* runRegistered({ "doc.md": "" }, { Failing: failing }, stream); expect(result.ok).toBe(false); // The object itself, not a description of it. Identity is the whole claim: @@ -957,9 +1020,13 @@ describe("Tier OM — the failed document is a determined outcome", () => { }); it("OM6b: reports a settled printed error as the documentation failure it is", function* () { - const result = yield* run({ - "doc.md": "\n\n```bash exec\nFAIL\n```\n\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": "\n\n```bash exec\nFAIL\n```\n\n", + }, + stream, + ); expect(result.ok).toBe(false); const carried = aggregateMembers(result.error); @@ -973,6 +1040,7 @@ describe("Tier OM — the failed document is a determined outcome", () => { }); it("OM6c: reports the aggregate a body and its teardown produced together", function* () { + const stream = yield* useJournalStream("doc.md"); const fromBody = new Error("body failed"); const fromTeardown = new Error("teardown failed"); const failing: FunctionComponentDefinition = { @@ -989,6 +1057,7 @@ describe("Tier OM — the failed document is a determined outcome", () => { const result = yield* runRegistered( { "doc.md": "\n\n\n\n" }, { Failing: failing }, + stream, ); expect(result.ok).toBe(false); @@ -1058,9 +1127,13 @@ describe("Tier OM — the failed document is a determined outcome", () => { }); it("OM8: closes the journal ok around the failed outcome", function* () { - const result = yield* run({ - "doc.md": "\n\n```bash exec\nFAIL\n```\n\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": "\n\n```bash exec\nFAIL\n```\n\n", + }, + stream, + ); const close = result.events.find((event) => event.type === "close"); expect(close?.result.status).toBe("ok"); @@ -1076,6 +1149,7 @@ describe("Tier OM — the failed document is a determined outcome", () => { * writes into the region and hands its segments back reddens here. */ describe("Tier OM — every visible producer keeps its prefix", () => { + beforeEach(journalBeforeEach(OWNER)); const CASES: { key: string; name: string; failing: string; succeeding: string }[] = [ { key: "a", @@ -1114,10 +1188,14 @@ describe("Tier OM — every visible producer keeps its prefix", () => { for (const subject of CASES) { it(`OM9 ${subject.key}: keeps what ${subject.name} rendered before failing`, function* () { - const result = yield* run({ - "components/Wrapper.md": WRAPPER, - "doc.md": `\n\n${subject.failing}\n\n`, - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Wrapper.md": WRAPPER, + "doc.md": `\n\n${subject.failing}\n\n`, + }, + stream, + ); expect(result.output).toContain("PREFIX"); expect(result.ok).toBe(false); @@ -1127,10 +1205,14 @@ describe("Tier OM — every visible producer keeps its prefix", () => { }); it(`OM10 ${subject.key}: renders ${subject.name} exactly once when it succeeds`, function* () { - const result = yield* run({ - "components/Wrapper.md": WRAPPER, - "doc.md": `\n\n${subject.succeeding}\n\n`, - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Wrapper.md": WRAPPER, + "doc.md": `\n\n${subject.succeeding}\n\n`, + }, + stream, + ); expect(result.ok).toBe(true); expect(result.output.match(/PREFIX/g) ?? []).toHaveLength(1); @@ -1139,6 +1221,7 @@ describe("Tier OM — every visible producer keeps its prefix", () => { }); describe("Tier OM — work the document was not going to render never reaches the output", () => { + beforeEach(journalBeforeEach(OWNER)); const STAGE = [ "", "", @@ -1152,64 +1235,84 @@ describe("Tier OM — work the document was not going to render never reaches th ].join("\n"); it("OM11a: keeps a prefix out of the document", function* () { - const result = yield* run({ - "doc.md": - '\n\n\n\nPREFIX\n\n```bash exec\nFAIL\n```\n\n\n\n', - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": + '\n\n\n\nPREFIX\n\n```bash exec\nFAIL\n```\n\n\n\n', + }, + stream, + ); expect(result.ok).toBe(false); expect(result.output).not.toContain("PREFIX"); }); it("OM11b: keeps an prefix out of the document", function* () { - const result = yield* run({ - "doc.md": - '\n\n\n\nPREFIX\n\n```bash exec\nFAIL\n```\n\n\n\n', - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": + '\n\n\n\nPREFIX\n\n```bash exec\nFAIL\n```\n\n\n\n', + }, + stream, + ); expect(result.ok).toBe(false); expect(result.output).not.toContain("PREFIX"); }); it("OM11c: keeps a string projection's prefix out of the document", function* () { - const result = yield* run({ - "components/Renderer.md": [ - "```ts eval", - "const projected = yield* renderChildren();", - "output(projected);", - "```", - ].join("\n"), - "doc.md": - "\n\n\n\nPREFIX\n\n```bash exec\nFAIL\n```\n\n\n\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Renderer.md": [ + "```ts eval", + "const projected = yield* renderChildren();", + "output(projected);", + "```", + ].join("\n"), + "doc.md": + "\n\n\n\nPREFIX\n\n```bash exec\nFAIL\n```\n\n\n\n", + }, + stream, + ); expect(result.ok).toBe(false); expect(result.output).not.toContain("PREFIX"); }); it("OM11d: keeps documentation out of the document", function* () { - const result = yield* run({ - "components/Stage.md": [ - "PREFIX", - "", - "```bash exec", - "FAIL", - "```", - "", - "ok", - ].join("\n"), - "doc.md": "\n\n\n\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Stage.md": [ + "PREFIX", + "", + "```bash exec", + "FAIL", + "```", + "", + "ok", + ].join("\n"), + "doc.md": "\n\n\n\n", + }, + stream, + ); expect(result.ok).toBe(false); expect(result.output).not.toContain("PREFIX"); }); it("OM11e: keeps a failing as= invocation's prefix out of the document", function* () { - const result = yield* run({ - "components/Stage.md": STAGE, - "doc.md": '\n\n\n\n', - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Stage.md": STAGE, + "doc.md": '\n\n\n\n', + }, + stream, + ); expect(result.ok).toBe(false); expect(result.output).not.toContain("PREFIX"); @@ -1438,6 +1541,7 @@ describe("Tier OM — the recorded failure is exactly these fields", () => { * ``) would do it just by wrapping the invocation. */ describe("Tier OM — a printing boundary does not resume a callee's own region", () => { + beforeEach(journalBeforeEach(OWNER)); const STAGE = [ "", "", @@ -1457,10 +1561,14 @@ describe("Tier OM — a printing boundary does not resume a callee's own region" ].join("\n"); it("OM14: stops a nested region wrapped in ", function* () { - const result = yield* run({ - "components/Stage.md": STAGE, - "doc.md": "\n\n\nMARKER\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Stage.md": STAGE, + "doc.md": "\n\n\nMARKER\n", + }, + stream, + ); expect(commands(result.events).some((name) => name.includes("LATER"))).toBe(false); // The region's decision reaches the caller too: a failure a region already @@ -1475,10 +1583,14 @@ describe("Tier OM — a printing boundary does not resume a callee's own region" // The same, where the boundary is a built-in that prints its own failures // rather than an explicit request from the author. it("OM15: stops a nested region wrapped in ", function* () { - const result = yield* run({ - "components/Stage.md": STAGE, - "doc.md": '\n\n\n\nMARKER', - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Stage.md": STAGE, + "doc.md": '\n\n\n\nMARKER', + }, + stream, + ); expect(commands(result.events).some((name) => name.includes("LATER"))).toBe(false); // `` writes nothing and does not print the failure of the content its @@ -1494,12 +1606,14 @@ describe("Tier OM — a printing boundary does not resume a callee's own region" // The same failure through a printing component that does not recover from a // content failure of its own. it("OM15b: passes the region's own failure past a printing component that does not recover", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* runRegistered( { "components/Stage.md": STAGE, "doc.md": "\n\n\n\nMARKER", }, { Relaying: RELAYING }, + stream, ); expect(commands(result.events).some((name) => name.includes("LATER"))).toBe(false); @@ -1515,12 +1629,14 @@ describe("Tier OM — a printing boundary does not resume a callee's own region" // print: there the failure is reported as a printed error rather than // settling, and the callee's own region is still not resumed. it("OM15c: prints the region's failure where the caller's region prints", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* runRegistered( { "components/Stage.md": STAGE, "doc.md": "\n\n\n\n", }, { Relaying: RELAYING }, + stream, ); expect(commands(result.events).some((name) => name.includes("LATER"))).toBe(false); @@ -1528,10 +1644,14 @@ describe("Tier OM — a printing boundary does not resume a callee's own region" }); it("OM16: still prints what is raised under its own error mode", function* () { - const result = yield* run({ - "components/Stage.md": "```bash exec\nFAIL\n```\n", - "doc.md": "\n\n\n\n\n\nMARKER\n\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Stage.md": "```bash exec\nFAIL\n```\n", + "doc.md": "\n\n\n\n\n\nMARKER\n\n", + }, + stream, + ); expect(result.ok).toBe(true); expect(result.output).toContain("MARKER"); @@ -1539,24 +1659,29 @@ describe("Tier OM — a printing boundary does not resume a callee's own region" }); describe("Tier OM — the partial output reaches the stream, not only the close", () => { + beforeEach(journalBeforeEach(OWNER)); // A consumer reading chunks is the case the preservation exists for. it("OM17: streams the failing region's output after an earlier segment streamed", function* () { - const result = yield* run({ - "components/Stage.md": [ - "", - "", - "```bash exec", - "echo BEFORE", - "```", - "", - "```bash exec", - "FAIL", - "```", - "", - "", - ].join("\n"), - "doc.md": "intro paragraph\n\n", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Stage.md": [ + "", + "", + "```bash exec", + "echo BEFORE", + "```", + "", + "```bash exec", + "FAIL", + "```", + "", + "", + ].join("\n"), + "doc.md": "intro paragraph\n\n", + }, + stream, + ); expect(result.ok).toBe(false); // The chunk stream, not just the close value: a CLI writing stdout as it @@ -1575,35 +1700,44 @@ describe("Tier OM — the partial output reaches the stream, not only the close" * nothing again. */ describe("Tier OM — a printed error crosses an invocation as data", () => { + beforeEach(journalBeforeEach(OWNER)); it("OM18: a child's printed error does not fail a parent's documentation", function* () { - const result = yield* run({ - "components/Child.md": [ - "", - "", - "", - "", - "```bash exec", - "FAIL", - "```", - "", - "", - "", - "", - ].join("\n"), - "components/Parent.md": "\n\n\n\nTAIL\n\n", - "doc.md": "", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Child.md": [ + "", + "", + "", + "", + "```bash exec", + "FAIL", + "```", + "", + "", + "", + "", + ].join("\n"), + "components/Parent.md": "\n\n\n\nTAIL\n\n", + "doc.md": "", + }, + stream, + ); expect(result.ok).toBe(true); expect(result.output).toContain("TAIL"); }); it("OM19: an uncaptured failure in the same position still propagates", function* () { - const result = yield* run({ - "components/Child.md": "\n\n```bash exec\nFAIL\n```\n\n", - "components/Parent.md": "\n\n\n\nTAIL\n\n", - "doc.md": "", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "components/Child.md": "\n\n```bash exec\nFAIL\n```\n\n", + "components/Parent.md": "\n\n\n\nTAIL\n\n", + "doc.md": "", + }, + stream, + ); expect(result.ok).toBe(false); expect(result.output).not.toContain("TAIL"); @@ -1665,6 +1799,7 @@ describe("Tier OM — a printed error crosses an invocation as data", () => { * work — the write, the relayed text — does not happen. */ describe("Tier OM — caller content at a plain root leaves the printing component", () => { + beforeEach(journalBeforeEach(OWNER)); /** The paths a write was asked for, with the host provider never reached. */ function runRecordingWrites( files: Record, @@ -1737,6 +1872,7 @@ describe("Tier OM — caller content at a plain root leaves the printing compone }); it("OM22: the same failure through a relaying component is observed once", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* scoped(function* () { yield* registerComponents([ { @@ -1746,9 +1882,12 @@ describe("Tier OM — caller content at a plain root leaves the printing compone fn: RELAYING.fn, }, ]); - return yield* runObserving({ - "doc.md": "\n\n\n\nMARKER", - }); + return yield* runObserving( + { + "doc.md": "\n\n\n\nMARKER", + }, + stream, + ); }); expect(result.ok).toBe(false); @@ -1769,6 +1908,7 @@ describe("Tier OM — caller content at a plain root leaves the printing compone * which regions render; it was never what made a failure count. */ describe("Tier RF — root failure settlement", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); const THROWING_STAGE = [ @@ -1786,7 +1926,8 @@ describe("Tier RF — root failure settlement", () => { ].join("\n"); it("RF1: an uncaught eval failure ends a root with no ", function* () { - const result = yield* runObserving({ "doc.md": THROWING_STAGE }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* runObserving({ "doc.md": THROWING_STAGE }, stream); expect(result.ok).toBe(false); expect(String((result.error as Error).message)).toContain("stage classifier failed"); @@ -1801,25 +1942,29 @@ describe("Tier RF — root failure settlement", () => { }); it("RF2: the same region inside prints once and continues", function* () { - const result = yield* runObserving({ - "doc.md": [ - "", - "", - "PREFIX-PROSE", - "", - "```js eval", - 'throw new Error("stage classifier failed");', - "```", - "", - "", - "", - "LATER-PROSE", - "", - "```bash exec", - "echo LATER", - "```", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* runObserving( + { + "doc.md": [ + "", + "", + "PREFIX-PROSE", + "", + "```js eval", + 'throw new Error("stage classifier failed");', + "```", + "", + "", + "", + "LATER-PROSE", + "", + "```bash exec", + "echo LATER", + "```", + ].join("\n"), + }, + stream, + ); expect(result.ok).toBe(true); expect(result.output).toContain("PREFIX-PROSE"); @@ -1832,11 +1977,15 @@ describe("Tier RF — root failure settlement", () => { }); it("RF3: a successful root with no still streams its complete body", function* () { - const result = yield* run({ - "doc.md": ["FIRST-PROSE", "", "```bash exec", "echo BETWEEN", "```", "", "LAST-PROSE"].join( - "\n", - ), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": ["FIRST-PROSE", "", "```bash exec", "echo BETWEEN", "```", "", "LAST-PROSE"].join( + "\n", + ), + }, + stream, + ); expect(result.ok).toBe(true); expect(result.output).toContain("FIRST-PROSE"); @@ -1846,23 +1995,27 @@ describe("Tier RF — root failure settlement", () => { }); it("RF4: a bound nonzero status continues; a classifier that throws after it does not", function* () { - const result = yield* run({ - "doc.md": [ - '```bash exec as="probe"', - "FAIL", - "```", - "", - "seen={probe.exitCode}", - "", - "```js eval", - 'if (probe.exitCode !== 0) { throw new Error("classifier rejected the probe"); }', - "```", - "", - "```bash exec", - "echo LATER", - "```", - ].join("\n"), - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + { + "doc.md": [ + '```bash exec as="probe"', + "FAIL", + "```", + "", + "seen={probe.exitCode}", + "", + "```js eval", + 'if (probe.exitCode !== 0) { throw new Error("classifier rejected the probe"); }', + "```", + "", + "```bash exec", + "echo LATER", + "```", + ].join("\n"), + }, + stream, + ); // The status was data the document read and rendered, so the run reached // the classifier at all. @@ -1873,9 +2026,11 @@ describe("Tier RF — root failure settlement", () => { }); it("RF5: printErrors(fn) still prints its own failure and the root continues", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* runRegistered( { "doc.md": "\n\nMARKER\n" }, { Printing: PRINTING }, + stream, ); expect(result.ok).toBe(true);