From 793bf7ab0a5f6651a39ebb501bf3d7a849afa532 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:06:10 -0500 Subject: [PATCH 1/9] wip: codecs --- .changeset/codec-standard.md | 22 +++ .../tests/__fixtures__/json-text.ts | 7 +- .../tests/front-ends.integration.test.ts | 11 +- apps/api-extractor-profile/profile.ts | 89 ++++----- packages/api-extractor/src/ApiModel.ts | 3 +- packages/api-extractor/src/FrontEnd.ts | 3 + packages/api-extractor/src/Json.ts | 7 + packages/api-extractor/src/Verdict.ts | 3 +- .../src/canonical-json.schema.ts | 124 ++++++++---- packages/api-extractor/src/cli.ts | 7 +- .../src/front-end/canonical-type-text.ts | 7 +- .../src/front-end/export-target.schema.ts | 46 +++++ .../src/front-end/package-source.schema.ts | 66 ++----- .../src/front-end/read-package.ts | 5 +- .../api-extractor/src/input/config-file.ts | 3 +- .../src/input/node-extraction-input.ts | 3 +- packages/api-extractor/src/mod.ts | 1 + .../src/model/api-model.schema.ts | 32 ++- packages/api-extractor/src/model/serialise.ts | 13 +- .../api-extractor/src/output/doc-model.ts | 6 +- .../src/output/tsdoc-metadata.ts | 5 +- .../src/pipeline/extract-package.blueprint.ts | 2 + .../src/pipeline/extract-surface.cell.ts | 25 +-- .../api-extractor/src/rules/corpus.schema.ts | 20 +- .../api-extractor/src/rules/default-corpus.ts | 8 +- .../api-extractor/src/schema-laws.test.ts | 185 ++++++++++++++++++ packages/api-extractor/src/verdict.cell.ts | 9 +- packages/api-extractor/src/verdict.schema.ts | 6 + .../tests/__fixtures__/json-text.ts | 7 +- .../tests/__fixtures__/surfaces.ts | 2 +- .../tests/doc-model.integration.test.ts | 6 +- .../tests/front-end-model.integration.test.ts | 11 +- ...front-end-routing-disk.integration.test.ts | 11 +- .../tests/serialise.integration.test.ts | 29 +-- packages/api-extractor/vitest.config.ts | 4 +- 35 files changed, 552 insertions(+), 236 deletions(-) create mode 100644 .changeset/codec-standard.md create mode 100644 packages/api-extractor/src/Json.ts create mode 100644 packages/api-extractor/src/front-end/export-target.schema.ts create mode 100644 packages/api-extractor/src/schema-laws.test.ts diff --git a/.changeset/codec-standard.md b/.changeset/codec-standard.md new file mode 100644 index 000000000..1f950228f --- /dev/null +++ b/.changeset/codec-standard.md @@ -0,0 +1,22 @@ +--- +"@systemfsoftware/api-extractor": minor +--- + +Every encoding now has one codec that holds both its writer and its reader, and +no published encode or decode throws. + +- `ApiModel.ApiModelFromJsonText` replaces `decode`, `encode` and `serialise`. + Decode accepts any JSON key order; encode orders items and keys canonically. + `ApiModel.decode`, `ApiModel.encode` and `ApiModel.serialise` are removed. +- `Verdict.RuleCorpusFromJsonText`, `Verdict.VerdictFromJsonText`, + `FrontEnd.PackageManifestFromJsonText` and + `FrontEnd.ExportTargetFromPackageExports` replace `decodeRuleCorpus` and + `ExportTargetCodec`. +- `Json` is a new namespace: `JsonFromJsonText` (the reader and canonical writer + of JSON text), `canonicalJson` (a `Result`) and `CanonicalJsonRejected`. +- `FrontEnd.formatDocModel` and `FrontEnd.formatTsdocMetadata` return a + `Result` instead of a `string`, and `Verdict.cell` reports a schema error on + its write channel. Callers propagate the typed failures. + +The serialised model's bytes and `API_MODEL_SCHEMA_VERSION` are unchanged. +Breaking for pre-1.0 consumers. diff --git a/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts b/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts index c24b8582d..c1f483a76 100644 --- a/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts +++ b/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts @@ -1,5 +1,4 @@ -import { Result, Schema } from 'effect' +import { Json } from '@systemfsoftware/api-extractor' +import { Result } from 'effect' -const codec = Schema.fromJsonString(Schema.Unknown) - -export const jsonText = (value: object): string => Result.getOrThrow(Schema.encodeResult(codec)(value)) +export const jsonText = (value: object): string => Result.getOrThrow(Json.canonicalJson(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 f691bd4e9..830dd31e6 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, @@ -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 f11ca2498..f1e94da0d 100644 --- a/apps/api-extractor-profile/profile.ts +++ b/apps/api-extractor-profile/profile.ts @@ -1,5 +1,5 @@ import { NodeRuntime, NodeServices } from '@effect/platform-node' -import { type ApiModel, FrontEnd } from '@systemfsoftware/api-extractor' +import { type ApiModel, FrontEnd, Json } from '@systemfsoftware/api-extractor' import { Array as Arr, Duration, Effect, FileSystem, Layer, Option, Order, Path, Result, Schema, Stream } from 'effect' import type { PlatformError } from 'effect/PlatformError' import { ChildProcess, ChildProcessSpawner } from 'effect/process' @@ -28,7 +28,7 @@ const Manifest = Schema.Struct({ }) type Manifest = typeof Manifest.Type -type ProfileError = PlatformError | Schema.SchemaError | UsageError | GitError +type ProfileError = PlatformError | Schema.SchemaError | UsageError | GitError | Json.CanonicalJsonRejected class UsageError extends Schema.TaggedError()('UsageError', { usage: Schema.String }) {} @@ -81,7 +81,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(Json.JsonFromJsonText)(text) + return yield* Schema.decodeUnknownEffect(Manifest)(json) }) const RELATIVE = /^\.\.?\// @@ -160,28 +161,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(Json.canonicalJson({ + 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 }) @@ -421,29 +420,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(Json.canonicalJson(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 +469,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(Json.canonicalJson(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/src/ApiModel.ts b/packages/api-extractor/src/ApiModel.ts index e48f185f4..8b71a648d 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 2b86a8c47..3e318e20d 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/Json.ts b/packages/api-extractor/src/Json.ts new file mode 100644 index 000000000..084131901 --- /dev/null +++ b/packages/api-extractor/src/Json.ts @@ -0,0 +1,7 @@ +export { + canonicalJson, + CanonicalJsonRejected, + canonicalJsonTextOf, + type Json, + JsonFromJsonText, +} from './canonical-json.schema.js' diff --git a/packages/api-extractor/src/Verdict.ts b/packages/api-extractor/src/Verdict.ts index f426d7967..401b8e1b2 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/canonical-json.schema.ts b/packages/api-extractor/src/canonical-json.schema.ts index 40dfa0d05..5a582360a 100644 --- a/packages/api-extractor/src/canonical-json.schema.ts +++ b/packages/api-extractor/src/canonical-json.schema.ts @@ -2,84 +2,91 @@ * 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. + * + * `JsonFromJsonText` is the JSON-text codec: decode parses any key order and + * encode writes canonical text (object keys in code-unit order, two-space + * indentation, trailing newline). The transform is subtractive: decode accepts + * any JSON text; encode emits one canonical form. A non-finite number cannot be + * written as JSON, so it is refused as `CanonicalJsonRejected`, never thrown. */ -import { Match, Order, Predicate, Result, Schema } from 'effect' +import { Effect, Match, Order, Predicate, Result, Schema, SchemaGetter, SchemaIssue, SchemaParser } from 'effect' +import type { Cause } 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] +type CanonicalJsonRejectedFields = { readonly issue: Schema.String } -const byKey: Order.Order = Order.mapInput(Order.String, ([key]: Entry) => key) +const CanonicalJsonRejectedBase: Schema.Class, Cause.YieldableError> = + Schema.TaggedError()('CanonicalJsonRejected', { issue: Schema.String }) -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) +/** A value that canonical JSON cannot carry, refused instead of thrown. */ +export class CanonicalJsonRejected extends CanonicalJsonRejectedBase { + override get message(): string { + return `the value cannot be written as canonical JSON: ${this.issue}` + } +} 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 isJsonArray = (value: Json): value is Schema.JsonArray => Array.isArray(value) -const textOfScalar = (scalar: Scalar): string => scalarText.get(scalar) ?? rememberScalar(scalar) +const isJsonObject = (value: Json): value is Schema.JsonObject => Predicate.isObject(value) && !isJsonArray(value) -const writeNumber = (value: number): string => { - if (!Number.isFinite(value)) throw new TypeError(`canonicalJson: non-finite number ${value}`) - return textOfScalar(value) -} +type Entry = readonly [string, Json] + +const byKey: Order.Order = Order.mapInput(Order.String, ([key]: Entry) => key) + +/** The members of an object, ordered by key code unit. */ +const entriesOf = (value: Schema.JsonObject): ReadonlyArray => Object.entries(value).sort(byKey) + +const textOfScalar = (scalar: Scalar): string => encodeText(scalar) -const writeArray = (items: Schema.JsonArray, indent: string): string => { +const writeNumber = (value: number): Result.Result => + Number.isFinite(value) + ? Result.succeed(textOfScalar(value)) + : Result.fail(new CanonicalJsonRejected({ issue: `the number ${value} is not finite` })) + +const writeArray = (items: Schema.JsonArray, indent: string): Result.Result => { const inner = `${indent} ` - return items.length === 0 ? '[]' : `[\n${items.map((item) => inner + write(item, inner)).join(',\n')}\n${indent}]` + return items.length === 0 + ? Result.succeed('[]') + : Result.map(Result.all(items.map((item) => write(item, inner))), (parts) => `[\n${parts.map((part) => inner + part).join(',\n')}\n${indent}]`) } -const writeObject = (value: Schema.JsonObject, indent: string): string => { +const writeObject = (value: Schema.JsonObject, indent: string): Result.Result => { 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}}` + ? Result.succeed('{}') + : Result.map( + Result.all(entries.map(([key, member]) => Result.map(write(member, inner), (part) => `${inner}${textOfScalar(key)}: ${part}`))), + (lines) => `{\n${lines.join(',\n')}\n${indent}}`, + ) } -const write = (value: Json, indent: string): string => +const write = (value: Json, indent: string): Result.Result => 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), + Match.orElse((scalar) => Result.succeed(textOfScalar(scalar))), ) /** Serialises a JSON value with sorted keys, two-space indentation and a trailing newline. */ -export const canonicalJson = (value: Json): string => `${write(value, '')}\n` +export const canonicalJson = (value: Json): Result.Result => + Result.map(write(value, ''), (text) => `${text}\n`) + +const numberKey = (value: number): string => (Number.isFinite(value) ? textOfScalar(value) : String(value)) const writeCompact = (value: Json): string => Match.value(value).pipe( - Match.when(Match.number, writeNumber), + Match.when(Match.number, numberKey), Match.when(isJsonArray, (items) => `[${items.map(writeCompact).join(',')}]`), Match.when(isJsonObject, (object) => `{${entriesOf(object).map(([key, member]) => `${textOfScalar(key)}:${writeCompact(member)}`).join(',')}}`), @@ -88,3 +95,36 @@ const writeCompact = (value: Json): string => /** The same ordering on one line: a structural identity key. */ export const canonicalKey = (value: Json): string => writeCompact(value) + +const canonicalText = (value: Json): Effect.Effect => + Result.match(canonicalJson(value), { + onFailure: (error) => Effect.fail(new SchemaIssue.InvalidValue({ message: error.message }, value)), + onSuccess: Effect.succeed, + }) + +export type JsonFromJsonText = Schema.Codec + +/** The JSON text encoding: decode parses any JSON text, encode writes canonical bytes. */ +export const JsonFromJsonText: JsonFromJsonText = Schema.String.pipe( + Schema.decodeTo(Schema.Json, { + decode: SchemaGetter.parseJson(), + encode: SchemaGetter.transformEffect(canonicalText), + }), +) + +export type CanonicalJsonTextOf = Schema.Codec + +/** + * The canonical JSON-text encoding of any codec: decode parses any key order and + * validates, encode writes canonical bytes. This is the codec a module exports + * as `FromJsonText`. + */ +export const canonicalJsonTextOf = (schema: Schema.Codec): CanonicalJsonTextOf => + Schema.fromJsonString(schema).pipe( + Schema.encode({ + decode: SchemaGetter.passthrough(), + encode: SchemaGetter.transformEffect((text: string) => + Effect.flatMap(SchemaParser.decodeEffect(JsonFromJsonText)(text), SchemaParser.encodeEffect(JsonFromJsonText)), + ), + }), + ) diff --git a/packages/api-extractor/src/cli.ts b/packages/api-extractor/src/cli.ts index 6d0b859ef..08a5727fc 100644 --- a/packages/api-extractor/src/cli.ts +++ b/packages/api-extractor/src/cli.ts @@ -1,7 +1,7 @@ import { Effect, FileSystem, Layer, Option, Path } from 'effect' import type { PlatformError } from 'effect/PlatformError' import { NodeServices, NodeRuntime } from '@effect/platform-node' -import { canonicalJson } from './canonical-json.schema.js' +import { canonicalJson, type CanonicalJsonRejected } 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 +84,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 +95,8 @@ const initialize = (path: Path.Path) => (folder: string): Effect.Effect process.stdout.write(`Writing configuration file: ${file}\n`)) }) 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 e8c2a1679..cee909ff7 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 } from 'effect' import type { BindingPattern, Expression, @@ -38,7 +38,7 @@ import type { TSTypeReference, TemplateElement, } from 'oxc-parser' -import { jsonText } from '../canonical-json.schema.js' +import { canonicalJson } from '../canonical-json.schema.js' import { KeywordName } from '../model/type-expr.schema.js' import { type Declaration, @@ -51,6 +51,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(Result.map(canonicalJson(value), (text) => text.slice(0, -1))) + 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 000000000..4f06c9975 --- /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 8c97d843e..6c0a1d8c2 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,16 @@ import { Match, Predicate, Schema, SchemaTransformation } from 'effect' +import { canonicalJsonTextOf } from '../canonical-json.schema.js' +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 +41,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 = canonicalJsonTextOf(PackageManifest) diff --git a/packages/api-extractor/src/front-end/read-package.ts b/packages/api-extractor/src/front-end/read-package.ts index 9fe2ec207..d0fb23879 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 8662b67db..b2a69c71f 100644 --- a/packages/api-extractor/src/input/config-file.ts +++ b/packages/api-extractor/src/input/config-file.ts @@ -1,5 +1,6 @@ import { Effect, FileSystem, Function as Fn, Match, Option, Path, Schema } from 'effect' import type { PlatformError } from 'effect/PlatformError' +import { JsonFromJsonText } from '../canonical-json.schema.js' import { isAbsent } from '../front-end/package-file.js' import { type JsonObject, isJsonObject } from './config-merge.js' import { ConfigRejected } from './extraction-input-error.schema.js' @@ -11,7 +12,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(JsonFromJsonText) 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 0d325b814..e4adb28a8 100644 --- a/packages/api-extractor/src/input/node-extraction-input.ts +++ b/packages/api-extractor/src/input/node-extraction-input.ts @@ -1,5 +1,6 @@ import { Array as Arr, Effect, FileSystem, Layer, Option, Path, Predicate, Schema } from 'effect' import type { PlatformError } from 'effect/PlatformError' +import { JsonFromJsonText } from '../canonical-json.schema.js' import type { CompilerOverride, PackageSource, SourceEntryPoint } from '../front-end/declarations.schema.js' import { type ManifestRejected, NoSourceEntry } from '../front-end/front-end-error.schema.js' import { readPackage } from '../front-end/read-package.js' @@ -103,7 +104,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(JsonFromJsonText)(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/mod.ts b/packages/api-extractor/src/mod.ts index 8b317c21d..6fcaef99f 100644 --- a/packages/api-extractor/src/mod.ts +++ b/packages/api-extractor/src/mod.ts @@ -1,4 +1,5 @@ export * as ApiModel from './ApiModel.js' export * as Extractor from './Extractor.js' export * as FrontEnd from './FrontEnd.js' +export * as Json from './Json.js' export * as Verdict from './Verdict.js' diff --git a/packages/api-extractor/src/model/api-model.schema.ts b/packages/api-extractor/src/model/api-model.schema.ts index 5f78bfe12..3c55b6dcf 100644 --- a/packages/api-extractor/src/model/api-model.schema.ts +++ b/packages/api-extractor/src/model/api-model.schema.ts @@ -1,5 +1,5 @@ -import { Array as Arr, Cause, Exit, Order, Schema } from 'effect' -import { canonicalKey, type Json } from '../canonical-json.schema.js' +import { Array as Arr, Order, Schema } from 'effect' +import { canonicalJsonTextOf, canonicalKey } from '../canonical-json.schema.js' import { type DocComment, DocComment as DocCommentCodec, ReleaseTag } from './doc-comment.schema.js' import { Member, Signature, TypeExpr, TypeParameter } from './type-expr.schema.js' @@ -171,24 +171,6 @@ 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, - }) - -/** 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, - }) - /** 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), @@ -215,3 +197,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 canonical code-unit 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 = canonicalJsonTextOf(ApiModel) diff --git a/packages/api-extractor/src/model/serialise.ts b/packages/api-extractor/src/model/serialise.ts index 404f2fd6d..f3955bc4c 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/output/doc-model.ts b/packages/api-extractor/src/output/doc-model.ts index 4f5fd762b..816f9b095 100644 --- a/packages/api-extractor/src/output/doc-model.ts +++ b/packages/api-extractor/src/output/doc-model.ts @@ -1,5 +1,5 @@ -import { Match, Option } from 'effect' -import { canonicalJson, type Json } from '../canonical-json.schema.js' +import { Match, Option, Result } from 'effect' +import { canonicalJson, CanonicalJsonRejected, type Json } from '../canonical-json.schema.js' 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 +288,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 b543d0414..aed2f06e3 100644 --- a/packages/api-extractor/src/output/tsdoc-metadata.ts +++ b/packages/api-extractor/src/output/tsdoc-metadata.ts @@ -1,4 +1,5 @@ -import { canonicalJson, type Json } from '../canonical-json.schema.js' +import { type Result } from 'effect' +import { canonicalJson, type CanonicalJsonRejected, type Json } from '../canonical-json.schema.js' import { ENGINE } from '../version.js' const TSDOC_VERSION = '0.12' @@ -13,4 +14,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 0105dc6af..e6dcc22e2 100644 --- a/packages/api-extractor/src/pipeline/extract-package.blueprint.ts +++ b/packages/api-extractor/src/pipeline/extract-package.blueprint.ts @@ -1,6 +1,7 @@ import { Blueprint } from '@systemfsoftware/effect-cell-types' import { Effect } from 'effect' import type { CompilerRejected, CompilerUnavailable, ManifestRejected, NoSourceEntry, NotIsolated, UnsupportedDeclaration } from '../front-end/front-end-error.schema.js' +import type { CanonicalJsonRejected } from '../canonical-json.schema.js' import type { ConfigRejected } from '../input/extraction-input-error.schema.js' import type { Platform } from '../input/config-file.js' import type { PlatformError } from 'effect/PlatformError' @@ -21,6 +22,7 @@ export type ExtractPackageError = | RollupRejected | UnsupportedDeclaration | PlatformError + | CanonicalJsonRejected 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 304a331e6..1d5686b0a 100644 --- a/packages/api-extractor/src/pipeline/extract-surface.cell.ts +++ b/packages/api-extractor/src/pipeline/extract-surface.cell.ts @@ -2,6 +2,7 @@ import { Array as Arr, Effect, FileSystem, Option, Path, Schema } from 'effect' import { TSDocConfigFile } from '@microsoft/tsdoc-config' import type { PlatformError } from 'effect/PlatformError' import type { ApiModel } from '../model/api-model.schema.js' +import type { CanonicalJsonRejected } from '../canonical-json.schema.js' import { analyseWith } from '../front-end/analyse.js' import { messageRoutingOf, reportWarnings } from '../front-end/message-reporting.js' import type { CompilerEmitterId, IsolatedEmitterId } from '../front-end/declaration-emitter.service.js' @@ -17,7 +18,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 | CanonicalJsonRejected export type SurfaceServices = FileSystem.FileSystem | Path.Path | IsolatedEmitterId | CompilerEmitterId | DeclarationParserId | RollupBundlerId @@ -85,22 +86,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, CanonicalJsonRejected> => 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, CanonicalJsonRejected> => + 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 +175,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 = canonicalJsonTextOf(RuleCorpus) /** 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 bb52d03cd..f1ce561ff 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.decodeEffect(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 000000000..645df5530 --- /dev/null +++ b/packages/api-extractor/src/schema-laws.test.ts @@ -0,0 +1,185 @@ +import { recursionLaws, ruleOfSchemas } from '@systemfsoftware/effect-schema-law' +import { Json as schema_0 } from './canonical-json.schema' +import { JsonFromJsonText as schema_1 } from './canonical-json.schema' +import { ChangeKind as schema_2 } from './diff/change.schema' +import { Direction as schema_3 } from './diff/direction.schema' +import { Position as schema_4 } from './diff/position.schema' +import { Variance as schema_5 } from './diff/position.schema' +import { ChannelType as schema_6 } from './diff/position.schema' +import { AnalysisMessageId as schema_7 } from './front-end/analysis-message.schema' +import { AnalysisMessage as schema_8 } from './front-end/analysis-message.schema' +import { Declarations as schema_9 } from './front-end/declarations.schema' +import { Reported as schema_10 } from './front-end/declarations.schema' +import { Note as schema_11 } from './front-end/declarations.schema' +import { Diagnostic as schema_12 } from './front-end/declarations.schema' +import { ExportPath as schema_13 } from './front-end/export-target.schema' +import { ExportExcluded as schema_14 } from './front-end/export-target.schema' +import { ExportConditions as schema_15 } from './front-end/export-target.schema' +import { ExportFallbacks as schema_16 } from './front-end/export-target.schema' +import { ExportTarget as schema_17 } from './front-end/export-target.schema' +import { ExportTargetFromPackageExports as schema_18 } from './front-end/package-source.schema' +import { PackageManifest as schema_19 } from './front-end/package-source.schema' +import { PackageManifestFromJsonText as schema_20 } from './front-end/package-source.schema' +import { FastPath as schema_21 } from './front-end/route.schema' +import { Fallback as schema_22 } from './front-end/route.schema' +import { Route as schema_23 } from './front-end/route.schema' +import { MessageLogLevel as schema_24 } from './input/api-extractor-file.schema' +import { MessageReportingRule as schema_25 } from './input/api-extractor-file.schema' +import { MessageReportingTable as schema_26 } from './input/api-extractor-file.schema' +import { ReportVariantKind as schema_27 } from './input/api-extractor-file.schema' +import { NewlineKind as schema_28 } from './input/api-extractor-file.schema' +import { EnumMemberOrder as schema_29 } from './input/api-extractor-file.schema' +import { ReleaseTagName as schema_30 } from './input/api-extractor-file.schema' +import { ApiExtractorFile as schema_31 } from './input/api-extractor-file.schema' +import { ModelVersion as schema_32 } from './model/api-model.schema' +import { TypeAliasItem as schema_33 } from './model/api-model.schema' +import { ApiItem as schema_34 } from './model/api-model.schema' +import { ApiModel as schema_35 } from './model/api-model.schema' +import { ApiModelFromJsonText as schema_36 } from './model/api-model.schema' +import { ReleaseTag as schema_37 } from './model/doc-comment.schema' +import { DocParam as schema_38 } from './model/doc-comment.schema' +import { DocComment as schema_39 } from './model/doc-comment.schema' +import { KeywordName as schema_40 } from './model/type-expr.schema' +import { TypeParameter as schema_41 } from './model/type-expr.schema' +import { Parameter as schema_42 } from './model/type-expr.schema' +import { Signature as schema_43 } from './model/type-expr.schema' +import { Member as schema_44 } from './model/type-expr.schema' +import { TypeExpr as schema_45 } from './model/type-expr.schema' +import { ReportOutcomeCommand as schema_46 } from './pipeline/report-outcome.schema' +import { Unchanged as schema_47 } from './pipeline/report-outcome.schema' +import { Changed as schema_48 } from './pipeline/report-outcome.schema' +import { New as schema_49 } from './pipeline/report-outcome.schema' +import { ReportOutcome as schema_50 } from './pipeline/report-outcome.schema' +import { ReportRejected as schema_51 } from './pipeline/report-outcome.schema' +import { Bump as schema_52 } from './rules/corpus.schema' +import { RuleCorpus as schema_53 } from './rules/corpus.schema' +import { RuleCorpusFromJsonText as schema_54 } from './rules/corpus.schema' +import { Finding as schema_55 } from './rules/finding.schema' +import { Findings as schema_56 } from './rules/finding.schema' +import { VerdictVersion as schema_57 } from './verdict.schema' +import { Verdict as schema_58 } from './verdict.schema' +import { VerdictFromJsonText as schema_59 } from './verdict.schema' +import { CompareSurfaces as schema_60 } from './verdict.schema' + +ruleOfSchemas('Json', schema_0) +recursionLaws('Json', schema_0) +ruleOfSchemas('JsonFromJsonText', schema_1) +recursionLaws('JsonFromJsonText', schema_1) +ruleOfSchemas('ChangeKind', schema_2) +recursionLaws('ChangeKind', schema_2) +ruleOfSchemas('Direction', schema_3) +recursionLaws('Direction', schema_3) +ruleOfSchemas('Position', schema_4) +recursionLaws('Position', schema_4) +ruleOfSchemas('Variance', schema_5) +recursionLaws('Variance', schema_5) +ruleOfSchemas('ChannelType', schema_6) +recursionLaws('ChannelType', schema_6) +ruleOfSchemas('AnalysisMessageId', schema_7) +recursionLaws('AnalysisMessageId', schema_7) +ruleOfSchemas('AnalysisMessage', schema_8) +recursionLaws('AnalysisMessage', schema_8) +ruleOfSchemas('Declarations', schema_9) +recursionLaws('Declarations', schema_9) +ruleOfSchemas('Reported', schema_10) +recursionLaws('Reported', schema_10) +ruleOfSchemas('Note', schema_11) +recursionLaws('Note', schema_11) +ruleOfSchemas('Diagnostic', schema_12) +recursionLaws('Diagnostic', schema_12) +ruleOfSchemas('ExportPath', schema_13) +recursionLaws('ExportPath', schema_13) +ruleOfSchemas('ExportExcluded', schema_14) +recursionLaws('ExportExcluded', schema_14) +ruleOfSchemas('ExportConditions', schema_15) +recursionLaws('ExportConditions', schema_15) +ruleOfSchemas('ExportFallbacks', schema_16) +recursionLaws('ExportFallbacks', schema_16) +ruleOfSchemas('ExportTarget', schema_17) +recursionLaws('ExportTarget', schema_17) +ruleOfSchemas('ExportTargetFromPackageExports', schema_18) +recursionLaws('ExportTargetFromPackageExports', schema_18) +ruleOfSchemas('PackageManifest', schema_19) +recursionLaws('PackageManifest', schema_19) +ruleOfSchemas('PackageManifestFromJsonText', schema_20) +recursionLaws('PackageManifestFromJsonText', schema_20) +ruleOfSchemas('FastPath', schema_21) +recursionLaws('FastPath', schema_21) +ruleOfSchemas('Fallback', schema_22) +recursionLaws('Fallback', schema_22) +ruleOfSchemas('Route', schema_23) +recursionLaws('Route', schema_23) +ruleOfSchemas('MessageLogLevel', schema_24) +recursionLaws('MessageLogLevel', schema_24) +ruleOfSchemas('MessageReportingRule', schema_25) +recursionLaws('MessageReportingRule', schema_25) +ruleOfSchemas('MessageReportingTable', schema_26) +recursionLaws('MessageReportingTable', schema_26) +ruleOfSchemas('ReportVariantKind', schema_27) +recursionLaws('ReportVariantKind', schema_27) +ruleOfSchemas('NewlineKind', schema_28) +recursionLaws('NewlineKind', schema_28) +ruleOfSchemas('EnumMemberOrder', schema_29) +recursionLaws('EnumMemberOrder', schema_29) +ruleOfSchemas('ReleaseTagName', schema_30) +recursionLaws('ReleaseTagName', schema_30) +ruleOfSchemas('ApiExtractorFile', schema_31) +recursionLaws('ApiExtractorFile', schema_31) +ruleOfSchemas('ModelVersion', schema_32) +recursionLaws('ModelVersion', schema_32) +ruleOfSchemas('TypeAliasItem', schema_33) +recursionLaws('TypeAliasItem', schema_33) +ruleOfSchemas('ApiItem', schema_34) +recursionLaws('ApiItem', schema_34) +ruleOfSchemas('ApiModel', schema_35) +recursionLaws('ApiModel', schema_35) +ruleOfSchemas('ApiModelFromJsonText', schema_36) +recursionLaws('ApiModelFromJsonText', schema_36) +ruleOfSchemas('ReleaseTag', schema_37) +recursionLaws('ReleaseTag', schema_37) +ruleOfSchemas('DocParam', schema_38) +recursionLaws('DocParam', schema_38) +ruleOfSchemas('DocComment', schema_39) +recursionLaws('DocComment', schema_39) +ruleOfSchemas('KeywordName', schema_40) +recursionLaws('KeywordName', schema_40) +ruleOfSchemas('TypeParameter', schema_41) +recursionLaws('TypeParameter', schema_41) +ruleOfSchemas('Parameter', schema_42) +recursionLaws('Parameter', schema_42) +ruleOfSchemas('Signature', schema_43) +recursionLaws('Signature', schema_43) +ruleOfSchemas('Member', schema_44) +recursionLaws('Member', schema_44) +ruleOfSchemas('TypeExpr', schema_45) +recursionLaws('TypeExpr', schema_45) +ruleOfSchemas('ReportOutcomeCommand', schema_46) +recursionLaws('ReportOutcomeCommand', schema_46) +ruleOfSchemas('Unchanged', schema_47) +recursionLaws('Unchanged', schema_47) +ruleOfSchemas('Changed', schema_48) +recursionLaws('Changed', schema_48) +ruleOfSchemas('New', schema_49) +recursionLaws('New', schema_49) +ruleOfSchemas('ReportOutcome', schema_50) +recursionLaws('ReportOutcome', schema_50) +ruleOfSchemas('ReportRejected', schema_51) +recursionLaws('ReportRejected', schema_51) +ruleOfSchemas('Bump', schema_52) +recursionLaws('Bump', schema_52) +ruleOfSchemas('RuleCorpus', schema_53) +recursionLaws('RuleCorpus', schema_53) +ruleOfSchemas('RuleCorpusFromJsonText', schema_54) +recursionLaws('RuleCorpusFromJsonText', schema_54) +ruleOfSchemas('Finding', schema_55) +recursionLaws('Finding', schema_55) +ruleOfSchemas('Findings', schema_56) +recursionLaws('Findings', schema_56) +ruleOfSchemas('VerdictVersion', schema_57) +recursionLaws('VerdictVersion', schema_57) +ruleOfSchemas('Verdict', schema_58) +recursionLaws('Verdict', schema_58) +ruleOfSchemas('VerdictFromJsonText', schema_59) +recursionLaws('VerdictFromJsonText', schema_59) +ruleOfSchemas('CompareSurfaces', schema_60) +recursionLaws('CompareSurfaces', schema_60) \ No newline at end of file diff --git a/packages/api-extractor/src/verdict.cell.ts b/packages/api-extractor/src/verdict.cell.ts index 9d5a21379..e307a170a 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, VerdictFromJsonText } 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.encodeUnknownEffect(VerdictFromJsonText)(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 0f2e55ac9..990e758e2 100644 --- a/packages/api-extractor/src/verdict.schema.ts +++ b/packages/api-extractor/src/verdict.schema.ts @@ -1,5 +1,6 @@ import { Workflow } from '@systemfsoftware/effect-cell-types' import { Cause, Schema } from 'effect' +import { canonicalJsonTextOf } from './canonical-json.schema.js' import { ApiModel } from './model/api-model.schema.js' import { Bump, RuleCorpus } from './rules/corpus.schema.js' import { Findings } from './rules/finding.schema.js' @@ -41,6 +42,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 = canonicalJsonTextOf(Verdict) + 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 c24b8582d..c1f483a76 100644 --- a/packages/api-extractor/tests/__fixtures__/json-text.ts +++ b/packages/api-extractor/tests/__fixtures__/json-text.ts @@ -1,5 +1,4 @@ -import { Result, Schema } from 'effect' +import { Json } from '@systemfsoftware/api-extractor' +import { Result } from 'effect' -const codec = Schema.fromJsonString(Schema.Unknown) - -export const jsonText = (value: object): string => Result.getOrThrow(Schema.encodeResult(codec)(value)) +export const jsonText = (value: object): string => Result.getOrThrow(Json.canonicalJson(value)) diff --git a/packages/api-extractor/tests/__fixtures__/surfaces.ts b/packages/api-extractor/tests/__fixtures__/surfaces.ts index 0d2d13d09..b5c05e7e0 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 0119d7224..5f20a673d 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 c30a8ebce..68f82ced9 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 09b3670dd..20803046f 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/serialise.integration.test.ts b/packages/api-extractor/tests/serialise.integration.test.ts index dc553c58f..2e59b7400 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/vitest.config.ts b/packages/api-extractor/vitest.config.ts index a1f9b84e7..f176d4471 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'], From fab31f9019d625db719fef26b4c4c5e4878cb0f5 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:08:59 -0500 Subject: [PATCH 2/9] wip: codecs typecheck fixes --- apps/api-extractor-e2e/tests/__fixtures__/json-text.ts | 2 +- .../tests/front-ends.integration.test.ts | 6 +++--- apps/api-extractor-profile/profile.ts | 10 +++++----- packages/api-extractor/src/rules/default-corpus.ts | 2 +- packages/api-extractor/tests/__fixtures__/json-text.ts | 2 +- .../tests/front-end-routing.integration.test.ts | 4 ++-- .../tests/package-reader.integration.test.ts | 4 ++-- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts b/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts index c1f483a76..091f17e8f 100644 --- a/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts +++ b/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts @@ -1,4 +1,4 @@ import { Json } from '@systemfsoftware/api-extractor' import { Result } from 'effect' -export const jsonText = (value: object): string => Result.getOrThrow(Json.canonicalJson(value)) +export const jsonText = (value: Json.Json): string => Result.getOrThrow(Json.canonicalJson(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 830dd31e6..1602d4fbd 100644 --- a/apps/api-extractor-e2e/tests/front-ends.integration.test.ts +++ b/apps/api-extractor-e2e/tests/front-ends.integration.test.ts @@ -1,5 +1,5 @@ import { NodeServices } from '@effect/platform-node' -import { ApiModel, FrontEnd } from '@systemfsoftware/api-extractor' +import { ApiModel, FrontEnd, Json } from '@systemfsoftware/api-extractor' import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' import { Effect, FileSystem, Layer, Match, Option, Path, Schema } from 'effect' import { jsonText } from './__fixtures__/json-text.js' @@ -31,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?: Json.Json) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path @@ -47,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 diff --git a/apps/api-extractor-profile/profile.ts b/apps/api-extractor-profile/profile.ts index f1e94da0d..1268e8490 100644 --- a/apps/api-extractor-profile/profile.ts +++ b/apps/api-extractor-profile/profile.ts @@ -44,7 +44,7 @@ interface Subject { readonly workspaceRoot: string } -interface Timing { +type Timing = { readonly coldMs: number readonly warmMedianMs: number } @@ -253,12 +253,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'] @@ -274,7 +274,7 @@ interface PackageProfile { readonly phases: Readonly> } -interface FrontEndOutcome { +type FrontEndOutcome = { readonly route: 'FastPath' | 'Fallback' | 'refused' readonly outcome: string readonly items: number @@ -407,7 +407,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 } diff --git a/packages/api-extractor/src/rules/default-corpus.ts b/packages/api-extractor/src/rules/default-corpus.ts index f1ce561ff..da984fd3f 100644 --- a/packages/api-extractor/src/rules/default-corpus.ts +++ b/packages/api-extractor/src/rules/default-corpus.ts @@ -4,4 +4,4 @@ import { RuleCorpus, type RuleCorpus as RuleCorpusType } from './corpus.schema.j // 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.decodeEffect(RuleCorpus)(corpusV1)) +export const defaultCorpus: RuleCorpusType = Effect.runSync(Schema.decodeUnknownEffect(RuleCorpus)(corpusV1)) diff --git a/packages/api-extractor/tests/__fixtures__/json-text.ts b/packages/api-extractor/tests/__fixtures__/json-text.ts index c1f483a76..091f17e8f 100644 --- a/packages/api-extractor/tests/__fixtures__/json-text.ts +++ b/packages/api-extractor/tests/__fixtures__/json-text.ts @@ -1,4 +1,4 @@ import { Json } from '@systemfsoftware/api-extractor' import { Result } from 'effect' -export const jsonText = (value: object): string => Result.getOrThrow(Json.canonicalJson(value)) +export const jsonText = (value: Json.Json): string => Result.getOrThrow(Json.canonicalJson(value)) 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 7d700de09..bd1023e2a 100644 --- a/packages/api-extractor/tests/front-end-routing.integration.test.ts +++ b/packages/api-extractor/tests/front-end-routing.integration.test.ts @@ -1,4 +1,4 @@ -import { FrontEnd } from '@systemfsoftware/api-extractor' +import { FrontEnd, Json } from '@systemfsoftware/api-extractor' import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' import { Effect, FileSystem, Layer, Path } from 'effect' import { jsonText } from './__fixtures__/json-text.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: Json.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 3eb47055c..1d23c38e7 100644 --- a/packages/api-extractor/tests/package-reader.integration.test.ts +++ b/packages/api-extractor/tests/package-reader.integration.test.ts @@ -1,4 +1,4 @@ -import { FrontEnd } from '@systemfsoftware/api-extractor' +import { FrontEnd, Json } from '@systemfsoftware/api-extractor' import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' import { Effect, FileSystem, Layer, Path } from 'effect' import { jsonText } from './__fixtures__/json-text.js' @@ -18,7 +18,7 @@ const writeSource = (root: string) => yield* fileSystem.writeFileString(target, text) }) -const packageOf = (exports: object, sources: Record) => +const packageOf = (exports: Json.Json, sources: Record) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path From ae150973924bd8a966f92dcc2511b26223f6e0c7 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:11:27 -0500 Subject: [PATCH 3/9] test: let effect-schema-vite generate the schema laws from a stub --- .../tests/__fixtures__/json-text.ts | 7 +- .../tests/front-ends.integration.test.ts | 6 +- .../api-extractor/src/schema-laws.test.ts | 190 +----------------- 3 files changed, 12 insertions(+), 191 deletions(-) diff --git a/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts b/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts index 091f17e8f..8c479ecb9 100644 --- a/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts +++ b/apps/api-extractor-e2e/tests/__fixtures__/json-text.ts @@ -1,4 +1,5 @@ -import { Json } from '@systemfsoftware/api-extractor' -import { Result } from 'effect' +import { Result, Schema } from 'effect' -export const jsonText = (value: Json.Json): string => Result.getOrThrow(Json.canonicalJson(value)) +const codec = Schema.fromJsonString(Schema.Json) + +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 1602d4fbd..45759c7a9 100644 --- a/apps/api-extractor-e2e/tests/front-ends.integration.test.ts +++ b/apps/api-extractor-e2e/tests/front-ends.integration.test.ts @@ -1,5 +1,5 @@ import { NodeServices } from '@effect/platform-node' -import { ApiModel, FrontEnd, Json } from '@systemfsoftware/api-extractor' +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, Schema } from 'effect' import { jsonText } from './__fixtures__/json-text.js' @@ -31,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?: Json.Json) => +const fallingBackPackage = (name: string, exports: Readonly>, files: Readonly>, tsconfig?: Schema.Json) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path @@ -47,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 diff --git a/packages/api-extractor/src/schema-laws.test.ts b/packages/api-extractor/src/schema-laws.test.ts index 645df5530..7fa4d5baa 100644 --- a/packages/api-extractor/src/schema-laws.test.ts +++ b/packages/api-extractor/src/schema-laws.test.ts @@ -1,185 +1,5 @@ -import { recursionLaws, ruleOfSchemas } from '@systemfsoftware/effect-schema-law' -import { Json as schema_0 } from './canonical-json.schema' -import { JsonFromJsonText as schema_1 } from './canonical-json.schema' -import { ChangeKind as schema_2 } from './diff/change.schema' -import { Direction as schema_3 } from './diff/direction.schema' -import { Position as schema_4 } from './diff/position.schema' -import { Variance as schema_5 } from './diff/position.schema' -import { ChannelType as schema_6 } from './diff/position.schema' -import { AnalysisMessageId as schema_7 } from './front-end/analysis-message.schema' -import { AnalysisMessage as schema_8 } from './front-end/analysis-message.schema' -import { Declarations as schema_9 } from './front-end/declarations.schema' -import { Reported as schema_10 } from './front-end/declarations.schema' -import { Note as schema_11 } from './front-end/declarations.schema' -import { Diagnostic as schema_12 } from './front-end/declarations.schema' -import { ExportPath as schema_13 } from './front-end/export-target.schema' -import { ExportExcluded as schema_14 } from './front-end/export-target.schema' -import { ExportConditions as schema_15 } from './front-end/export-target.schema' -import { ExportFallbacks as schema_16 } from './front-end/export-target.schema' -import { ExportTarget as schema_17 } from './front-end/export-target.schema' -import { ExportTargetFromPackageExports as schema_18 } from './front-end/package-source.schema' -import { PackageManifest as schema_19 } from './front-end/package-source.schema' -import { PackageManifestFromJsonText as schema_20 } from './front-end/package-source.schema' -import { FastPath as schema_21 } from './front-end/route.schema' -import { Fallback as schema_22 } from './front-end/route.schema' -import { Route as schema_23 } from './front-end/route.schema' -import { MessageLogLevel as schema_24 } from './input/api-extractor-file.schema' -import { MessageReportingRule as schema_25 } from './input/api-extractor-file.schema' -import { MessageReportingTable as schema_26 } from './input/api-extractor-file.schema' -import { ReportVariantKind as schema_27 } from './input/api-extractor-file.schema' -import { NewlineKind as schema_28 } from './input/api-extractor-file.schema' -import { EnumMemberOrder as schema_29 } from './input/api-extractor-file.schema' -import { ReleaseTagName as schema_30 } from './input/api-extractor-file.schema' -import { ApiExtractorFile as schema_31 } from './input/api-extractor-file.schema' -import { ModelVersion as schema_32 } from './model/api-model.schema' -import { TypeAliasItem as schema_33 } from './model/api-model.schema' -import { ApiItem as schema_34 } from './model/api-model.schema' -import { ApiModel as schema_35 } from './model/api-model.schema' -import { ApiModelFromJsonText as schema_36 } from './model/api-model.schema' -import { ReleaseTag as schema_37 } from './model/doc-comment.schema' -import { DocParam as schema_38 } from './model/doc-comment.schema' -import { DocComment as schema_39 } from './model/doc-comment.schema' -import { KeywordName as schema_40 } from './model/type-expr.schema' -import { TypeParameter as schema_41 } from './model/type-expr.schema' -import { Parameter as schema_42 } from './model/type-expr.schema' -import { Signature as schema_43 } from './model/type-expr.schema' -import { Member as schema_44 } from './model/type-expr.schema' -import { TypeExpr as schema_45 } from './model/type-expr.schema' -import { ReportOutcomeCommand as schema_46 } from './pipeline/report-outcome.schema' -import { Unchanged as schema_47 } from './pipeline/report-outcome.schema' -import { Changed as schema_48 } from './pipeline/report-outcome.schema' -import { New as schema_49 } from './pipeline/report-outcome.schema' -import { ReportOutcome as schema_50 } from './pipeline/report-outcome.schema' -import { ReportRejected as schema_51 } from './pipeline/report-outcome.schema' -import { Bump as schema_52 } from './rules/corpus.schema' -import { RuleCorpus as schema_53 } from './rules/corpus.schema' -import { RuleCorpusFromJsonText as schema_54 } from './rules/corpus.schema' -import { Finding as schema_55 } from './rules/finding.schema' -import { Findings as schema_56 } from './rules/finding.schema' -import { VerdictVersion as schema_57 } from './verdict.schema' -import { Verdict as schema_58 } from './verdict.schema' -import { VerdictFromJsonText as schema_59 } from './verdict.schema' -import { CompareSurfaces as schema_60 } from './verdict.schema' - -ruleOfSchemas('Json', schema_0) -recursionLaws('Json', schema_0) -ruleOfSchemas('JsonFromJsonText', schema_1) -recursionLaws('JsonFromJsonText', schema_1) -ruleOfSchemas('ChangeKind', schema_2) -recursionLaws('ChangeKind', schema_2) -ruleOfSchemas('Direction', schema_3) -recursionLaws('Direction', schema_3) -ruleOfSchemas('Position', schema_4) -recursionLaws('Position', schema_4) -ruleOfSchemas('Variance', schema_5) -recursionLaws('Variance', schema_5) -ruleOfSchemas('ChannelType', schema_6) -recursionLaws('ChannelType', schema_6) -ruleOfSchemas('AnalysisMessageId', schema_7) -recursionLaws('AnalysisMessageId', schema_7) -ruleOfSchemas('AnalysisMessage', schema_8) -recursionLaws('AnalysisMessage', schema_8) -ruleOfSchemas('Declarations', schema_9) -recursionLaws('Declarations', schema_9) -ruleOfSchemas('Reported', schema_10) -recursionLaws('Reported', schema_10) -ruleOfSchemas('Note', schema_11) -recursionLaws('Note', schema_11) -ruleOfSchemas('Diagnostic', schema_12) -recursionLaws('Diagnostic', schema_12) -ruleOfSchemas('ExportPath', schema_13) -recursionLaws('ExportPath', schema_13) -ruleOfSchemas('ExportExcluded', schema_14) -recursionLaws('ExportExcluded', schema_14) -ruleOfSchemas('ExportConditions', schema_15) -recursionLaws('ExportConditions', schema_15) -ruleOfSchemas('ExportFallbacks', schema_16) -recursionLaws('ExportFallbacks', schema_16) -ruleOfSchemas('ExportTarget', schema_17) -recursionLaws('ExportTarget', schema_17) -ruleOfSchemas('ExportTargetFromPackageExports', schema_18) -recursionLaws('ExportTargetFromPackageExports', schema_18) -ruleOfSchemas('PackageManifest', schema_19) -recursionLaws('PackageManifest', schema_19) -ruleOfSchemas('PackageManifestFromJsonText', schema_20) -recursionLaws('PackageManifestFromJsonText', schema_20) -ruleOfSchemas('FastPath', schema_21) -recursionLaws('FastPath', schema_21) -ruleOfSchemas('Fallback', schema_22) -recursionLaws('Fallback', schema_22) -ruleOfSchemas('Route', schema_23) -recursionLaws('Route', schema_23) -ruleOfSchemas('MessageLogLevel', schema_24) -recursionLaws('MessageLogLevel', schema_24) -ruleOfSchemas('MessageReportingRule', schema_25) -recursionLaws('MessageReportingRule', schema_25) -ruleOfSchemas('MessageReportingTable', schema_26) -recursionLaws('MessageReportingTable', schema_26) -ruleOfSchemas('ReportVariantKind', schema_27) -recursionLaws('ReportVariantKind', schema_27) -ruleOfSchemas('NewlineKind', schema_28) -recursionLaws('NewlineKind', schema_28) -ruleOfSchemas('EnumMemberOrder', schema_29) -recursionLaws('EnumMemberOrder', schema_29) -ruleOfSchemas('ReleaseTagName', schema_30) -recursionLaws('ReleaseTagName', schema_30) -ruleOfSchemas('ApiExtractorFile', schema_31) -recursionLaws('ApiExtractorFile', schema_31) -ruleOfSchemas('ModelVersion', schema_32) -recursionLaws('ModelVersion', schema_32) -ruleOfSchemas('TypeAliasItem', schema_33) -recursionLaws('TypeAliasItem', schema_33) -ruleOfSchemas('ApiItem', schema_34) -recursionLaws('ApiItem', schema_34) -ruleOfSchemas('ApiModel', schema_35) -recursionLaws('ApiModel', schema_35) -ruleOfSchemas('ApiModelFromJsonText', schema_36) -recursionLaws('ApiModelFromJsonText', schema_36) -ruleOfSchemas('ReleaseTag', schema_37) -recursionLaws('ReleaseTag', schema_37) -ruleOfSchemas('DocParam', schema_38) -recursionLaws('DocParam', schema_38) -ruleOfSchemas('DocComment', schema_39) -recursionLaws('DocComment', schema_39) -ruleOfSchemas('KeywordName', schema_40) -recursionLaws('KeywordName', schema_40) -ruleOfSchemas('TypeParameter', schema_41) -recursionLaws('TypeParameter', schema_41) -ruleOfSchemas('Parameter', schema_42) -recursionLaws('Parameter', schema_42) -ruleOfSchemas('Signature', schema_43) -recursionLaws('Signature', schema_43) -ruleOfSchemas('Member', schema_44) -recursionLaws('Member', schema_44) -ruleOfSchemas('TypeExpr', schema_45) -recursionLaws('TypeExpr', schema_45) -ruleOfSchemas('ReportOutcomeCommand', schema_46) -recursionLaws('ReportOutcomeCommand', schema_46) -ruleOfSchemas('Unchanged', schema_47) -recursionLaws('Unchanged', schema_47) -ruleOfSchemas('Changed', schema_48) -recursionLaws('Changed', schema_48) -ruleOfSchemas('New', schema_49) -recursionLaws('New', schema_49) -ruleOfSchemas('ReportOutcome', schema_50) -recursionLaws('ReportOutcome', schema_50) -ruleOfSchemas('ReportRejected', schema_51) -recursionLaws('ReportRejected', schema_51) -ruleOfSchemas('Bump', schema_52) -recursionLaws('Bump', schema_52) -ruleOfSchemas('RuleCorpus', schema_53) -recursionLaws('RuleCorpus', schema_53) -ruleOfSchemas('RuleCorpusFromJsonText', schema_54) -recursionLaws('RuleCorpusFromJsonText', schema_54) -ruleOfSchemas('Finding', schema_55) -recursionLaws('Finding', schema_55) -ruleOfSchemas('Findings', schema_56) -recursionLaws('Findings', schema_56) -ruleOfSchemas('VerdictVersion', schema_57) -recursionLaws('VerdictVersion', schema_57) -ruleOfSchemas('Verdict', schema_58) -recursionLaws('Verdict', schema_58) -ruleOfSchemas('VerdictFromJsonText', schema_59) -recursionLaws('VerdictFromJsonText', schema_59) -ruleOfSchemas('CompareSurfaces', schema_60) -recursionLaws('CompareSurfaces', schema_60) \ No newline at end of file +// 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 {} From 7179685a6d69c530c7bd93fe645edf463e4c550f Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:18:16 -0500 Subject: [PATCH 4/9] refactor: canonical JSON is Effect's fromJsonString with a key-sorting replacer --- apps/api-extractor-profile/profile.ts | 6 +- packages/api-extractor/src/Json.ts | 8 +- .../src/canonical-json.schema.ts | 133 +++--------------- packages/api-extractor/src/cli.ts | 8 +- .../src/front-end/canonical-type-text.ts | 6 +- .../src/front-end/package-source.schema.ts | 4 +- .../api-extractor/src/input/config-file.ts | 4 +- .../src/input/node-extraction-input.ts | 4 +- .../src/model/api-model.schema.ts | 4 +- .../api-extractor/src/output/doc-model.ts | 6 +- .../src/output/tsdoc-metadata.ts | 6 +- .../src/pipeline/extract-package.blueprint.ts | 5 +- .../src/pipeline/extract-surface.cell.ts | 7 +- .../api-extractor/src/rules/corpus.schema.ts | 4 +- packages/api-extractor/src/verdict.schema.ts | 4 +- 15 files changed, 54 insertions(+), 155 deletions(-) diff --git a/apps/api-extractor-profile/profile.ts b/apps/api-extractor-profile/profile.ts index 1268e8490..cd01cadc1 100644 --- a/apps/api-extractor-profile/profile.ts +++ b/apps/api-extractor-profile/profile.ts @@ -28,7 +28,7 @@ const Manifest = Schema.Struct({ }) type Manifest = typeof Manifest.Type -type ProfileError = PlatformError | Schema.SchemaError | UsageError | GitError | Json.CanonicalJsonRejected +type ProfileError = PlatformError | Schema.SchemaError | UsageError | GitError class UsageError extends Schema.TaggedError()('UsageError', { usage: Schema.String }) {} @@ -81,7 +81,7 @@ const readManifest = (root: string) => const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path const text = yield* fileSystem.readFileString(path.join(root, 'package.json')) - const json = yield* Schema.decodeUnknownEffect(Json.JsonFromJsonText)(text) + const json = yield* Schema.decodeUnknownEffect(Json.CanonicalJson)(text) return yield* Schema.decodeUnknownEffect(Manifest)(json) }) @@ -420,7 +420,7 @@ type 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): Result.Result => { +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) => diff --git a/packages/api-extractor/src/Json.ts b/packages/api-extractor/src/Json.ts index 084131901..b9998a36e 100644 --- a/packages/api-extractor/src/Json.ts +++ b/packages/api-extractor/src/Json.ts @@ -1,7 +1 @@ -export { - canonicalJson, - CanonicalJsonRejected, - canonicalJsonTextOf, - type Json, - JsonFromJsonText, -} from './canonical-json.schema.js' +export { CanonicalJson, canonicalJson, canonicalJsonOf, type Json } from './canonical-json.schema.js' diff --git a/packages/api-extractor/src/canonical-json.schema.ts b/packages/api-extractor/src/canonical-json.schema.ts index 5a582360a..98029b807 100644 --- a/packages/api-extractor/src/canonical-json.schema.ts +++ b/packages/api-extractor/src/canonical-json.schema.ts @@ -1,130 +1,37 @@ /** - * 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. - * - * `JsonFromJsonText` is the JSON-text codec: decode parses any key order and - * encode writes canonical text (object keys in code-unit order, two-space - * indentation, trailing newline). The transform is subtractive: decode accepts - * any JSON text; encode emits one canonical form. A non-finite number cannot be - * written as JSON, so it is refused as `CanonicalJsonRejected`, never thrown. + * Canonical JSON is Effect's `Schema.fromJsonString` with one replacer that + * orders object keys by UTF-16 code unit (`Order.String`), so the bytes never + * depend on the process locale, time zone or host. `Schema.Json` refuses a + * non-finite number, so no output can hold one. */ -import { Effect, Match, Order, Predicate, Result, Schema, SchemaGetter, SchemaIssue, SchemaParser } from 'effect' -import type { Cause } from 'effect' +import { Order, Predicate, Result, Schema, SchemaGetter } 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 CanonicalJsonRejectedFields = { readonly issue: Schema.String } - -const CanonicalJsonRejectedBase: Schema.Class, Cause.YieldableError> = - Schema.TaggedError()('CanonicalJsonRejected', { issue: Schema.String }) - -/** A value that canonical JSON cannot carry, refused instead of thrown. */ -export class CanonicalJsonRejected extends CanonicalJsonRejectedBase { - override get message(): string { - return `the value cannot be written as canonical JSON: ${this.issue}` - } -} - -const jsonTextCodec = Schema.fromJsonString(Schema.Unknown) - -const encodeText = (value: Json): string => Result.getOrThrow(Schema.encodeResult(jsonTextCodec)(value)) - -type Scalar = string | number | boolean | null - -const isJsonArray = (value: Json): value is Schema.JsonArray => Array.isArray(value) - -const isJsonObject = (value: Json): value is Schema.JsonObject => Predicate.isObject(value) && !isJsonArray(value) - type Entry = readonly [string, Json] const byKey: Order.Order = Order.mapInput(Order.String, ([key]: Entry) => key) -/** The members of an object, ordered by key code unit. */ -const entriesOf = (value: Schema.JsonObject): ReadonlyArray => Object.entries(value).sort(byKey) - -const textOfScalar = (scalar: Scalar): string => encodeText(scalar) - -const writeNumber = (value: number): Result.Result => - Number.isFinite(value) - ? Result.succeed(textOfScalar(value)) - : Result.fail(new CanonicalJsonRejected({ issue: `the number ${value} is not finite` })) +const isJsonObject = (value: Json): value is Schema.JsonObject => Predicate.isObject(value) && !Array.isArray(value) -const writeArray = (items: Schema.JsonArray, indent: string): Result.Result => { - const inner = `${indent} ` - return items.length === 0 - ? Result.succeed('[]') - : Result.map(Result.all(items.map((item) => write(item, inner))), (parts) => `[\n${parts.map((part) => inner + part).join(',\n')}\n${indent}]`) -} +const sortKeys = (_key: string, value: Json): Json => + isJsonObject(value) ? Object.fromEntries(Object.entries(value).sort(byKey)) : value -const writeObject = (value: Schema.JsonObject, indent: string): Result.Result => { - const inner = `${indent} ` - const entries = entriesOf(value) - return entries.length === 0 - ? Result.succeed('{}') - : Result.map( - Result.all(entries.map(([key, member]) => Result.map(write(member, inner), (part) => `${inner}${textOfScalar(key)}: ${part}`))), - (lines) => `{\n${lines.join(',\n')}\n${indent}}`, - ) -} +/** A schema's canonical JSON text: keys in code-unit order, two-space indentation, a trailing newline. Decode accepts any key order. */ +export type CanonicalJsonText = Schema.Codec -const write = (value: Json, indent: string): Result.Result => - 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((scalar) => Result.succeed(textOfScalar(scalar))), +export const canonicalJsonOf = (schema: Schema.Codec): CanonicalJsonText => + Schema.fromJsonString(schema, { replacer: sortKeys, space: 2 }).pipe( + Schema.encode({ decode: SchemaGetter.passthrough(), encode: SchemaGetter.transform((text: string) => `${text}\n`) }), ) -/** Serialises a JSON value with sorted keys, two-space indentation and a trailing newline. */ -export const canonicalJson = (value: Json): Result.Result => - Result.map(write(value, ''), (text) => `${text}\n`) +/** Any JSON value as canonical JSON text. */ +export const CanonicalJson: Schema.Codec = canonicalJsonOf(Schema.Json) -const numberKey = (value: number): string => (Number.isFinite(value) ? textOfScalar(value) : String(value)) +/** Writes a JSON value as canonical JSON text. */ +export const canonicalJson = (value: Json): Result.Result => Schema.encodeResult(CanonicalJson)(value) -const writeCompact = (value: Json): string => - Match.value(value).pipe( - Match.when(Match.number, numberKey), - 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) - -const canonicalText = (value: Json): Effect.Effect => - Result.match(canonicalJson(value), { - onFailure: (error) => Effect.fail(new SchemaIssue.InvalidValue({ message: error.message }, value)), - onSuccess: Effect.succeed, - }) - -export type JsonFromJsonText = Schema.Codec - -/** The JSON text encoding: decode parses any JSON text, encode writes canonical bytes. */ -export const JsonFromJsonText: JsonFromJsonText = Schema.String.pipe( - Schema.decodeTo(Schema.Json, { - decode: SchemaGetter.parseJson(), - encode: SchemaGetter.transformEffect(canonicalText), - }), -) +const CompactJson: Schema.Codec = Schema.fromJsonString(Schema.Json, { replacer: sortKeys }) -export type CanonicalJsonTextOf = Schema.Codec - -/** - * The canonical JSON-text encoding of any codec: decode parses any key order and - * validates, encode writes canonical bytes. This is the codec a module exports - * as `FromJsonText`. - */ -export const canonicalJsonTextOf = (schema: Schema.Codec): CanonicalJsonTextOf => - Schema.fromJsonString(schema).pipe( - Schema.encode({ - decode: SchemaGetter.passthrough(), - encode: SchemaGetter.transformEffect((text: string) => - Effect.flatMap(SchemaParser.decodeEffect(JsonFromJsonText)(text), SchemaParser.encodeEffect(JsonFromJsonText)), - ), - }), - ) +/** The same key order on one line: a structural identity key. */ +export const canonicalKey = (value: Json): string => Result.getOrThrow(Schema.encodeResult(CompactJson)(value)) diff --git a/packages/api-extractor/src/cli.ts b/packages/api-extractor/src/cli.ts index 08a5727fc..87c259264 100644 --- a/packages/api-extractor/src/cli.ts +++ b/packages/api-extractor/src/cli.ts @@ -1,7 +1,7 @@ -import { Effect, FileSystem, Layer, Option, Path } from 'effect' +import { Effect, FileSystem, Layer, Option, Path, Predicate, type Schema } from 'effect' import type { PlatformError } from 'effect/PlatformError' import { NodeServices, NodeRuntime } from '@effect/platform-node' -import { canonicalJson, type CanonicalJsonRejected } from './canonical-json.schema.js' +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 +84,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) @@ -126,7 +126,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/front-end/canonical-type-text.ts b/packages/api-extractor/src/front-end/canonical-type-text.ts index cee909ff7..5ebd2cc1d 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, Result } from 'effect' +import { Array as Arr, Effect, HashMap, HashSet, Match, Option } from 'effect' import type { BindingPattern, Expression, @@ -38,7 +38,7 @@ import type { TSTypeReference, TemplateElement, } from 'oxc-parser' -import { canonicalJson } from '../canonical-json.schema.js' +import { canonicalKey } from '../canonical-json.schema.js' import { KeywordName } from '../model/type-expr.schema.js' import { type Declaration, @@ -52,7 +52,7 @@ import { 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(Result.map(canonicalJson(value), (text) => text.slice(0, -1))) +const jsonText = (value: string): string => canonicalKey(value) export type ReferenceTarget = { readonly name: string 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 6c0a1d8c2..570b1a040 100644 --- a/packages/api-extractor/src/front-end/package-source.schema.ts +++ b/packages/api-extractor/src/front-end/package-source.schema.ts @@ -1,5 +1,5 @@ import { Match, Predicate, Schema, SchemaTransformation } from 'effect' -import { canonicalJsonTextOf } from '../canonical-json.schema.js' +import { canonicalJsonOf } from '../canonical-json.schema.js' 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. */ @@ -67,4 +67,4 @@ 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 = canonicalJsonTextOf(PackageManifest) +export const PackageManifestFromJsonText: PackageManifestFromJsonText = canonicalJsonOf(PackageManifest) diff --git a/packages/api-extractor/src/input/config-file.ts b/packages/api-extractor/src/input/config-file.ts index b2a69c71f..7a78673c6 100644 --- a/packages/api-extractor/src/input/config-file.ts +++ b/packages/api-extractor/src/input/config-file.ts @@ -1,6 +1,6 @@ import { Effect, FileSystem, Function as Fn, Match, Option, Path, Schema } from 'effect' import type { PlatformError } from 'effect/PlatformError' -import { JsonFromJsonText } from '../canonical-json.schema.js' +import { CanonicalJson } from '../canonical-json.schema.js' import { isAbsent } from '../front-end/package-file.js' import { type JsonObject, isJsonObject } from './config-merge.js' import { ConfigRejected } from './extraction-input-error.schema.js' @@ -12,7 +12,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(JsonFromJsonText) +const jsonTextCodec = Schema.decodeEffect(CanonicalJson) 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 e4adb28a8..a1357546b 100644 --- a/packages/api-extractor/src/input/node-extraction-input.ts +++ b/packages/api-extractor/src/input/node-extraction-input.ts @@ -1,6 +1,6 @@ import { Array as Arr, Effect, FileSystem, Layer, Option, Path, Predicate, Schema } from 'effect' import type { PlatformError } from 'effect/PlatformError' -import { JsonFromJsonText } from '../canonical-json.schema.js' +import { CanonicalJson } from '../canonical-json.schema.js' import type { CompilerOverride, PackageSource, SourceEntryPoint } from '../front-end/declarations.schema.js' import { type ManifestRejected, NoSourceEntry } from '../front-end/front-end-error.schema.js' import { readPackage } from '../front-end/read-package.js' @@ -104,7 +104,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(JsonFromJsonText)(text).pipe( + Schema.decodeEffect(CanonicalJson)(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 3c55b6dcf..91305b5a1 100644 --- a/packages/api-extractor/src/model/api-model.schema.ts +++ b/packages/api-extractor/src/model/api-model.schema.ts @@ -1,5 +1,5 @@ import { Array as Arr, Order, Schema } from 'effect' -import { canonicalJsonTextOf, canonicalKey } from '../canonical-json.schema.js' +import { canonicalJsonOf, canonicalKey } from '../canonical-json.schema.js' import { type DocComment, DocComment as DocCommentCodec, ReleaseTag } from './doc-comment.schema.js' import { Member, Signature, TypeExpr, TypeParameter } from './type-expr.schema.js' @@ -206,4 +206,4 @@ export const sortModel = (model: ApiModel): ApiModel => ({ */ export type ApiModelFromJsonText = Schema.Codec -export const ApiModelFromJsonText: ApiModelFromJsonText = canonicalJsonTextOf(ApiModel) +export const ApiModelFromJsonText: ApiModelFromJsonText = canonicalJsonOf(ApiModel) diff --git a/packages/api-extractor/src/output/doc-model.ts b/packages/api-extractor/src/output/doc-model.ts index 816f9b095..a533baa5d 100644 --- a/packages/api-extractor/src/output/doc-model.ts +++ b/packages/api-extractor/src/output/doc-model.ts @@ -1,5 +1,5 @@ -import { Match, Option, Result } from 'effect' -import { canonicalJson, CanonicalJsonRejected, type Json } from '../canonical-json.schema.js' +import { Match, Option, Result, type Schema } from 'effect' +import { canonicalJson, type Json } from '../canonical-json.schema.js' 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 +288,7 @@ const metadataJson = (request: DocModelRequest): Json => const projectUrlField = (request: DocModelRequest): JsonRecord => (request.projectFolderUrl === undefined ? {} : { projectFolderUrl: request.projectFolderUrl }) -export const formatDocModel = (request: DocModelRequest): Result.Result => +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 aed2f06e3..f63dcdcb4 100644 --- a/packages/api-extractor/src/output/tsdoc-metadata.ts +++ b/packages/api-extractor/src/output/tsdoc-metadata.ts @@ -1,5 +1,5 @@ -import { type Result } from 'effect' -import { canonicalJson, type CanonicalJsonRejected, type Json } from '../canonical-json.schema.js' +import type { Result, Schema } from 'effect' +import { canonicalJson, type Json } from '../canonical-json.schema.js' import { ENGINE } from '../version.js' const TSDOC_VERSION = '0.12' @@ -14,4 +14,4 @@ export const tsdocMetadataJson = (): Json => ({ toolPackages: [toolPackageJson()], }) -export const formatTsdocMetadata = (): Result.Result => 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 e6dcc22e2..2bba98756 100644 --- a/packages/api-extractor/src/pipeline/extract-package.blueprint.ts +++ b/packages/api-extractor/src/pipeline/extract-package.blueprint.ts @@ -1,7 +1,6 @@ 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 { CanonicalJsonRejected } from '../canonical-json.schema.js' import type { ConfigRejected } from '../input/extraction-input-error.schema.js' import type { Platform } from '../input/config-file.js' import type { PlatformError } from 'effect/PlatformError' @@ -22,7 +21,7 @@ export type ExtractPackageError = | RollupRejected | UnsupportedDeclaration | PlatformError - | CanonicalJsonRejected + | 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 1d5686b0a..9ca63434c 100644 --- a/packages/api-extractor/src/pipeline/extract-surface.cell.ts +++ b/packages/api-extractor/src/pipeline/extract-surface.cell.ts @@ -2,7 +2,6 @@ import { Array as Arr, Effect, FileSystem, Option, Path, Schema } from 'effect' import { TSDocConfigFile } from '@microsoft/tsdoc-config' import type { PlatformError } from 'effect/PlatformError' import type { ApiModel } from '../model/api-model.schema.js' -import type { CanonicalJsonRejected } from '../canonical-json.schema.js' import { analyseWith } from '../front-end/analyse.js' import { messageRoutingOf, reportWarnings } from '../front-end/message-reporting.js' import type { CompilerEmitterId, IsolatedEmitterId } from '../front-end/declaration-emitter.service.js' @@ -18,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 | CanonicalJsonRejected +export type SurfaceError = CompilerRejected | CompilerUnavailable | NotIsolated | UnsupportedDeclaration | RollupRejected | PlatformError | Schema.SchemaError export type SurfaceServices = FileSystem.FileSystem | Path.Path | IsolatedEmitterId | CompilerEmitterId | DeclarationParserId | RollupBundlerId @@ -86,7 +85,7 @@ const tsdocConfigOf = (spec: ExtractionSpec): Schema.Json => () => ({}), ) -const docModelOf = (spec: ExtractionSpec) => (model: ApiModel): Effect.Effect<{ readonly file: string; readonly text: string } | null, CanonicalJsonRejected> => +const docModelOf = (spec: ExtractionSpec) => (model: ApiModel): Effect.Effect<{ readonly file: string; readonly text: string } | null, Schema.SchemaError> => spec.docModel.enabled ? Effect.map( Effect.fromResult(formatDocModel({ @@ -100,7 +99,7 @@ const docModelOf = (spec: ExtractionSpec) => (model: ApiModel): Effect.Effect<{ ) : Effect.succeed(null) -const tsdocMetadataOf = (spec: ExtractionSpec): Effect.Effect<{ readonly file: string; readonly text: string } | null, CanonicalJsonRejected> => +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) diff --git a/packages/api-extractor/src/rules/corpus.schema.ts b/packages/api-extractor/src/rules/corpus.schema.ts index c6e9673ec..2e56b5022 100644 --- a/packages/api-extractor/src/rules/corpus.schema.ts +++ b/packages/api-extractor/src/rules/corpus.schema.ts @@ -1,5 +1,5 @@ import { Array as Arr, Function, Option, Order, Schema } from 'effect' -import { canonicalJsonTextOf } from '../canonical-json.schema.js' +import { canonicalJsonOf } from '../canonical-json.schema.js' import { type Change, ChangeKind } from '../diff/change.schema.js' import { Direction } from '../diff/direction.schema.js' import { ChannelType, Position } from '../diff/position.schema.js' @@ -54,7 +54,7 @@ export const RuleCorpus: Schema.Codec = Schema.Struct({ */ export type RuleCorpusFromJsonText = Schema.Codec -export const RuleCorpusFromJsonText: RuleCorpusFromJsonText = canonicalJsonTextOf(RuleCorpus) +export const RuleCorpusFromJsonText: RuleCorpusFromJsonText = canonicalJsonOf(RuleCorpus) /** Semver order, least first: the order `Bump` declares its literals in. */ const BUMP_ORDER: ReadonlyArray = Bump.literals diff --git a/packages/api-extractor/src/verdict.schema.ts b/packages/api-extractor/src/verdict.schema.ts index 990e758e2..9f4670ee8 100644 --- a/packages/api-extractor/src/verdict.schema.ts +++ b/packages/api-extractor/src/verdict.schema.ts @@ -1,6 +1,6 @@ import { Workflow } from '@systemfsoftware/effect-cell-types' import { Cause, Schema } from 'effect' -import { canonicalJsonTextOf } from './canonical-json.schema.js' +import { canonicalJsonOf } from './canonical-json.schema.js' import { ApiModel } from './model/api-model.schema.js' import { Bump, RuleCorpus } from './rules/corpus.schema.js' import { Findings } from './rules/finding.schema.js' @@ -45,7 +45,7 @@ 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 = canonicalJsonTextOf(Verdict) +export const VerdictFromJsonText: VerdictFromJsonText = canonicalJsonOf(Verdict) type CorpusAmbiguityFields = { readonly corpusVersion: Schema.String From c51c3b5a95905667294c33ba30e50047dba72d6f Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:23:56 -0500 Subject: [PATCH 5/9] docs: describe the schema-only encodings in the changeset --- .changeset/codec-standard.md | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/.changeset/codec-standard.md b/.changeset/codec-standard.md index 1f950228f..05eb4bf5b 100644 --- a/.changeset/codec-standard.md +++ b/.changeset/codec-standard.md @@ -2,21 +2,12 @@ "@systemfsoftware/api-extractor": minor --- -Every encoding now has one codec that holds both its writer and its reader, and -no published encode or decode throws. +Every JSON encoding is now an Effect Schema, and no published encode or decode throws. -- `ApiModel.ApiModelFromJsonText` replaces `decode`, `encode` and `serialise`. - Decode accepts any JSON key order; encode orders items and keys canonically. - `ApiModel.decode`, `ApiModel.encode` and `ApiModel.serialise` are removed. -- `Verdict.RuleCorpusFromJsonText`, `Verdict.VerdictFromJsonText`, - `FrontEnd.PackageManifestFromJsonText` and - `FrontEnd.ExportTargetFromPackageExports` replace `decodeRuleCorpus` and - `ExportTargetCodec`. -- `Json` is a new namespace: `JsonFromJsonText` (the reader and canonical writer - of JSON text), `canonicalJson` (a `Result`) and `CanonicalJsonRejected`. -- `FrontEnd.formatDocModel` and `FrontEnd.formatTsdocMetadata` return a - `Result` instead of a `string`, and `Verdict.cell` reports a schema error on - its write channel. Callers propagate the typed failures. +- `ApiModel.ApiModelFromJsonText` replaces `ApiModel.decode` and `ApiModel.encode`, which are removed. +- `Verdict.RuleCorpusFromJsonText` replaces `Verdict.decodeRuleCorpus`, which is removed. `Verdict.VerdictFromJsonText` is new. +- `FrontEnd.PackageManifestFromJsonText`, `FrontEnd.ExportTargetFromPackageExports` and the `FrontEnd.ExportTarget` type are new. +- `Json` is a new namespace: `canonicalJsonOf(schema)` gives a schema's canonical JSON text (keys in code-unit order, two-space indentation, a trailing newline), and `CanonicalJson` and `canonicalJson` do the same for any JSON value. +- `FrontEnd.formatDocModel` and `FrontEnd.formatTsdocMetadata` return a `Result`, and `Verdict.cell` reports a `SchemaError` on its write channel, instead of throwing. -The serialised model's bytes and `API_MODEL_SCHEMA_VERSION` are unchanged. -Breaking for pre-1.0 consumers. +The serialised model's bytes and `API_MODEL_SCHEMA_VERSION` are unchanged. This is breaking for pre-1.0 consumers. From 301e21cd227c465c52d13020ca1ba84c9c6a843c Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:28:21 -0500 Subject: [PATCH 6/9] fix: compare canonical keys in the verdict property; pin key order in canonical JSON --- .changeset/codec-standard.md | 3 ++- .../judge-surfaces.workflow.property.test.ts | 4 ++-- .../tests/serialise.integration.test.ts | 19 +++++++++++++++++-- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/.changeset/codec-standard.md b/.changeset/codec-standard.md index 05eb4bf5b..20c84310e 100644 --- a/.changeset/codec-standard.md +++ b/.changeset/codec-standard.md @@ -8,6 +8,7 @@ Every JSON encoding is now an Effect Schema, and no published encode or decode t - `Verdict.RuleCorpusFromJsonText` replaces `Verdict.decodeRuleCorpus`, which is removed. `Verdict.VerdictFromJsonText` is new. - `FrontEnd.PackageManifestFromJsonText`, `FrontEnd.ExportTargetFromPackageExports` and the `FrontEnd.ExportTarget` type are new. - `Json` is a new namespace: `canonicalJsonOf(schema)` gives a schema's canonical JSON text (keys in code-unit order, two-space indentation, a trailing newline), and `CanonicalJson` and `canonicalJson` do the same for any JSON value. +- `ApiModel.serialise` returns an `Effect` that can fail with a `SchemaError`, instead of a `string`. - `FrontEnd.formatDocModel` and `FrontEnd.formatTsdocMetadata` return a `Result`, and `Verdict.cell` reports a `SchemaError` on its write channel, instead of throwing. -The serialised model's bytes and `API_MODEL_SCHEMA_VERSION` are unchanged. This is breaking for pre-1.0 consumers. +The serialised model's bytes and `API_MODEL_SCHEMA_VERSION` are unchanged. In a free-form JSON value, an object whose keys look like array indexes (`"2"`, `"10"`) now lists those keys first in ascending numeric order, as JavaScript does; every other key is still in code-unit order. This is breaking for pre-1.0 consumers. 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 01f1cad3b..49532cc99 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,6 @@ import { describe } from '@systemfsoftware/vitest' import { Result } from 'effect' -import { canonicalJson, type Json } from '../canonical-json.schema.js' +import { canonicalKey, type Json } from '../canonical-json.schema.js' 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 +37,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: Json, right: Json): boolean => canonicalKey(left) === canonicalKey(right) const verdict = (bump: Bump, ...findings: ReadonlyArray]>) => ({ bump, findings }) const surface = (item: ApiItem): ApiModel => rootedWith(empty, [item]) diff --git a/packages/api-extractor/tests/serialise.integration.test.ts b/packages/api-extractor/tests/serialise.integration.test.ts index 2e59b7400..48d9a142b 100644 --- a/packages/api-extractor/tests/serialise.integration.test.ts +++ b/packages/api-extractor/tests/serialise.integration.test.ts @@ -1,6 +1,6 @@ import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' -import { ApiModel } from '@systemfsoftware/api-extractor' -import { Arbitrary, Effect, Layer, Schema } from 'effect' +import { ApiModel, Json } from '@systemfsoftware/api-extractor' +import { Arbitrary, Effect, Layer, Result, Schema } from 'effect' import { empty, functionItem, ref, rootedWith, signature } from './__fixtures__/surfaces.js' type Model = ApiModel.ApiModel @@ -90,6 +90,21 @@ Feature('The serialised model is a canonical, versioned form of the surface') ), ) + scenario( + 'a JSON object written with its keys in either order gives the same canonical text', + Gherkin.Do.pipe( + Given('one nested object built with its keys in opposite orders')('objects', () => + Effect.sync(() => ({ left: { b: 1, a: { d: true, c: null } }, right: { a: { c: null, d: true }, b: 1 } })), + ), + When('each is written as canonical JSON')('texts', (scope) => + Effect.sync(() => ({ left: Json.canonicalJson(scope.objects.left), right: Json.canonicalJson(scope.objects.right) })), + ), + Then('both texts list the keys in code-unit order')((scope, expect) => + expect([scope.texts.left, scope.texts.right]).toEqual([0, 1].map(() => Result.succeed('{\n "a": {\n "c": null,\n "d": true\n },\n "b": 1\n}\n'))), + ), + ), + ) + scenario( 'a model declaring an older schema version is refused', Gherkin.Do.pipe( From d672b0f00f7139c77cb5394c55ebde2d049b9986 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:41:28 -0500 Subject: [PATCH 7/9] refactor: delete the canonical JSON module; each format encodes through its own schema Every JSON text is Schema.fromJsonString over the format's schema. The shared wrapper, the key-sorting replacer, canonicalKey and the Json namespace are deleted. Structural keys for types, signatures and items encode through their own schemas. The verdict writer encodes from Schema.toEncoded(Verdict), because the cell hands it the encoded verdict. The scenario asserting the removed trailing newline is deleted. --- .changeset/codec-standard.md | 11 ++---- AGENTS.md | 4 +- apps/api-extractor-profile/profile.ts | 14 ++++--- packages/api-extractor/src/Json.ts | 1 - .../judge-surfaces.workflow.property.test.ts | 5 +-- .../src/canonical-json.schema.ts | 37 ------------------- packages/api-extractor/src/cli.ts | 5 +-- .../api-extractor/src/diff/change.schema.ts | 28 +++++++++----- .../src/diff/direction.schema.ts | 5 +-- .../src/front-end/canonical-type-text.ts | 5 +-- .../src/front-end/package-source.schema.ts | 3 +- .../api-extractor/src/input/config-file.ts | 3 +- .../src/input/node-extraction-input.ts | 3 +- packages/api-extractor/src/mod.ts | 1 - .../src/model/api-model.schema.ts | 12 ++++-- .../src/model/type-expr.schema.ts | 19 +++++++--- .../api-extractor/src/output/doc-model.ts | 7 +++- .../src/output/tsdoc-metadata.ts | 7 +++- .../api-extractor/src/rules/corpus.schema.ts | 3 +- packages/api-extractor/src/verdict.cell.ts | 4 +- packages/api-extractor/src/verdict.schema.ts | 3 +- .../tests/__fixtures__/json-text.ts | 7 ++-- .../front-end-routing.integration.test.ts | 6 +-- .../tests/package-reader.integration.test.ts | 6 +-- .../tests/serialise.integration.test.ts | 19 +--------- .../tests/verdict.integration.test.ts | 21 ----------- 26 files changed, 93 insertions(+), 146 deletions(-) delete mode 100644 packages/api-extractor/src/Json.ts delete mode 100644 packages/api-extractor/src/canonical-json.schema.ts diff --git a/.changeset/codec-standard.md b/.changeset/codec-standard.md index 20c84310e..656885463 100644 --- a/.changeset/codec-standard.md +++ b/.changeset/codec-standard.md @@ -2,13 +2,10 @@ "@systemfsoftware/api-extractor": minor --- -Every JSON encoding is now an Effect Schema, and no published encode or decode throws. +Every JSON encoding is now its format's Effect Schema through `Schema.fromJsonString`, and no published encode or decode throws. -- `ApiModel.ApiModelFromJsonText` replaces `ApiModel.decode` and `ApiModel.encode`, which are removed. +- `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` type are new. -- `Json` is a new namespace: `canonicalJsonOf(schema)` gives a schema's canonical JSON text (keys in code-unit order, two-space indentation, a trailing newline), and `CanonicalJson` and `canonicalJson` do the same for any JSON value. -- `ApiModel.serialise` returns an `Effect` that can fail with a `SchemaError`, instead of a `string`. +- `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. - -The serialised model's bytes and `API_MODEL_SCHEMA_VERSION` are unchanged. In a free-form JSON value, an object whose keys look like array indexes (`"2"`, `"10"`) now lists those keys first in ascending numeric order, as JavaScript does; every other key is still in code-unit order. This is breaking for pre-1.0 consumers. +- 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 ed3afa8c2..718e77674 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-profile/profile.ts b/apps/api-extractor-profile/profile.ts index cd01cadc1..419eaa49d 100644 --- a/apps/api-extractor-profile/profile.ts +++ b/apps/api-extractor-profile/profile.ts @@ -1,5 +1,5 @@ import { NodeRuntime, NodeServices } from '@effect/platform-node' -import { type ApiModel, FrontEnd, Json } from '@systemfsoftware/api-extractor' +import { type ApiModel, FrontEnd } from '@systemfsoftware/api-extractor' import { Array as Arr, Duration, Effect, FileSystem, Layer, Option, Order, Path, Result, Schema, Stream } from 'effect' import type { PlatformError } from 'effect/PlatformError' import { ChildProcess, ChildProcessSpawner } from 'effect/process' @@ -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) @@ -81,7 +85,7 @@ const readManifest = (root: string) => const fileSystem = yield* FileSystem.FileSystem const path = yield* Path.Path const text = yield* fileSystem.readFileString(path.join(root, 'package.json')) - const json = yield* Schema.decodeUnknownEffect(Json.CanonicalJson)(text) + const json = yield* Schema.decodeUnknownEffect(JsonText)(text) return yield* Schema.decodeUnknownEffect(Manifest)(json) }) @@ -161,7 +165,7 @@ 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') - const text = yield* Effect.fromResult(Json.canonicalJson({ + const text = yield* Effect.fromResult(jsonText({ extends: tsconfig, compilerOptions: { noEmit: false, @@ -427,7 +431,7 @@ const markdownOf = (report: Report): Result.Result = `| ${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 Result.map(Json.canonicalJson(Object.fromEntries(Object.entries(report).filter(([key]) => key !== 'packages'))), (summary) => + return Result.map(jsonText(Object.fromEntries(Object.entries(report).filter(([key]) => key !== 'packages'))), (summary) => [ '# Front-end phase profile', '', @@ -469,7 +473,7 @@ const program = Effect.gen(function* () { totals: Object.fromEntries(PHASES.map((phase) => [phase, total(packages, phase, 'warmMedianMs')])), packages, } - yield* fileSystem.writeFileString(`${outputArgument}.json`, yield* Effect.fromResult(Json.canonicalJson(report))) + yield* fileSystem.writeFileString(`${outputArgument}.json`, yield* Effect.fromResult(jsonText(report))) yield* fileSystem.writeFileString(`${outputArgument}.md`, yield* Effect.fromResult(markdownOf(report))) }) diff --git a/packages/api-extractor/src/Json.ts b/packages/api-extractor/src/Json.ts deleted file mode 100644 index b9998a36e..000000000 --- a/packages/api-extractor/src/Json.ts +++ /dev/null @@ -1 +0,0 @@ -export { CanonicalJson, canonicalJson, canonicalJsonOf, type Json } from './canonical-json.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 49532cc99..f81b61641 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 { canonicalKey, 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 => canonicalKey(left) === canonicalKey(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 98029b807..000000000 --- a/packages/api-extractor/src/canonical-json.schema.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Canonical JSON is Effect's `Schema.fromJsonString` with one replacer that - * orders object keys by UTF-16 code unit (`Order.String`), so the bytes never - * depend on the process locale, time zone or host. `Schema.Json` refuses a - * non-finite number, so no output can hold one. - */ -import { Order, Predicate, Result, Schema, SchemaGetter } from 'effect' - -export type Json = Schema.Json - -type Entry = readonly [string, Json] - -const byKey: Order.Order = Order.mapInput(Order.String, ([key]: Entry) => key) - -const isJsonObject = (value: Json): value is Schema.JsonObject => Predicate.isObject(value) && !Array.isArray(value) - -const sortKeys = (_key: string, value: Json): Json => - isJsonObject(value) ? Object.fromEntries(Object.entries(value).sort(byKey)) : value - -/** A schema's canonical JSON text: keys in code-unit order, two-space indentation, a trailing newline. Decode accepts any key order. */ -export type CanonicalJsonText = Schema.Codec - -export const canonicalJsonOf = (schema: Schema.Codec): CanonicalJsonText => - Schema.fromJsonString(schema, { replacer: sortKeys, space: 2 }).pipe( - Schema.encode({ decode: SchemaGetter.passthrough(), encode: SchemaGetter.transform((text: string) => `${text}\n`) }), - ) - -/** Any JSON value as canonical JSON text. */ -export const CanonicalJson: Schema.Codec = canonicalJsonOf(Schema.Json) - -/** Writes a JSON value as canonical JSON text. */ -export const canonicalJson = (value: Json): Result.Result => Schema.encodeResult(CanonicalJson)(value) - -const CompactJson: Schema.Codec = Schema.fromJsonString(Schema.Json, { replacer: sortKeys }) - -/** The same key order on one line: a structural identity key. */ -export const canonicalKey = (value: Json): string => Result.getOrThrow(Schema.encodeResult(CompactJson)(value)) diff --git a/packages/api-extractor/src/cli.ts b/packages/api-extractor/src/cli.ts index 87c259264..442e74eac 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, Predicate, type Schema } 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' @@ -95,7 +94,7 @@ const initialize = (path: Path.Path) => (folder: string): Effect.Effect process.stdout.write(`Writing configuration file: ${file}\n`)) }) diff --git a/packages/api-extractor/src/diff/change.schema.ts b/packages/api-extractor/src/diff/change.schema.ts index a9a332e42..892fcbc06 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 f97f53233..bc829d9dd 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 5ebd2cc1d..fbaebaf4d 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 { canonicalKey } from '../canonical-json.schema.js' import { KeywordName } from '../model/type-expr.schema.js' import { type Declaration, @@ -52,7 +51,7 @@ import { 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 => canonicalKey(value) +const jsonText = (value: string): string => Result.getOrThrow(Schema.encodeResult(Schema.fromJsonString(Schema.String))(value)) export type ReferenceTarget = { readonly name: string 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 570b1a040..0227a74bf 100644 --- a/packages/api-extractor/src/front-end/package-source.schema.ts +++ b/packages/api-extractor/src/front-end/package-source.schema.ts @@ -1,5 +1,4 @@ import { Match, Predicate, Schema, SchemaTransformation } from 'effect' -import { canonicalJsonOf } from '../canonical-json.schema.js' 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. */ @@ -67,4 +66,4 @@ 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 = canonicalJsonOf(PackageManifest) +export const PackageManifestFromJsonText: PackageManifestFromJsonText = Schema.fromJsonString(PackageManifest, { space: 2 }) diff --git a/packages/api-extractor/src/input/config-file.ts b/packages/api-extractor/src/input/config-file.ts index 7a78673c6..e08969304 100644 --- a/packages/api-extractor/src/input/config-file.ts +++ b/packages/api-extractor/src/input/config-file.ts @@ -1,6 +1,5 @@ import { Effect, FileSystem, Function as Fn, Match, Option, Path, Schema } from 'effect' import type { PlatformError } from 'effect/PlatformError' -import { CanonicalJson } from '../canonical-json.schema.js' import { isAbsent } from '../front-end/package-file.js' import { type JsonObject, isJsonObject } from './config-merge.js' import { ConfigRejected } from './extraction-input-error.schema.js' @@ -12,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(CanonicalJson) +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 a1357546b..797ac4ab4 100644 --- a/packages/api-extractor/src/input/node-extraction-input.ts +++ b/packages/api-extractor/src/input/node-extraction-input.ts @@ -1,6 +1,5 @@ import { Array as Arr, Effect, FileSystem, Layer, Option, Path, Predicate, Schema } from 'effect' import type { PlatformError } from 'effect/PlatformError' -import { CanonicalJson } from '../canonical-json.schema.js' import type { CompilerOverride, PackageSource, SourceEntryPoint } from '../front-end/declarations.schema.js' import { type ManifestRejected, NoSourceEntry } from '../front-end/front-end-error.schema.js' import { readPackage } from '../front-end/read-package.js' @@ -104,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(CanonicalJson)(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/mod.ts b/packages/api-extractor/src/mod.ts index 6fcaef99f..8b317c21d 100644 --- a/packages/api-extractor/src/mod.ts +++ b/packages/api-extractor/src/mod.ts @@ -1,5 +1,4 @@ export * as ApiModel from './ApiModel.js' export * as Extractor from './Extractor.js' export * as FrontEnd from './FrontEnd.js' -export * as Json from './Json.js' export * as Verdict from './Verdict.js' diff --git a/packages/api-extractor/src/model/api-model.schema.ts b/packages/api-extractor/src/model/api-model.schema.ts index 91305b5a1..2f723e9df 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, Order, Schema } from 'effect' -import { canonicalJsonOf, canonicalKey } 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,11 +170,16 @@ export const ApiModel: Schema.Codec = Schema.Struct({ ).check(uniqueBy('entry points', (entry: { readonly path: string }) => entry.path)), }) +const ApiItemText: Schema.Codec = Schema.fromJsonString(ApiItem) + +/** 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) @@ -206,4 +210,4 @@ export const sortModel = (model: ApiModel): ApiModel => ({ */ export type ApiModelFromJsonText = Schema.Codec -export const ApiModelFromJsonText: ApiModelFromJsonText = canonicalJsonOf(ApiModel) +export const ApiModelFromJsonText: ApiModelFromJsonText = Schema.fromJsonString(ApiModel, { space: 2 }) diff --git a/packages/api-extractor/src/model/type-expr.schema.ts b/packages/api-extractor/src/model/type-expr.schema.ts index b0c483e22..370c6c076 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 a533baa5d..19505013a 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, Result, type Schema } 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' diff --git a/packages/api-extractor/src/output/tsdoc-metadata.ts b/packages/api-extractor/src/output/tsdoc-metadata.ts index f63dcdcb4..74b6d281b 100644 --- a/packages/api-extractor/src/output/tsdoc-metadata.ts +++ b/packages/api-extractor/src/output/tsdoc-metadata.ts @@ -1,5 +1,8 @@ -import type { Result, Schema } from 'effect' -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' diff --git a/packages/api-extractor/src/rules/corpus.schema.ts b/packages/api-extractor/src/rules/corpus.schema.ts index 2e56b5022..24c9f833d 100644 --- a/packages/api-extractor/src/rules/corpus.schema.ts +++ b/packages/api-extractor/src/rules/corpus.schema.ts @@ -1,5 +1,4 @@ import { Array as Arr, Function, Option, Order, Schema } from 'effect' -import { canonicalJsonOf } from '../canonical-json.schema.js' import { type Change, ChangeKind } from '../diff/change.schema.js' import { Direction } from '../diff/direction.schema.js' import { ChannelType, Position } from '../diff/position.schema.js' @@ -54,7 +53,7 @@ export const RuleCorpus: Schema.Codec = Schema.Struct({ */ export type RuleCorpusFromJsonText = Schema.Codec -export const RuleCorpusFromJsonText: RuleCorpusFromJsonText = canonicalJsonOf(RuleCorpus) +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/verdict.cell.ts b/packages/api-extractor/src/verdict.cell.ts index e307a170a..6f10d72a7 100644 --- a/packages/api-extractor/src/verdict.cell.ts +++ b/packages/api-extractor/src/verdict.cell.ts @@ -4,7 +4,7 @@ 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, Verdict, VerdictFromJsonText } 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). */ @@ -34,7 +34,7 @@ export const verdictCell: Sandwich.WrittenCell Schema.encodeUnknownEffect(VerdictFromJsonText)(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 9f4670ee8..b27cee62d 100644 --- a/packages/api-extractor/src/verdict.schema.ts +++ b/packages/api-extractor/src/verdict.schema.ts @@ -1,6 +1,5 @@ import { Workflow } from '@systemfsoftware/effect-cell-types' import { Cause, Schema } from 'effect' -import { canonicalJsonOf } from './canonical-json.schema.js' import { ApiModel } from './model/api-model.schema.js' import { Bump, RuleCorpus } from './rules/corpus.schema.js' import { Findings } from './rules/finding.schema.js' @@ -45,7 +44,7 @@ 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 = canonicalJsonOf(Verdict) +export const VerdictFromJsonText: VerdictFromJsonText = Schema.fromJsonString(Verdict, { space: 2 }) type CorpusAmbiguityFields = { readonly corpusVersion: Schema.String diff --git a/packages/api-extractor/tests/__fixtures__/json-text.ts b/packages/api-extractor/tests/__fixtures__/json-text.ts index 091f17e8f..65ac442e6 100644 --- a/packages/api-extractor/tests/__fixtures__/json-text.ts +++ b/packages/api-extractor/tests/__fixtures__/json-text.ts @@ -1,4 +1,5 @@ -import { Json } from '@systemfsoftware/api-extractor' -import { Result } from 'effect' +import { Result, Schema } from 'effect' -export const jsonText = (value: Json.Json): string => Result.getOrThrow(Json.canonicalJson(value)) +const codec = Schema.fromJsonString(Schema.Json, { space: 2 }) + +export const jsonText = (value: Schema.Json): string => Result.getOrThrow(Schema.encodeResult(codec)(value)) 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 bd1023e2a..a3f6f0f48 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, Json } from '@systemfsoftware/api-extractor' +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: Json.Json, 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 1d23c38e7..8ea932257 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, Json } from '@systemfsoftware/api-extractor' +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: Json.Json, 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 48d9a142b..2e59b7400 100644 --- a/packages/api-extractor/tests/serialise.integration.test.ts +++ b/packages/api-extractor/tests/serialise.integration.test.ts @@ -1,6 +1,6 @@ import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec' -import { ApiModel, Json } from '@systemfsoftware/api-extractor' -import { Arbitrary, Effect, Layer, Result, Schema } from 'effect' +import { ApiModel } from '@systemfsoftware/api-extractor' +import { Arbitrary, Effect, Layer, Schema } from 'effect' import { empty, functionItem, ref, rootedWith, signature } from './__fixtures__/surfaces.js' type Model = ApiModel.ApiModel @@ -90,21 +90,6 @@ Feature('The serialised model is a canonical, versioned form of the surface') ), ) - scenario( - 'a JSON object written with its keys in either order gives the same canonical text', - Gherkin.Do.pipe( - Given('one nested object built with its keys in opposite orders')('objects', () => - Effect.sync(() => ({ left: { b: 1, a: { d: true, c: null } }, right: { a: { c: null, d: true }, b: 1 } })), - ), - When('each is written as canonical JSON')('texts', (scope) => - Effect.sync(() => ({ left: Json.canonicalJson(scope.objects.left), right: Json.canonicalJson(scope.objects.right) })), - ), - Then('both texts list the keys in code-unit order')((scope, expect) => - expect([scope.texts.left, scope.texts.right]).toEqual([0, 1].map(() => Result.succeed('{\n "a": {\n "c": null,\n "d": true\n },\n "b": 1\n}\n'))), - ), - ), - ) - scenario( 'a model declaring an older schema version is refused', Gherkin.Do.pipe( diff --git a/packages/api-extractor/tests/verdict.integration.test.ts b/packages/api-extractor/tests/verdict.integration.test.ts index f532ac07a..1c7adb9af 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( From 07fbd57e9a9b65b9141ead31954aa62e8b5ccaaf Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:50:37 -0500 Subject: [PATCH 8/9] fix: key items as plain JSON so a typed item with repeated enum members has a key --- .changeset/codec-standard.md | 4 ++-- packages/api-extractor/README.md | 2 +- packages/api-extractor/src/model/api-model.schema.ts | 8 +++----- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/.changeset/codec-standard.md b/.changeset/codec-standard.md index 656885463..333c3ff3e 100644 --- a/.changeset/codec-standard.md +++ b/.changeset/codec-standard.md @@ -2,10 +2,10 @@ "@systemfsoftware/api-extractor": minor --- -Every JSON encoding is now its format's Effect Schema through `Schema.fromJsonString`, and no published encode or decode throws. +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.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/packages/api-extractor/README.md b/packages/api-extractor/README.md index 091f2862e..2fdf3ff71 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/model/api-model.schema.ts b/packages/api-extractor/src/model/api-model.schema.ts index 2f723e9df..80e15b5c9 100644 --- a/packages/api-extractor/src/model/api-model.schema.ts +++ b/packages/api-extractor/src/model/api-model.schema.ts @@ -170,10 +170,8 @@ export const ApiModel: Schema.Codec = Schema.Struct({ ).check(uniqueBy('entry points', (entry: { readonly path: string }) => entry.path)), }) -const ApiItemText: Schema.Codec = Schema.fromJsonString(ApiItem) - -/** An item's structural identity: its JSON text. */ -export const itemKey = (item: ApiItem): string => Result.getOrThrow(Schema.encodeResult(ApiItemText)(item)) +/** An item's structural identity: its JSON text, encoded as plain JSON so the item's own checks never refuse a typed item. */ +export const itemKey = (item: ApiItem): string => Result.getOrThrow(Schema.encodeResult(Schema.fromJsonString(Schema.Json))(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([ @@ -205,7 +203,7 @@ export const sortModel = (model: ApiModel): ApiModel => ({ /** * 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 canonical code-unit order. Item order is canonicalised by + * 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 From df52a2a47f530c7e121c01080c3f15c9897d8da0 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:51:29 -0500 Subject: [PATCH 9/9] revert: key items through the item schema again; plain JSON keys followed insertion order --- packages/api-extractor/src/model/api-model.schema.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/api-extractor/src/model/api-model.schema.ts b/packages/api-extractor/src/model/api-model.schema.ts index 80e15b5c9..537131984 100644 --- a/packages/api-extractor/src/model/api-model.schema.ts +++ b/packages/api-extractor/src/model/api-model.schema.ts @@ -170,8 +170,10 @@ export const ApiModel: Schema.Codec = Schema.Struct({ ).check(uniqueBy('entry points', (entry: { readonly path: string }) => entry.path)), }) -/** An item's structural identity: its JSON text, encoded as plain JSON so the item's own checks never refuse a typed item. */ -export const itemKey = (item: ApiItem): string => Result.getOrThrow(Schema.encodeResult(Schema.fromJsonString(Schema.Json))(item)) +const ApiItemText: Schema.Codec = Schema.fromJsonString(ApiItem) + +/** 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([