On this page

API reference

Every public method, option and field. For explanations and examples, see the guide.

new ComponentBuilder(options?)

Creates a builder with its own registry of components.

OptionTypeDefaultDescription
apiEndpointstring | nullnull Base URL of your component server. Needed for export(…, { type: 'cloud' }) and importing by name.

Other options are kept on builder.config but not used.

define(name, definition)

define(name: string, definition: ComponentDefinition): ComponentData

Stores the component in the registry and, in a browser, registers it as a custom element. Returns the serializable component data.

Throws if:

When it throws, nothing is registered.

export(name, options?)

export(name: string, options?: { type?: 'json' | 'script' | 'cloud' }): Promise
typeResolves to
'json' (default){ type: 'json', data: ComponentData, usage: string }
'script'A standalone script as a string. See Standalone scripts.
'cloud'The JSON your server returns from POST {apiEndpoint}/components.

data also includes exportedAt (a timestamp) and exportOptions. Rejects if the component isn't in the registry, if type: 'cloud' is used without apiEndpoint, or if the server responds with a non-2xx status.

import(source, options?)

import(source: string | ComponentData | JsonExport, options?: { name?: string }): Promise<string>

Registers a component and resolves to its tag name.

sourceTreated as
An objectComponent data. An export() result ({ type: 'json', data }) is unwrapped.
String starting with {JSON to parse.
String starting with http://, https://, //, /, ./ or ../A URL to fetch.
Any other stringA name to load from GET {apiEndpoint}/components/{name}.

options.name registers the component under a different tag name. Rejects on invalid data, an invalid or taken name, a non-2xx response, or a missing apiEndpoint when loading by name. A failed import registers nothing.

Importing evaluates the component's function sources. Only import from sources you trust.

ComponentBuilder.escapeHtml(value)

static escapeHtml(value: unknown): string

Converts value to a string and escapes &, <, >, " and '. null and undefined become ''. Templates receive the same function as helpers.escape.

Properties

PropertyTypeDescription
registryMap<string, ComponentData>Components defined or imported by this builder, by name.
configobjectThe options passed to the constructor, with defaults applied.

Lower-level methods

define, export and import use these. They're public for custom workflows.

generateScript(data)

generateScript(data: ComponentData): string

Returns the standalone script for component data. Throws if data.name is invalid.

registerFromData(data, options?)

registerFromData(data: ComponentData, options?: { name?: string }): string

The synchronous part of import: validates data, rebuilds functions, registers the element and stores it in the registry.

registerWebComponent(name, definition)

registerWebComponent(name: string, definition: ComponentDefinition): boolean

Registers a custom element from a definition with real functions, without touching the registry. Returns false where customElements doesn't exist, such as Node. Throws if the name is already registered on the page.

serializeMethods(methods)

serializeMethods(methods: Record<string, Function>): Record<string, string>

Turns each function into source text that evaluates to a function. Method shorthand such as save(x) { … } becomes function (x) { … }.

generateMethodsCode(methods)

generateMethodsCode(methods: Record<string, string>): string

Returns object-literal entries ("name": source) for serialized methods.

fetchJson(url, init?)

fetchJson(url: string, init?: RequestInit): Promise<any>

fetch plus response.json(), rejecting on non-2xx responses.

saveToCloud(data) and loadFromCloud(name)

saveToCloud(data: ComponentData): Promise<any>
loadFromCloud(name: string): Promise<ComponentData>

The two requests to your component server. Both reject without apiEndpoint.

toPascalCase(str) and generateUsageInstructions(name)

toPascalCase('tally-counter') returns 'TallyCounter'. generateUsageInstructions returns the text placed in a JSON export's usage field.

ComponentDefinition

The object passed to define.

FieldTypeDescription
template(props, state, helpers) => stringRequired. Returns the element's HTML. helpers is { escape }.
propsstring[]Attributes to observe and pass to the template. Default [].
stylesstringCSS added to the Shadow DOM. Default ''.
methodsRecord<string, Function>Added to the element. Called from on-* attributes as (event, element).
initialStateobjectJSON-serializable starting state, copied for each element. Default {}.
mounted() => voidRuns after the first render each time the element is added to the page.
versionstringStored with the component. Default '1.0.0'.
eventsstring[]Names of events the component emits, for documentation. Default [].
Anything elseJSON valueKept as metadata, for example description. Function values are dropped.

Element instance

Available as this in templates, methods and mounted, and on the element in the page.

MemberDescription
propsCurrent values of the observed attributes, as strings.
stateThis element's state.
setState(partial)Merges partial into state and re-renders if the element is on the page.
render()Re-renders the Shadow DOM from the template.
emit(name, detail?)Dispatches a bubbling, composed CustomEvent. Returns false if a listener called preventDefault().
Your methodsEvery function in methods.

Delegated events for on-* attributes: click, dblclick, input, change, submit, keydown, keyup, focusin, focusout, pointerdown, pointerup.

ComponentData

The serializable form returned by define, stored in the registry and sent by export.

FieldTypeDescription
namestringTag name.
versionstringFrom the definition.
propsstring[]Observed attributes.
templatestringSource of the template function.
stylesstringCSS.
methodsRecord<string, string>Source of each method.
eventsstring[]From the definition.
initialStateobjectStarting state.
mountedstring | nullSource of mounted.
creatednumberWhen it was defined (ms since epoch).
exportedAt, exportOptionsAdded by export; not kept when imported.

Errors

Message starts withCause
Invalid component nameThe name breaks the custom element naming rules.
Component "…" is already definedThe name is taken in this registry or on the page.
Component "…" needs a template functiondefine was called without a template.
Component … not foundexport was called with a name that isn't in the registry.
API endpoint not configuredA server operation was used without apiEndpoint.
Request to … failed with statusThe server or URL returned a non-2xx response.
Invalid template source, Invalid method "…" sourceImported source isn't valid JavaScript.
… must be a function source string, … does not evaluate to a functionImported data has a missing or non-function template, method or mounted.
Component source must beimport was called with something other than a string or object.