Invoke another schematic
invoke runs another schematic of the workspace from inside a factory. The invoked schematic,
the child, runs on its own runner against the same Run. When it succeeds, its edits join the
Run and the factory that invoked it, the parent, sees them on its next read. Nothing reaches the
disk until the root schematic finishes and the Run commits, so a composed Run is still all or
nothing.
Use it when one schematic should reuse what another one already does. A page generator can call the route generator instead of copying its code, and a schematic can run an evaluation and act on its findings.
Requirements
Section titled “Requirements”You need the builder CLI v0.20.0 and @pbuilder/sdk 0.22.0 or later, the first SDK that
exports invoke. A typed invoke needs @pbuilder/sdk 0.24.0, and that SDK
needs the builder CLI v0.24.0 or later. Every output below comes from builder v0.20.0 and
@pbuilder/sdk 0.23.0.
With an older CLI, every invoke fails with
this engine cannot invoke a child schematic; upgrade the Project Builder CLI.
A minimal example
Section titled “A minimal example”Two schematics of the default collection, both created with builder new schematic:
add-page writes a page and invokes add-route, which writes the route for it.
"collections": { "default": { "add-page": { "path": "./schematics/add-page" }, "add-route": { "path": "./schematics/add-route" } }}Both take the same input. Codegen requires a label on every input:
{ "properties": { "name": { "type": "string", "label": "Page name", "required": true } }}The child is an ordinary factory:
import { create } from "@pbuilder/sdk/commons";import type { Input } from "./schema.generated.ts";
export default (input: Input) => { create(`src/routes/${input.name}.ts`, { template: "export const path = '/{= .name =}';\n", options: { name: input.name }, });};The parent is async and awaits the invoke. The first argument is the child’s qualified name,
collection:schematic, and the second holds the child’s inputs:
import { create, invoke } from "@pbuilder/sdk/commons";import type { Input } from "./schema.generated.ts";
export default async (input: Input) => { create(`src/pages/${input.name}.ts`, { template: "export const title = '{= .name =}';\n", options: { name: input.name }, }); await invoke("default:add-route", { name: input.name });};Run the parent:
builder execute default:add-page --name=aboutcreate (2) create src/pages/about.ts create src/routes/about.ts✓ done — 2 createThe command exits with code 0. The Plan lists the child’s file next to the parent’s, and a
--dry-run reports the same two operations without writing them.
What a child sees and does
Section titled “What a child sees and does”- Every edit the parent made before the invoke is visible to the child, and the child’s edits are visible to the parent after it.
- The child’s inputs are validated against its own
schema.json. - The child’s
scaffoldandcopyInread their source files from the child’s own package, not from the parent’s. - While the child runs, the parent waits. The runner never times an invoke out; only the Run’s deadline stops a child.
- The child can invoke other schematics. A Run holds at most 32 schematics on its stack, the root included.
Receive a Result
Section titled “Receive a Result”invoke resolves to the child’s Result, or undefined when the child returns none. A
generator child can return a Result only when its schema.json declares one under result:
{ "properties": {}, "result": { "type": "object", "properties": { "port": { "type": "number" } }, "required": ["port"] }}export default () => ({ port: 3001 });const { port } = (await invoke("default:allocate-port")) as { port: number };The cast is needed only while the call is untyped. Type the call to drop it.
A child that returns a value without declaring a Result fails, and the runner log holds
invalid Result: the factory declares no Result in schema.json but returned a value.
An evaluation schematic always returns its Findings. See Invoke an evaluation.
Type the call
Section titled “Type the call”From @pbuilder/sdk 0.24.0, invoke can check a call against the child’s own types. Codegen in
project mode writes invoke.generated.ts next to project-builder.json. The file adds every
local schematic of the Manifest to the InvokeRegistry interface of @pbuilder/sdk/commons,
keyed collection:schematic, with the child’s Input and Result types:
npx pbuilder-codegenimport type { Input as Input0 } from "./schematics/add-page/schema.generated.ts";import type { Input as Input1 } from "./schematics/add-route/schema.generated.ts";import type { Input as Input2, Result as Result2 } from "./schematics/allocate-port/schema.generated.ts";
declare module "@pbuilder/sdk/commons" { interface InvokeRegistry { "default:add-page": { input: Input0; result: undefined }; "default:add-route": { input: Input1; result: undefined }; "default:allocate-port": { input: Input2; result: Result2 }; }}Add invoke.generated.ts to the include of the project’s tsconfig.json, or the compiler
never reads it. A schematic that declares no Result has result: undefined.
With the registry in place, a call by a listed name is typed:
const { port } = await invoke("default:allocate-port");await invoke("default:add-route", { name: input.name });- The call resolves to the child’s Result type, so
portis anumberwith no cast. - The inputs must match the child’s Input type. A wrong or missing input, or an unknown input
key such as
{ nme: "about" }, fails to compile. inputscan be left out only when every input of the child is optional.- Any other name, including a misspelled one such as
"default:alocate-port"or a name held in astringvariable, takes any inputs and resolves tounknown, as before. Using thatunknownas a typed value, for example destructuringportfrom it, fails to compile. The call itself still compiles and fails at run time as an unknown schematic.
Run codegen again after you add a schematic or change a schema.json. Codegen rewrites the
registry only when every entry succeeds, so a failed run keeps the previous file. In project
mode it also refuses:
- an entry whose collection or schematic name is empty or contains
:, since a qualified name holds exactly one:; - a directory registered under two entries with different roles. The second entry fails, and its diagnostic names the first.
Single-schematic mode (npx pbuilder-codegen <schematic-directory>) writes no registry, and
schematics of other libraries are not typed yet. See
Type generation.
Which schematics you can invoke
Section titled “Which schematics you can invoke”The CLI hands the Run every schematic of every collection the Manifest defines, whether the
collection is a schematic container in project-builder.json (path entries) or a
collection.json. A schematic can invoke one in another collection of the same Manifest, for
example forms:render from default:add-page.
These are not invocable:
- A schematic registered only inline, under the reserved
schematicskey. Invoking it fails as an unknown schematic of its collection. - A schematic the CLI cannot resolve, such as a path entry whose directory does not exist. It fails as an unknown schematic of its collection.
- A schematic of an external library. Its collection is not one the Manifest defines, so the invoke fails as an undeclared collection.
A schematic that does not resolve never stops a root that does not invoke it.
When an invoke fails
Section titled “When an invoke fails”An invoke that fails rejects with a typed error from @pbuilder/sdk/commons. If the parent does
not catch it, the parent fails, the Run fails and nothing is written. builder execute exits
with code 5 and the error engine_native_developer_fault. Its runner_note names the parent
and carries the error’s message. Here default:probe invokes the name its target input
gives, and default:missing does not exist:
builder execute --dry-run default:probe --target=default:missingdry run: nothing is written to the workspace✗ [ENGINE] sidecar runner exited with code 4 engine_native_developer_fault · factory at schematics/probe failed: the collection "default" has no schematic "missing"; check the name, or invoke a schematic the collection declares check the schematic's file writes and inputs for the underlying cause Diagnostic log: ~/.pbuilder/logs/runner-9b850a0b3c12837f.ndjsonEach error and its message:
| Error | Message | Cause | Fix |
|---|---|---|---|
UnknownSchematicError (collection, schematic) |
the collection "default" has no schematic "missing"; check the name, or invoke a schematic the collection declares |
The collection exists, but has no invocable schematic of that name. Names match byte for byte | Fix the name, or register the schematic as a path entry or in a collection.json |
UndeclaredCollectionError (collection) |
the collection "nope" is not declared in the Manifest of this schematic's library; declare it, or invoke a collection the library declares |
No collection of the Manifest has that name | Declare the collection in project-builder.json, or fix the name |
ChildFailedError (child, reason) |
the child schematic "default:boom" failed (exception): the child schematic failed |
The child failed. Its edits are discarded | Read the child’s own error in the runner log (below) |
FrameDepthExceededError (limit) |
the invoke would exceed the limit of 32 nested schematics on this run's stack; nothing ran |
The invoke would put a 33rd schematic on the stack, for example a schematic that invokes itself | Stop the recursion before it reaches the limit |
InvokeUnavailableError |
this engine cannot invoke a child schematic; upgrade the Project Builder CLI |
The CLI’s engine cannot launch a child, or a test ran without children |
Upgrade the CLI to v0.20.0 or later. In tests, pass children; see Testing schematics |
plain Error |
invalid params |
The name is not collection:schematic (for example invoke("add-route")), or the inputs are not an object |
Pass the qualified name and an object of inputs |
plain Error |
invoke failed |
Any other failure of the engine’s own. A collection.json entry whose factory file does not exist fails this way |
Check that the child’s factory file exists |
On the wire these are the engine’s codes -32006, -32002, -32003, -32005, -32004,
-32602 and -32000, in that order.
The child’s own error
Section titled “The child’s own error”ChildFailedError.reason is one of exception, invalid-input, invalid-result,
runner-guard, instruction-rejected and invoke-still-running. When the engine cannot tell
why the child failed, the reason is exception and the message is the fixed
the child schematic failed. The child’s own message is then in the runner log that the
Diagnostic log line names. For a child that threw new Error("the route table is missing"),
the log holds these lines:
pbuilder-runner: factory at schematics/boom failed: the route table is missinginvoke default:boom failed: child runner exited with code 4pbuilder-runner: factory at schematics/probe failed: the child schematic "default:boom" failed (exception): the child schematic failedA child that reads a file over the 8 MiB read cap without catching ReadTooLargeError also
reaches the parent as a ChildFailedError. Run on its own with CLI v0.26.0 and @pbuilder/sdk
0.26.0, the same schematic fails with the code execute_read_ceiling_exceeded. Under an invoke,
a parent that does not catch the ChildFailedError fails with engine_native_developer_fault. See
When nothing catches the read.
The same applies to a child given inputs its schema rejects. Under builder execute it fails
with the reason exception, and the log holds the child’s line, for example
invalid input: name must be string.
A child that creates a file the workspace already has, without { force: true }, fails with
the reason instruction-rejected:
the child schematic "default:claim-child" failed (instruction-rejected): the engine rejected an instruction of the child (collision)Recover from a failed child
Section titled “Recover from a failed child”Catch the error to keep the Run going. The failed child’s edits are already gone, and the parent’s own edits stay:
import { create, invoke, ChildFailedError } from "@pbuilder/sdk/commons";
export default async () => { try { await invoke("default:boom", {}); } catch (error) { if (!(error instanceof ChildFailedError)) throw error; create("notes/skipped.txt", { template: `${error.child} ${error.reason}\n`, options: {} }); }};This Run succeeds with one operation, create notes/skipped.txt, whose content is
default:boom exception. UnknownSchematicError, UndeclaredCollectionError,
FrameDepthExceededError and InvokeUnavailableError can be caught the same way, since none
of them started a child.
Two schematics write the same file
Section titled “Two schematics write the same file”A path that this Run created can be claimed again by any schematic of the Run, and the last
claim wins. When default:claim-parent creates src/index.ts and then invokes a child that
creates src/index.ts with other content, the Plan holds one create src/index.ts and the
file gets the child’s content.
A file that was already in the workspace is different. A create of it without
{ force: true } is still a collision, in the parent as in a child. Running
default:claim-parent a second time, once src/index.ts exists, fails with:
engine_native_developer_fault · factory at schematics/claim-parent failed: create failed at src/index.ts: path-collisionRead the file first and branch, or pass { force: true }, as
Error handling describes.
Every runner, the child’s included, starts in its own empty temporary directory, not in the
workspace. Reach the workspace through the SDK’s verbs, find and glob.
Limits
Section titled “Limits”- Only the Manifest’s own collections are invocable. Externals and inline entries are not.
- A Run holds at most 32 nested schematics, and no setting changes it.
- A generator child returns a Result only when its
schema.jsondeclares one. - An invoked evaluation runs read-only: its edits are discarded even when it succeeds.
- When a child fails for a reason the engine cannot classify, the parent sees only
the child schematic failed; the child’s own message is in the runner log. - The typed
invokecovers the Manifest’s local schematics only. A name outside the registry resolves tounknown.
Next steps
Section titled “Next steps”- Write an evaluation schematic, including how to invoke one.
- Testing schematics: test a parent with its children in memory.
- The life of a Run: netting, the Plan and the Commit.