Skip to content

inker ​

@c9up/inker: server-side templates in .inker files, parsed in Rust, rendered with HTML escaping by default. Guide: Templates.

Installation ​

bash
pnpm add @c9up/inker

Register the provider in reamrc.ts (providers: [() => import('@c9up/inker/provider')]); the package has no configure hook. @c9up/rosetta, an optional peer dependency, supplies the t() helper. The parser is a native engine. It comes as one small package per platform, @c9up/inker-<platform>, for linux x64 and arm64 (glibc), macOS x64 and arm64, and Windows x64. @c9up/inker lists them as optional dependencies, and your package manager installs only the one that matches your machine. No Rust toolchain is needed. Do not install with optional dependencies turned off (--no-optional, --omit=optional): the engine would be left out.

There is no JavaScript fallback. Without the engine, rendering throws E_INKER_NAPI_REQUIRED, and its message names the package to install, for example @c9up/inker-linux-x64-gnu.

Entry points ​

ImportContents
@c9up/inkerTemplates, TemplateRenderer, SafeString, Stacks, Processor, InkerError, errors and the types. The default export is the plugin registrar (plugins).
@c9up/inker/providerInkerProvider (default export) and InkerProviderConfig.
@c9up/inker/services/mainThe booted InkerRenderer (default export), plus setInker, getInker, clearInker. Reading it before the provider has started throws.
@c9up/inker/testingcreateTestTemplates, an engine over in-memory templates.

Exports ​

@c9up/inker ​

ExportKindDescription
TemplatesclassThe engine: disks, rendering, globals, tags, plugins, cache.
TemplateRendererclassA renderer with shared state of its own; ctx.view is one.
SafeStringclassA string emitted without escaping.
StacksclassThe store behind @stack, @pushTo and @pushOnceTo.
ProcessorclassSource (raw) and output (output) transforms; templates.processor.
InkerErrorclassThe error of a template, at a position in it; see InkerError, errors.
errorsnamespaceThe errors a call raises outside any template, one flare class per code; see InkerError, errors.
plugins (also the default export)constRegistrar: plugins pushed here reach every engine the provider builds.
TemplatesOptionsinterface{ root: string; cacheMode?: CacheMode; helpers?: ReadonlyMap<string, HelperFn> }.
InkerPluginFntype(templates: Templates, firstRun: boolean, options: T | undefined) => void.
InkerPluginOptionsinterface{ readonly recurring?: boolean }: run the plugin before every render, not only the first.
InkerSharedRendererinterface{ render(template: string, data?: Readonly<Record<string, unknown>>): Promise<string> }, what plugins.share() returns.
InkerTaginterfaceA custom tag: tagName, block, seekable, noNewLine?, compile(parser, buffer, token).
InkerTagBufferinterfacewriteRaw(text), outputExpression(jsExpression, filename, line, shouldEscape).
InkerTagTokeninterfaceproperties.jsArg (the argument source), filename, loc, renderBody(locals?), evaluate(expression).
InkerTagParserinterface{ readonly utils: Readonly<Record<string, never>> }.
RawProcessorValueinterface{ raw: string; path?: string }.
OutputProcessorValueinterface{ output: string; template?: string }.
InkerErrorCodetypeUnion of the codes an InkerError carries.
InkerErrorPositioninterface{ line: number; col: number; filename: string }, the third argument of new InkerError().
HelperFntype(...args: readonly unknown[]) => unknown.
THelpertype(key: string, params?: Record<string, unknown>) => string.
UrlHelpertype(name: string, params?: Record<string, unknown>) => string.
AssetHelpertype(name: string) => string.
CsrfFieldHelper, CsrfMetaHelpertype() => SafeString.
CspNonceHelpertype() => string.

Templates ​

MemberSignatureDescription
constructornew Templates(options: TemplatesOptions)root is canonicalised and is the containment boundary of every path.
createstatic create(options: TemplatesOptions): TemplatesSame as the constructor.
renderrender(name: string, data?: Readonly<Record<string, unknown>>): Promise<string>Renders <root>/<name>.inker with its layouts, partials and components.
renderSyncrenderSync(name: string, data?: Readonly<Record<string, unknown>>): stringSame, synchronously; an await in the template raises E_INKER_ASYNC_NOT_SUPPORTED.
renderString / renderRawSyncrenderRawSync(source: string, data?: Readonly<Record<string, unknown>>, templatePath?: string): stringRenders a string. It cannot load other templates: @layout, @include, @component and {{> body }} raise E_INKER_DISK_REQUIRED; use render. renderString takes no templatePath.
renderRawrenderRaw(source: string, data?: Readonly<Record<string, unknown>>, templatePath?: string): Promise<string>Async form of renderRawSync.
compilecompile(name: string): voidParses a template without rendering it; throws an InkerError with its filename, line and col when it does not parse.
compileRawcompileRaw(source: string, templateName?: string): voidSame, for a string.
mountmount(dir: string | URL): void / mount(diskName: string, dir: string | URL): voidWithout a name, re-points the default disk. With one, templates are addressed as diskName::template. Re-mounting a name to another directory raises E_INKER_DISK_COLLISION.
unmountunmount(diskName: string): voidNo-op when absent.
mountedget mounted(): Readonly<Record<string, string>>Disk name to root; default is the root in force.
makePathmakePath(name: string): stringThe absolute path a name resolves to, without touching the disk.
resolveresolve(name: string): { template: string }A template's source; a registered template wins over the disk.
registerTemplateregisterTemplate(name: string, contents: { template: string }): voidAn in-memory template, which wins over a file of the same name. A name already registered raises E_INKER_TEMPLATE_COLLISION.
removeTemplateremoveTemplate(name: string): void
templatesget templates(): Readonly<Record<string, { template: string }>>The registered templates.
listComponentslistComponents(): { diskName: string; components: { componentName: string; tagName: string }[] }[]Every component reachable as a tag: components/form/input.inker is @form.input.
registerTagregisterTag(tag: InkerTag): voidRegisters @tagName(...). compile runs at render time and may be async; a block tag reads its rendered body with token.renderBody(). Clears the cache.
tagsget tags(): ReadonlyMap<string, InkerTag>
globalglobal(name: string, value: unknown): voidA value in every render; render data wins over it.
globalsget globals(): ReadonlyMap<string, unknown>
useuse<T extends InkerPluginOptions>(plugin: InkerPluginFn<T>, options?: T): thisQueues a plugin, run just before the first render.
createRenderercreateRenderer(): TemplateRenderer
onRenderonRender(callback: (renderer: TemplateRenderer) => void): thisRuns on every renderer created.
shareshare(data: Readonly<Record<string, unknown>>): TemplateRenderercreateRenderer().share(data).
processorreadonly processor: Processorprocessor.process('raw', fn) or processor.process('output', fn); a raw transform clears the cache.
configureconfigure(options: Readonly<{ cacheMode?: CacheMode }>): voidChanges the cache mode, dropping the cache.
clearCacheclearCache(): voidDrops every parsed template.

TemplateRenderer ​

MemberSignatureDescription
shareshare(data: Readonly<Record<string, unknown>>): thisMerges data into the shared state, deeply.
renderrender(name: string, data?: Readonly<Record<string, unknown>>): Promise<string>
renderSyncrenderSync(name: string, data?: Readonly<Record<string, unknown>>): string
renderStringrenderString(source: string, data?: Readonly<Record<string, unknown>>): string
renderRawSync / renderRawrenderRawSync(source: string, data?: Readonly<Record<string, unknown>>, templatePath?: string): stringrenderRaw returns a Promise<string>.
cloneclone(): TemplateRendererA renderer with a copy of the shared state.
getStategetState(): Record<string, unknown>Engine globals with the shared values on top.

InkerRenderer (@c9up/inker/services/main) ​

MemberSignatureDescription
renderrender(ctx: InkerHttpContext, name: string, data: Readonly<Record<string, unknown>>): Promise<void>Renders and sends the page as text/html; charset=utf-8.
renderToStringrenderToString(ctx: InkerHttpContext, name: string, data: Readonly<Record<string, unknown>>): Promise<string>
mount / unmountmount(diskName: string, dir: string): voidOn the shared engine, for a package that ships its own templates.
templatesget templates(): TemplatesThe engine.

plugins ​

MemberSignatureDescription
useuse<T extends InkerPluginOptions>(plugin: InkerPluginFn<T>, options?: T): thisQueues a plugin for every engine, including one already built.
shareshare(state: Readonly<Record<string, unknown>>): InkerSharedRendererRenders outside a request, with shared state; raises E_INKER_ENGINE_MISSING before the provider has started.
sizeget size(): numberPlugins queued.

SafeString, Stacks ​

MemberSignatureDescription
SafeString constructornew SafeString(value: string)Only for markup you wrote or escaped: wrapping user input is an XSS.
SafeString#valuereadonly value: string
Stacks#createcreate(name: string, position?: InkerErrorPosition): stringA placeholder; a second @stack of one name throws an InkerError at position, or errors.E_INKER_INVALID_EXPRESSION without one.
Stacks#pushTo / pushToToppushTo(name: string, contents: string): this
Stacks#pushOnceTo / pushOnceToToppushOnceTo(name: string, sourceId: string, contents: string): thisOnce per sourceId.
Stacks#hasSourcehasSource(name: string, sourceId: string): boolean
Stacks#fillPlaceholdersfillPlaceholders(contents: string): string

InkerError, errors ​

An error at a position in a template (it does not parse, an expression fails, a layout or slot is misused) is an InkerError. An error a call raises outside any template (a root or name refused, a provider not started, a helper given a bad argument) is one of the errors namespace, a flare class per code. Some codes come both ways, see Errors: test error.code to cover both, or instanceof. An errors exception a helper raises during a render reaches the caller as it is, without a position.

MemberSignatureDescription
InkerError constructornew InkerError(message: string, code: InkerErrorCode, options: InkerErrorPosition, errorOptions?: ErrorOptions)The original error, when there is one, is on cause.
#codecode: InkerErrorCode
#line / #colline: number, col: number1-based; 0 when the failure has no line of its own.
#filenamefilename: stringThe template's name (pages/home, admin::dashboard), or the label given to renderRaw / compileRaw; empty for an unlabelled source string.
#stackstack: stringIts second line is at anonymous (<filename>:<line>:<col>), pointing at the template.
#statusstatus: number500. InkerError extends flare's Exception, so the exception handler treats it as any ream error.
errors.E_INKER_* constructornew errors.E_INKER_NOT_BOOTED([message], options?: ErrorOptions)The same for every class of the namespace: flare's createError, with code and status 500.

@c9up/inker/testing ​

ExportKindDescription
createTestTemplatesfunctioncreateTestTemplates(options?: CreateTestTemplatesOptions): TestTemplates. Templates registered in memory, cacheMode: 'never'.
CreateTestTemplatesOptionsinterface{ templates?: Readonly<Record<string, string>>; helpers?: ReadonlyMap<string, HelperFn>; globals?: Readonly<Record<string, unknown>> }.
TestTemplatesinterface{ engine: Templates; render(name, data?); renderString(source, data?); dispose() }. dispose() removes the temporary root.

Globals and helpers ​

Every render has the core globals (camelCase, pascalCase, snakeCase, dashCase, capitalCase, sentenceCase, dotCase, noCase, titleCase, truncate, excerpt, nl2br, pluralize, sentence, prettyBytes, toBytes, prettyMs, toMs, ordinal, inspect, html.attrs, html.classNames, html.safe, html.escape, html.jsonLd, js.stringify). The provider adds app and qs and the helpers t, url / urlFor / route, signedUrlFor / signedRoute, routes, routesJSON, asset, config, csrfField, csrfMeta, cspNonce and formAttributes. See Helpers and custom tags.

Configuration ​

config/inker.ts, read by the provider:

OptionTypeDefaultDescription
templatesRootstring<appRoot>/resources/templatesAbsolute, or relative to the application root.
cacheMode'auto' | 'mtime' | 'never''auto'auto is never in production, mtime elsewhere. Any other value throws at start.
assetManifestReadonly<Record<string, string>><appRoot>/public/manifest.jsonWhat asset() resolves against.
additionalHelpersReadonly<Record<string, HelperFn>>noneMerged over the provider's helpers; overriding one warns once.
Cache modeBehaviour
mtimeStats the file on every render and reparses when its mtime moves.
neverNever re-stats: a template is parsed once and kept until clearCache(), registerTag() or a raw processor.

The cache belongs to one Templates: two engines with different roots share nothing.

Container bindings ​

TokenResolves to
InkerRenderer (class), 'inker'The InkerRenderer. Resolving it before the provider has started throws.

'inker' is declared on ContainerBindings. The provider also gives every HTTP context a view (ctx.view: TemplateRenderer), seeded with the request, and sets app.usingInker to true.

Errors ​

Class says how a code is raised: as an InkerError (with a position in a template), as a class of errors (by a call, without one), or both, where a call and a template can each fail that way (E_INKER_INVALID_PATH: a root a call is given, or a name a template includes).

CodeClassRaised when
E_INKER_TEMPLATE_NOT_FOUNDbothNo template has this name; the ENOENT is on cause.
E_INKER_PARSE_ERRORInkerErrorThe template cannot be parsed.
E_INKER_UNKNOWN_IDENTIFIERInkerErrorAn expression names something not in scope, or reads a property of null / undefined.
E_INKER_INVALID_PATHbothAn invalid root, template name, disk name, tag definition or plugin.
E_INKER_UNCLOSED_INTERPOLATIONInkerErrorA {{ has no matching }}.
E_INKER_UNCLOSED_BLOCK_TAGInkerErrorA block tag is not closed.
E_INKER_UNCLOSED_BLOCKInkerErrorA block has no @end.
E_INKER_UNMATCHED_BLOCK_ENDInkerErrorAn @end closes no block.
E_INKER_MISMATCHED_BLOCK_ENDInkerErrorAn @end closes another block than the open one.
E_INKER_UNKNOWN_DIRECTIVEInkerErrorA directive the engine does not know.
E_INKER_UNKNOWN_TAGInkerErrorNo tag is registered under this name.
E_INKER_INVALID_LAYOUT_POSITIONInkerError@layout is not the first statement.
E_INKER_DUPLICATE_LAYOUTInkerErrorA template declares more than one layout.
E_INKER_NESTED_LAYOUT_UNSUPPORTEDInkerErrorA layout extends another layout.
E_INKER_LAYOUT_IN_PARTIALInkerErrorA partial declares a layout.
E_INKER_CIRCULAR_INCLUDEInkerErrorTemplates include each other in a loop.
E_INKER_MISSING_SLOTInkerErrorA component requires a slot the caller did not fill.
E_INKER_UNKNOWN_SLOTInkerErrorThe caller fills a slot the component does not declare.
E_INKER_DISK_REQUIREDInkerErrorA string render (renderString, renderRaw) uses @layout, @include, @component or {{> body }}.
E_INKER_DISK_COLLISIONerrorsA disk name is mounted again on another directory.
E_INKER_TEMPLATE_COLLISIONerrorsregisterTemplate was given a name already registered.
E_INKER_INVALID_EXPRESSIONbothAn expression cannot be evaluated, or SafeString was given a non-string.
E_INKER_INVALID_ITERABLEInkerError@each was given something that is not iterable.
E_INKER_HELPER_THROWbothA helper threw during the render.
E_INKER_ASYNC_NOT_SUPPORTEDInkerErrorawait in a synchronous render.
E_INKER_RENDER_DEPTHInkerErrorPartials or components nested too deep, or a helper overflowed the stack.
E_INKER_DUMP_DIEInkerError@dd() stopped the render.
E_INKER_INVALID_JSON_LDerrorshtml.jsonLd was given a value JSON-LD cannot hold.
E_INKER_TEMPLATE_ERRORInkerErrorA template raised an error itself.
E_INKER_ENGINE_MISSINGerrorsThe plugins singleton rendered before the provider built an engine.
E_INKER_NAPI_REQUIREDbothThe native inker engine is missing or failed to load. The message names the package to install.
E_INKER_NOT_BOOTEDerrorsThe renderer (@c9up/inker/services/main, or the container's InkerRenderer) was used before InkerProvider.start() ran or setInker() seated one.
E_INKER_INVALID_CONFIGerrorsconfig.inker holds a value the provider cannot use: a cacheMode other than mtime, never or auto, or an additionalHelpers entry that is not a function.
E_INKER_INVALID_HELPER_ARGUMENTerrorsA view helper (t, url, route, signedRoute, config, formAttributes, asset) got an argument it cannot use: a name or key that is not a string, or route params that are not a plain object of finite, non-null primitives.
E_INKER_OUTSIDE_RENDERerrorsA helper that reads the request was called outside inker.render().

Migration ​

  • InkerRenderError is gone. An error at a position in a template is an InkerError (import { InkerError } from '@c9up/inker'), with code, line, col and filename as properties: error.context.line becomes error.line, error.context.column becomes error.col, and error.context.templateName becomes error.filename. templatePath and expression are gone; a missing template names its path in its message.
  • An error a call raises outside any template is one of errors (import { errors } from '@c9up/inker'), tested with error instanceof errors.E_INKER_NOT_BOOTED or error.code. It has no position.
  • error.code keeps every value it had.
  • To build one yourself, new InkerRenderError('E_INKER_PARSE_ERROR', message, { line, column, templateName }) becomes new InkerError(message, 'E_INKER_PARSE_ERROR', { line, col: column, filename: templateName }).

See also ​