TypeScript datamodel packages

Every datamodel project gets an npm package next to its Java artifact and its Python package, so a Node service or klok-cli can produce and consume the datamodel on the broker with the same bytes a Java route reads and writes. The datamodel pipeline does not need to know about it: the pipeline already runs gradle publish jreleaserFullRelease in the generated Java project on main, and for a project with projectType = DATAMODEL the plugin makes publish depend on publishKlokTypeScriptDatamodel.

Java TypeScript
dev.klok.klok.datamodel:kloktaskevent-v1:1.0.0-build.260923014318 @klok/datamodel-kloktaskevent-v1@1.0.0-build.260923014318
dev.klok.klok.datamodel.common.kloktaskevent_v1.KlokTaskStatusEventV1 import { KlokTaskStatusEventV1 } from "@klok/datamodel-kloktaskevent-v1"
published to the project's Maven registry published to the project's npm registry, or staged on npmjs.org when public

Names, registries and versions

Datamodel visibility (klok.projectVisibility) npm name Registry License
PUBLIC @klok-integration/datamodel-<artifact> https://registry.npmjs.org/, public access, staged for a person to publish with 2FA Apache-2.0
anything else @<tenant>/datamodel-<artifact> the GitLab npm registry of the datamodel project UNLICENSED

<artifact> is the Maven artifact id and <tenant> is klok.tenant, both in lower case with anything but letters and digits turned into a dash, as in the Python distribution name. klok-integration is the scope Klok owns on the public registry.

The version is the Java version. 1.0.0-build.<timestamp> is valid semver and is used as it is; a Java version x.y.z+<timestamp> becomes x.y.z-build.<timestamp>, because npm ignores build metadata and two builds would otherwise claim the same version. Every datamodel version is therefore a semver prerelease, which a range such as ^1.0.0 does not select: pin the exact version, as a Java project takes it from the catalog.

Installing a datamodel package

A private package is in the GitLab npm registry of its datamodel project, and the group registry of the tenant aggregates them. In .npmrc:

@klok:registry=https://git.klok.dev/api/v4/groups/<group id>/-/packages/npm/
//git.klok.dev/api/v4/groups/<group id>/-/packages/npm/:_authToken=${GITLAB_TOKEN}

The token is a personal access token with read_api by hand, or CI_JOB_TOKEN in a pipeline. Then:

npm install --save-exact @klok/datamodel-kloktaskevent-v1@1.0.0-build.260923014318

A public package needs no configuration: npm install --save-exact @klok-integration/datamodel-<artifact>@<version>.

What the package contains

package.json
README.md
index.js          ESM entry
index.cjs         CommonJS entry, the same code
index.d.ts        types for import
index.d.cts       the same types for require
_avro.js / _avro.cjs    avsc helpers: the logical types, one parsed type per schema, the writer schema resolver
schemas/reflected/<Record>.avsc   the wire schema of each record class (schemas/<Record>.avsc once embedded)

The package depends on avsc (^5.7.9) only, needs Node 18 or later, and knows nothing about the broker. It exports KLOK_PACKAGE_VERSION, KLOK_TENANT, KLOK_JAVA_ARTIFACT (group:artifact:version), KLOK_DOC_ID and KLOK_WIRE_SCHEMA_SOURCE ("reflected" or "embedded"), and one class per record and one enum per enum:

export const KlokTaskStatusType = { PENDING: "PENDING", IN_PROGRESS: "IN_PROGRESS", /* ... */ } as const;
export type KlokTaskStatusType = (typeof KlokTaskStatusType)[keyof typeof KlokTaskStatusType];

export class KlokTaskStatusEventV1 {
  static readonly KLOK_JAVA_CLASS: string;   // the Java class it mirrors
  static readonly KLOK_MODEL_NAME: string;   // the simple name, which topic names and the default ce-type use
  static readonly KLOK_AVRO_SCHEMA: string;  // the exact schema string Java registers on the topic
  static readonly KLOK_DATA_SCHEMA: string;  // urn:klok:schema:<docId>:<Record>:<Java version>, for ce-dataschema

  taskId: string | null;
  sequence: number;                          // a Java primitive: never null, 0 by default
  status: KlokTaskStatusType | null;
  timestamp: Date | null;
  // ...

  constructor(init?: KlokTaskStatusEventV1Init);   // every field optional
  toAvro(): Record<string, unknown>;
  static fromAvro(value: Record<string, unknown>): KlokTaskStatusEventV1;
  toAvroBuffer(): Buffer;
  static fromAvroBuffer(data: Uint8Array, writerSchema?: string | null): KlokTaskStatusEventV1;
}

A record that only appears nested in another has KLOK_AVRO_SCHEMA and KLOK_DATA_SCHEMA typed null, and its toAvroBuffer() throws: encode the record that contains it. KLOK_DATA_SCHEMA is also null when the plugin does not know the documentation id of the project (no klokDocs.repoPath and no CI_PROJECT_PATH).

Enum values are the symbols Java writes, which are the Java constant names ("IN_PROGRESS"), not the values in the XSD. Field names are the wire names; a field that would shadow a method (toAvro, toAvroBuffer, constructor) gets a trailing underscore as a property and keeps its name on the wire.

Encoding and decoding

import { KlokTaskStatusEventV1, KlokTaskStatusType } from "@klok/datamodel-kloktaskevent-v1";

const event = new KlokTaskStatusEventV1({
  taskId: "task-1",
  sequence: 3,
  status: KlokTaskStatusType.IN_PROGRESS,
  timestamp: new Date(),
});
const bytes = event.toAvroBuffer();                        // what a Java route reads with Schema.AVRO
const back = KlokTaskStatusEventV1.fromAvroBuffer(bytes);  // nested records are class instances again

toAvroBuffer() writes Avro binary without a header, as Pulsar carries a payload. A value the schema does not accept fails with the fields named (Cannot encode ...KlokTaskStatusEventV1: invalid value in sequence, status). fromAvroBuffer(data, writerSchema) decodes with the package's schema, or, when the producer wrote with another version of the schema, resolves from writerSchema to it.

Avro in the wire schema TypeScript
string string
boolean boolean
int, long, float, double number
long with timestamp-micros or timestamp-millis Date
int with date Date at midnight UTC
int with time-millis, long with time-micros the time of day as an ISO 8601 string, "08:30:15.250" ("08:30:15.250000" for micros)
bytes, fixed Buffer
enum the enum's string union
array T[]
map Record<string, T>
["null", T] T | null, optional in Init, null by default
record the generated class

A field that is not nullable keeps Java's default when it is not set: 0, false, "", an empty array or map.

With the broker client

The Klok broker client for TypeScript takes the generated class, never a plain object literal, as the Python client refuses dicts. A class is a payload class when it has a static string KLOK_AVRO_SCHEMA and a static fromAvroBuffer, and its instances have toAvroBuffer. From it the client takes:

Member Used for
KLOK_AVRO_SCHEMA the Avro schema the producer and the consumer register, unchanged
KLOK_MODEL_NAME the topic name and the default ce-type
KLOK_DATA_SCHEMA ce-dataschema
KLOK_JAVA_CLASS messageType of the V4 log event
toAvroBuffer(), fromAvroBuffer(data, writerSchema) the payload; the client passes the producer's schema when it differs

The client's own API is described in the broker client documentation (klok/framework/klok-brokerclient-java).

Where the schema comes from

The package is generated from the schema Java registers on the topic, from the same build/klok/datamodel/wire-schemas.json the Python package is generated from, and not from the .avsc the pipeline derives from the XSD. The two differ in namespace, field order, nullability and enum symbols, and an encoding with the .avsc is unreadable by a Java consumer; Python datamodel packages explains the dump and the measurement behind it. While the datamodels are plain POJOs the package carries schemas/reflected/<Record>.avsc and KLOK_WIRE_SCHEMA_SOURCE = "reflected"; once a datamodel embeds SCHEMA$, the same dump yields that schema and the package carries schemas/<Record>.avsc and "embedded", with no generator change.

A time of day is what Java's LocalTime is on the wire, and what an xs:time element of a datamodel becomes: a count since midnight. JavaScript has no type for it, so the package reads and writes the ISO 8601 form Java prints: "08:30", "08:30:15" and "08:30:15.250" are accepted, digits beyond the precision are dropped as LocalTime drops them, and anything else ("24:00", "8:30") fails the encoding with the field named.

Anything the package cannot express faithfully stops the build with the record and field named, rather than producing a package that writes bytes Java misreads: a logical type other than the ones in the table above (and uuid, which stays a string), or a union other than ["null", T]. Reflected schemas do not contain them today.

Tasks

Task Does
dumpKlokWireSchemas writes build/klok/datamodel/wire-schemas.json; shared with the Python package and run once
buildKlokTypeScriptDatamodel writes the package to build/klok/typescript/package/ and packs build/klok/typescript/<name without scope>-<version>.tgz
publishKlokTypeScriptDatamodel publishes the tarball, or stages it when public; publish depends on it

Run them by hand in a generated datamodel project:

./gradlew updateKlokLibsToml buildKlokTypeScriptDatamodel
npm install ./build/klok/typescript/datamodel-<artifact>-<version>.tgz

The tarball is packed in Java (entries under package/, sorted, mode 0644, the fixed time npm pack uses), so the pipeline needs no Node, and the same build gives the same bytes. Publishing to GitLab is the registry's own protocol, the single PUT of a JSON document that npm publish sends, also without the npm CLI. Staging on the public registry runs npm stage publish, which needs npm 11.15 or newer (see below).

How the package is checked

No TypeScript compiler runs when a package is generated, so the plugin's own build checks the generator against a real Node (TypeScriptInteropTest). Java encodes a sample record with Schema.AVRO and a KlokTaskStatusEventV1 of the real KlokTaskEvent_v1 schema with the Avro Pulsar encodes with; the generated package decodes both through the ESM and the CommonJS entry, encodes them again, and Java decodes the result. A producer on an older version of the schema is read through its writer schema. tsc --strict then type checks a consumer of the declarations as ESM (nodenext) and as CommonJS (node16). The test needs node and npm (to fetch avsc and typescript) and is skipped without them; KLOK_TEST_NODE points it at another Node.

Publishing target

Setting Gradle property Environment variable Default
Registry klokNpmRegistry KLOK_NPM_REGISTRY PUBLIC: https://registry.npmjs.org/; otherwise $CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/npm/
Token for PUBLIC klokNpmToken NPM_TOKEN exported by the Klok Vault login in a pipeline; stage-only
npm CLI for staging klokNpmExecutable KLOK_NPM_EXECUTABLE npm on the PATH
Token otherwise klokNpmToken KLOK_NPM_TOKEN CI_JOB_TOKEN for the pipeline's own project, then klokGitAuthToken / GITLAB_TOKEN
Switch off klokTypeScriptDatamodel=false KLOK_TYPESCRIPT_DATAMODEL=false on

Tokens do not cross registries: NPM_TOKEN is only ever sent to the public registry, and no GitLab token is ever sent there. The job token only goes to the registry of the pipeline's own project, not to a klokNpmRegistry.

Without a target the publish task reports where the tarball is and does nothing, so ./gradlew publish still works on a laptop; a PUBLIC datamodel has a target in a pipeline (CI is set) or when a token is given. A target without a token fails the build, and so does a registry that refuses the package: a release without its TypeScript package is not a complete release. klokTypeScriptDatamodel=false is the way out if a release has to go out without it.

Public packages are staged, and a person publishes them

The public registry follows npm's recommendation: a pipeline never publishes a version of a @klok-integration package, it stages it, and a maintainer publishes it with two-factor authentication. The same holds for klok-cli and the TypeScript broker client, and all of them use one token: NPM_TOKEN in secret/klok/common/repo/cicd-environment-variables, a granular access token with "Read and write (stage only)" on the @klok-integration packages and no 2FA bypass.

For a PUBLIC datamodel publishKlokTypeScriptDatamodel therefore:

  1. reads the package from the registry. A version that is there already is left alone, so a re-run is harmless;
  2. runs npm stage publish <tarball> --access public --tag latest with NPM_TOKEN in the environment (the temporary .npmrc only names ${NPM_TOKEN}, so the token is never written to disk). npm older than 11.15 fails the task; the Klok build image carries a newer one. The --tag latest is required: every datamodel version is a semver prerelease, and npm 11 refuses to stage or publish a prerelease without an explicit dist-tag;
  3. logs that the version is staged. A maintainer publishes it under Staged Packages on npmjs.com, or with npm stage approve <id>, with 2FA.

The first version of a new package is published by hand. npm cannot stage a package that does not exist, so when the registry does not know the package the task stages nothing, logs a warning with the steps, and lets the Java release go on. The tarball is in the job's artifacts (build/klok/typescript/*.tgz):

npm login
npm publish ./datamodel-<artifact>-<version>.tgz --access public --tag latest

The warning prints this command with the real file name. Leave out --tag latest and npm 11 stops with You must specify a tag using --tag when publishing a prerelease version, because the version is a prerelease.

Unless the stage-only token already covers the whole @klok-integration scope, the person who publishes it then adds the new package to the token on npmjs.com (Access Tokens, the token's packages and scopes). After that every release of the datamodel is staged automatically. npm can take a few minutes to show a brand-new package, so a pipeline that runs right after the first publish may still say the package is missing; re-running it then stages normally.

Known limits

  • Timestamps lose their microseconds. A Date holds milliseconds, so decoding a timestamp-micros drops the digits below the millisecond, and a Node service that passes an event on writes …123000 where Java wrote …123456.
  • A long is a number. avsc accepts ±(2^53 − 2) and refuses anything beyond, on decode (potential precision loss) and on encode. Epoch microseconds stay inside that until the year 2255.
  • Not in the dependency catalog. npm versions are not recorded in the catalog, which is Gradle's format, as for Python (klok/framework/klok-gradle-plugin#4); a service pins the version in its own package.json.
  • Public npm needs a person. A staged version is not installable until a maintainer publishes it with 2FA, and the first version of a new public package is published by hand (above). NPM_TOKEN must cover the package, or staging fails with npm's E403/E404 and the release of the datamodel with it.
  • Two entries, two module instances. import and require of the package load separate copies (the usual dual package hazard), so a class from one is not instanceof the other. The broker client recognises a payload class by its members, not by identity.