Skip to content

Write a generator ​

Write a package that registers a golem.yaml block and emits source files, and let golem generate run it before the models job.

Configure the block ​

yaml
payment-events:
  output: src/events
  events:
    PaymentCaptured: { paymentId: string, amount: string }
    PaymentRefunded: { paymentId: string, reason: string }

The key payment-events is the block that the package registers. Its keys are the package's own: output is the directory that the generator owns, and events is an option that the plan entry reads. Golem runs the job before the models job, because the job reads no TypeScript program and the models job does, so the models job reads the files that the generator writes (job order).

Register the block ​

The golem field in the package.json of the package sets four things: apiVersion (2), the block name (payment-events here), and the plan and generator entries.

  • plan exports plan. It reads the block, checks it, and declares the job: the output folder that the job owns. It loads no TypeScript.
  • generator exports apiVersion and generate(context). It runs the job.
  • Both subpaths are keys of exports in the same package.json. The example exports both from one file.

The plan entry of the example:

js
/**
 * The plan entry of the `payment-events` block of golem.yaml (`golem.plan` in package.json): it declares the one job that owns the `output` folder.
 * @type {import('@exprtlabs/golem/generator-api').GolemPlanEntry}
 */
export const plan = {
  declare({ directory, block, profile }) {
    const { output, events } = block ?? {};
    if (typeof output !== 'string') throw new TypeError('payment-events.output must be a string.');
    const folder = path.resolve(directory, output);
    return [{
      facts: { id: 'payment-events', outputs: [{ path: folder, kind: 'folder' }], ownedRoots: [], inputFiles: [], inputFolders: [], readsProgram: false, provides: [], needs: [], hooks: [], watch: [] },
      options: { directory, output: folder, options: { events }, profile },
    }];
  },
};

The field, the plan entry and the facts of a job are in Register a block.

Write the generator ​

The generator module exports apiVersion and generate(context):

js
import path from 'node:path';

const OWNER = 'payments-example';

/** The API version this generator implements. */
export const apiVersion = 1;

/**
 * Writes one `IModel` declaration per entry of `options.events`.
 * @param {import('@exprtlabs/golem/generator-api').GeneratorHostContext & { output: string, options?: { events?: Record<string, Record<string, string>> } }} context
 */
export function generate(context) {
  const events = context.options?.events;
  if (typeof events !== 'object' || events === null || Array.isArray(events)) {
    throw new TypeError('options.events must map event names to their field types.');
  }
  const names = Object.keys(events);
  const declarations = names.map(name => {
    const fields = Object.entries(events[name]).map(([field, type]) => `${field}: ${type}`);
    return [
      `export type T${name} = IModel<{ ${fields.join('; ')} }>;`,
      `export class ${name} extends model<T${name}>() {}`,
    ].join('\n');
  });
  const content = [
    `/* Generated by ${OWNER}. Do not edit. */`, // Every artifact starts with the package's ownership header.
    "import { model, type IModel } from '@exprtlabs/golem/model';",
    '',
    declarations.join('\n\n'),
    '',
  ].join('\n');
  return {
    apiVersion: 1,
    artifacts: [{ path: path.join(context.output, 'payment-events.model.ts'), content }],
    manifestPaths: [],
    watchInputs: [],
  };
}
  • apiVersion is 1. The CLI rejects a generator that reports another version.
  • context holds the options that your plan entry returned for the job, and onInput. In this example the options are the absolute output directory, the events and the profile.
  • generate returns the files as artifacts with absolute paths. It does not write them. Golem does.
  • Each artifact carries your package name as its ownership marker. A text file starts with /* Generated by <package>. Do not edit. */, or with //, # or <!-- in place of /*. A JSON file holds your package name in a top-level x-generator property or in generator.name. A space, a line end or a full stop must follow the package name in a comment. Without a marker, golem refuses the file. golem check reports a file in the output of a job that carries the marker of a configured package and that golem did not record.
  • Throw an error, or return diagnostics with severity error, to stop generation with a message.

Your code imports from golem only through @exprtlabs/golem/generator-api (extension API). It offers helpers such as stableJson, compareText and resolveProfile.

The generator writes source models. The models job makes their codecs. Your package version does not need to match the version of golem.

Announce inputs ​

manifestPaths and watchInputs list the manifests and input files that the generator reads. This generator reads only its options, so both are empty.

Golem skips a generator whose inputs did not change. It learns an input when the generator calls context.onInput(path) before it reads the file. Golem also records a file in watchInputs that the generator did not announce, but it reads that file when the generator returns. If the file changed during the run, the next run runs the generator again. A directory that the generator did not announce makes the generator run every time. Call context.onInput(path) for each file you read, so golem records it at the read.

Check what it writes ​

The generator writes payment-events.model.ts into the output directory. The models job then writes its generated codec file inside model.output (default .golem/models/), leaving src/ clean. Both are generated files. Ignore or commit them with the others (ignore or commit generated files). The .gitignore of the example lists the first file by path.

Use the generated models ​

Import the declarations like any model:

ts
export function readCaptured(text: string): PaymentCaptured {
  return parse<PaymentCaptured>(text); // a PaymentCaptured instance from the generated declaration
}

Publish and install ​

In your own project, publish the generator as a package and install it:

sh
npm install --save-dev your-generator-package

The example project registers the block in its own package.json, so it runs without an install.

Full example: examples/payments.