How-to › Model, configure and generate

How to add a custom generation action to an application model#

Write an @voxgig/model action that emits a Terraform variables file from every service and environment, under an explicit output root, with a byte-identical rerun.

Audience
Platform team
Level
intermediate
Topic
Model an application and generate from it
Languages
TypeScript
Verified

Read first: Split an application model into entity and service files

Every service in your model reads environment variables, and the Terraform that deploys them declares a variable for each one by hand. A service adds a secret, the model gains a field, and the deploy goes out without the variable, because no generator you run writes a variables file. The copy kept in infra/ drifts one service at a time.

What you get

You will end up with a @voxgig/model action that writes a Terraform variables file from every service and environment in the model, beside the actions you already run. This is for you if a platform team owns a model that spans services and needs an artifact nobody ships a generator for.

Short answer

Write a CommonJS module that receives (model, build, ctx), declare it under sys: model: action in .model-config/model-config.aontu, and list it in sys.model.order.action after the existing actions. Derive its output root from build.path, write through build.fs, and refuse any path outside that root. Add a field, run voxgig-model, and assert the artifact gained it and a second run is byte identical.

You will need

Node 22 or later, @voxgig/model 12.0.2 with its peer pino 10.4.0, and an application model in .aontu files. The sample’s model has two services, orders and billing, each with a var map, and two environments, dev and prod. Its existing action, services, writes a Markdown table of services and ports.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
@voxgig/model actionsThe artifact spans services, environments and entities held in one modelYou write the renderer, its escaping and its write guard yourselfThe artifact is about one schema your toolchain already reads
NSwagA .NET build that already runs nswag run from an MSBuild targetIts configuration document has no step for other files, so a second command follows itYou need data that is not in the OpenAPI document
orvalA TypeScript client from one OpenAPI document, with one artifact derived from itThe hook sees the files it wrote, and your script reads the document itselfThe artifact needs more than one service’s document
Prisma generatorThe artifact derives from the database schema, in a project that runs prisma generateIt gets the datamodel, plus string settings from its own generator blockServices and environments matter to the output
Projen ComponentThe artifact is project configuration that Projen should own and keep read-onlyProjen synthesizes its own bookkeeping files beside yours and replaces a hand-edited fileThe repository is not a Projen project
TypeSpec emitterAPI definitions in TypeSpec, and an output its standard emitters lackAn emitter is a library against the compiler’s type graph and its APIThe data lives outside the TypeSpec program

Voxgig maintains @voxgig/model, the tool this page is about; the other five rows belong to other projects.

Reach is the difference. The action gets the whole unified model, so one file can name every service’s variables and every environment. orval, NSwag, Prisma, and TypeSpec each hand you one schema, and they plug into toolchains your team may already run. Projen sits between: its component reads whatever your code loads, and it owns the files it writes.

Declare the action beside the existing one

Add the action to the config file and set the order explicitly:

sys: model: action: {
  services: load: 'build/services.cjs'
  tfvars:   load: 'build/tfvars.cjs'
}
# Without this line the actions run in sorted key order.
sys: model: order: action: 'services,tfvars'

The action is called with the unified model object, (build.model, build, ctx), in local.ts at line 74; it never reads model.json. The config file reference comments its example with “When omitted, every declared action runs in declaration order”, but the run disagrees. On 12.0.2 the order is Object.keys of the action map (lines 28 to 30), and the unified map comes out sorted. A test declares tfvars before services and sees services run first. The same order turned up in Emit TypeScript types and SQL from one application model, which covers the types, the SQL, and the colored log in CI.

Write under an explicit output root

The reference’s first example writes out/docs.html, a path relative to the working directory. Find the root from build.path instead, and send every write through one guard:

// generated/ beside model/, found from the root model file rather than from
// the working directory, so the run writes to the same place wherever it starts.
function outputRoot(build) {
  return Path.resolve(build.path, '..', '..', 'generated')
}

// Write text to rel under the output root, through build.fs so --dryrun holds.
// Refuses a path that leaves the root, and refuses to replace a file that
// does not carry the generated header, which is how a hand-kept file looks.
function writeGenerated(build, rel, text) {
  if (typeof rel !== 'string' || rel === '' || Path.isAbsolute(rel) || rel.includes('\\')) {
    throw new Error(`output path must be relative to generated/: ${JSON.stringify(rel)}`)
  }
  const root = outputRoot(build)
  const target = Path.resolve(root, rel)
  const inside = Path.relative(root, target)
  if (inside === '' || inside.startsWith('..') || Path.isAbsolute(inside)) {
    throw new Error(`refusing to write outside generated/: ${rel}`)
  }

The renderer in build/tfvars.cjs sorts services and variables in code-point order, writes default = null for an optional variable and sensitive = true for a secret, and refuses a name that cannot be a Terraform identifier.1 Description text goes through an HCL string escape.

Add a field and run it twice

demo.mjs runs voxgig-model three times on a scratch copy: as committed, after one line adds STRIPE_WEBHOOK_SECRET to billing, and again with nothing changed.

node demo.mjs
run 1, the model as committed
  generated/ holds: SERVICES.md, terraform/variables.tf
  SERVICES.md: same as the committed file
  terraform/variables.tf: same as the committed file
run 2, STRIPE_WEBHOOK_SECRET added to billing
  SERVICES.md: 1 removed, 1 added
    - | billing | 8081 | ORDERS_URL, STRIPE_API_KEY |
    + | billing | 8081 | ORDERS_URL, STRIPE_API_KEY, STRIPE_WEBHOOK_SECRET |
  terraform/variables.tf: 0 removed, 6 added
    + variable "billing_stripe_webhook_secret" {
    +   type        = string
    +   description = "billing: Signing secret for Stripe webhooks"
    +   sensitive   = true
    + }
    +
run 3, the same model again
  SERVICES.md: byte identical to run 2: true
  terraform/variables.tf: byte identical to run 2: true

One field reached both artifacts in the same run. record.sh ran terraform validate 1.17.2 on the committed file, which passed.

Check it worked

Run the suite. It covers the renderer, the escape, the guard, the three runs, --dryrun, and the run order:

node --test action.test.mjs
1..8
# tests 8
# suites 0
# pass 8
# fail 0
# cancelled 0
# skipped 0
# todo 0

The --dryrun test leaves generated/ empty with the guarded action, then swaps in a copy that writes with node:fs and finds terraform/variables.tf on disk. The command line reference says a dry run will “redirect all file writes to an in-memory filesystem (nothing touches disk)”. It redirects build.fs alone, in model.ts lines 47 to 51.

Derive the same table in orval and NSwag

A team that generates its SDK with orval adds the step through hooks.afterAllFilesWrite, a command run after orval writes, with the written paths appended. A team on NSwag has no such key: the configuration document holds runtime, documentGenerator, and codeGenerators, so the step goes after nswag run in the MSBuild target or the script. Both ran compare/env-table.mjs on the billing document, once, in record.sh:

node compare.mjs
orval 8.48.0, hooks.afterAllFilesWrite running env-table.mjs
  exit 0; orval-out/ holds ENV.md, billing.ts
  variables it could name: BILLING_BASE_URL, BILLING_API_KEY
NSwag 14.8.0, nswag run nswag.json, then env-table.mjs
  exit 0; configuration document keys: runtime, documentGenerator, codeGenerators
  nswag-out/ holds ENV.md, billing.ts; variables it could name: BILLING_BASE_URL, BILLING_API_KEY
Prisma 7.10.1 / 7.10.1, a generator built with generatorHandler
  exit 0; it was handed: allowNoModels, datamodel, datasources, dmmf, generator, otherGenerators, schemaPath, version
  models: Order(id, total, note); generator block config: {"environments":"dev,prod"}
TypeSpec 1.18.0, an emitter's $onEmit
  exit 0; models in the program: Order(id, total, note)
Projen 0.105.7, a Component that reads model/model.json
  wrote .gitattributes, .gitignore, .projen/files.json, .projen/tasks.json, ENV.md; ENV.md has 4 rows, mode 444
  over a hand-written ENV.md: exit 0, first line now | Service | Variable | Secret |

Both generators read one service’s OpenAPI document, so the table names its base URL and its API key and nothing about orders. Prisma took the environment names only as a string in its own generator block.

When it goes wrong

The hand-kept infra/variables.tf is gone after a build that exited 0. The action wrote to a path relative to the working directory. pitfall.mjs runs a naive copy of the action and the guarded one:

node pitfall.mjs
naive action, run from the project root
  exit 0, infra/variables.tf overwritten, generated/: SERVICES.md
naive action, run from model/
  exit 1, infra/variables.tf kept, generated/: SERVICES.md
  ENOENT: no such file or directory, open 'infra/variables.tf'
guarded action, run from model/
  exit 0, infra/variables.tf kept, generated/: SERVICES.md, terraform/variables.tf
guarded action, -b "{tfvars:'../infra/variables.tf'}"
  exit 1, infra/variables.tf kept, generated/: SERVICES.md
  refusing to write outside generated/: ../infra/variables.tf
guarded action, a hand-kept file at generated/terraform/variables.tf
  exit 1, infra/variables.tf kept, generated/: SERVICES.md, terraform/variables.tf
  refusing to replace a file that was not generated: generated/terraform/variables.tf

A failed action still leaves the earlier action’s SERVICES.md, so read the exit status before the files.

A description holding ${ becomes a Terraform interpolation. The escape is $${, but an escape written as the replacement string '$${' gives back ${, because $$ there means one $.2 Pass a function to replace, as hcl() does, and test the escape with a ${ in the input. record.sh ran terraform validate on both forms: escaped, it passed; spliced raw, it failed with Invalid character.

When not to do this

Do not write an action for an artifact your schema tool already owns. If the variables come from one OpenAPI document and the client comes from orval, the afterAllFilesWrite hook does the job in the toolchain you run, with no model to maintain. The same holds for NSwag inside an MSBuild target.

Skip @voxgig/model when the services are not in one model already. Moving them there to get one file is the larger project.

Do not let an action take its output path from a build argument without the guard. The page’s guard refuses .., an absolute path and a backslash, and it does not resolve symbolic links inside generated/.

Prefer a Projen component when the artifact is project configuration and the team wants it read-only, since Projen writes ENV.md with mode 444 and owns it.

Last verified

Verified 2026-11-22 against Node 22.23.5, @voxgig/model 12.0.2, aontu 0.76.3, and pino 10.4.0. Every output block is what the command before it printed. orval 8.48.0, NSwag 14.8.0 on the ASP.NET Core 10 runtime, Prisma 7.10.1, TypeSpec 1.18.0, Projen 0.105.7 and Terraform 1.17.2 ran once in record.sh, and compare.mjs reads what each recorded. The script sets CHECKPOINT_DISABLE=1, which turns off the checkpoint calls of the Prisma command line and of Terraform. npm listed no @voxgig/model release after 12.0.2 on that day, so the sorted run order and the dry-run gap are on that release.

Footnotes

  1. The environment variable the action writes has the shape of the example on Terraform’s variables page, contains call and all. That example allows dev, staging, and prod; this model declares two environments, and the list follows the model. ↩︎ Back to text

  2. The table of replacement patterns on MDN puts $$ first, as the pattern that inserts a single $. Terraform’s escape for a literal ${ is $${, so writing it through a replacement string takes four dollar signs, and writing it through a function takes two. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.