VERSION_FIELDconstconst VERSION_FIELD: "$version"The field of a document that holds its version.
The version of a document as code: a schema has the number of the version it writes, the decoder of that version and the pure functions that bring each older version to the next. A document carries its version in the field $version; one without the field is version 1. A document of a version newer than the schema's is refused and never guessed at, and one of an older version is read through the migrations and said to be stale, so that a collection can write it again at the current version.
import { defineSchema, versioned } from "./schema.ts";
import { jsonTree } from "./codec.ts";
import { number, object, string } from "@intellectual-frontiers/core";
const schema = defineSchema({ current: 1, decoder: object({ name: string, size: number }) });
schema.kind === "ok" && versioned(jsonTree, schema.value).mediaType; // "application/json"VERSION_FIELDconstconst VERSION_FIELD: "$version"The field of a document that holds its version.
Migrationtypetype Migration = { readonly from: number; readonly up: (value: JsonObject) => Result<JsonObject, string> };The step from one version to the next: a pure function of the object of that version, without its version field.
Schematypeno test imports ittype Schema<T> = {
readonly current: number;
readonly decoder: Decoder<T>;
readonly encode: (value: T) => Result<JsonObject, string>;
readonly migrations: readonly Migration[];
};The version a document is written at, how to read it and how to bring an older one forward.
SchemaSpectypeno test imports ittype SchemaSpec<T> = {
readonly current: number;
readonly decoder: Decoder<T>;
readonly encode?: (value: T) => Result<JsonObject, string>;
readonly migrations?: readonly Migration[];
};What a schema is made from.
defineSchemafunctionfunction defineSchema<T>(spec: SchemaSpec<T>): Result<Schema<T>, string>A schema, or why the specification is not one: the version is a positive whole number and the migrations step from 1 to the version before it, in order and with none missing.
versionedfunctionfunction versioned<T>(tree: Codec<JsonValue>, schema: Schema<T>): Codec<T>The codec of a schema over a codec of JSON trees: it writes the current version and reads any version up to it.