diff --git a/.changeset/codec-standard.md b/.changeset/codec-standard.md new file mode 100644 index 00000000..333c3ff3 --- /dev/null +++ b/.changeset/codec-standard.md @@ -0,0 +1,11 @@ +--- +"@systemfsoftware/api-extractor": minor +--- + +Every JSON encoding is now its format's Effect Schema through `Schema.fromJsonString`. + +- `ApiModel.ApiModelFromJsonText` replaces `ApiModel.decode` and `ApiModel.encode`, which are removed. `ApiModel.serialise` returns an `Effect` that can fail with a `SchemaError`, instead of a `string`. +- `Verdict.RuleCorpusFromJsonText` replaces `Verdict.decodeRuleCorpus`, which is removed. `Verdict.VerdictFromJsonText` is new. +- `FrontEnd.PackageManifestFromJsonText`, `FrontEnd.ExportTargetFromPackageExports` and the `FrontEnd.ExportTarget` and `FrontEnd.PackageManifest` types are new. +- `FrontEnd.formatDocModel` and `FrontEnd.formatTsdocMetadata` return a `Result`, and `Verdict.cell` reports a `SchemaError` on its write channel, instead of throwing. `FrontEnd.ExtractPackageError` gains `SchemaError`. +- The JSON this package writes lists object keys in the order its schema declares them, not sorted, and has no trailing newline. Decoding accepts any key order, and `API_MODEL_SCHEMA_VERSION` is unchanged. diff --git a/AGENTS.md b/AGENTS.md index ed3afa8c..718e7767 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,8 +15,8 @@ verdict. Requirements and decisions: `docs/plans/2026-10-10-1146-feat-effect-api ## Rules - Read `docs/solutions/` before planning or changing code here. -- Every output goes through `canonicalJson` (`packages/api-extractor/src/canonical-json.schema.ts`). - Order strings by UTF-16 code unit with effect's `Order.String`; never `localeCompare`, +- Every JSON output is its format's Effect Schema encoded with `Schema.fromJsonString`; never a + hand-written writer, reader or key sorter. Order strings by UTF-16 code unit with effect's `Order.String`; never `localeCompare`, `toLocale*` or `Intl` in `src`. - Code the verdict decision reaches lives in the workflow file or in `*.schema.ts` files beside the type it operates on (gate: `pnpm lint`, rule `dmmf-workflow(make-body-purity)`). diff --git a/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts b/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts index c24b8582..8c479ecb 100644 --- a/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts +++ b/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts @@ -1,5 +1,5 @@ import { Result, Schema } from 'effect' -const codec = Schema.fromJsonString(Schema.Unknown) +const codec = Schema.fromJsonString(Schema.Json) -export const jsonText = (value: object): string => Result.getOrThrow(Schema.encodeResult(codec)(value)) +export const jsonText = (value: Schema.Json): string => Result.getOrThrow(Schema.encodeResult(codec)(value)) diff --git a/apps/api-extractor-e2e/tests/front-ends.integration.test.ts b/apps/api-extractor-e2e/tests/front-ends.integration.test.ts index f691bd4e..45759c7a 100644 --- a/apps/api-extractor-e2e/tests/front-ends.integration.test.ts +++ b/apps/api-extractor-e2e/tests/front-ends.integration.test.ts @@ -1,7 +1,7 @@ import { NodeServices } from '@effect/platform-node' import { ApiModel, FrontEnd } from '@systemfsoftware/api-extractor' import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' -import { Effect, FileSystem, Layer, Match, Option, Path } from 'effect' +import { Effect, FileSystem, Layer, Match, Option, Path, Schema } from 'effect' import { jsonText } from './__fixtures__/json-text.js' const Feature = makeFeature({ it }) @@ -18,6 +18,11 @@ const STANDALONE_TSCONFIG = { const SOURCE_CONDITION = FrontEnd.FAMILY_SOURCE_CONDITION +const roundTripped = (model: ApiModel.ApiModel): ApiModel.ApiModel => + Effect.runSync( + Effect.flatMap(Schema.encodeEffect(ApiModel.ApiModelFromJsonText)(model), (text) => Schema.decodeEffect(ApiModel.ApiModelFromJsonText)(text)), + ) + const manifestWith = (name: string, exports: Readonly>): string => jsonText({ name, @@ -26,7 +31,7 @@ const manifestWith = (name: string, exports: Readonly>): exports: Object.fromEntries(Object.entries(exports).map(([exportPath, source]) => [exportPath, { [SOURCE_CONDITION]: source }])), }) -const fallingBackPackage = (name: string, exports: Readonly>, files: Readonly>, tsconfig?: object) => +const fallingBackPackage = (name: string, exports: Readonly>, files: Readonly>, tsconfig?: Schema.Json) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path @@ -42,7 +47,7 @@ const fallingBackPackage = (name: string, exports: Readonly +const packageWith = (name: string, source: string, compilerOptions: Readonly> = {}) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path @@ -244,7 +249,7 @@ const analysedThrough = (emitter: Effect.Effect entry.items.map((item) => item.name)), messages: yield* FrontEnd.resolveMessages(declarations), files: declarations.files.map((file) => file.path), @@ -587,7 +592,7 @@ Feature('Analysing a package into one model') producer: scope.analysis.model.producer.declarations, entryPoints: scope.analysis.model.entryPoints.map((entry) => entry.path), exports: scope.analysis.model.entryPoints.flatMap((entry) => entry.items.map((item) => `${item.kind}:${item.name}`)), - decoded: ApiModel.decode(ApiModel.encode(scope.analysis.model)), + decoded: roundTripped(scope.analysis.model), }).toEqual({ route: 'Fallback', producer: FrontEnd.TYPESCRIPT_PRODUCER, diff --git a/apps/api-extractor-profile/profile.ts b/apps/api-extractor-profile/profile.ts index f11ca249..419eaa49 100644 --- a/apps/api-extractor-profile/profile.ts +++ b/apps/api-extractor-profile/profile.ts @@ -9,6 +9,10 @@ import { parseSync } from 'oxc-parser' import { isolatedDeclarationSync } from 'oxc-transform' import ts59 from 'typescript-5.9' +const JsonText: Schema.Codec = Schema.fromJsonString(Schema.Json, { space: 2 }) + +const jsonText = (value: Schema.Json): Result.Result => Schema.encodeResult(JsonText)(value) + const WARM_RUNS = 5 const require = createRequire(import.meta.url) @@ -44,7 +48,7 @@ interface Subject { readonly workspaceRoot: string } -interface Timing { +type Timing = { readonly coldMs: number readonly warmMedianMs: number } @@ -81,7 +85,8 @@ const readManifest = (root: string) => const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path const text = yield* fileSystem.readFileString(path.join(root, 'package.json')) - return yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Manifest))(text) + const json = yield* Schema.decodeUnknownEffect(JsonText)(text) + return yield* Schema.decodeUnknownEffect(Manifest)(json) }) const RELATIVE = /^\.\.?\// @@ -160,28 +165,26 @@ const writeDerivedConfig = (tsconfig: string, workspaceRoot: string, outDir: str const readConfigFile = (fileName: string): string | undefined => ts59.sys.readFile(fileName) const parsed = ts59.parseJsonConfigFileContent(ts59.readConfigFile(tsconfig, readConfigFile).config, ts59.sys, path.dirname(tsconfig), undefined, tsconfig) const derived = path.join(outDir, 'tsconfig.json') - yield* fileSystem.writeFileString( - derived, - JSON.stringify({ - extends: tsconfig, - compilerOptions: { - noEmit: false, - declaration: true, - emitDeclarationOnly: true, - declarationMap: false, - sourceMap: false, - stripInternal: false, - isolatedDeclarations: false, - removeComments: false, - incremental: false, - composite: false, - rootDir: workspaceRoot, - outDir, - declarationDir: outDir, - }, - files: parsed.fileNames, - }), - ) + const text = yield* Effect.fromResult(jsonText({ + extends: tsconfig, + compilerOptions: { + noEmit: false, + declaration: true, + emitDeclarationOnly: true, + declarationMap: false, + sourceMap: false, + stripInternal: false, + isolatedDeclarations: false, + removeComments: false, + incremental: false, + composite: false, + rootDir: workspaceRoot, + outDir, + declarationDir: outDir, + }, + files: parsed.fileNames, + })) + yield* fileSystem.writeFileString(derived, text) return derived }) @@ -254,12 +257,12 @@ const PHASES = [ ] as const type Phase = (typeof PHASES)[number] -interface Cleanliness { +type Cleanliness = { readonly diagnostics: number readonly clean: boolean } -interface PackageProfile { +type PackageProfile = { readonly name: string readonly version: string readonly origin: Subject['origin'] @@ -275,7 +278,7 @@ interface PackageProfile { readonly phases: Readonly> } -interface FrontEndOutcome { +type FrontEndOutcome = { readonly route: 'FastPath' | 'Fallback' | 'refused' readonly outcome: string readonly items: number @@ -408,7 +411,7 @@ const versionOf = (specifier: string) => return manifest.version }) -interface Report { +type Report = { readonly corpus: { readonly repository: string; readonly commit: string } readonly ownPackage: { readonly repository: string; readonly commit: string } readonly host: { readonly cpu: string; readonly cores: number; readonly platform: string; readonly node: string } @@ -421,29 +424,31 @@ interface Report { const total = (packages: ReadonlyArray, phase: Phase, key: keyof Timing): number => round(packages.reduce((sum, item) => sum + item.phases[phase][key], 0)) -const markdownOf = (report: Report): string => { +const markdownOf = (report: Report): Result.Result => { const header = `| Package | Origin | Sources | oxc clean | tD clean | tsc ID clean | ${PHASES.join(' | ')} | TS7≠5.9.3 | no 5.9.3 emit | route | model |` const rule = `|${'---|'.repeat(PHASES.length + 10)}` const rows = report.packages.map((item) => `| ${item.name} | ${item.origin} | ${item.sourceFiles} | ${item.clean['oxc-transform'].diagnostics} | ${item.clean.transpileDeclaration.diagnostics} | ${item.clean['tsc --isolatedDeclarations'].diagnostics} | ${PHASES.map((phase) => item.phases[phase].warmMedianMs).join(' | ')} | ${item.divergence.differing}/${item.divergence.compared} | ${item.divergence.missing} | ${item.frontEnd.route} | ${item.frontEnd.outcome} |` ) const totals = `| **total** | | ${report.packages.reduce((sum, item) => sum + item.sourceFiles, 0)} | | | | ${PHASES.map((phase) => report.totals[phase]).join(' | ')} | ${report.packages.reduce((sum, item) => sum + item.divergence.differing, 0)}/${report.packages.reduce((sum, item) => sum + item.divergence.compared, 0)} | ${report.packages.reduce((sum, item) => sum + item.divergence.missing, 0)} | | |` - return [ - '# Front-end phase profile', - '', - 'Generated by `apps/api-extractor-profile/profile.ts`; the JSON beside this file is the record. Times are warm medians in milliseconds;', - 'the clean columns count isolated-declaration diagnostics over the files the entry sources reach.', - '', - '```json', - JSON.stringify(Object.fromEntries(Object.entries(report).filter(([key]) => key !== 'packages')), null, 2), - '```', - '', - header, - rule, - ...rows, - totals, - '', - ].join('\n') + return Result.map(jsonText(Object.fromEntries(Object.entries(report).filter(([key]) => key !== 'packages'))), (summary) => + [ + '# Front-end phase profile', + '', + 'Generated by `apps/api-extractor-profile/profile.ts`; the JSON beside this file is the record. Times are warm medians in milliseconds;', + 'the clean columns count isolated-declaration diagnostics over the files the entry sources reach.', + '', + '```json', + summary, + '```', + '', + header, + rule, + ...rows, + totals, + '', + ].join('\n'), + ) } const program = Effect.gen(function* () { @@ -468,8 +473,8 @@ const program = Effect.gen(function* () { totals: Object.fromEntries(PHASES.map((phase) => [phase, total(packages, phase, 'warmMedianMs')])), packages, } - yield* fileSystem.writeFileString(`${outputArgument}.json`, `${JSON.stringify(report, null, 2)}\n`) - yield* fileSystem.writeFileString(`${outputArgument}.md`, markdownOf(report)) + yield* fileSystem.writeFileString(`${outputArgument}.json`, yield* Effect.fromResult(jsonText(report))) + yield* fileSystem.writeFileString(`${outputArgument}.md`, yield* Effect.fromResult(markdownOf(report))) }) const emitters = Layer.mergeAll(FrontEnd.isolatedEmitterLayer, FrontEnd.compilerEmitterLayer).pipe( diff --git a/packages/api-extractor/README.md b/packages/api-extractor/README.md index 091f2862..2fdf3ff7 100644 --- a/packages/api-extractor/README.md +++ b/packages/api-extractor/README.md @@ -190,7 +190,7 @@ The config left `projectFolder` as ``, and neither the package nor a par **`a surface or the corpus does not decode`** -`Verdict.cell.run` was given a value that is not an API model, or a corpus that is not the rule corpus. Produce models with `FrontEnd.analyse`, or decode them with `ApiModel.decode`. +`Verdict.cell.run` was given a value that is not an API model, or a corpus that is not the rule corpus. Produce models with `FrontEnd.analyse`, or decode them with `ApiModel.ApiModelFromJsonText`. **`api-extractor: the API report changed; run with --local to update it`** diff --git a/packages/api-extractor/src/ApiModel.ts b/packages/api-extractor/src/ApiModel.ts index e48f185f..8b71a648 100644 --- a/packages/api-extractor/src/ApiModel.ts +++ b/packages/api-extractor/src/ApiModel.ts @@ -5,9 +5,8 @@ export { API_MODEL_SCHEMA_VERSION as SCHEMA_VERSION, ApiItem, ApiModel, + ApiModelFromJsonText, type ClassItem, - decodeApiModel as decode, - encodeApiModel as encode, type EntryPoint, type EnumItem, type EnumMember, diff --git a/packages/api-extractor/src/FrontEnd.ts b/packages/api-extractor/src/FrontEnd.ts index 2b86a8c4..3e318e20 100644 --- a/packages/api-extractor/src/FrontEnd.ts +++ b/packages/api-extractor/src/FrontEnd.ts @@ -10,6 +10,9 @@ export { } from './front-end/declaration-emitter.service.js' export { DeclarationParser, type DeclarationParserId, type ParsedDeclarations, type VisitorHandlers } from './front-end/declaration-parser.service.js' export { type DeclarationFile, Declarations, Diagnostic, Note, type PackageSource, Reported, type SourceEntryPoint } from './front-end/declarations.schema.js' +export { type ExportTarget } from './front-end/export-target.schema.js' +export { type PackageManifest, PackageManifestFromJsonText } from './front-end/package-source.schema.js' +export { ExportTargetFromPackageExports } from './front-end/package-source.schema.js' export { CompilerRejected, CompilerUnavailable, ManifestRejected, NoSourceEntry, NotIsolated, UnsupportedDeclaration } from './front-end/front-end-error.schema.js' export { layer as isolatedEmitterLayer, OXC_TRANSFORM_PRODUCER } from './front-end/oxc-isolated-emitter.js' export { layer as declarationParserLayer } from './front-end/oxc-declaration-parser.js' diff --git a/packages/api-extractor/src/Verdict.ts b/packages/api-extractor/src/Verdict.ts index f426d796..401b8e1b 100644 --- a/packages/api-extractor/src/Verdict.ts +++ b/packages/api-extractor/src/Verdict.ts @@ -6,7 +6,7 @@ export { type Change, ChangeKind, type Changes, diffModels as diff } from './dif export { Direction } from './diff/direction.schema.js' export { ChannelType, Position, Variance } from './diff/position.schema.js' export { judgeSurfaces as judge } from './judge-surfaces.workflow.js' -export { Bump, classify, decodeRuleCorpus, maxBump, type Rule, RuleCorpus, type RuleMatch, UNCLASSIFIED } from './rules/corpus.schema.js' +export { Bump, classify, maxBump, type Rule, RuleCorpus, RuleCorpusFromJsonText, type RuleMatch, UNCLASSIFIED } from './rules/corpus.schema.js' export { defaultCorpus } from './rules/default-corpus.js' export { bumpOf, Finding, Findings } from './rules/finding.schema.js' export { type VerdictInput as Input, verdictCell as cell } from './verdict.cell.js' @@ -16,6 +16,7 @@ export { RuleCorpusRejected, SurfaceRejected, Verdict, + VerdictFromJsonText, VERDICT_SCHEMA_VERSION as SCHEMA_VERSION, VerdictTypeId, } from './verdict.schema.js' diff --git a/packages/api-extractor/src/__tests__/judge-surfaces.workflow.property.test.ts b/packages/api-extractor/src/__tests__/judge-surfaces.workflow.property.test.ts index 01f1cad3..f81b6164 100644 --- a/packages/api-extractor/src/__tests__/judge-surfaces.workflow.property.test.ts +++ b/packages/api-extractor/src/__tests__/judge-surfaces.workflow.property.test.ts @@ -1,6 +1,5 @@ import { describe } from '@systemfsoftware/vitest' -import { Result } from 'effect' -import { canonicalJson, type Json } from '../canonical-json.schema.js' +import { Result, Schema } from 'effect' import { judgeSurfaces } from '../judge-surfaces.workflow.js' import type { ApiItem, ApiModel } from '../model/api-model.schema.js' import type { TypeExpr } from '../model/type-expr.schema.js' @@ -37,7 +36,7 @@ const located = (result: Judged) => ? { bump: result.success.bump, findings: result.success.findings.map((finding) => [finding.reason_code, finding.locations]) } : { refused: result.failure.ambiguities } -const same = (left: Json, right: Json): boolean => canonicalJson(left) === canonicalJson(right) +const same = (left: Schema.Json, right: Schema.Json): boolean => Schema.toEquivalence(Schema.Json)(left, right) const verdict = (bump: Bump, ...findings: ReadonlyArray]>) => ({ bump, findings }) const surface = (item: ApiItem): ApiModel => rootedWith(empty, [item]) diff --git a/packages/api-extractor/src/canonical-json.schema.ts b/packages/api-extractor/src/canonical-json.schema.ts deleted file mode 100644 index 40dfa0d0..00000000 --- a/packages/api-extractor/src/canonical-json.schema.ts +++ /dev/null @@ -1,90 +0,0 @@ -/** - * The one serialiser every output goes through. Keys are ordered by UTF-16 code - * unit (`Order.String`), so the bytes never depend on the process locale, time - * zone or host. - */ -import { Match, Order, Predicate, Result, Schema } from 'effect' - -/** A JSON value: what every output is serialised from. */ -export const Json: typeof Schema.Json = Schema.Json -export type Json = Schema.Json - -type Entry = readonly [string, Json] - -const byKey: Order.Order = Order.mapInput(Order.String, ([key]: Entry) => key) - -const isJsonArray = (value: Json): value is Schema.JsonArray => Array.isArray(value) - -const isJsonObject = (value: Json): value is Schema.JsonObject => Predicate.isObject(value) && !isJsonArray(value) - -/** The members of an object, ordered by key code unit. */ -const entriesOf = (value: Schema.JsonObject): ReadonlyArray => Object.entries(value).sort(byKey) - -const jsonTextCodec = Schema.fromJsonString(Schema.Unknown) - -const encodeText = (value: Json): string => Result.getOrThrow(Schema.encodeResult(jsonTextCodec)(value)) - -/** The JSON text of one string — the quoted literal with its escapes. Refuses any other value. */ -export const jsonText = (value: Json): string => { - if (typeof value !== 'string') throw new TypeError(`jsonText: a string is required, got ${typeof value}`) - return encodeText(value) -} - -type Scalar = string | number | boolean | null - -const scalarText = new Map([ - [null, 'null'], - [true, 'true'], - [false, 'false'], -]) -const SCALAR_CACHE_LIMIT = 2048 - -const rememberScalar = (scalar: Scalar): string => { - const text = encodeText(scalar) - if (scalarText.size >= SCALAR_CACHE_LIMIT) scalarText.clear() - scalarText.set(scalar, text) - return text -} - -const textOfScalar = (scalar: Scalar): string => scalarText.get(scalar) ?? rememberScalar(scalar) - -const writeNumber = (value: number): string => { - if (!Number.isFinite(value)) throw new TypeError(`canonicalJson: non-finite number ${value}`) - return textOfScalar(value) -} - -const writeArray = (items: Schema.JsonArray, indent: string): string => { - const inner = `${indent} ` - return items.length === 0 ? '[]' : `[\n${items.map((item) => inner + write(item, inner)).join(',\n')}\n${indent}]` -} - -const writeObject = (value: Schema.JsonObject, indent: string): string => { - const inner = `${indent} ` - const entries = entriesOf(value) - return entries.length === 0 - ? '{}' - : `{\n${entries.map(([key, member]) => `${inner}${textOfScalar(key)}: ${write(member, inner)}`).join(',\n')}\n${indent}}` -} - -const write = (value: Json, indent: string): string => - Match.value(value).pipe( - Match.when(Match.number, writeNumber), - Match.when(isJsonArray, (items) => writeArray(items, indent)), - Match.when(isJsonObject, (object) => writeObject(object, indent)), - Match.orElse(textOfScalar), - ) - -/** Serialises a JSON value with sorted keys, two-space indentation and a trailing newline. */ -export const canonicalJson = (value: Json): string => `${write(value, '')}\n` - -const writeCompact = (value: Json): string => - Match.value(value).pipe( - Match.when(Match.number, writeNumber), - Match.when(isJsonArray, (items) => `[${items.map(writeCompact).join(',')}]`), - Match.when(isJsonObject, (object) => - `{${entriesOf(object).map(([key, member]) => `${textOfScalar(key)}:${writeCompact(member)}`).join(',')}}`), - Match.orElse(textOfScalar), - ) - -/** The same ordering on one line: a structural identity key. */ -export const canonicalKey = (value: Json): string => writeCompact(value) diff --git a/packages/api-extractor/src/cli.ts b/packages/api-extractor/src/cli.ts index 6d0b859e..442e74ea 100644 --- a/packages/api-extractor/src/cli.ts +++ b/packages/api-extractor/src/cli.ts @@ -1,7 +1,6 @@ -import { Effect, FileSystem, Layer, Option, Path } from 'effect' +import { Effect, FileSystem, Layer, Option, Path, Predicate, Schema } from 'effect' import type { PlatformError } from 'effect/PlatformError' import { NodeServices, NodeRuntime } from '@effect/platform-node' -import { canonicalJson } from './canonical-json.schema.js' import { layer as declarationParserLayer } from './front-end/oxc-declaration-parser.js' import { layer as isolatedEmitterLayer } from './front-end/oxc-isolated-emitter.js' import { layer as compilerEmitterLayer } from './front-end/typescript-declaration-emitter.js' @@ -84,7 +83,7 @@ const parsedArguments = (argv: ReadonlyArray): ParsedArguments => { return { command, folder: folderOf(command)(positionals), configFile: configFileOf(argv), local: argv.includes('--local') } } -const initialize = (path: Path.Path) => (folder: string): Effect.Effect => +const initialize = (path: Path.Path) => (folder: string): Effect.Effect => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem const file = path.join(folder, CONFIG_FILE_NAME) @@ -95,7 +94,8 @@ const initialize = (path: Path.Path) => (folder: string): Effect.Effect process.stdout.write(`Writing configuration file: ${file}\n`)) }) @@ -125,7 +125,7 @@ const runExtraction = (request: { readonly folder: string; readonly configFile: yield* Effect.sync(() => reportOutcomeOf(outcome)) }) -const issueTextOf = (error: ExtractPackageError): Option.Option => Option.fromNullishOr('issue' in error ? error.issue : undefined) +const issueTextOf = (error: ExtractPackageError): Option.Option => Option.filter(Option.fromNullishOr('issue' in error ? error.issue : undefined), Predicate.isString) const messageTextOf = (error: ExtractPackageError): string => (error instanceof Error ? error.message : 'the extraction failed') diff --git a/packages/api-extractor/src/diff/change.schema.ts b/packages/api-extractor/src/diff/change.schema.ts index a9a332e4..892fcbc0 100644 --- a/packages/api-extractor/src/diff/change.schema.ts +++ b/packages/api-extractor/src/diff/change.schema.ts @@ -1,5 +1,4 @@ -import { Array as Arr, Function, Order, Schema } from 'effect' -import { canonicalKey } from '../canonical-json.schema.js' +import { Array as Arr, Function, Order, Result, Schema } from 'effect' import type { ApiItem, ApiModel, @@ -13,6 +12,7 @@ import type { TypeAliasItem, VariableItem, } from '../model/api-model.schema.js' +import { itemKey } from '../model/api-model.schema.js' import { type ArrayType, type FunctionType, @@ -26,11 +26,17 @@ import { type TupleType, type TypeExpr, type TypeParameter, + signatureKey, + typeExprKey, typeKey, } from '../model/type-expr.schema.js' import { type Direction, direction } from './direction.schema.js' import { type ChannelType, compose, flip, type Position } from './position.schema.js' +const StringsText: Schema.Codec, string> = Schema.String.pipe(Schema.Array, Schema.fromJsonString) + +const stringsKey = (values: ReadonlyArray): string => Result.getOrThrow(Schema.encodeResult(StringsText)(values)) + const CHANGE_KINDS = [ 'entry-point-added', 'entry-point-removed', @@ -331,7 +337,7 @@ const isTupleType = (type: TypeExpr): type is TupleType => type.kind === 'tuple' const compareType = (context: Context, before: TypeExpr, after: TypeExpr, at: At): ReadonlyArray => { const b = normaliseType(before) const a = normaliseType(after) - return canonicalKey(b) === canonicalKey(a) ? [] : compareNormalised(context, b, a, at) + return typeExprKey(b) === typeExprKey(a) ? [] : compareNormalised(context, b, a, at) } const compareNormalised = (context: Context, b: TypeExpr, a: TypeExpr, at: At): ReadonlyArray => { @@ -436,8 +442,13 @@ const typeParameterKey = (parameter: TypeParameter) => ({ default: optionalTypeKey(parameter.default), }) +const TypeParameterKeysText = Schema.Struct({ name: Schema.String, constraint: Schema.NullOr(Schema.String), default: Schema.NullOr(Schema.String) }).pipe( + Schema.Array, + Schema.fromJsonString, +) + const typeParametersKey = (parameters: ReadonlyArray): string => - canonicalKey(parameters.map(typeParameterKey)) + Result.getOrThrow(Schema.encodeResult(TypeParameterKeysText)(parameters.map(typeParameterKey))) const becameRequired = (before: { readonly optional: boolean }, after: { readonly optional: boolean }): boolean => before.optional && !after.optional @@ -540,7 +551,6 @@ const matchingPartner = (dataFirst: Signature, dataLast: Signature, dataLastRetu const partners = (dataFirst: Signature, dataLast: Signature): boolean => dataLast.returns.kind === 'function' && matchingPartner(dataFirst, dataLast, dataLast.returns.signature) -const signatureKey = (signature: Signature): string => canonicalKey(signature) interface SignatureEntry { readonly signature: Signature @@ -718,7 +728,7 @@ const compareMembers = ( return [...callChanges, ...removed, ...added, ...changed] } -const heritageKey = (types: ReadonlyArray): string => canonicalKey(types.map(typeKey).sort(Order.String)) +const heritageKey = (types: ReadonlyArray): string => stringsKey(types.map(typeKey).sort(Order.String)) const isFunctionItem = (item: ApiItem): item is FunctionItem => item.kind === 'function' const isVariableItem = (item: ApiItem): item is VariableItem => item.kind === 'variable' @@ -752,7 +762,7 @@ const compareTypeAliasPair = (context: Context, before: TypeAliasItem, after: Ty const compareTypeAliasItem = (context: Context, before: TypeAliasItem, after: ApiItem, at: At): ReadonlyArray => isTypeAliasItem(after) ? compareTypeAliasPair(context, before, after, at) : [] -const classHeritage = (item: ClassItem): string => canonicalKey([heritageKey(item.extends), heritageKey(item.implements)]) +const classHeritage = (item: ClassItem): string => stringsKey([heritageKey(item.extends), heritageKey(item.implements)]) const interfaceHeritage = (item: InterfaceItem): string => heritageKey(item.extends) @@ -861,7 +871,7 @@ const compareItems = ( } const unmatched = (from: ReadonlyArray, to: ReadonlyArray): ReadonlyArray => { - const [fromKeys, toKeys] = [from.map(canonicalKey), to.map(canonicalKey)] + const [fromKeys, toKeys] = [from.map(itemKey), to.map(itemKey)] return from.filter((_, index) => { const key = fromKeys[index] return fromKeys.slice(0, index).filter((other) => other === key).length >= toKeys.filter((other) => other === key).length @@ -869,7 +879,7 @@ const unmatched = (from: ReadonlyArray, to: ReadonlyArray): Re } const inCanonicalOrder = (items: ReadonlyArray): ReadonlyArray => - [...items].sort((left, right) => Order.String(canonicalKey(left), canonicalKey(right))) + [...items].sort((left, right) => Order.String(itemKey(left), itemKey(right))) const compareNamed = ( context: Context, diff --git a/packages/api-extractor/src/diff/direction.schema.ts b/packages/api-extractor/src/diff/direction.schema.ts index f97f5323..bc829d9d 100644 --- a/packages/api-extractor/src/diff/direction.schema.ts +++ b/packages/api-extractor/src/diff/direction.schema.ts @@ -1,6 +1,5 @@ import { Function, Match, Schema } from 'effect' -import { canonicalKey } from '../canonical-json.schema.js' -import type { KeywordName, TypeExpr } from '../model/type-expr.schema.js' +import { type KeywordName, type TypeExpr, typeExprKey } from '../model/type-expr.schema.js' /** How a type moved: it admits more values, fewer, or neither. */ export const Direction: Schema.Literals = Schema.Literals(['widened', 'narrowed', 'changed']) @@ -44,7 +43,7 @@ const BELOW: ReadonlyArray<(left: Keyed, right: Keyed) => boolean> = [ const below = (left: Keyed, right: Keyed): boolean => BELOW.some((assignable) => assignable(left, right)) -const keyed = (type: TypeExpr): Keyed => ({ type, key: canonicalKey(type) }) +const keyed = (type: TypeExpr): Keyed => ({ type, key: typeExprKey(type) }) const membersOf = (type: TypeExpr): ReadonlyArray => Match.value(type) diff --git a/packages/api-extractor/src/front-end/canonical-type-text.ts b/packages/api-extractor/src/front-end/canonical-type-text.ts index e8c2a167..fbaebaf4 100644 --- a/packages/api-extractor/src/front-end/canonical-type-text.ts +++ b/packages/api-extractor/src/front-end/canonical-type-text.ts @@ -1,4 +1,4 @@ -import { Array as Arr, Effect, HashMap, HashSet, Match, Option } from 'effect' +import { Array as Arr, Effect, HashMap, HashSet, Match, Option, Result, Schema } from 'effect' import type { BindingPattern, Expression, @@ -38,7 +38,6 @@ import type { TSTypeReference, TemplateElement, } from 'oxc-parser' -import { jsonText } from '../canonical-json.schema.js' import { KeywordName } from '../model/type-expr.schema.js' import { type Declaration, @@ -51,6 +50,9 @@ import { } from './declaration-graph.js' import { UnsupportedDeclaration } from './front-end-error.schema.js' +/** The JSON text of one string: the quoted literal with its escapes. */ +const jsonText = (value: string): string => Result.getOrThrow(Schema.encodeResult(Schema.fromJsonString(Schema.String))(value)) + export type ReferenceTarget = { readonly name: string readonly module: Option.Option diff --git a/packages/api-extractor/src/front-end/export-target.schema.ts b/packages/api-extractor/src/front-end/export-target.schema.ts new file mode 100644 index 00000000..4f06c997 --- /dev/null +++ b/packages/api-extractor/src/front-end/export-target.schema.ts @@ -0,0 +1,46 @@ +import { Schema } from 'effect' + +const PathTag = { _tag: 'Path' } as const +type PathTag = typeof PathTag + +const ConditionsTag = { _tag: 'Conditions' } as const +type ConditionsTag = typeof ConditionsTag + +const FallbacksTag = { _tag: 'Fallbacks' } as const +type FallbacksTag = typeof FallbacksTag + +const ExcludedTag = { _tag: 'Excluded' } as const +type ExcludedTag = typeof ExcludedTag + +export interface ExportPath extends PathTag { + readonly path: string +} + +export interface ExportConditions extends ConditionsTag { + readonly conditions: { readonly [condition: string]: ExportTarget } +} + +export interface ExportFallbacks extends FallbacksTag { + readonly targets: ReadonlyArray +} + +export interface ExportExcluded extends ExcludedTag {} + +/** One package export path's target, as the front-end resolves it (not npm's first-match order). */ +export type ExportTarget = ExportPath | ExportConditions | ExportFallbacks | ExportExcluded + +export const ExportPath: Schema.Codec = Schema.TaggedStruct('Path', { path: Schema.String }) + +export const ExportExcluded: Schema.Codec = Schema.TaggedStruct('Excluded', {}) + +export const ExportConditions: Schema.Codec = Schema.suspend((): Schema.Codec => + Schema.TaggedStruct('Conditions', { conditions: Schema.Record(Schema.String, ExportTarget) }), +) + +export const ExportFallbacks: Schema.Codec = Schema.suspend((): Schema.Codec => + Schema.TaggedStruct('Fallbacks', { targets: Schema.Array(ExportTarget) }), +) + +export const ExportTarget: Schema.Codec = Schema.suspend((): Schema.Codec => + Schema.Union([ExportPath, ExportConditions, ExportFallbacks, ExportExcluded]), +).annotate({ recursionBudget: { maxDepth: 6, depthSize: 'small' } }) diff --git a/packages/api-extractor/src/front-end/package-source.schema.ts b/packages/api-extractor/src/front-end/package-source.schema.ts index 8c97d843..0227a74b 100644 --- a/packages/api-extractor/src/front-end/package-source.schema.ts +++ b/packages/api-extractor/src/front-end/package-source.schema.ts @@ -1,57 +1,15 @@ import { Match, Predicate, Schema, SchemaTransformation } from 'effect' +import { ExportConditions, ExportExcluded, ExportFallbacks, ExportPath, ExportTarget } from './export-target.schema.js' +/** npm's own `exports` grammar: a path, `null`, an ordered fallback list, or a condition map. */ type EncodedConditions = { readonly [condition: string]: EncodedExportTarget } -export type EncodedExportTarget = string | null | ReadonlyArray | EncodedConditions +type EncodedExportTarget = string | null | ReadonlyArray | EncodedConditions const EncodedExportTarget: Schema.Codec = Schema.suspend((): Schema.Codec => Schema.Union([Schema.String, Schema.Null, Schema.Array(EncodedExportTarget), Schema.Record(Schema.String, EncodedExportTarget)]), ).annotate({ recursionBudget: { maxDepth: 6, depthSize: 'small' } }) -const PathTag = { _tag: 'Path' } as const -type PathTag = typeof PathTag - -const ConditionsTag = { _tag: 'Conditions' } as const -type ConditionsTag = typeof ConditionsTag - -const FallbacksTag = { _tag: 'Fallbacks' } as const -type FallbacksTag = typeof FallbacksTag - -const ExcludedTag = { _tag: 'Excluded' } as const -type ExcludedTag = typeof ExcludedTag - -interface ExportPath extends PathTag { - readonly path: string -} - -interface ExportConditions extends ConditionsTag { - readonly conditions: { readonly [condition: string]: ExportTarget } -} - -interface ExportFallbacks extends FallbacksTag { - readonly targets: ReadonlyArray -} - -interface ExportExcluded extends ExcludedTag {} - -export type ExportTarget = ExportPath | ExportConditions | ExportFallbacks | ExportExcluded - -const ExportPath: Schema.Codec = Schema.TaggedStruct('Path', { path: Schema.String }) - -const ExportExcluded: Schema.Codec = Schema.TaggedStruct('Excluded', {}) - -const ExportConditions: Schema.Codec = Schema.suspend((): Schema.Codec => - Schema.TaggedStruct('Conditions', { conditions: Schema.Record(Schema.String, ExportTarget) }), -) - -const ExportFallbacks: Schema.Codec = Schema.suspend((): Schema.Codec => - Schema.TaggedStruct('Fallbacks', { targets: Schema.Array(ExportTarget) }), -) - -export const ExportTarget: Schema.Codec = Schema.suspend((): Schema.Codec => - Schema.Union([ExportPath, ExportConditions, ExportFallbacks, ExportExcluded]), -).annotate({ recursionBudget: { maxDepth: 6, depthSize: 'small' } }) - const isEncodedArray = (target: EncodedExportTarget): target is ReadonlyArray => Array.isArray(target) const isEncodedConditions = (target: EncodedExportTarget): target is EncodedConditions => @@ -82,19 +40,30 @@ function encodedOf(target: ExportTarget): EncodedExportTarget { ) } -export const ExportTargetCodec: Schema.Codec = EncodedExportTarget.pipe( +/** + * npm `exports` → `ExportTarget`: decode reads any key order, encode writes the + * grammar back. The condition map keeps its declared order; the front-end asks + * for one named condition rather than npm's first-match resolution, so the + * domain does not model that order. + */ +export const ExportTargetFromPackageExports: Schema.Codec = EncodedExportTarget.pipe( Schema.decodeTo(ExportTarget, SchemaTransformation.transform({ decode: exportTargetOf, encode: encodedOf })), ) type PackageManifestFields = { readonly name: Schema.String readonly version: Schema.String - readonly exports: Schema.optionalKey]>> + readonly exports: Schema.optionalKey]>> } export const PackageManifest: Schema.Struct = Schema.Struct({ name: Schema.String, version: Schema.String, - exports: Schema.optionalKey(Schema.Union([Schema.String, Schema.Record(Schema.String, ExportTargetCodec)])), + exports: Schema.optionalKey(Schema.Union([Schema.String, Schema.Record(Schema.String, ExportTargetFromPackageExports)])), }) export type PackageManifest = typeof PackageManifest.Type + +export type PackageManifestFromJsonText = Schema.Codec + +/** package.json's encoding: decode accepts any key order, encode writes canonical bytes. */ +export const PackageManifestFromJsonText: PackageManifestFromJsonText = Schema.fromJsonString(PackageManifest, { space: 2 }) diff --git a/packages/api-extractor/src/front-end/read-package.ts b/packages/api-extractor/src/front-end/read-package.ts index 9fe2ec20..d0fb2387 100644 --- a/packages/api-extractor/src/front-end/read-package.ts +++ b/packages/api-extractor/src/front-end/read-package.ts @@ -3,8 +3,9 @@ import type { PlatformError } from 'effect/PlatformError' import type { PackageSource, SourceEntryPoint } from './declarations.schema.js' import { directoryOf, relativeWithin } from './declaration-graph.js' import { ManifestRejected, NoSourceEntry } from './front-end-error.schema.js' +import type { ExportTarget } from './export-target.schema.js' import { isAbsent } from './package-file.js' -import { type ExportTarget, PackageManifest } from './package-source.schema.js' +import { type PackageManifest, PackageManifestFromJsonText } from './package-source.schema.js' export const FAMILY_SOURCE_CONDITION = '@systemfsoftware/source' @@ -13,7 +14,7 @@ export type ReadPackageRequest = { readonly sourceCondition?: string } -const decodeManifest = Schema.decodeEffect(Schema.fromJsonString(PackageManifest)) +const decodeManifest = Schema.decodeEffect(PackageManifestFromJsonText) const TYPESCRIPT_SOURCE = /\.(?:ts|tsx|mts|cts)$/ diff --git a/packages/api-extractor/src/input/config-file.ts b/packages/api-extractor/src/input/config-file.ts index 8662b67d..e0896930 100644 --- a/packages/api-extractor/src/input/config-file.ts +++ b/packages/api-extractor/src/input/config-file.ts @@ -11,7 +11,7 @@ export const rejected: { (issue: string): (configFile: string) => ConfigRejected } = Fn.dual(2, (configFile: string, issue: string): ConfigRejected => new ConfigRejected({ configFile, issue })) -const jsonTextCodec = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown)) +const jsonTextCodec = Schema.decodeEffect(Schema.fromJsonString(Schema.Json)) const parseJson = (configFile: string, text: string): Effect.Effect => jsonTextCodec(text).pipe( diff --git a/packages/api-extractor/src/input/node-extraction-input.ts b/packages/api-extractor/src/input/node-extraction-input.ts index 0d325b81..797ac4ab 100644 --- a/packages/api-extractor/src/input/node-extraction-input.ts +++ b/packages/api-extractor/src/input/node-extraction-input.ts @@ -103,7 +103,7 @@ const chainOf = (configFile: string): Effect.Effect, C type PackageFields = { readonly name: string; readonly version: string; readonly manifest: JsonObject } const parseManifest = (manifestFile: string, text: string): Effect.Effect => - Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))(text).pipe( + Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(text).pipe( Effect.catchTag('SchemaError', () => Effect.fail(rejected(manifestFile, 'the manifest is not JSON'))), Effect.filterOrFail(isJsonObject, () => rejected(manifestFile, 'the manifest does not hold a JSON object')), ) diff --git a/packages/api-extractor/src/model/api-model.schema.ts b/packages/api-extractor/src/model/api-model.schema.ts index 5f78bfe1..53713198 100644 --- a/packages/api-extractor/src/model/api-model.schema.ts +++ b/packages/api-extractor/src/model/api-model.schema.ts @@ -1,5 +1,4 @@ -import { Array as Arr, Cause, Exit, Order, Schema } from 'effect' -import { canonicalKey, type Json } from '../canonical-json.schema.js' +import { Array as Arr, Order, Result, Schema } from 'effect' import { type DocComment, DocComment as DocCommentCodec, ReleaseTag } from './doc-comment.schema.js' import { Member, Signature, TypeExpr, TypeParameter } from './type-expr.schema.js' @@ -171,29 +170,16 @@ export const ApiModel: Schema.Codec = Schema.Struct({ ).check(uniqueBy('entry points', (entry: { readonly path: string }) => entry.path)), }) -/** Decodes a JSON value (e.g. parsed JSON) into a model; rejects any other `schemaVersion`. */ -export const decodeApiModel: (input: Json) => ApiModel = (input) => - Exit.match(Schema.decodeUnknownExit(ApiModel)(input), { - onFailure: (cause) => { - throw Cause.squash(cause) - }, - onSuccess: (model) => model, - }) +const ApiItemText: Schema.Codec = Schema.fromJsonString(ApiItem) -/** The model as a JSON value. */ -export const encodeApiModel: (model: ApiModel) => Json = (model) => - Exit.match(Schema.encodeExit(ApiModel)(model), { - onFailure: (cause) => { - throw Cause.squash(cause) - }, - onSuccess: (encoded) => encoded, - }) +/** An item's structural identity: its JSON text. */ +export const itemKey = (item: ApiItem): string => Result.getOrThrow(Schema.encodeResult(ApiItemText)(item)) /** By name; items sharing a name (a value beside a type) by kind, then by content, so input order never shows. */ const itemOrder: Order.Order = Order.combineAll([ Order.mapInput(Order.String, (item: ApiItem) => item.name), Order.mapInput(Order.String, (item: ApiItem) => item.kind), - Order.mapInput(Order.String, canonicalKey), + Order.mapInput(Order.String, (item: ApiItem) => itemKey(item)), ]) const byName = (values: ReadonlyArray): ReadonlyArray => Arr.sort(values, itemOrder) @@ -215,3 +201,13 @@ export const sortModel = (model: ApiModel): ApiModel => ({ Order.mapInput(Order.String, (entryPoint: EntryPoint) => entryPoint.path), ), }) + +/** + * The model's canonical JSON-text encoding: the one writer and reader of the + * model's text. Decode accepts any key order and any item order; encode writes + * object keys in schema declaration order. Item order is canonicalised by + * `sortModel`, which the canonical-bytes writer composes with this codec. + */ +export type ApiModelFromJsonText = Schema.Codec + +export const ApiModelFromJsonText: ApiModelFromJsonText = Schema.fromJsonString(ApiModel, { space: 2 }) diff --git a/packages/api-extractor/src/model/serialise.ts b/packages/api-extractor/src/model/serialise.ts index 404f2fd6..f3955bc4 100644 --- a/packages/api-extractor/src/model/serialise.ts +++ b/packages/api-extractor/src/model/serialise.ts @@ -1,5 +1,10 @@ -import { canonicalJson } from '../canonical-json.schema.js' -import { type ApiModel, encodeApiModel, sortModel } from './api-model.schema.js' +import { Effect, Schema } from 'effect' +import { ApiModelFromJsonText, sortModel, type ApiModel } from './api-model.schema.js' -/** The model as canonical JSON bytes: equal surfaces give equal bytes in any environment. */ -export const serialiseApiModel = (model: ApiModel): string => canonicalJson(encodeApiModel(sortModel(model))) +/** + * The model as canonical JSON bytes: `sortModel` orders items and entry points, + * the text codec orders object keys. Equal surfaces give equal bytes in any + * environment. + */ +export const serialiseApiModel: (model: ApiModel) => Effect.Effect = (model) => + Schema.encodeEffect(ApiModelFromJsonText)(sortModel(model)) diff --git a/packages/api-extractor/src/model/type-expr.schema.ts b/packages/api-extractor/src/model/type-expr.schema.ts index b0c483e2..370c6c07 100644 --- a/packages/api-extractor/src/model/type-expr.schema.ts +++ b/packages/api-extractor/src/model/type-expr.schema.ts @@ -1,6 +1,5 @@ -import { Array as Arr, Order, Schema } from 'effect' +import { Array as Arr, Order, Result, Schema } from 'effect' import { type DocComment, DocComment as DocCommentCodec, ReleaseTag } from './doc-comment.schema.js' -import { canonicalKey, type Json } from '../canonical-json.schema.js' const KEYWORD_NAMES = [ 'any', @@ -211,11 +210,21 @@ export const TypeExpr: Schema.Codec = Schema.suspend((): Schema.Codec< Schema.Struct({ kind: Schema.Literal('text'), text: Schema.String }), ])).annotate({ recursionBudget: { maxDepth: 4, depthSize: 'small' } }) +const TypeExprText: Schema.Codec = Schema.fromJsonString(TypeExpr) + +/** A type's structural identity: its JSON text. */ +export const typeExprKey = (type: TypeExpr): string => Result.getOrThrow(Schema.encodeResult(TypeExprText)(type)) + +const SignatureText: Schema.Codec = Schema.fromJsonString(Signature) + +/** A signature's structural identity: its JSON text. */ +export const signatureKey = (signature: Signature): string => Result.getOrThrow(Schema.encodeResult(SignatureText)(signature)) + const never: TypeExpr = { kind: 'keyword', name: 'never' } const unknown: TypeExpr = { kind: 'keyword', name: 'unknown' } -const byKey = (values: ReadonlyArray): ReadonlyArray => - Array.from(new Map(values.map((value) => [canonicalKey(value), value] as const))) +const byKey = (values: ReadonlyArray): ReadonlyArray => + Array.from(new Map(values.map((value) => [typeExprKey(value), value] as const))) .sort(([left], [right]) => Order.String(left, right)) .map(([, value]) => value) @@ -287,4 +296,4 @@ export const normaliseType = (type: TypeExpr): TypeExpr => { } /** The structural identity of a type: equal keys mean the same type. */ -export const typeKey = (type: TypeExpr): string => canonicalKey(normaliseType(type)) +export const typeKey = (type: TypeExpr): string => typeExprKey(normaliseType(type)) diff --git a/packages/api-extractor/src/output/doc-model.ts b/packages/api-extractor/src/output/doc-model.ts index 4f5fd762..19505013 100644 --- a/packages/api-extractor/src/output/doc-model.ts +++ b/packages/api-extractor/src/output/doc-model.ts @@ -1,5 +1,8 @@ -import { Match, Option } from 'effect' -import { canonicalJson, type Json } from '../canonical-json.schema.js' +import { Match, Option, Result, Schema } from 'effect' + +type Json = Schema.Json + +const canonicalJson = (value: Json): Result.Result => Schema.encodeResult(Schema.fromJsonString(Schema.Json, { space: 2 }))(value) import type { ApiItem, ApiModel, EntryPoint } from '../model/api-model.schema.js' import type { Member, Parameter, Signature, TypeParameter } from '../model/type-expr.schema.js' import { sortByKey, sortByName } from '../model/member-order.js' @@ -288,7 +291,7 @@ const metadataJson = (request: DocModelRequest): Json => const projectUrlField = (request: DocModelRequest): JsonRecord => (request.projectFolderUrl === undefined ? {} : { projectFolderUrl: request.projectFolderUrl }) -export const formatDocModel = (request: DocModelRequest): string => +export const formatDocModel = (request: DocModelRequest): Result.Result => canonicalJson( jsonObject({ metadata: metadataJson(request), diff --git a/packages/api-extractor/src/output/tsdoc-metadata.ts b/packages/api-extractor/src/output/tsdoc-metadata.ts index b543d041..74b6d281 100644 --- a/packages/api-extractor/src/output/tsdoc-metadata.ts +++ b/packages/api-extractor/src/output/tsdoc-metadata.ts @@ -1,4 +1,8 @@ -import { canonicalJson, type Json } from '../canonical-json.schema.js' +import { Result, Schema } from 'effect' + +type Json = Schema.Json + +const canonicalJson = (value: Json): Result.Result => Schema.encodeResult(Schema.fromJsonString(Schema.Json, { space: 2 }))(value) import { ENGINE } from '../version.js' const TSDOC_VERSION = '0.12' @@ -13,4 +17,4 @@ export const tsdocMetadataJson = (): Json => ({ toolPackages: [toolPackageJson()], }) -export const formatTsdocMetadata = (): string => canonicalJson(tsdocMetadataJson()) +export const formatTsdocMetadata = (): Result.Result => canonicalJson(tsdocMetadataJson()) diff --git a/packages/api-extractor/src/pipeline/extract-package.blueprint.ts b/packages/api-extractor/src/pipeline/extract-package.blueprint.ts index 0105dc6a..2bba9875 100644 --- a/packages/api-extractor/src/pipeline/extract-package.blueprint.ts +++ b/packages/api-extractor/src/pipeline/extract-package.blueprint.ts @@ -1,5 +1,5 @@ import { Blueprint } from '@systemfsoftware/effect-cell-types' -import { Effect } from 'effect' +import { Effect, type Schema } from 'effect' import type { CompilerRejected, CompilerUnavailable, ManifestRejected, NoSourceEntry, NotIsolated, UnsupportedDeclaration } from '../front-end/front-end-error.schema.js' import type { ConfigRejected } from '../input/extraction-input-error.schema.js' import type { Platform } from '../input/config-file.js' @@ -21,6 +21,7 @@ export type ExtractPackageError = | RollupRejected | UnsupportedDeclaration | PlatformError + | Schema.SchemaError export type ExtractPackageServices = ExtractionInputId | Platform | SurfaceServices diff --git a/packages/api-extractor/src/pipeline/extract-surface.cell.ts b/packages/api-extractor/src/pipeline/extract-surface.cell.ts index 304a331e..9ca63434 100644 --- a/packages/api-extractor/src/pipeline/extract-surface.cell.ts +++ b/packages/api-extractor/src/pipeline/extract-surface.cell.ts @@ -17,7 +17,7 @@ import { bundledDeclarations } from './emit-declarations.cell.js' import type { ExtractedSurface, ReportVariantText, RollupText } from './extraction-pipeline.schema.js' import { ReportOutcomeCommand, type ReportOutcome, reportOutcomeFor } from './report-outcome.schema.js' -export type SurfaceError = CompilerRejected | CompilerUnavailable | NotIsolated | UnsupportedDeclaration | RollupRejected | PlatformError +export type SurfaceError = CompilerRejected | CompilerUnavailable | NotIsolated | UnsupportedDeclaration | RollupRejected | PlatformError | Schema.SchemaError export type SurfaceServices = FileSystem.FileSystem | Path.Path | IsolatedEmitterId | CompilerEmitterId | DeclarationParserId | RollupBundlerId @@ -85,22 +85,24 @@ const tsdocConfigOf = (spec: ExtractionSpec): Schema.Json => () => ({}), ) -const docModelOf = (spec: ExtractionSpec) => (model: ApiModel): { readonly file: string; readonly text: string } | null => +const docModelOf = (spec: ExtractionSpec) => (model: ApiModel): Effect.Effect<{ readonly file: string; readonly text: string } | null, Schema.SchemaError> => spec.docModel.enabled - ? { - file: spec.docModel.apiJsonFilePath, - text: withNewline(spec)(formatDocModel({ + ? Effect.map( + Effect.fromResult(formatDocModel({ model, releaseTagsToTrim: spec.docModel.releaseTagsToTrim, projectFolderUrl: spec.docModel.projectFolderUrl, enumMemberOrder: spec.enumMemberOrder, tsdocConfig: tsdocConfigOf(spec), })), - } - : null + (text) => ({ file: spec.docModel.apiJsonFilePath, text: withNewline(spec)(text) }), + ) + : Effect.succeed(null) -const tsdocMetadataOf = (spec: ExtractionSpec): { readonly file: string; readonly text: string } | null => - spec.tsdocMetadata.enabled ? { file: spec.tsdocMetadata.tsdocMetadataFilePath, text: withNewline(spec)(formatTsdocMetadata()) } : null +const tsdocMetadataOf = (spec: ExtractionSpec): Effect.Effect<{ readonly file: string; readonly text: string } | null, Schema.SchemaError> => + spec.tsdocMetadata.enabled + ? Effect.map(Effect.fromResult(formatTsdocMetadata()), (text) => ({ file: spec.tsdocMetadata.tsdocMetadataFilePath, text: withNewline(spec)(text) })) + : Effect.succeed(null) type RollupTarget = { readonly variant: RollupVariantName | 'untrimmed'; readonly file: string } @@ -172,8 +174,8 @@ export const extractSurface = (request: ExtractSurfaceRequest): Effect.Effect = Schema.Struct({ rules: Schema.Array(Rule), }) -/** Decodes a rule corpus; whether its rules are unambiguous is the verdict decision's to judge. */ -export const decodeRuleCorpus: (input: Json) => RuleCorpus = (input) => - Exit.match(Schema.decodeUnknownExit(RuleCorpus)(input), { - onFailure: (cause) => { - throw Cause.squash(cause) - }, - onSuccess: (corpus) => corpus, - }) +/** + * The corpus's canonical JSON-text encoding: the one writer and reader of a + * corpus read from or written to a file. The shipped corpus decodes through the + * `RuleCorpus` schema itself. + */ +export type RuleCorpusFromJsonText = Schema.Codec + +export const RuleCorpusFromJsonText: RuleCorpusFromJsonText = Schema.fromJsonString(RuleCorpus, { space: 2 }) /** Semver order, least first: the order `Bump` declares its literals in. */ const BUMP_ORDER: ReadonlyArray = Bump.literals diff --git a/packages/api-extractor/src/rules/default-corpus.ts b/packages/api-extractor/src/rules/default-corpus.ts index bb52d03c..da984fd3 100644 --- a/packages/api-extractor/src/rules/default-corpus.ts +++ b/packages/api-extractor/src/rules/default-corpus.ts @@ -1,5 +1,7 @@ +import { Effect, Schema } from 'effect' import corpusV1 from './corpus.v1.json' with { type: 'json' } -import { decodeRuleCorpus, type RuleCorpus } from './corpus.schema.js' +import { RuleCorpus, type RuleCorpus as RuleCorpusType } from './corpus.schema.js' -/** The rule corpus this engine ships. */ -export const defaultCorpus: RuleCorpus = decodeRuleCorpus(corpusV1) +// The shipped corpus is repository source, checked by this package's tests, so a +// corpus that does not decode is a defect; module load is where it surfaces. +export const defaultCorpus: RuleCorpusType = Effect.runSync(Schema.decodeUnknownEffect(RuleCorpus)(corpusV1)) diff --git a/packages/api-extractor/src/schema-laws.test.ts b/packages/api-extractor/src/schema-laws.test.ts new file mode 100644 index 00000000..7fa4d5ba --- /dev/null +++ b/packages/api-extractor/src/schema-laws.test.ts @@ -0,0 +1,5 @@ +// Generated: @systemfsoftware/effect-schema-vite rewrites this file, injecting a +// `ruleOfSchemas` law pair for every exported Effect Schema in this package. +// The generated body carries real import edges to each schema file so vitest's +// related-file walk (and therefore `stryker --related`) reaches them. +export {} diff --git a/packages/api-extractor/src/verdict.cell.ts b/packages/api-extractor/src/verdict.cell.ts index 9d5a2137..6f10d72a 100644 --- a/packages/api-extractor/src/verdict.cell.ts +++ b/packages/api-extractor/src/verdict.cell.ts @@ -1,11 +1,10 @@ import { Sandwich } from '@systemfsoftware/effect-cell-types' -import { Effect } from 'effect' -import { canonicalJson } from './canonical-json.schema.js' +import { Effect, Schema } from 'effect' import { judgeSurfaces } from './judge-surfaces.workflow.js' import type { ApiModel } from './model/api-model.schema.js' import type { RuleCorpus } from './rules/corpus.schema.js' import { defaultCorpus } from './rules/default-corpus.js' -import { RuleCorpusRejected, SurfaceRejected, type Verdict } from './verdict.schema.js' +import { RuleCorpusRejected, SurfaceRejected, Verdict } from './verdict.schema.js' import { ENGINE } from './version.js' /** Two encoded surfaces of one package, and the corpus to judge them by (the shipped one when absent). */ @@ -20,7 +19,7 @@ export type VerdictInput = { * stamped with this engine. Both surfaces and the corpus are decoded before the * decision sees them. */ -export const verdictCell: Sandwich.WrittenCell = Sandwich.named( +export const verdictCell: Sandwich.WrittenCell = Sandwich.named( 'api_extractor.verdict', )((input: VerdictInput) => // The encoded command, not `new CompareSurfaces(...)`: the constructor validates and would throw @@ -35,7 +34,7 @@ export const verdictCell: Sandwich.WrittenCell Effect.succeed(canonicalJson(verdict)), + Verdict: (verdict) => Schema.encodeEffect(Schema.fromJsonString(Schema.toEncoded(Verdict), { space: 2 }))(verdict), AmbiguousRuleCorpus: ({ corpusVersion, ambiguities }) => Effect.fail(new RuleCorpusRejected({ corpusVersion, ambiguities })), CommandRejected: ({ issue }) => Effect.fail(new SurfaceRejected({ issue })), }) diff --git a/packages/api-extractor/src/verdict.schema.ts b/packages/api-extractor/src/verdict.schema.ts index 0f2e55ac..b27cee62 100644 --- a/packages/api-extractor/src/verdict.schema.ts +++ b/packages/api-extractor/src/verdict.schema.ts @@ -41,6 +41,11 @@ export const Verdict: Schema.Class = Schem }) Object.defineProperty(Verdict.prototype, VerdictTypeId, { value: VerdictTypeId }) +export type VerdictFromJsonText = Schema.Codec + +/** The verdict document's canonical JSON-text encoding: the one writer and reader of the emitted bytes. */ +export const VerdictFromJsonText: VerdictFromJsonText = Schema.fromJsonString(Verdict, { space: 2 }) + type CorpusAmbiguityFields = { readonly corpusVersion: Schema.String readonly ambiguities: Schema.$Array diff --git a/packages/api-extractor/tests/__fixtures__/json-text.ts b/packages/api-extractor/tests/__fixtures__/json-text.ts index c24b8582..65ac442e 100644 --- a/packages/api-extractor/tests/__fixtures__/json-text.ts +++ b/packages/api-extractor/tests/__fixtures__/json-text.ts @@ -1,5 +1,5 @@ import { Result, Schema } from 'effect' -const codec = Schema.fromJsonString(Schema.Unknown) +const codec = Schema.fromJsonString(Schema.Json, { space: 2 }) -export const jsonText = (value: object): string => Result.getOrThrow(Schema.encodeResult(codec)(value)) +export const jsonText = (value: Schema.Json): string => Result.getOrThrow(Schema.encodeResult(codec)(value)) diff --git a/packages/api-extractor/tests/__fixtures__/surfaces.ts b/packages/api-extractor/tests/__fixtures__/surfaces.ts index 0d2d13d0..b5c05e7e 100644 --- a/packages/api-extractor/tests/__fixtures__/surfaces.ts +++ b/packages/api-extractor/tests/__fixtures__/surfaces.ts @@ -94,7 +94,7 @@ export const empty: Model = rooted({ entryPoints: [], }) -export const decodeVerdict = (document: string) => Schema.decodeResult(Schema.fromJsonString(Verdict.Verdict))(document) +export const decodeVerdict = (document: string) => Schema.decodeResult(Verdict.VerdictFromJsonText)(document) export const rootedWith: { (model: Model, items: ReadonlyArray, locals?: ReadonlyArray): Model diff --git a/packages/api-extractor/tests/doc-model.integration.test.ts b/packages/api-extractor/tests/doc-model.integration.test.ts index 0119d722..5f20a673 100644 --- a/packages/api-extractor/tests/doc-model.integration.test.ts +++ b/packages/api-extractor/tests/doc-model.integration.test.ts @@ -100,7 +100,7 @@ Feature('Formatting the doc model and tsdoc metadata') Gherkin.Do.pipe( Given('a package model with a class, an internal value and a namespace')('model', () => Effect.succeed(modelOf())), When('the doc model is formatted and deserialized')('decoded', (scope) => - deserializeEffectOf(FrontEnd.formatDocModel({ model: scope.model })), + Effect.flatMap(Effect.fromResult(FrontEnd.formatDocModel({ model: scope.model })), deserializeEffectOf), ), Then('the package kind and the entry point item names come back')((scope, expect) => expect({ kind: scope.decoded.kind, names: entryNamesOf(scope.decoded) }).toEqual({ @@ -115,7 +115,7 @@ Feature('Formatting the doc model and tsdoc metadata') Gherkin.Do.pipe( Given('a package model with an internal value')('model', () => Effect.succeed(modelOf())), When('the doc model is formatted trimming @internal')('json', (scope) => - Effect.sync(() => FrontEnd.formatDocModel({ model: scope.model, releaseTagsToTrim: ['@internal'] })), + Effect.fromResult(FrontEnd.formatDocModel({ model: scope.model, releaseTagsToTrim: ['@internal'] })), ), Then('the internal value is absent and the public class is present')((scope, expect) => expect({ @@ -129,7 +129,7 @@ Feature('Formatting the doc model and tsdoc metadata') 'the tsdoc metadata names the tool package and its version', Gherkin.Do.pipe( Given('the engine run')('nothing', () => Effect.void), - When('the metadata is formatted')('metadata', () => Effect.sync(() => FrontEnd.formatTsdocMetadata())), + When('the metadata is formatted')('metadata', () => Effect.fromResult(FrontEnd.formatTsdocMetadata())), Then('it carries the tsdoc version and the tool package')((scope, expect) => expect({ hasTsdocVersion: scope.metadata.includes('0.12'), diff --git a/packages/api-extractor/tests/front-end-model.integration.test.ts b/packages/api-extractor/tests/front-end-model.integration.test.ts index c30a8ebc..68f82ced 100644 --- a/packages/api-extractor/tests/front-end-model.integration.test.ts +++ b/packages/api-extractor/tests/front-end-model.integration.test.ts @@ -1,6 +1,6 @@ import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' import { ApiModel, FrontEnd } from '@systemfsoftware/api-extractor' -import { Effect } from 'effect' +import { Effect, Schema } from 'effect' import { isolatedDeclarationSync } from 'oxc-transform' import { builtOf, declarations, entryAt, itemOf, itemsNamed, type Model } from './__fixtures__/declarations.js' @@ -259,7 +259,14 @@ Feature('Building a package API model from its declaration text') ]), )), When('the model is built and encoded')('roundTrip', (scope) => - Effect.map(FrontEnd.buildModel(scope.declarations), (model) => ({ model, decoded: ApiModel.decode(ApiModel.encode(model)) }))), + Effect.flatMap(FrontEnd.buildModel(scope.declarations), (model) => + Effect.map( + Effect.flatMap(Schema.encodeEffect(ApiModel.ApiModelFromJsonText)(model), (bytes) => + Schema.decodeEffect(ApiModel.ApiModelFromJsonText)(bytes), + ), + (decoded) => ({ model, decoded }), + ), + )), Then('decoding the bytes restores schema version four')((scope, expect) => expect({ built: scope.roundTrip.model.schemaVersion, diff --git a/packages/api-extractor/tests/front-end-routing-disk.integration.test.ts b/packages/api-extractor/tests/front-end-routing-disk.integration.test.ts index 09b3670d..20803046 100644 --- a/packages/api-extractor/tests/front-end-routing-disk.integration.test.ts +++ b/packages/api-extractor/tests/front-end-routing-disk.integration.test.ts @@ -1,10 +1,17 @@ import { NodeServices } from '@effect/platform-node' import { ApiModel, FrontEnd } from '@systemfsoftware/api-extractor' import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' -import { Effect, Layer, Path } from 'effect' +import { Effect, Layer, Path, Schema } from 'effect' const Feature = makeFeature({ it }) +const roundTripped = (model: ApiModel.ApiModel): ApiModel.ApiModel => + Effect.runSync( + Effect.flatMap(Schema.encodeEffect(ApiModel.ApiModelFromJsonText)(model), (bytes) => + Schema.decodeEffect(ApiModel.ApiModelFromJsonText)(bytes), + ), + ) + const emitters = Layer.mergeAll(FrontEnd.isolatedEmitterLayer, FrontEnd.compilerEmitterLayer).pipe( Layer.provideMerge(FrontEnd.operatingSystemFiles), Layer.provideMerge(Layer.mergeAll(FrontEnd.declarationParserLayer, NodeServices.layer)), @@ -36,7 +43,7 @@ Feature('A package is routed to the front-end its declarations allow') producer: scope.analysis.model.producer.declarations, entryPoints: scope.analysis.model.entryPoints.map((entry) => entry.path), exports: scope.analysis.model.entryPoints.flatMap((entry) => entry.items.map((item) => `${item.kind}:${item.name}`)), - decoded: ApiModel.decode(ApiModel.encode(scope.analysis.model)), + decoded: roundTripped(scope.analysis.model), }).toEqual({ route: 'FastPath', producer: FrontEnd.OXC_TRANSFORM_PRODUCER, diff --git a/packages/api-extractor/tests/front-end-routing.integration.test.ts b/packages/api-extractor/tests/front-end-routing.integration.test.ts index 7d700de0..a3f6f0f4 100644 --- a/packages/api-extractor/tests/front-end-routing.integration.test.ts +++ b/packages/api-extractor/tests/front-end-routing.integration.test.ts @@ -1,6 +1,6 @@ import { FrontEnd } from '@systemfsoftware/api-extractor' import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' -import { Effect, FileSystem, Layer, Path } from 'effect' +import { Effect, FileSystem, Layer, Path, Schema } from 'effect' import { jsonText } from './__fixtures__/json-text.js' import { memoryFileSystem, memoryPath } from './__fixtures__/memory-file-system.js' @@ -13,7 +13,7 @@ const emitters = Layer.mergeAll(FrontEnd.isolatedEmitterLayer, FrontEnd.compiler Layer.provideMerge(Layer.mergeAll(FrontEnd.declarationParserLayer, memory.layer, memoryPath)), ) -const packageOf = (manifest: object, sources: Record) => +const packageOf = (manifest: Schema.Json, sources: Record) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path diff --git a/packages/api-extractor/tests/package-reader.integration.test.ts b/packages/api-extractor/tests/package-reader.integration.test.ts index 3eb47055..8ea93225 100644 --- a/packages/api-extractor/tests/package-reader.integration.test.ts +++ b/packages/api-extractor/tests/package-reader.integration.test.ts @@ -1,6 +1,6 @@ import { FrontEnd } from '@systemfsoftware/api-extractor' import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' -import { Effect, FileSystem, Layer, Path } from 'effect' +import { Effect, FileSystem, Layer, Path, Schema } from 'effect' import { jsonText } from './__fixtures__/json-text.js' import { memoryFileSystem, memoryPath } from './__fixtures__/memory-file-system.js' @@ -18,7 +18,7 @@ const writeSource = (root: string) => yield* fileSystem.writeFileString(target, text) }) -const packageOf = (exports: object, sources: Record) => +const packageOf = (exports: Schema.Json, sources: Record) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path diff --git a/packages/api-extractor/tests/serialise.integration.test.ts b/packages/api-extractor/tests/serialise.integration.test.ts index dc553c58..2e59b740 100644 --- a/packages/api-extractor/tests/serialise.integration.test.ts +++ b/packages/api-extractor/tests/serialise.integration.test.ts @@ -13,7 +13,10 @@ const type: Item = { kind: 'typeAlias', name: 'Shared', typeParameters: [], type const first: Item = functionItem(signature([], ref('A'))) const second: Item = functionItem(signature([], ref('B'))) -const bytePairs = (left: Model, right: Model) => ({ left: ApiModel.serialise(left), right: ApiModel.serialise(right) }) +const bytePairs = (left: Model, right: Model) => + Effect.gen(function* () { + return { left: yield* encodeBytes(left), right: yield* encodeBytes(right) } + }) const SAMPLE_COUNT = 50 const sample = Arbitrary.sampleEffect(Arbitrary.schema(ApiModel.ApiModel), { count: SAMPLE_COUNT, seed: 20261010 }) @@ -23,9 +26,15 @@ const reversed = (model: Model): Model => ({ entryPoints: [...model.entryPoints].reverse().map((entry) => ({ ...entry, items: [...entry.items].reverse() })), }) -const decodeBytes = Schema.decodeEffect(Schema.fromJsonString(ApiModel.ApiModel)) +const encodeBytes = ApiModel.serialise + +const decodeBytes = Schema.decodeEffect(ApiModel.ApiModelFromJsonText) -const roundOf = (bytes: string) => Effect.map(decodeBytes(bytes), (decoded) => ({ bytes, again: ApiModel.serialise(decoded) })) +const roundOf = (bytes: string) => + Effect.gen(function* () { + const decoded = yield* decodeBytes(bytes) + return { bytes, again: yield* encodeBytes(decoded) } + }) const otherVersion: Schema.Json = { schemaVersion: 2, @@ -42,7 +51,7 @@ Feature('The serialised model is a canonical, versioned form of the surface') Gherkin.Do.pipe( Given('a fixed sample of generated models')('models', () => sample), When('each model is serialised, decoded and serialised again')('rounds', (scope) => - Effect.forEach(scope.models.map((model) => ApiModel.serialise(model)), roundOf), + Effect.forEach(scope.models, (model) => Effect.flatMap(encodeBytes(model), roundOf)), ), Then('every second serialisation equals the first')((scope, expect) => expect(scope.rounds.filter((round) => round.again !== round.bytes)).toEqual([]), @@ -54,7 +63,7 @@ Feature('The serialised model is a canonical, versioned form of the surface') 'every generated model serialises the same whatever order its exports arrive in', Gherkin.Do.pipe( Given('a fixed sample of generated models')('models', () => sample), - When('each model and its reversal are serialised')('pairs', (scope) => Effect.sync(() => scope.models.map((model) => bytePairs(model, reversed(model))))), + When('each model and its reversal are serialised')('pairs', (scope) => Effect.forEach(scope.models, (model) => bytePairs(model, reversed(model)))), Then('every pair of byte strings is equal')((scope, expect) => expect(scope.pairs.filter((pair) => pair.left !== pair.right)).toEqual([])), ), ) @@ -65,7 +74,7 @@ Feature('The serialised model is a canonical, versioned form of the surface') Given('two models storing the same two exports in opposite order')('models', () => Effect.sync(() => ({ left: rootedWith(empty, [first, second]), right: rootedWith(empty, [second, first]) })), ), - When('each model is serialised to canonical bytes')('bytes', (scope) => Effect.sync(() => bytePairs(scope.models.left, scope.models.right))), + When('each model is serialised to canonical bytes')('bytes', (scope) => bytePairs(scope.models.left, scope.models.right)), Then('the two byte strings are equal')((scope, expect) => expect(scope.bytes.left).toBe(scope.bytes.right)), ), ) @@ -76,7 +85,7 @@ Feature('The serialised model is a canonical, versioned form of the surface') Given('a value and a type sharing a name, stored in either order')('models', () => Effect.sync(() => ({ left: rootedWith(empty, [value, type]), right: rootedWith(empty, [type, value]) })), ), - When('each model is serialised to canonical bytes')('bytes', (scope) => Effect.sync(() => bytePairs(scope.models.left, scope.models.right))), + When('each model is serialised to canonical bytes')('bytes', (scope) => bytePairs(scope.models.left, scope.models.right)), Then('the two byte strings are equal')((scope, expect) => expect(scope.bytes.left).toBe(scope.bytes.right)), ), ) @@ -85,12 +94,10 @@ Feature('The serialised model is a canonical, versioned form of the surface') 'a model declaring an older schema version is refused', Gherkin.Do.pipe( Given('an encoded model declaring schema version 2')('encoded', () => Effect.succeed(otherVersion)), - When('the model is decoded')('refusal', (scope) => - Effect.flip(Effect.try({ try: () => ApiModel.decode(scope.encoded), catch: String })), - ), + When('the model is decoded')('refusal', (scope) => Effect.flip(Schema.decodeUnknownEffect(ApiModel.ApiModel)(scope.encoded))), Then('the refusal names the schema version')((scope, expect) => expect(scope.refusal).toSatisfy( - (message: string) => message.includes('schemaVersion'), + (refusal: Schema.SchemaError) => refusal.message.includes('schemaVersion'), 'the refusal names schemaVersion', ), ), diff --git a/packages/api-extractor/tests/verdict.integration.test.ts b/packages/api-extractor/tests/verdict.integration.test.ts index f532ac07..1c7adb9a 100644 --- a/packages/api-extractor/tests/verdict.integration.test.ts +++ b/packages/api-extractor/tests/verdict.integration.test.ts @@ -41,27 +41,6 @@ const named = (name: string, type: ReturnType): Item => ({ kind: 'fu Feature('The verdict cell judges two surfaces and refuses the ones it cannot') .withLayer(Layer.empty) .body(({ scenario, scenarioOutline }) => { - scenario( - 'a widened error channel produces a canonical verdict document', - Gherkin.Do.pipe( - Given('two surfaces whose returned error channel gains a tag')('surfaces', () => Effect.sync(() => ({ before, after }))), - When('the verdict cell judges them')('document', (scope) => Verdict.cell.run(scope.surfaces)), - Then('the document is canonical JSON naming the widened error')((scope, expect) => - expect({ - terminated: scope.document.endsWith('}\n'), - body: Result.getOrThrow(decodeVerdict(scope.document)), - }).toMatchObject({ - terminated: true, - body: { - _tag: 'Verdict', - bump: 'major', - findings: [{ reason_code: 'E_WIDENED', locations: ['.:target/signature[0]/returns/E'] }], - }, - }), - ), - ), - ) - scenario( 'a verdict decoded from the document carries the family brand', Gherkin.Do.pipe( diff --git a/packages/api-extractor/vitest.config.ts b/packages/api-extractor/vitest.config.ts index a1f9b84e..f176d447 100644 --- a/packages/api-extractor/vitest.config.ts +++ b/packages/api-extractor/vitest.config.ts @@ -1,9 +1,9 @@ -import { recursionBudgetTransform } from '@systemfsoftware/effect-schema-recursion-budget' +import { inlineSchemaTests } from '@systemfsoftware/effect-schema-vite' import { defineConfig, sharedConfig } from '@systemfsoftware/vitest-config' export default defineConfig({ ...sharedConfig, - plugins: [recursionBudgetTransform()], + plugins: [inlineSchemaTests()], test: { ...sharedConfig.test, include: ['src/**/*.test.ts', 'tests/**/*.test.ts'],