Skip to content

Runtime API ​

Find every @exprtlabs/golem subpath that your application or build tool imports, the NestJS entry of @exprtlabs/golem-ts-openapi, and the MobX entries of @exprtlabs/golem-openapi-ts, with their signatures.

SubpathUseExtra dependency
modelmodel<T>(), IModel, IObject, ModelClass and model helper typesnone
validationvalidate<T>, validateInstance, getValidator, ModelValidatornone
@exprtlabs/golem-openapi-ts/mobxasGenObservable and observable API operations@exprtlabs/golem-openapi-ts, mobx
@exprtlabs/golem-openapi-ts/mobx-validationObservable validator state@exprtlabs/golem-openapi-ts, mobx
errorsLibError, LibErrorKind and the Issue typenone
clientApiOperation and createApiOperationnone
tagsType-only validation constraints, TValidation, TSerdenone
temporalTemporal field types and their codecsa Temporal global, such as temporal-polyfill
serdeparse<T>, stringify<T>, assertValue<T>, toWireFormat<T>, fromWireFormat<T>none
@exprtlabs/golem-ts-openapi/nestNestModelInterceptor and the helpers for your own interceptor@exprtlabs/golem-ts-openapi, @nestjs/common, rxjs
generator-apiContracts shared by the generatorsnone
manifestRead and find model-manifest.json filesnone
rewriteApply a file's rewrite edits to its text and get its source mapnone
loaderNode load hook that rewrites TypeScript as Node loads itnone
registernode --import entry that installs the loadernone
viteVite plugin that rewrites TypeScript before Vite strips its typesvite
esbuildesbuild plugin that rewrites TypeScript before esbuild strips its typesesbuild
eslintESLint config with a rule that reports code no build tool can rewriteeslint

A path that starts with internal/ is for the generators and may change in any release. These subpaths are internal: internal/emitter, internal/generated-paths, internal/generator-support, internal/plan-support, internal/schema, internal/schema-graph, internal/static-value, internal/ts, internal/type-analysis, internal/validation-plan, internal/validator-compiler the runtime entries internal/model-runtime, internal/validation-runtime, internal/client-runtime, internal/api-operation-runtime, internal/client-validation-runtime and internal/temporal-runtime, and the runtime entries of the extension packages: @exprtlabs/golem-openapi-ts/internal/mobx-runtime, @exprtlabs/golem-openapi-ts/internal/mobx-validation-runtime and @exprtlabs/golem-ts-openapi/internal/nest-runtime. Do not import them (Compatibility).

With validation: true or validation: sanity, generated files import their own validator modules and need no extra package (validation profiles). Generated files also import runtime helpers from the internal entries (Generated code).

@exprtlabs/golem/model ​

ts
import { model, type IModel, type IObject, type ModelInit } from '@exprtlabs/golem/model';
ts
import { model, type IModel } from '@exprtlabs/golem/model';
import type { Integer, Maximum, MinLength, Minimum, TSerde } from '@exprtlabs/golem/tags';
import type { fromPriorityWord, toPriorityWord } from './priority-word.js';

export type TTask = IModel<{
  title: string & MinLength<1>;
  done: boolean;
  // Your code sorts by a number from 1 to 3; the JSON carries a word.
  priority: number & Integer & Minimum<1> & Maximum<3> & TSerde<typeof toPriorityWord, typeof fromPriorityWord>;
}>;

export class Task extends model<TTask>() {
  public toggle(): void {
    this.done = !this.done;
  }
}
MemberSignatureBehavior
modelmodel<T>(): ModelClass<Fields>Returns the model base for export class Task extends model<TTask>(). Rewritten at build time to modelBase(...) plus a side-effect import of the generated codec. Calling model<T>() without a build tool throws LibError of kind ValidationUnavailable.
ModelClassModelClass<Fields>Constructor accepting ModelInit<Fields>, plus static parse(text, options?), fromWireFormat(wire, options?), stringify(value, options?), toWireFormat(value, options?), validate(value, options?) and assert(value, options?) methods bound to the subclass.
IObjectIObject<Fields, Options = {}>Declares fields whose values stay plain objects. The type is Fields.
IModelIModel<Fields, Options = {}>Declares fields for a model class that extends model<T>().
IModelOptions{ exact?, allowAny?, validation? }The second type argument of IObject and IModel.
ModelInitModelInit<Value>Constructor values: nested models or their initializers.
WireFormatWireFormat<Value>The JSON shape toWireFormat<Value> returns.
ModelFieldModelField<Model>String field names, without methods and $-prefixed keys.
ModelValidationContext{ resolve }Validator source for one call (validation context).
IModelOptions keyDefaultEffect
exactroot exact, trueControls extra keys (Objects and exact).
allowAnyroot allowAny, falseControls any and unknown fields (any and unknown).
validationroot validation, trueDefault level of the checks for this named IObject or IModel: true, 'sanity' or false. It is at or below the root level; a higher level stops generation with RUNM1089. false generates no validators for the model. A nested model is checked at the level of the call that reaches it; only false (no validators) belongs to the nested model (validation profiles).

For IModel types, use WireFormat<T> and ModelInit<T> directly. IObject declarations also emit <Alias>Fields, <Alias>Init and <Alias>JSON in their generated file inside model.output (derived type names).

Types of model classes:

TypeDescribes
GeneratedModelResult<Constructor>The instance type of a model class constructor.

@exprtlabs/golem/validation ​

ts
import { getValidator, validate, validateInstance } from '@exprtlabs/golem/validation';

function getValidator<Fields extends object, Owner extends object>(
  model: Owner & { readonly [generatedModelFieldsBrand]: Fields },
): ModelValidator<Fields, Owner>;
ts
import { TaskInput } from './task-input.model.js';
import { getValidator } from '@exprtlabs/golem/validation';

export async function checkTitleRule() {
  const task = new TaskInput({ title: 'Write release notes', done: false });
  const validator = getValidator(task);
  validator.extend({
    title: value => value.startsWith('Ship') || 'Start the title with Ship.',
  });

  const valid = await validator.validate();

  // -> { valid: false, message: 'Start the title with Ship.' }
  return { valid, message: validator.error('title') };
}
MemberSignatureBehavior
getValidator(model): ModelValidator<Fields, Owner>Returns the same stateful validator for a model instance every time. Fields are the generated field types.
validateInstance(model, options?: ValidateOptions): Promise<readonly Issue[]>Returns the current issues without changing the stored state (validation).
validate<T>(value: unknown, options?: ValidateOptions & AllowGetterOptions): value is TChecks a value against a named IObject or IModel and narrows it. Needs a build that rewrites it.
ModelValidatorclass ModelValidator<Fields, Owner = Fields>The stateful validator. Members are below.

validateInstance, validate and ModelValidator.validate stop at the first issue unless you pass { failFast: false }. An invalid value is an ordinary result. They throw LibError when validation cannot run, for example when the model was generated with validation: false, or when validate names a level above the project level (ValidationUnavailable).

ModelValidator members ​

MemberSignatureBehavior
constructor(model, options: ModelValidatorOptions), with ModelValidatorOptions = { cache: 'attach' | 'defer' }Attaches a validator to a model instance. cache: 'attach' stores it for getValidator; 'defer' does not.
validate(options?: ValidateOptions): Promise<boolean>Runs generated checks, then instance rules, and stores the issues. With validate: 'sanity' it runs the shape checks only and skips the instance rules. A newer call wins over an older one.
issuesreadonly Issue[]Stored issues, frozen.
errorsReadonly<Record<string, readonly string[]>>Messages keyed by escaped JSON Pointer, such as /items/0/sku.
validbooleantrue when no issues are stored. It does not track later edits.
pendingbooleantrue while validate runs.
error(field): string | undefinedFirst message for a field name or path array such as ['items', 0, 'sku'].
errorsFor(field): readonly string[]All messages for that field name or path.
extend(rules: ModelValidationRules<Fields, Owner>): thisAdds rules for this instance (instance rules).
messages(messages: ValidationMessages<Fields>): thisReplaces generated messages by code ('tooSmall') or field and code ('title.tooSmall').
setErrors(errors): voidStores messages from outside, such as a server response, as external issues. Takes a field map or { path, message }[].
clear(): voidRemoves stored issues and resets pending.
setIssues(issues: readonly Issue[]): voidReplaces the stored issues.
setPending(pending: boolean): voidSets pending.
formatIssue(issue: Issue, explicit: boolean): IssueApplies messages() overrides unless explicit.

Types for these members: ModelValidationRules, ValidationRule, ValidationRuleResult, ValidationMessages, ValidationMessage, ValidationMessageKey, FieldValidationMessage, ExternalFieldError, ValidationMode, Issue and IssuePath.

Runtime validators ​

ts
function runValidation(validator: Validator, value: unknown, all = true): Promise<{ valid: boolean; issues: readonly SchemaIssue[] }>;
MemberBehavior
runValidationRuns one Validator and returns { valid, issues }. all defaults to true, which reports every issue. false stops at the first. A validator that does not return an array throws TypeError.
Validator(value, all) => readonly SchemaIssue[], empty when the value is valid.
OperationRuntimeValidatorsThe value type of a client's operationValidators option: the input validator, the optional requestHeaders validator, the response validators keyed status:contentType, and the optional responseHeaders validators keyed status:name.
SchemaIssue, SchemaIssueDetailIssue types of a Validator.
Evaluation, JsonValueTypes that generated validators name in their code.

@exprtlabs/golem-openapi-ts/mobx ​

ts
import { asGenObservable } from '@exprtlabs/golem-openapi-ts/mobx';

Install @exprtlabs/golem-openapi-ts in dependencies, with mobx. Generated files import the same MobX runtime when the mobx extension is on.

ts
import { model, type IModel, type ModelInit } from '@exprtlabs/golem/model';
import { asGenObservable } from '@exprtlabs/golem-openapi-ts/mobx';
import { getValidator } from '@exprtlabs/golem/validation';
import { action, computed } from 'mobx';
import type { TMoney } from '../sdk/index.js';

export type TPaymentEditor = IModel<{ money: TMoney; note: string }>;

export class PaymentEditor extends model<TPaymentEditor>() {
  public constructor(values: Partial<ModelInit<TPaymentEditor>> = {}) {
    super({ money: { amount: '0.00', currency: 'USD' }, note: '', ...values });
    asGenObservable(this, { summary: computed, setAmount: action, setCurrency: action, setNote: action });
    getValidator(this).extend({ note: value => value.length <= 140 || 'Keep the note within 140 characters' });
    // Readable messages for the generated pattern checks of the nested money object.
    getValidator(this).messages([
      { path: ['money', 'amount'], code: 'pattern', message: 'Enter an amount like 12.50' },
      { path: ['money', 'currency'], code: 'pattern', message: 'Use a three-letter currency code like USD' },
    ]);
  }

  public get summary(): string {
    return `${this.money.amount} ${this.money.currency}${this.note ? `: ${this.note}` : ''}`;
  }

  public setAmount(amount: string): void {
    this.money.amount = amount; // The nested money model is observable too.
  }

  public setCurrency(currency: string): void {
    this.money.currency = currency.toUpperCase();
  }

  public setNote(note: string): void {
    this.note = note;
  }
}
MemberSignatureBehavior
asGenObservable(model, annotations?: ModelAnnotations<Model>): voidMakes every generated field observable, then nested generated models (MobX). A second call on the same instance throws.
ModelAnnotationsAnnotationsMap<Model, never>MobX annotations for your class members. They override the field defaults.
ObservableApiOperationApiOperation plus readonly loading: booleanloading is observable and stays true until every execution settles.
createObservableApiOperation(name: string, run): ObservableApiOperationcreateApiOperation with loading. Generated clients of a project with the mobx extension return it.

@exprtlabs/golem-openapi-ts/mobx-validation ​

ts
import { getValidator } from '@exprtlabs/golem-openapi-ts/mobx-validation';
MemberSignatureBehavior
getValidator(model): ModelValidatorThe validator validation returns for that instance, made observable.
enhanceValidatorWithMobX(validator): validatorMakes issues, errors, valid and pending computed, and setIssues, setPending, clear and setErrors actions. Repeated calls change nothing.
ModelValidatorclass extends ModelValidatorA validator that is observable from construction.

The module re-exports the types ModelField, ModelValidationRules, Issue, ValidationMessage and ValidationMessages.

@exprtlabs/golem/errors ​

ts
import { LibError, LibErrorKind } from '@exprtlabs/golem/errors';
ts
export async function chargeAmountIssues(client: ProviderClient, amount: string) {
  try {
    await client.createCharge().execute({ body: { amount, currency: 'USD' } });
    return [];
  } catch (error) {
    if (error instanceof LibError && error.kind === LibErrorKind.Validation) {
      return error.issues; // "12,50" violates the amount pattern; issue.path identifies the field.
    }
    throw error;
  }
}
LibError memberTypeMeaning
constructor(kind, message, issues?, options?: LibErrorOptions)options takes cause and causedByInput.
kindLibErrorKindThe failure category.
issuesreadonly Issue[]Frozen copy of the issues.
causedByInputbooleantrue when the rejected value is at fault, false for a program fault. Defaults to true for Validation and InvalidJson. A Deserialize function that throws on wire input sets it to true.
causeunknownThe original exception a LibError wraps.
LibErrorKindValueThrown when
ValidationvalidationA checked call rejects a value.
SerializationserializationA value cannot be written as JSON, such as an invalid Date or a value that holds itself.
DeserializationdeserializationJSON cannot be decoded, such as an unparsable date.
InvalidJsoninvalid_jsonparse receives text that is not JSON.
ValidationUnavailablevalidation_unavailableChecks were not generated, no build rewrote a call, or a validation context lacks a validator.
ResponseresponseA generated client receives a status or media type the operation does not declare.
  • ModelValidator.validate() returns false for an invalid value. Checked serde calls and generated client checks throw LibError instead.
  • A Deserialize function that throws becomes a LibError of kind Deserialization with the exception as its cause. A Serialize function that throws is not wrapped. Its exception reaches your code unchanged, in stringify and toWireFormat, at any depth.
  • A TValidation predicate that throws, or returns neither a boolean nor a string, makes every checked call throw LibError of kind Validation with the message Model validation could not finish., causedByInput set to false and the original error as cause. This covers parse, stringify, toWireFormat, fromWireFormat, validate<T>, assertValue<T>, validateInstance and ModelValidator.validate.
  • A thrown LibError passes through unchanged.

Errors and issues shows how to read them.

Issue fieldTypeMeaning
codeIssueCodeThe failed check. Each code adds the typed fields listed below.
messagestringDisplay text.
pathIssuePathString and number segments, such as ['items', 0, 'amount'].
sourceIssueSourcetypescript, openapi, custom, external, json or serde.
representationIssueRepresentationOptional: model for the model value, wire for the JSON value.

Issue is a union keyed by code. Check issue.code and TypeScript narrows to that code's fields, such as issue.limit after issue.code === 'tooSmall'.

codeExtra fieldsFailed check
typeexpectedThe value has another type. expected lists string, number, integer, boolean, null, object or array.
instancemodelThe value is not an instance of the class of the field: a model class, a Date, a Temporal class or the class of a TSerde field. model holds the class name, such as Date. An invalid Date (new Date(NaN)) fails too.
requiredkeyA property is missing. path ends at the missing key.
unknownKeykeyThe object has a property the schema does not allow. path ends at the key.
invalidKeykeyA property name is not allowed. path points at the object.
literalexpectedThe value is not one of the allowed constants, including an anyOf or oneOf whose alternatives are all constants.
unionmatchedThe value matches no alternative (0) or more than one where one is required.
tooSmall, tooBigmeasure, limit, inclusiveA limit is crossed. measure is length, items, properties, value or matches. inclusive is false for an exclusive bound.
patternpatternA string does not match the pattern.
formatformatA string is not in the named format.
multipleOfdivisorA number is not a multiple of divisor.
uniqueindexesTwo items are equal. indexes gives their positions.
notnoneThe value matches a shape that is excluded.
nevernoneThe schema allows no value here.
customreason (optional)A TValidation function or an instance rule rejected the value. reason holds the message the rule returned.
externalnoneA message from setErrors().
invalid_json, serialization, deserializationnoneThe failures of the matching LibErrorKind.

The default message is golem's English text built from these fields. messages() overrides replace it by code.

Translating issues ​

ts
import {
  setIssueTranslator,
  translateIssues,
  type IssueTranslate,
} from '@exprtlabs/golem/errors';
MemberSignatureBehavior
IssueTranslate(key: string, options: { readonly defaultValue: string } & Readonly<Record<string, unknown>>) => stringTranslator function shape compatible with i18next.t. Returning a non-string throws TypeError.
setIssueTranslator(translate: IssueTranslate | undefined) => voidSets or clears the process-wide issue translator used when issues are created. Intended for single-locale environments such as browsers (Translate messages).
translateIssues(issues: readonly Issue[], translate: IssueTranslate) => readonly Issue[]Returns a frozen copy of issues translated with translate for per-request localization on servers. Preserves setErrors(), messages(), TValidation string reasons and extend() rule reasons unchanged.

Other exports: toIssue(issue, source, representation?) adds the default or translated message to a validator's issue. snapshotIssues(issues) freezes a list of issues while preserving internal field-owner and final-message metadata. LibErrorOptions, IssueDetail, JsonValue and the enums IssueSource and IssueRepresentation are exported too.

@exprtlabs/golem/client ​

ts
import { createApiOperation, type ApiOperation } from '@exprtlabs/golem/client';

interface ApiOperation<Input, Result, Options = unknown> {
  execute(input: Input, options?: Options): Promise<Result>;
}
ts
export async function readTwoCharges(client: ProviderClient, firstId: string, secondId: string) {
  const getOne = client.getCharge();
  const first = await getOne.execute({ path: { id: firstId } });
  const second = await getOne.execute({ path: { id: secondId } });
  return { first, second };
}
MemberSignatureBehavior
ApiOperation{ execute(input, options?) }Generated client methods return one. Creating it sends nothing. Each execute sends a new request.
ApiOperationRun(input, options?) => Promise<Result>The work execute runs.
createApiOperation(name: string, run: ApiOperationRun): ApiOperationWraps your own asynchronous call in the same interface.
  • Overlapping execute calls all run. Each one after the first logs Concurrent execute() invocation for <name>.
  • An operation caches no results or errors.

Create a client shows the generated client options.

Generated client ​

ts
new <Client>Client(options: <Client>ClientOptions)
client.<operation>().execute(input, options?: <Client>RequestOptions): Promise<HttpResponse>

<Client> is the client name in golem.yaml. Each operation method returns an ApiOperation.

OptionPresent when the API hasValue
baseUrlalwaysThe API address. It wins over server. Required when the document lists no servers.
serverservers in the documentA number is the index of a server in the document's servers. A string is its name or description; a name wins. The default is the first server. An operation whose own servers, or its path item's, replace the document's list ignores server and goes to the first server of that list.
serverVariablesservers in the documentA record of values for the {variables} in the URL of the chosen document server. An operation that has its own servers uses their variable defaults.
fetchImplalwaysA fetch function. The default is the global fetch.
headersalwaysHeadersInit that the client adds to every request.
autha security scheme that is not mutual TLSCredentials by scheme name, or functions that return them (Client authentication).
mutualTlsa mutual TLS security scheme{ fetchImpl }, a transport that you configure with the certificate (Mutual TLS).
bodyEncodersa request bodyRequest codecs by media type (Codec options).
responseDecodersresponse contentResponse codecs by media type (Codec options).
parameterSerializersa parameter that uses content, or a querystring parameterParameter writers by media type.
responseHeaderDecodersa response header that declares contentHeader decoders by media type.
streamDecodersa response that declares itemSchemaFraming decoders for streams other than NDJSON, JSON-seq and SSE (Connect a custom stream decoder).
operationValidatorsvalidation turned onA map of operation name to validators. Each entry replaces the generated validators of that operation (Runtime validators).
validatevalidation turned onThe check level of every call of this client (The validate option).
Request optionValue
signalAn AbortSignal that cancels the request.
validateThe check level of this call. It wins over the validate of the client (The validate option). Present when the client has the option.
  • The client type has the first three options always. It adds each other option only when the API needs it. A key that the type does not have is a type error.
  • baseUrl loses its surrounding spaces and one trailing /. An empty value throws Error with the message <Client>Client requires a non-empty baseUrl when you create the client.
  • A server URL is used as the document writes it, after the variables are filled. A variable that serverVariables leaves out uses its default. A value that is not in the enum of the variable, a variable that the server does not declare, or a server that the document does not list, throws Error when you create the client. A relative server URL such as /api is used as written, so it works where fetch accepts a relative URL, such as a browser. The client reads the servers of the document root.
  • mutualTls.fetchImpl replaces fetchImpl for every request of the client, also for operations without a mutual TLS requirement.
  • A codec map that you leave out is empty. A codec that you pass replaces the built-in one.
  • Each execute call resolves with the response that the operation declares, as in the table below. A declared error status resolves too (Read responses and handle failures).
execute resultValue
matchedstatus for an exact status code, range for a range such as 2XX, default for the default response.
statusThe HTTP status of the reply.
contentTypeThe declared media type that matched the reply, or null when the response declares no content.
bodyThe decoded body. A response that declares no content has no body. A stream response has an AsyncIterable (Streaming responses).
headersThe declared response headers that the reply holds, decoded.
  • A stream body is lazy. With validation on, each item is checked when your loop reads it. A failed item throws from for await, not from execute.
  • Selection follows Response matching.
FailureResult
A request input or a response breaks its schemaLibError of kind Validation with the message API data validation failed. The issues have source openapi and representation wire. causedByInput is true. The error does not hold the response body.
A validator crashesLibError of kind Validation with cause, no issues and causedByInput false.
The generated validator of the request input is missingLibError of kind ValidationUnavailable.
The reply has a status or media type that the operation does not declareLibError of kind Response with causedByInput true and no issues. It also has client, operation, status, headers and contentType (the media type in lower case, without parameters). The message is Undeclared OpenAPI response for <operation>: HTTP <status> <type>. The runtime cancels the body.
The body is not valid JSONSyntaxError, not a LibError.
No codec or decoder exists for the body, or the operation requires a custom codec you did not passA plain Error that names the media type or the missing option.
No security requirement has all its credentialsA plain Error whose message starts with No configured credentials satisfy. It rejects before fetch runs (Client authentication).
The network failsThe rejection of fetchImpl, unchanged.
  • The client converts what it carries. A response body, a stream item and a declared response header arrive as plain objects with converted values, such as Date or Temporal for dates. A request body and the path, query, header and cookie values go out in their JSON form. No class is involved, in either SDK mode.
  • Test an undeclared response with the generated guard is<Client>UndeclaredResponseError(error).
  • With validation off, the client checks no request or response. With it on, a response that declares no content has no body to check.

The validate option ​

ValueChecks
trueEverything.
'sanity'The shape only: types, required fields and extra keys.
falseNothing. Conversion still runs.
{ request, response, requestHeaders, responseHeaders }Each side apart. A side takes true, 'sanity' or false.
  • request covers the body and the path, query and cookie values. response covers the body and the stream items.
  • A level alone sets request and response. The header sides, requestHeaders and responseHeaders, are off unless the option names them.
  • A side takes the level of the call, else of the client, else of the SDK. The level of the SDK is the cap.
  • A level above the cap rejects execute with LibError of kind ValidationUnavailable. Any other value rejects it with TypeError.
  • The option works the same in a standalone and in a golem SDK.

Create a client shows the options in use. Read responses and handle failures and Handle errors show how to read the result and the errors.

Client authentication ​

ts
auth?: <Client>Auth;
mutualTls?: { readonly fetchImpl: typeof fetch };

<Client>Auth has one optional key for each declared security scheme except mutual TLS. Each value is a TokenAuthValue or a BasicAuthValue. The client has auth when an operation requires a scheme that is not mutual TLS. It has mutualTls when an operation requires a mutual TLS scheme. Authentication shows the usage.

TypeShapeMeaning
AuthContext{ scheme, type, scopes, flows?, openIdConnectUrl? }The argument of an auth function. scheme is the scheme name, type its OpenAPI type and scopes the scopes of the requirement. flows is set for OAuth2. openIdConnectUrl is set for OpenID Connect.
TokenAuthValue<Context = AuthContext>string | (context: Context) => string | Promise<string>A token or an API key, or a function that returns one.
BasicCredentials{ username: string; password: string }The credentials of an HTTP Basic scheme.
BasicAuthValue<Context = AuthContext>BasicCredentials | (context: Context) => BasicCredentials | Promise<BasicCredentials>The credentials, or a function that returns them.
MutualTlsTransport{ readonly fetchImpl: typeof fetch }The value of mutualTls.
RuntimeSecuritySchemesReadonly<Record<string, RuntimeSecurityScheme>>The scheme metadata that a generated client gives to the runtime. You do not build it.

Each SDK declares these types again with the client name, such as <Client>Auth, the type of the auth option. It also declares a context type for each scheme with narrowed fields.

OpenAPI schemeAuth valueWhat the client sends
apiKey in headerTokenAuthValueA header named by the scheme's name. The scheme key is the name when name is missing.
apiKey in queryTokenAuthValueA query parameter with that name.
apiKey in cookieTokenAuthValueA cookie with that name. The value is percent-encoded.
http with bearerTokenAuthValueAuthorization: Bearer <token>.
http with basicBasicAuthValueAuthorization: Basic <credentials>, Base64 of username:password in UTF-8.
oauth2TokenAuthValueAuthorization: Bearer <access token>. The context has scopes and flows.
openIdConnectTokenAuthValueAuthorization: Bearer <access token>. The context has openIdConnectUrl.
mutualTLSnone: use mutualTlsNo credential. The requirement holds when mutualTls is set.
  • A value is a string, a credentials object or a function. The client calls a function with an AuthContext on each execute and awaits it.
  • An operation can list several security requirements. The client uses the first requirement for which every scheme has a value. It applies all schemes of that requirement together.
  • A scheme with no key in auth has no value.
  • An empty requirement allows a request without credentials. The client uses it only after every other requirement fails.
  • Security on an operation replaces the security of the document. security: [] on an operation asks for no credentials.
  • The client resolves credentials before it calls fetch. A failure rejects execute and sends no request.
FailureResult
No requirement has all its credentialsA plain Error with the message No configured credentials satisfy the operation security requirements.
An auth function returns a value that is not a string or a credentials objectTypeError with the message Authentication provider for <scheme> returned an invalid value. A function that returns undefined counts as no value.
An auth function throwsexecute rejects with that error, unchanged.
A Basic username contains :TypeError.
An http scheme is not basic or bearerA plain Error with the message Unsupported HTTP authentication scheme: <scheme>.

Authentication shows how to pass credentials, read a token for each request and use mutual TLS.

@exprtlabs/golem/tags ​

ts
import type { MinLength, TSerde, TValidation } from '@exprtlabs/golem/tags';

Every export is a type. Intersect a tag with a field type. Assignment is unchanged and generation never runs your code. A tag that is not intersected with a value type is an error (RUNM1045).

MemberSignatureBehavior
Built-in constraintsInteger, Minimum<N>, MinLength<N>, Pattern<S>, Format<S>, …JSON Schema keywords (built-in tags).
Short namesMin, Max, ExclusiveMin, ExclusiveMax, MinProps, MaxPropsAliases of Minimum, Maximum, ExclusiveMinimum, ExclusiveMaximum, MinProperties, MaxProperties.
DiscriminatorDiscriminator<Key, Default?>Names the property that tells the variants of a model union apart (name the tag).
TValidationTValidation<typeof predicate>Runs an exported synchronous function that returns true, false or an error message (TValidation).
TSerdeTSerde<typeof serialize, typeof deserialize>Converts the field between model value and JSON value (TSerde).
TSerdeWireTSerdeWire<Value>[Wire], the deserializer's input type, or [] without TSerde.
BuiltinModelTagunion typeEvery built-in constraint.
ModelValidationFunction(value: unknown) => boolean | stringThe shape that TValidation accepts.
ModelSerializeFunction, ModelDeserializeFunction(value: unknown) => unknownThe shapes that TSerde accepts.

TSerde ​

ts
type TSerde<
  Serialize extends (...args: never[]) => unknown,
  Deserialize extends (...args: never[]) => unknown,
>;
PartNamesRule
Serializetypeof an exported function from the model value to the JSON valueIts parameter accepts the model type of the field. Its return type is assignable to the parameter type of Deserialize.
Deserializetypeof an exported function from the JSON value to the model valueIts parameter type is the JSON type of the field. Its return type is assignable to the model type of the field.
  • Each function has one call signature and one required parameter. It is synchronous: a function that returns a thenable is an error.
  • Declare each function in its own module and export it. A function in a *.model.ts file stops generation (RUNM1065).
  • A function from an installed package needs a package exports entry that reaches its file (RUNM1060).
  • In a type alias, write typeof an exported function. A type parameter is an error (RUNM1061).
  • A field has one TSerde pair. Two different pairs on one field stop generation.
  • The deserializer parameter type sets the JSON schema of the field. A tag on that type checks the JSON value. A plain string parameter drops the tags of an alias such as string & MinLength<3>.
  • Tags on the field type check the model value, after decoding and before encoding. Tags on the return type of Serialize add no JSON check.
  • A parameter of type any or unknown is an error unless allowAny is true (RUNM1011).
  • The JSON value is checked before decoding and after encoding. { validate: false } skips the checks and keeps the functions.
  • Serialize returns JSON-compatible data. A non-finite number or a cycle throws Serialization, also with validate: false.
  • A field can hold a class instance or a bigint. The class needs a name and an export, and no type parameter without a default (RUNM1063).
  • A class field is checked with instanceof. A model value of another class gives one instance issue. A type with no class behind it at run time, such as an interface, has no instance check.
  • A class that a *.model.ts file declares stops generation (RUNM1065).
  • A Deserialize function whose parameter is a string reads only a string. Another JSON value throws Deserialization at every validation level.
  • Date and the Temporal classes have a built-in TSerde, so a field of that type needs no tag. A TSerde on the field replaces it.
  • The Temporal tags are TSerde tags with their own functions.
FailureWhereResult
A Deserialize function throwsparse, fromWireFormatLibError of kind Deserialization. cause holds the exception, the issue has source serde, and causedByInput is true, because the function reads wire input. A LibError that the function throws passes through.
A Serialize function throwsstringify, toWireFormatThe exception reaches your code unchanged. It is not bad input, and the call does not wrap it.
JSON or model value fails a checkthe same callsLibError of kind Validation with the issues.
A function is not usablegenerationRUNM1040, RUNM1042, RUNM1046, RUNM1047
A type does not fit the pairgenerationRUNM1049

The usage is in Change the JSON form. The declarations are compared in Which type controls validation, and class fields are in Class values.

TValidation ​

ts
type TValidation<Predicate extends (...args: never[]) => boolean | string>;
Predicate resultEffect
trueThe value passes.
false or ''The value fails with an issue of code custom and the default message.
A non-empty stringThe value fails with an issue of code custom. reason and message hold the string.
Any other valueThe check throws TypeError.
  • The predicate is an exported function with one required parameter. It is synchronous and returns boolean, string or a union of the two.
  • Declare it in its own module. A predicate in a *.model.ts file stops generation (RUNM1065). The package and alias rules of TSerde apply (RUNM1060, RUNM1061).
  • The model type of the field is assignable to the predicate parameter (RUNM1050).
  • The predicate runs only after the built-in checks of the same value passed. It never sees a value of the wrong shape. Do not depend on the order of several predicates on one value.
  • On a model type, it checks the model value. On the parameter type of a TSerde decoder, it checks the JSON value.
  • Money & TValidation<typeof extra> adds a rule to an SDK type. The rule runs with the checks of that type.
  • A predicate does not become part of an OpenAPI document. The document carries the JSON schema only.
  • Every checked call wraps an exception from a predicate, or a result that is not a boolean or a string, in a LibError of kind Validation. cause holds the exception and causedByInput is false.
FailureWhereResult
The predicate rejectsany checked callIssue with code custom, source custom and optional reason (Issue).
The function is not usablegenerationRUNM1040, RUNM1041, RUNM1046, RUNM1047, RUNM1048

Add a custom field rule shows the usage.

Built-in tags ​

Each built-in tag writes one JSON Schema keyword. A tag that does not fit the field type stops generation (RUNM1051).

GroupTagJSON Schema keywordField types
NumbersIntegertype: integernumber
NumbersMinimum<N>, Min<N>minimumnumber
NumbersMaximum<N>, Max<N>maximumnumber
NumbersExclusiveMinimum<N>, ExclusiveMin<N>exclusiveMinimumnumber
NumbersExclusiveMaximum<N>, ExclusiveMax<N>exclusiveMaximumnumber
NumbersMultipleOf<N>multipleOfnumber
StringsMinLength<N>minLengthstring
StringsMaxLength<N>maxLengthstring
StringsPattern<S>patternstring
StringsFormat<S>formatstring
ArraysMinItems<N>minItemsarray or tuple
ArraysMaxItems<N>maxItemsarray or tuple
ArraysUniqueItemsuniqueItemsarray or tuple
ArraysContains<T>containsarray or tuple
ArraysMinContains<N>minContainsarray or tuple, with Contains
ArraysMaxContains<N>maxContainsarray or tuple, with Contains
ObjectsMinProperties<N>, MinProps<N>minPropertiesobject
ObjectsMaxProperties<N>, MaxProps<N>maxPropertiesobject
ObjectsPropertyNames<T>propertyNamesobject
ObjectsPatternProperties<Map>patternPropertiesobject
ObjectsAdditionalProperties<T>additionalPropertiesobject
ObjectsUnevaluatedProperties<T>unevaluatedPropertiesobject
Related fieldsDependentRequired<Map>dependentRequiredobject
Related fieldsDependentSchemas<Map>dependentSchemasobject
AlternativesOneOf<Tuple>oneOfany type
AlternativesNot<T>notany type
AlternativesIfThenElse<Condition, Then, Else>if, then, elseany type
  • An object type is not an array, a tuple or a function type.
  • A union fits when every member fits. null, undefined, any and unknown always fit, so an optional or nullable field keeps its tags.
  • The same rules apply to the JSON value of a TSerde field.
  • N is a finite numeric literal. Length, item, property and count limits are non-negative integers. MultipleOf is positive (RUNM1043).
  • Pattern is a valid Unicode regular expression. Format and the keys of DependentRequired are string literals (RUNM1044).
  • A schema-valued argument is a type that golem can describe as a schema (RUNM1043).

The usage is in Built-in validation constraints, and the format names are in Formats. Validation tags is the guide.

@exprtlabs/golem/temporal ​

Temporal field types for models. Each converts to an ISO 8601 string in JSON. Use Temporal fields shows the setup.

TagModel typeJSON string
TemporalInstantTemporal.Instant2025-01-02T03:04:05Z, with fractional seconds only when the value has them
TemporalZonedDateTimeTemporal.ZonedDateTime2025-01-02T03:04:05+01:00[Europe/Paris]
TemporalPlainDateTemporal.PlainDate2025-01-02
TemporalPlainDateTimeTemporal.PlainDateTime2025-01-02T03:04:05
TemporalPlainTimeTemporal.PlainTime03:04:05.123
TemporalDurationTemporal.DurationP1DT2H

The JSON string has a four-digit year and no calendar annotation.

Each deserializeTemporalX accepts only that form, at every validation level, off included. Text that Temporal.X.from would read but the form rejects, such as 20250102 for a date, throws Deserialization with causedByInput: true. Each serializeTemporalX writes only that form: a value whose text falls outside it, such as a year beyond 9999 or a non-ISO calendar annotation, throws Serialization.

Each tag TemporalX has the functions serializeTemporalX and deserializeTemporalX and the type TemporalXWire. Its TSerde uses the two functions.

A field typed with the class itself, such as Temporal.PlainDate, uses the same two functions and has the same JSON string as the tag. A model value that is not an instance of the class fails with an instance issue.

@exprtlabs/golem/serde ​

ts
import { fromWireFormat, parse, stringify, toWireFormat } from '@exprtlabs/golem/serde';
ts
import { parse } from '@exprtlabs/golem/serde';
import { Task } from './task.model.js';
import type { TTask } from './task.model.js';

export function readTask(text: string): Task {
  return parse<Task>(text); // a Task instance with toggle()
}

export function readTaskData(text: string): TTask {
  return parse<TTask>(text); // a plain object with the same fields
}

Build with golem

parse<T>, stringify<T>, assertValue<T>, toWireFormat<T>, fromWireFormat<T> and validate<T> throw unless a build tool rewrote them. tsc does not rewrite them.

The error is a LibError of kind ValidationUnavailable. Its message starts with the call, as in parse<T> was not rewritten to a generated function, and then lists the build tools that rewrite calls.

T names a generated IObject or IModel. A type alias returns a plain object. Your class returns an instance of it.

MemberSignatureBehavior
parse<T>(text: string, options?: DecodeOptions): TJSON text to a value. Checks the JSON, runs TSerde decoders, checks the result.
stringify<T>(value: T, options?: EncodeOptions & AllowGetterOptions): stringValue to JSON text of the declared fields, with TSerde applied and both sides checked.
fromWireFormat<T>(wire: unknown, options?: DecodeOptions): Tparse for a plain object instead of text.
toWireFormat<T>(value: T, options?: EncodeOptions & AllowGetterOptions): WireFormat<T>stringify that returns the plain object, such as TTaskJSON.
assertValue<T>(value: unknown, options?: ValidateOptions & AllowGetterOptions): TChecks the value and returns it unchanged, typed as T. Throws LibError Validation with the issues.
OptionInDefaultEffect
validateboththe level of the modelSerdeOptions: true, false or 'sanity'. ValidateOptions: true or 'sanity'. 'sanity' checks the shape only and false skips the checks. A level above the project level throws ValidationUnavailable. For parse, stringify, fromWireFormat and toWireFormat, any other value throws TypeError (levels).
failFastbothtruefalse reports every issue. It does not skip checks.
validationContextbothnoneResolves validators from your own function (validation context).
maxDepthboth512Bounds how many levels of objects and arrays the input of a recursive model may nest (below).
stripDecodeOptions, EncodeOptionsfalsetrue removes the keys that a closed object does not declare, before the checks run (below).
allowGetterAllowGetterOptionsfalsetrue reads declared root fields through getters and inherited values (below).

ValidateOptions has validate, failFast, validationContext and maxDepth. The rewrite also passes construct in SerdeOptions for a class T. Each call runs the checks in the table of Checks during conversion.

maxDepth ​

A model that reaches a recursive model (it refers to itself, directly or through another model) bounds its input before the generated code walks it. The codec calls parse, fromWireFormat, validate and assert count the levels of nested objects and arrays and reject input deeper than maxDepth, 512 by default. A model that reaches no recursive model has no bound.

  • parse, fromWireFormat and assert throw a LibError of kind deserialization with causedByInput: true. The message names the limit and the option. NestModelInterceptor answers HTTP 400.
  • validate returns false.
  • Each array, plain object and model instance counts as one level; a class value such as a Uint8Array, a Date or a Map is a leaf. With allowGetter: true, the fields that a root getter supplies count too. A tree whose children array holds nodes adds two levels for each node.
  • Raise the bound for one call with { maxDepth: 2000 }, or for the interceptor with new NestModelInterceptor({ maxDepth: 2000 }). Infinity turns it off. Very deep input can then end the call stack.
  • strip: true bounds the value that it keeps, on a decode and on an encode (toWireFormat, stringify). A key that a closed object removes does not count, and strip reads none of it. An encode that is too deep throws a LibError of kind serialization with causedByInput: false.
  • A value below 1 is a TypeError.

strip ​

DecodeOptions and EncodeOptions extend SerdeOptions with strip?: true. parse and fromWireFormat take DecodeOptions, stringify and toWireFormat take EncodeOptions, and so do the same calls of an ObjectCodec.

ts
const env = fromWireFormat<TEnv>(process.env, { strip: true });
const body = toWireFormat<TUser>(rowFromDatabase, { strip: true });

By default an extra key of a closed object fails validation. With strip: true, golem removes that key at every level, before it checks the value, at each validation level. A declared key that has a bad value still reports its issue. A decode result holds the declared keys only, also when it is a class instance.

  • Strip keeps the data that a model declares as extra: a Record, an AdditionalProperties tag, PatternProperties and an object with exact: false.
  • A union of objects with a Discriminator tag chooses the variant by the tag, and strip then removes the keys that variant does not declare. A union of objects with no tag keeps exact matching.
  • Strip copies the object that it changes. It does not change the input.
  • An encode strips the plain objects of the model value, also those that an instance of a class holds in its declared fields. An instance keeps its class and the keys that it holds. A model that does not keep other keys writes the declared fields of an instance only, as stringify and toWireFormat always did. An instance of a model that keeps other keys (an index signature or AdditionalProperties, with or without pattern properties) also has the plain objects that those keys hold stripped. An encode leaves the value of a TSerde field as it is, because the shape of that value is the serializer's own.

allowGetter ​

AllowGetterOptions has allowGetter?: boolean. stringify, toWireFormat, validate and assertValue take it, and so do the same calls of an ObjectCodec.

ts
stringify<TTask>(task, { allowGetter: true });

By default a field counts when it is an own enumerable property, as in JSON.stringify. With allowGetter: true, a declared field of the root object also counts when a getter or an inherited value supplies it.

  • It applies to the root value of an IObject or IModel codec. Nested values are judged as without it.
  • With strip: true, a getter of a key that strip removes is not read.
  • parse, fromWireFormat, validateInstance and ModelValidator do not take it.

Validation context ​

Pass one ModelValidationContext to repeated serde, validateInstance and ModelValidator.validate calls to reuse resolved validators.

FieldBehavior
resolve(reference, mode)Returns the Validator for a schema reference and 'first' or 'all' mode, or undefined when it has none.

objectCodecValidationReference(codec, plane) returns the reference for one ValidationPlane: Id (the id of the codec) for model, and Id#plane for every other plane, Id#wire included, also when the JSON value has the same schema as the model value.

ValidationPlaneChecksUsed by
modelthe model valuevalidate, validateInstance, and stringify / toWireFormat before encoding
wirethe JSON valueparse / fromWireFormat before decoding
model-onlyconverted fields and TValidation rules on the model valueparse / fromWireFormat after decoding
wire-onlythe JSON written for converted fieldsstringify / toWireFormat after encoding
  • A context is authoritative. A missing validator throws ValidationUnavailable instead of using the generated one.
  • Resolved validators are cached per context object, reference and mode. Create a new context when schemas change.
  • A validator returns an array of issues, empty when the value is valid. Any other result throws TypeError. A promise throws ValidationUnavailable in synchronous serde calls.

Look up a codec ​

MemberSignatureBehavior
getObjectCodec(id): ObjectCodec | undefinedReturns the codec whose id is exactly id. A short model name finds nothing.
getIModelClass(id): GeneratedModelConstructor | undefinedReturns the IModel class registered under the exact id id. GeneratedModelConstructor is abstract new (...arguments: never[]) => object, exported from @exprtlabs/golem/model.

Types: AllowGetterOptions, DecodeOptions, EncodeOptions, ObjectCodec, SerdeOptions, ValidateOptions, ValidationPlane, WireFormat. IssueRepresentation and IssueSource are re-exported from errors.

@exprtlabs/golem-ts-openapi/nest ​

ts
import { NestModelInterceptor } from '@exprtlabs/golem-ts-openapi/nest';

Install @exprtlabs/golem-ts-openapi in dependencies. @nestjs/common and rxjs are its optional peers. The interceptor needs the nest extension in golem.yaml.

ts
import 'reflect-metadata';
import { Module, type DynamicModule } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { NestModelInterceptor } from '@exprtlabs/golem-ts-openapi/nest';
import { PaymentNotesController } from './payment-notes.controller.js';
import { PaymentsController } from './payments.controller.js';
import { ProviderCharges, type ProviderOptions } from './provider-charges.js';

@Module({
  controllers: [PaymentsController, PaymentNotesController],
})
class PaymentsModule {
  static with(provider: ProviderOptions): DynamicModule {
    return { module: PaymentsModule, providers: [{ provide: ProviderCharges, useValue: new ProviderCharges(provider) }] };
  }
}

export async function createApplication(provider: ProviderOptions = {}) {
  const application = await NestFactory.create(PaymentsModule.with(provider), { logger: false });
  application.setGlobalPrefix('api');
  // @Body() and @Query() become the declared model before the handler.
  // An IModel or IObject return is written as that type's JSON.
  application.useGlobalInterceptors(new NestModelInterceptor());
  return application;
}
MemberSignatureBehavior
NestModelInterceptorclass NestModelInterceptor implements NestInterceptorConverts model-typed @Body() and @Query() parameters before the handler and writes model returns (request contract). Its options object has maxDepth and validate, the level of the request check (level).
nestModelStringifyInterceptor(codec: ObjectCodec): NestInterceptorWrites every non-null result with that codec's stringify, an array item by item.
objectCodecFromMetatype<T>(metatype: unknown): ObjectCodec<T> | undefinedThe codec of a parameter token that the rewrite placed, such as the design:paramtypes entry of a @Body() parameter. undefined for a raw class.
nestUnionFromMetatype(metatype: unknown): NestUnionInput | undefinedThe converter of a parameter token for a union of models, such as the design:paramtypes entry of a @Body() or @Query() parameter typed TCircle | TRect. fromWireFormat(wire, options?) returns the model of the variant that the tag picks and throws a LibError for a missing or unknown tag or invalid input. decodeQuery(query) turns query strings into the types that variant declares. undefined for any other token.
nestQueryDecoder(metatype: unknown): ((query: unknown) => unknown) | undefinedThe function that decodes a query of a parameter token to the numbers, booleans and arrays that its model declares, for a single model or a union of models, such as the design:paramtypes entry of a @Query() parameter. A value that does not fit stays text, so fromWireFormat rejects it. undefined for any other token, and for a union whose variant codecs are not registered yet.
nestModelConstruct(metatype: unknown): GeneratedModelConstructor | undefinedThe class that token constructs, or undefined.
nestReturnCodec(controllerClass: Function, handler: Function): NestReturnCodec | undefinedThe codec of the declared return of a handler, as { codec, array }. array is true when the handler returns an array of the model. undefined for a handler with no mark (mark rules). It throws a TypeError that starts with golem fault when the build marked the handler and the codec of the model is not registered. The lookup runs at each call, so cache the result for each handler if you need to.
nestHeadersCodec(controllerClass: Function, handler: Function): NestHeadersCodec | undefinedThe decoder of the whole @Headers() model of a handler, as { decode(headers, options?) }. decode treats a header that holds empty text as not sent, keeps the declared fields only, and returns the model, or throws a LibError for headers the model rejects. options are the fromWireFormat options except strip and construct. undefined for a handler with no header model (rules). It throws a TypeError that starts with golem fault when the build rewrote the parameter and the codec of its model is not registered. The lookup runs at each call, so cache the result for each handler if you need to.
setNestHeaders(request: object, value: unknown): voidStores the decoded headers on the request. The @Headers() parameter of the handler gets them. request.headers does not change. A handler with a header model that runs with nothing stored fails with a TypeError that starts with golem fault.

For inbound conversion in your own interceptor or pipe, get the codec with objectCodecFromMetatype and call its fromWireFormat. For a union of models, use nestUnionFromMetatype. For a @Query(), pass request.query through nestQueryDecoder before fromWireFormat. For an outbound response in your own interceptor, get the codec of the handler with nestReturnCodec(context.getClass(), context.getHandler()) and call its stringify. For a @Headers() model, decode the headers and store the result:

ts
const headers = nestHeadersCodec(context.getClass(), context.getHandler());
if (headers) {
  const request = context.switchToHttp().getRequest();
  setNestHeaders(request, headers.decode(request.headers));
}

@exprtlabs/golem/loader ​

A Node load hook that rewrites TypeScript files as Node loads them. Install it through register. Import loader only to call module.register yourself (Node loader).

  • It rewrites .ts, .mts, .cts and .tsx files outside node_modules. A workspace package that is linked into node_modules counts as outside it, also with preserveSymlinks.
  • Node cannot strip the types of a .tsx file. It also rejects a decorator, an enum, a namespace that holds a value, and a constructor parameter with an access modifier or readonly. The loader compiles each such file with your TypeScript. The jsx, decorator and target options of your tsconfig set the output. If the tsconfig has no jsx option that turns JSX into calls (react, react-jsx or react-jsxdev), a .tsx file fails to load and the error names the option. A syntax error in a file that the loader compiles fails the load with the file, the line and the message. A relative .js import can name a .tsx source.
  • It needs ES modules. A .cts file, or a .ts file under a CommonJS package.json, that holds a call to rewrite throws golem rewrites need ES modules. The message names the file.
  • A call that cannot be rewritten fails the load with the file, the line and the instruction to run golem generate.
  • Without a golem.yaml, the load fails with golem needs a golem.yaml to rewrite parse<T>() calls; set config or GOLEM_CONFIG.

@exprtlabs/golem/register ​

sh
node --import @exprtlabs/golem/register src/main.ts

Every later import of the process goes through the loader. The loader opens your project from the file that GOLEM_CONFIG names, else ./golem.yaml in the working directory (Node loader).

@exprtlabs/golem/vite ​

ts
import { golem } from '@exprtlabs/golem/vite';
import { defineConfig } from 'vite';

export default defineConfig({ plugins: [golem()] });
OptionTypeBehavior
configstringThe golem.yaml to open, relative to Vite's root. Without it the plugin uses GOLEM_CONFIG, else ./golem.yaml in root.

The plugin rewrites TypeScript in memory before Vite strips its types (Vite). Put golem() before plugins that transform TypeScript.

  • An id with a query, such as ?raw, is not rewritten.
  • The dev server rewrites a module again when a file its rewrite depends on, or a generated model file, changes.
  • The page reloads once for the file events of one run. The first event opens a 100 ms window, and the events in that window share one reload.
  • Without a golem.yaml, or for a call that cannot be rewritten, the build fails with the same messages as the loader.

@exprtlabs/golem/esbuild ​

ts
import { golem } from '@exprtlabs/golem/esbuild';
import { build } from 'esbuild';

await build({ entryPoints: ['src/main.ts'], bundle: true, outfile: 'dist/main.js', plugins: [golem()] });
OptionTypeBehavior
configstringThe golem.yaml to open, relative to absWorkingDir (default: the current directory). Without it the plugin uses GOLEM_CONFIG, else ./golem.yaml in absWorkingDir.

The plugin rewrites TypeScript in memory before esbuild strips its types and chains the source map into the bundle's (esbuild). A plugin that needs the TypeScript files goes before golem().

  • Watch mode builds a file again when a file its rewrite depends on changes.
  • Without a golem.yaml, or for a call that cannot be rewritten, the build fails with the same messages as the loader.

@exprtlabs/golem/eslint ​

js
import { golem } from '@exprtlabs/golem/eslint';

export default [await golem()];
OptionTypeBehavior
configstringThe golem.yaml to open, relative to cwd. Without it the function uses GOLEM_CONFIG, else ./golem.yaml in cwd.
cwdstringThe folder that config is relative to. Default: the current directory.
parser'text'Sets a parser that gives ESLint an empty program. Use it when your project has no ESLint parser for TypeScript. Without it, a config object before golem() sets the parser, such as the typescript-eslint parser.

golem() returns a promise of an ESLint flat-config object. It sets the rule golem/no-unrewritable-code to error for .ts, .mts, .cts and .tsx files (Lint for unrewritable code). Without a golem.yaml the promise rejects with the same message as the loader.

  • The rule reports the errors that golem check reports for the file, with the code and the position. It reads the text that ESLint holds.
  • Without parser: 'text', put a config object with a TypeScript parser before it.