diff --git a/.changeset/schema-aot-preserve-dependencies.md b/.changeset/schema-aot-preserve-dependencies.md new file mode 100644 index 0000000000..42027bf2da --- /dev/null +++ b/.changeset/schema-aot-preserve-dependencies.md @@ -0,0 +1,5 @@ +--- +"effect": patch +--- + +Preserve existing compiled decoders for dependencies when installing a parent decoder generated by `SchemaAOTCompiler.compile`. diff --git a/packages/effect/src/internal/schema/compilerRegistry.ts b/packages/effect/src/internal/schema/compilerRegistry.ts index 58694a325e..1617344fcf 100644 --- a/packages/effect/src/internal/schema/compilerRegistry.ts +++ b/packages/effect/src/internal/schema/compilerRegistry.ts @@ -212,6 +212,12 @@ export function setCompiler( return entry } +/** @internal */ +export function setCompilerDependency(ast: SchemaAST.AST, compile: Compile): Entry { + const cached = cache.get(ast) + return cached?.compiled !== undefined ? cached : setCompiler(ast, compile) +} + /** @internal */ export function install(compile: CompileSource): void { activateCompilerAdapters() diff --git a/packages/effect/src/schema/SchemaAOTCompiler.ts b/packages/effect/src/schema/SchemaAOTCompiler.ts index 32dc4cb31f..b43b891202 100644 --- a/packages/effect/src/schema/SchemaAOTCompiler.ts +++ b/packages/effect/src/schema/SchemaAOTCompiler.ts @@ -97,10 +97,12 @@ export interface Target { * time. Functions and symbols are read from those ASTs, not serialized. * Suspend thunks are not evaluated during generation; their contents and other * unsupported nodes use the interpreter. - * Installation replaces generated entries, but parsers that already captured - * older entries keep them. Type-side and flipped ASTs are separate registry - * keys; generate and install them separately when needed. Importing the - * generated module alone does not install anything. + * Installation preserves existing compiled dependencies. If you explicitly + * target a dependency and the compiler generates a decoder for it, installation + * replaces its entry. Parsers that captured older entries keep them. + * Type-side and flipped ASTs are separate registry keys; generate and install + * them separately when needed. Importing the generated module alone does not + * install anything. * In particular, target `SchemaAST.toType(schema.ast)` with `make` to prepare * construction when it differs from the encoded root. Target * `SchemaAST.flip(schema.ast)` with `decode` to prepare encoding. Unsupported @@ -214,12 +216,15 @@ export const compile = (targets: ReadonlyArray): string => { } } + const explicitTargets = new Set() targets.forEach((target, index) => { + if (target.operations.length === 0) return + explicitTargets.add(target.ast) for (const operation of operationOrder) { if (target.operations.includes(operation)) visit(target.ast, `asts[${index}]`, operation) } }) - for (const plan of seen.values()) { + for (const [ast, plan] of seen) { bindings.push(`const ${plan.name}=${plan.reference};`) const source = compiler(plan.sources) if (source !== undefined) { @@ -229,7 +234,8 @@ export const compile = (targets: ReadonlyArray): string => { factoryNames.set(source, factory) factories.push(`function ${factory}(ast,resolve,operation){const R=runtime;${source}}`) } - installations.push(`${helper("setCompiler")}(${plan.name},${factory});`) + const install = explicitTargets.has(ast) ? "setCompiler" : "setCompilerDependency" + installations.push(`${helper(install)}(${plan.name},${factory});`) } } return [ diff --git a/packages/effect/src/schema/SchemaCompiler/runtime.ts b/packages/effect/src/schema/SchemaCompiler/runtime.ts index 0a389980fc..97e9988005 100644 --- a/packages/effect/src/schema/SchemaCompiler/runtime.ts +++ b/packages/effect/src/schema/SchemaCompiler/runtime.ts @@ -9,7 +9,14 @@ import * as Effect from "../../Effect.ts" import { effectIsExit, resolveConcurrency } from "../../internal/effect.ts" import * as InternalRecord from "../../internal/record.ts" -import { lazyParser, type Resolve, resolve, setCompiler, withDecode } from "../../internal/schema/compilerRegistry.ts" +import { + lazyParser, + type Resolve, + resolve, + setCompiler, + setCompilerDependency, + withDecode +} from "../../internal/schema/compilerRegistry.ts" import * as Interpreter from "../../internal/schema/interpreter.ts" import * as InternalParser from "../../internal/schema/parser.ts" import * as SchemaAST from "../../SchemaAST.ts" @@ -267,6 +274,7 @@ export const runtime = { make, resolve, setCompiler, + setCompilerDependency, invalid, missing: InternalParser.missing, missingExit: InternalParser.missingExit, diff --git a/packages/effect/test/schema/SchemaAOTCompiler.test.ts b/packages/effect/test/schema/SchemaAOTCompiler.test.ts index 0bd4194088..0286d98fe0 100644 --- a/packages/effect/test/schema/SchemaAOTCompiler.test.ts +++ b/packages/effect/test/schema/SchemaAOTCompiler.test.ts @@ -9,6 +9,19 @@ import { join } from "node:path" import { fileURLToPath, pathToFileURL } from "node:url" import { roots, schemas, suspendEvaluations } from "./fixtures/aot.ts" +async function compileInstaller(...targets: ReadonlyArray): Promise<() => void> { + const directory = mkdtempSync(fileURLToPath(new URL("../../.schema-aot-test-", import.meta.url))) + try { + const file = join(directory, "compiled.mjs") + writeFileSync(file, SchemaAOTCompiler.compile(targets)) + const { install } = await import(pathToFileURL(file).href) + const asts = targets.map((target) => target.ast) + return () => install(asts) + } finally { + rmSync(directory, { recursive: true, force: true }) + } +} + describe("SchemaAOTCompiler", { concurrent: false }, () => { it("emits deterministic modules without installing a decoder", () => { let checks = 0 @@ -48,7 +61,7 @@ describe("SchemaAOTCompiler", { concurrent: false }, () => { it("allows a target without requested operations", () => { const schema = Schema.Struct({ value: Schema.String }) const source = SchemaAOTCompiler.compile([{ ast: schema.ast, operations: [] }]) - assert.notInclude(source, "runtime.setCompiler(") + assert.strictEqual(source, SchemaAOTCompiler.compile([])) }) it("omits fast decode operations from diagnostic-only dependencies", () => { @@ -68,25 +81,79 @@ describe("SchemaAOTCompiler", { concurrent: false }, () => { it("uses registry fallbacks for operations that were not requested", async () => { const schema = Schema.Struct({ value: Schema.String }) - const directory = mkdtempSync(fileURLToPath(new URL("../../.schema-aot-operations-test-", import.meta.url))) - try { - const file = join(directory, "decode.mjs") - writeFileSync(file, SchemaAOTCompiler.compile([{ ast: schema.ast, operations: ["decode"] }])) - const generated = await import(`${pathToFileURL(file).href}?test=${Date.now()}`) - generated.install([schema.ast]) + const install = await compileInstaller({ ast: schema.ast, operations: ["decode"] }) + install() - const entry = CompilerRegistry.resolve(schema.ast) - assert.strictEqual(typeof entry.compiled, "function") - assert.isDefined(entry.decode) - assert.isUndefined(entry.is) - assert.isUndefined(entry.make) - assert.strictEqual(SchemaParser.is(schema)({ value: "a" }), true) - assert.deepStrictEqual(SchemaParser.make(schema)({ value: "a" }), { value: "a" }) - } finally { - rmSync(directory, { recursive: true, force: true }) - } + const entry = CompilerRegistry.resolve(schema.ast) + assert.strictEqual(typeof entry.compiled, "function") + assert.isDefined(entry.decode) + assert.isUndefined(entry.is) + assert.isUndefined(entry.make) + assert.strictEqual(SchemaParser.is(schema)({ value: "a" }), true) + assert.deepStrictEqual(SchemaParser.make(schema)({ value: "a" }), { value: "a" }) }) + it("preserves registered dependencies in both directions without initializing them", async () => { + const codec = Schema.NumberFromString.annotate({ title: "registered child" }) + const parent = Schema.Struct({ payload: codec }) + const children = [codec.ast, SchemaAST.flip(codec.ast)] + const calls = [0, 0] + let initialized = 0 + const entries = children.map((ast, i) => { + const fallback = CompilerRegistry.resolve(ast).parser + return CompilerRegistry.set(ast, { + get decodeEffect(): SchemaParser.Parser { + initialized++ + return (input, options) => { + calls[i]++ + return fallback(input, options) + } + } + }) + }) + const install = await compileInstaller( + { ast: parent.ast, operations: ["decode"] }, + { ast: SchemaAST.flip(parent.ast), operations: ["decode"] } + ) + install() + install() + children.forEach((ast, i) => assert.strictEqual(CompilerRegistry.resolve(ast), entries[i])) + assert.strictEqual(initialized, 0) + + const value = { payload: 36 } + const encoded = SchemaParser.encodeUnknownSync(parent, { errors: "all" })(value) + assert.deepStrictEqual(encoded, { payload: "36" }) + assert.deepStrictEqual(SchemaParser.decodeUnknownSync(parent, { errors: "all" })(encoded), value) + assert.deepStrictEqual(calls, [1, 1]) + }) + + for (const order of ["parent-first", "child-first", "dependency-only"] as const) { + it(`replaces dependencies only when explicitly targeted: ${order}`, async () => { + const child = Schema.NumberFromString.annotate({ title: order }) + const parent = Schema.Struct({ value: child }) + const childTarget = { ast: child.ast, operations: ["decode"] as const } + const parentTarget = { ast: parent.ast, operations: ["decode"] as const } + const installChild = await compileInstaller(childTarget) + installChild() + const original = CompilerRegistry.resolve(child.ast) + const captured = SchemaParser.decodeUnknownSync(child) + assert.strictEqual(captured("1"), 1) + + const targets = { + "parent-first": [parentTarget, childTarget], + "child-first": [childTarget, parentTarget], + "dependency-only": [parentTarget, { ast: child.ast, operations: [] }] + }[order] + const install = await compileInstaller(...targets) + install() + const installed = CompilerRegistry.resolve(child.ast) + if (order === "dependency-only") assert.strictEqual(installed, original) + else assert.notStrictEqual(installed, original) + assert.strictEqual(captured("2"), 2) + assert.deepStrictEqual(SchemaParser.decodeUnknownSync(parent)({ value: "3" }), { value: 3 }) + }) + } + it("honors enumerable excess checking directly in generated operations", async () => { const visible = Symbol("visible") const hidden = Symbol("hidden") @@ -94,41 +161,34 @@ describe("SchemaAOTCompiler", { concurrent: false }, () => { Schema.Record(Schema.TemplateLiteral(["field-", Schema.Number]), Schema.Number), Schema.Record(Schema.Symbol, Schema.Number) ]) - const directory = mkdtempSync(fileURLToPath(new URL("../../.schema-aot-excess-test-", import.meta.url))) - try { - const file = join(directory, "decode.mjs") - writeFileSync(file, SchemaAOTCompiler.compile([{ ast: schema.ast, operations: ["decode", "is"] }])) - const generated = await import(pathToFileURL(file).href) - generated.install([schema.ast]) - const { decode, is } = CompilerRegistry.resolve(schema.ast) - assert.ok(decode, "Expected a compiled decoder") - assert.ok(is, "Expected a compiled type guard") - const strict = { onExcessProperty: "error" } as const - const expected = { "field-1": 1, [visible]: 2 } - const input = Object.defineProperties({ ...expected }, { - fixed: { value: "declared", enumerable: false }, - "field-2": { value: "invalid", enumerable: false }, - [hidden]: { - enumerable: false, - get() { - throw new Error("Non-enumerable properties must not be read") - } + const install = await compileInstaller({ ast: schema.ast, operations: ["decode", "is"] }) + install() + const { decode, is } = CompilerRegistry.resolve(schema.ast) + assert.ok(decode, "Expected a compiled decoder") + assert.ok(is, "Expected a compiled type guard") + const strict = { onExcessProperty: "error" } as const + const expected = { "field-1": 1, [visible]: 2 } + const input = Object.defineProperties({ ...expected }, { + fixed: { value: "declared", enumerable: false }, + "field-2": { value: "invalid", enumerable: false }, + [hidden]: { + enumerable: false, + get() { + throw new Error("Non-enumerable properties must not be read") } - }) - for (const options of [SchemaAST.defaultParseOptions, strict]) { - assert.deepStrictEqual(decode(input, options), { ...expected, fixed: "declared" }) - assert.isTrue(is(input, options)) - assert.strictEqual(decode({ [visible]: "invalid" }, options), CompilerRegistry.invalid) } - assert.strictEqual(decode({ ...expected, extra: 1 }, strict), CompilerRegistry.invalid) - assert.isFalse(is({ ...expected, extra: 1 }, strict)) - assert.deepStrictEqual(decode({}, strict), {}) - } finally { - rmSync(directory, { recursive: true, force: true }) + }) + for (const options of [SchemaAST.defaultParseOptions, strict]) { + assert.deepStrictEqual(decode(input, options), { ...expected, fixed: "declared" }) + assert.isTrue(is(input, options)) + assert.strictEqual(decode({ [visible]: "invalid" }, options), CompilerRegistry.invalid) } + assert.strictEqual(decode({ ...expected, extra: 1 }, strict), CompilerRegistry.invalid) + assert.isFalse(is({ ...expected, extra: 1 }, strict)) + assert.deepStrictEqual(decode({}, strict), {}) }) - it("initializes dependency operations on first use", async () => { + it("upgrades an interpreted dependency and initializes its compiled operations on first use", async () => { const child = Schema.String.pipe( Schema.decodeTo( Schema.Number, @@ -137,25 +197,22 @@ describe("SchemaAOTCompiler", { concurrent: false }, () => { Schema.annotate({ title: "lazy AOT dependency" }) ) const schema = Schema.Struct({ child }) - const directory = mkdtempSync(fileURLToPath(new URL("../../.schema-aot-lazy-test-", import.meta.url))) - try { - const file = join(directory, "decode.mjs") - writeFileSync(file, SchemaAOTCompiler.compile([{ ast: schema.ast, operations: ["decode"] }])) - const generated = await import(`${pathToFileURL(file).href}?test=${Date.now()}`) - generated.install([schema.ast]) + assert.strictEqual(SchemaParser.decodeUnknownSync(child)("1"), 1) + assert.isUndefined(CompilerRegistry.resolve(child.ast).compiled) - const dependency = CompilerRegistry.resolve(child.ast) - assert.isFalse(Object.hasOwn(dependency, "decodeEffect")) + const install = await compileInstaller({ ast: schema.ast, operations: ["decode"] }) + install() - const decode = SchemaParser.decodeUnknownSync(schema) - assert.deepStrictEqual(decode({ child: "1" }), { child: 1 }) - assert.isFalse(Object.hasOwn(dependency, "decodeEffect")) + const dependency = CompilerRegistry.resolve(child.ast) + assert.isFunction(dependency.compiled) + assert.isFalse(Object.hasOwn(dependency, "decodeEffect")) - assert.throws(() => decode({ child: false })) - assert.isTrue(Object.hasOwn(dependency, "decodeEffect")) - } finally { - rmSync(directory, { recursive: true, force: true }) - } + const decode = SchemaParser.decodeUnknownSync(schema) + assert.deepStrictEqual(decode({ child: "1" }), { child: 1 }) + assert.isFalse(Object.hasOwn(dependency, "decodeEffect")) + + assert.throws(() => decode({ child: false })) + assert.isTrue(Object.hasOwn(dependency, "decodeEffect")) }) it("deduplicates repeated roots and dependencies shared across roots", () => { @@ -175,7 +232,7 @@ describe("SchemaAOTCompiler", { concurrent: false }, () => { ]), source ) - assert.strictEqual(source.match(/runtime\.setCompiler\(/g)?.length, 3) + assert.strictEqual(source.match(/runtime\.setCompiler(?:Dependency)?\(/g)?.length, 3) }) it("reuses identical decoder factories", () => {