UCE API

Markup Functions

markdown_to_ast

DValue markdown_to_ast(String src)
DValue markdown_to_ast(String src, DValue options)

Parameters

src : markdown source text
options : optional markdown options tree
return value : a DValue document AST

Parses Markdown source into a structured DValue document tree.

The parser targets a practical GitHub-flavored subset by default:

The returned AST uses type plus node-specific fields such as level, text, lang, href, src, name, argument, attrs, and children.

Top-level documents use:

Common block nodes:

Common inline nodes:

Example:

Options:

markdown_to_html

String markdown_to_html(String src)
String markdown_to_html(String src, DValue options)

Parameters

src : markdown source text
options : optional markdown options tree
return value : rendered HTML string

Renders Markdown source into HTML and returns the generated markup as a String.

markdown_to_html() does not write to the output stream directly. This keeps it aligned with the UCE naming convention where render_* names are reserved for direct-output helpers.

Because the return value is HTML markup, embed it with <?: markdown_to_html(...) ?>, print(markdown_to_html(...)), or pass it through a component.

By default the function aims at a practical GitHub-flavored Markdown target, including tables, task lists, fenced code blocks, autolinks, and strikethrough.

Example:

Supported syntax:

Options:

Directive hook example:

Generic node hook examples:

If both an exact directive hook and a generic node.directive hook exist, the exact directive hook wins.

When a markdown hook component is called, its props arrive in context.props.

Useful fields include:

Directive blocks use this form:

The parser stores:

That makes directive components a good fit for alerts, callouts, cards, embeds, and richer page-level Markdown extensions.

xml_decode

DValue xml_decode(String s)

Parameters

s : XML source string
return value : element-shaped DValue

Parses a simple XML document into a structured DValue.

xml_decode() parses a compact XML subset. It does not validate schemas, DTDs, namespaces, or document types. It parses the first root element and returns the same structural element shape accepted by xml_encode().

Try the live example in the XML demo.

Return shape:

Example:

CDATA and numeric entities are folded into text:

Supported parser features:

Whitespace-only text between child elements is ignored. Mixed non-empty text is concatenated into node["text"].

Malformed XML raises a request-visible runtime error.

xml_encode

String xml_encode(DValue t)
String xml_encode(DValue t, String root_name)

Parameters

t : tree to serialize as XML
root_name : optional element name to use when t is not already an element-shaped tree, defaults to root
return value : XML string

Serializes a DValue into a simple XML string.

xml_encode() does not validate against a schema, DTD, or namespace rules. It is a structural converter for application data, similar in spirit to json_encode().

Try the live example in the XML demo.

The native element shape is:

Example:

The result is:

For simple map/list/scalar trees, xml_encode() creates ordinary child elements:

Result:

Notes:

yaml_decode

DValue yaml_decode(String s)

Parameters

s : YAML source string
return value : decoded DValue

Parses a practical YAML subset into a DValue.

yaml_decode() is designed for concise UCE config files. It supports a practical YAML subset and does not implement anchors, aliases, tags, directives, or complex inline collection syntax.

Try the live example in the YAML demo.

Example:

Supported syntax:

Numeric-looking values are stored as strings, matching json_decode()'s current behavior. Use to_s64(), to_u64(), or to_f64() when reading numeric config values.

Malformed input raises a request-visible yaml_decode(): ... runtime error.

yaml_encode

String yaml_encode(DValue t)

Parameters

t : tree to serialize as YAML
return value : YAML string

Serializes a DValue into a compact YAML string for configuration files.

yaml_encode() focuses on the ordinary data shapes UCE apps use for config: nested maps, lists, strings, booleans, and numeric f64 values. It does not emit YAML tags, anchors, aliases, or custom schema features.

Try the live example in the YAML demo.

Example:

Typical result:

Notes:

Memcache Functions

memcache_command

String memcache_command(u64 connection, String command)

Parameters

connection : connection handle
command : string containing the Memcache command
return value : string containing the Memcache server's response

Executes a raw command on an open Memcache connection and returns the server response as a string.

This is the low-level escape hatch for Memcache operations that are not covered by the dedicated helpers.

memcache_connect

u64 memcache_connect(String host = "127.0.0.1", u16 port = 11211)

Parameters

host : optional host name of the memcache server, defaults to local address 127.0.0.1
port : optional memcache server's port, defaults to 11211
return value : the connection handle (or -1 if an error occurred)

Connects to a Memcache server instance.

If the connection fails, the function returns -1.

memcache_delete

bool memcache_delete(u64 connection, String key)

Parameters

connection : connection handle
key : key string
return value : true if the operation was successful

Deletes the entry identified by key.

The return value is true when the operation succeeds.

memcache_get

String memcache_get(u64 connection, String key, String default_value = "")

Parameters

connection : connection handle
key : key string
default_value : optional default value
return value : value that was returned by the Memcache server

Retrieves a value from an existing Memcache connection.

If the key is missing, default_value is returned instead.

memcache_get_multiple

StringMap memcache_get_multiple(u64 connection, StringList keys)

Parameters

connection : connection handle
keys : a list of strings containing the keys to be retrieved
return value : a StringMap with the retrieved entries

Retrieves multiple entries in one call.

The result is returned as a StringMap keyed by the requested Memcache keys.

memcache_set

bool memcache_set(u64 connection, String key, String value, u64 expires_in = 60*60)

Parameters

connection : connection handle
key : the entry's key
value : the value to be set
expires_in : optional expiration timeout, defaults to one hour
return value : true if the operation was successful

Stores value under key on the Memcache server.

expires_in controls the expiration timeout and defaults to one hour.

memcache_escape_key

String memcache_escape_key(String key)

Parameters

key : application key
return value : memcache-safe key string

Normalizes whitespace in a memcache key to underscores before it is placed into a text protocol command.

memcache_escape_keys

StringList memcache_escape_keys(StringList keys)

Parameters

keys : list of application keys
return value : escaped keys

Applies memcache_escape_key() to each key in a list.

MySQL Functions

mysql_connect

MySQL* mysql_connect(String host = "localhost", String username = "root", String password = "")

Parameters

host : host name of the MySQL server
username : user name
password : password
return value : pointer to the MySQL connection struct

Establishes a connection to a MySQL server and returns a pointer to the connection struct.

This connection handle is then used with helpers such as mysql_query(), mysql_error(), and mysql_disconnect().

mysql_disconnect

void mysql_disconnect(MySQL* m)

Parameters

m : pointer to an existing MySQL connection struct

Closes an existing connection to a MySQL server.

Call this when you are done using a MySQL* connection handle.

mysql_error

String mysql_error(MySQL* m)

Parameters

m : pointer to a MySQL connection struct
return value : MySQL error message (if present, otherwise empty string)

Returns the last error message associated with the given MySQL connection.

If there is no current error, the result is an empty string.

mysql_escape

String mysql_escape(String raw, char quote_char)

Parameters

raw : the string to be escaped
quote_char : the character that should be used to wrap the string (pass NULL for no wrapping)
return value : the safe version of the 'raw' string

Escapes a string so it can be used safely as a value inside an SQL expression.

If quote_char is provided, the escaped result is wrapped with that quote character. Pass NULL when you only want escaping without wrapping.

mysql_insert_id

u64 mysql_insert_id(MySQL* m)

Parameters

m : pointer to an active MySQL connection
return value : the last used automatic row ID

Returns the last automatically assigned row ID used by the current MySQL connection.

This is typically used after an INSERT into a table with an AUTO_INCREMENT primary key.

mysql_query

DValue mysql_query(MySQL* m, String q, StringMap params)

Parameters

m : pointer to an active MySQL connection struct
q : a string containing a MySQL query
params : optional, a list of query parameter keys and values
return value : a list of rows returned from executing the query

Executes a MySQL query and returns the resulting data, if any.

params provides the query parameter values used by the statement. Use named :name placeholders only; positional ? placeholders are rejected.

The result is returned as a DValue, which makes it easy to iterate through rows and read fields with the usual DValue accessors.

Noise/Hash Functions

draw_float

f64 draw_float(f64 from, f64 to, f64 decimal_precision = 0.000000000001)

Parameters

from : minimum value
to : maximum value
return value : a noise value between 'from' and 'to'

Works like generate_float(), but uses context.random_index for the index value and context.random_seed for the seed.

After each call, context.random_index is increased by one. At the start of every request, context.random_seed is automatically populated with a new seed value.

draw_int

u64 draw_int(u64 from, u64 to)

Parameters

from : minimum value
to : maximum value
return value : a noise value between 'from' and 'to'

Works like generate_int(), but uses context.random_index for the index value and context.random_seed for the seed.

After each call, context.random_index is increased by one. At the start of every request, context.random_seed is automatically populated with a new seed value.

gen_noise01

f64 gen_noise01(u64 index, u64 seed = 0)

Parameters

index : index position
seed : seed set (defaults to 0)
return value : a noise value from 0 to 1

Generates a deterministic noise value in the range from 0 to 1 for the given index and seed.

gen_noise32

u32 gen_noise32(u32 index, u32 seed = 0)

Parameters

index : index position
seed : seed set (defaults to 0)
return value : a noise value given the 'index' and 'seed' values.

Generates a deterministic 32-bit noise value for the given index and seed.

gen_noise64

u64 gen_noise64(u64 index, u64 seed = 0)

Parameters

index : index position
seed : seed set (defaults to 0)
return value : a noise value given the 'index' and 'seed' values.

Generates a deterministic 64-bit-indexed noise value for the given index and seed.

gen_float

f64 gen_float(f64 from, f64 to, u64 index, u64 seed = 0, f64 decimal_precision = 0.000000000001)

Parameters

from : minimum result
to : maximum result
index : index position to generate number from
seed : seed position to generate number from (defaults to 0)
return value : noise value

Generates a deterministic noise value between from and to for the given index and seed.

gen_int

u64 gen_int(u64 from, u64 to, u64 index, u64 seed = 0)

Parameters

from : minimum result
to : maximum result
index : index position to generate number from
seed : seed position to generate number from (defaults to 0)
return value : noise value

Generates a deterministic noise value between from and to for the given index and seed.

gen_sha1

String gen_sha1(String s, bool as_binary = false)

Parameters

s : data to be hashed
as_binary : when set to false, returns hash in hexadecimal notation (defaults to false)
return value : the resulting hash value

Returns the SHA-1 hash of s.

When as_binary is false, the hash is returned as hexadecimal text. When it is true, the raw binary hash bytes are returned.

sha256

String sha256(String data)

Parameters

data : bytes to hash
return value : the raw 32-byte SHA-256 digest

Returns the SHA-256 digest of data as raw bytes. Prefer sha256_hex() when you need printable text; use the raw form when feeding the digest into other binary operations.

sha256_hex

String sha256_hex(String data)

Parameters

data : bytes to hash
return value : the SHA-256 digest as a 64-character lowercase hex string

Returns the SHA-256 digest of data as hex text. Use it for checksums, cache keys, and content fingerprints where you want a printable digest. For the raw 32-byte digest use sha256().

hmac_sha256

String hmac_sha256(String key, String data)

Parameters

key : secret key
data : message to authenticate
return value : the raw 32-byte HMAC-SHA256

Computes an HMAC-SHA256 and returns it as raw bytes. Prefer hmac_sha256_hex() for printable signatures; use the raw form for binary protocols.

hmac_sha256_hex

String hmac_sha256_hex(String key, String data)

Parameters

key : secret key
data : message to authenticate
return value : the HMAC-SHA256 as a 64-character lowercase hex string

Computes an HMAC-SHA256 message authentication code and returns it as hex. Use it to sign tokens, cookies, and webhook payloads, then verify with crypto_equal() to avoid timing leaks.

random_bytes

String random_bytes(u64 n)

Parameters

n : number of bytes to generate
return value : n cryptographically random bytes

Returns n cryptographically secure random bytes, suitable for session IDs, tokens, and salts. The bytes are binary; wrap them with base64_encode() or sha256_hex() when you need printable text.

crypto_equal

bool crypto_equal(String a, String b)

Parameters

a : first value
b : second value
return value : true if the byte strings are equal

Compares two byte strings in constant time, so the comparison takes the same time whether they differ in the first byte or the last. Always use it to check secrets such as HMACs, tokens, and password hashes — == can leak how much of a secret matched via timing.

Output / Invocation Functions

coming_from_react

RENDER

RENDER(Request& context)

Defines the main HTTP render handler for the current .uce page.

When a page is requested over HTTP, the runtime loads the target file and calls its RENDER(Request& context) function.

Entry Point Behavior

The default page entrypoint is always the plain RENDER(Request& context) handler.

Reusable component handlers live on COMPONENT(Request& context) and COMPONENT:NAME(Request& context). The component helpers call those handlers, not RENDER().

The request environment is passed explicitly through context, including params, cookies, post data, session state, headers, uploaded files, and the current context.props tree.

If the file defines ONCE(Request& context), the runtime calls that hook once per request before the first RENDER() or COMPONENT... entrypoint from that unit runs.

If the file defines INIT(Request& context), the runtime calls that hook once when the worker loads the compiled unit into memory.

For a normal direct page request, context.props starts empty.

If the page is invoked from another UCE file via unit_render(file_name, context), the callee receives that same context.

Pages that serve WebSocket traffic may expose both RENDER(Request& context) and WS(Request& context). Files may also define COMPONENT() handlers when one unit needs both page and component behavior.

In that case:

CLI

CLI(Request& context)

Defines a local command-line entrypoint for a UCE unit.

CLI(Request& context) is invoked only through the local UCE CLI Unix socket, not through ordinary public HTTP requests. This lets web apps keep test runners, migrations, maintenance tasks, and admin tooling beside the rest of their UCE units while still separating those commands from browser-facing RENDER() routes.

The default CLI socket path is /run/uce/cli.sock and is configured with CLI_SOCKET_PATH.

Example convenience script usage:

Equivalent curl probe:

For structured commands, prefer JSON POST bodies. The scripts/uce-cli helper sends key=value parameters as JSON POST by default, while still allowing --get for simple query-string probes.

Inside the handler, the usual Request& context fields are available:

CLI responses default to text/plain; charset=utf-8, but the handler may set headers and status explicitly.

Use cli_input(context) to merge query parameters, form parameters, and JSON POST fields into one DValue.

ONCE(Request& context) runs before CLI() in the same way it runs before render and component entrypoints. INIT(Request& context) runs when the unit is loaded into a worker.

cli_input

DValue cli_input(Request& context)

Returns a structured parameter tree for a CLI(Request& context) invocation.

cli_input() merges simple command inputs into one DValue:

  1. query parameters from context.get

  2. form parameters from context.post

  3. JSON object fields from an application/json or *+json request body

Later sources override earlier ones, so a JSON body can override a query or form key with the same name.

If the JSON body is a scalar or array instead of an object, the decoded value is stored under input["_"].

Convenience script usage:

cli_arg

String cli_arg(Request& context, String key, String default_value = "")

Reads one value from the merged cli_input(context) parameter tree.

If the key is missing, or the resolved value is empty, default_value is returned.

For commands that need multiple values or typed reads, prefer calling cli_input(context) once and reading the returned DValue directly.

unit_call

DValue* unit_call(String file_name, String function_name, DValue* call_param = null)

Parameters

file_name : UCE file to load and execute
function_name : name of the function to invoke
call_param : optional, call parameter
return value : DValue* returned from function

Calls an exported function inside another UCE file.

Use unit_call() when you need structured data exchange between units rather than rendered HTML output.

The callee must expose an EXPORT function whose name matches function_name. Arguments are passed through call_param, and the return value is a DValue* owned by the callee.

unit_call() also understands the request-bound UCE entrypoint names:

When function_name matches one of those macro-style entrypoints, unit_call() does not look for a plain EXPORT DValue* ... function. Instead, it translates the name to the generated C++ symbol, uses the current Request context, and passes call_param into context.props, matching the normal component invocation model.

For RENDER... and COMPONENT..., the unit's ONCE(Request& context) hook is still honored automatically before the selected handler runs.

Example:

Calling a named component handler through unit_call():

Calling a page render handler through unit_call():

component

String component(String name, [DValue props], [Request& context])

Renders another .uce file as a component and returns the captured output as a String.

component() resolves the target file relative to the current page and also tries the components/ prefix automatically, mirroring the shorthand used by the starter example project.

Component props are passed in context.props.

Because <?= ... ?> HTML-escapes its value, embed component markup with <?: component(...) ?>, print(component(...)), or use component_render(...) for direct output.

Named Components

When name contains a colon, such as components/card:BODY, the part after the colon selects a named component handler exported from the component file through COMPONENT:BODY(Request& context).

The default handler is COMPONENT(Request& context).

When name starts with a colon, such as :BODY, the target resolves against the current .uce file so component files can call their own named handlers without repeating the file name.

When a component unit defines ONCE(Request& context), the runtime calls that hook once per request, per resolved component file, before the first COMPONENT() or COMPONENT:NAME() handler from that file runs.

Resolution Order

Common Patterns

Default component handler:

Named component handler:

Self-targeted named handler from inside the same file:

Preparing props in C++ before rendering:

Embedding returned component markup inside a literal block:

Because <?= ... ?> escapes HTML, use <?: ... ?> when inserting the returned markup from component().

Lifecycle Notes

component_exists

bool component_exists(String name)

Checks whether a component file can be resolved from the current page context.

Resolution uses the same host resolver as component_resolve(): candidate bases include absolute targets, the entry unit directory, the current unit directory, and the site root; each base tries exact, .uce, components/name, and components/name.uce forms.

If name contains a colon, only the file portion is used for existence checks.

This is useful when a page wants to render an optional component if it is present without hard-failing when it is missing.

component_resolve

String component_resolve(String name)

Resolves a component name to the concrete .uce file path that will be loaded.

Resolution searches host-side candidate bases in order: absolute target when supplied, entry unit directory, current unit directory, and site root. Within each base it tries the exact file name, the same name with .uce appended, and the same two forms under the components/ prefix.

If name contains a colon, only the file portion is used for resolution.

This is primarily a debugging helper so you can see which concrete file a shorthand component name maps to.

load

#load "myfile.uce"

Parameters

file name : name of an UCE file that should be included

Includes another UCE file.

Use #load when you want the current file to pull in declarations or reusable content from another UCE source file.

ob_close

void ob_close()

Parameters

return value : none

Discards the current output buffer and its contents, switching back to the previous buffer on the stack. Use it when you captured output only to throw it away (e.g. rendering for a side effect).

ob_get

String ob_get()

Parameters

return value : the current buffer's contents

Returns the current output buffer's contents WITHOUT discarding the buffer, so more output can still be appended. Use ob_get_close() when you also want to pop the buffer.

ob_get_close

String ob_get_close()

Parameters

return value : the current buffer's contents

Returns the current output buffer's contents and discards the buffer, switching back to the previous one on the stack. This is the usual way to capture rendered output for post-processing.

ob_start

void ob_start()

Parameters

return value : none

Starts a new output buffer. Subsequent print() output is captured into it instead of the response until you collect it with ob_get_close() (or discard it with ob_close()). Buffers nest: each ob_start() pushes another buffer onto the stack. Use it to render a fragment, post-process it, then emit the result.

print

void print(...val)

Parameters

...val : one or more values that should be output

Appends data to the current request output stream.

Use print() when you want to emit response content directly from UCE code.

component_render

void component_render(String name, [DValue props], [Request& context])

Renders another .uce file as a component and writes the result directly to the current output buffer.

This is the direct-output counterpart to component().

Component props are passed through context.props, and name:COMPONENTFUNC may be used to select a named handler exported by COMPONENT:COMPONENTFUNC(Request& context).

When name starts with :, the runtime resolves that named handler against the current .uce file.

If the target file defines ONCE(Request& context), that hook runs once per request before the file's first component or render entrypoint.

Use component_render() when you want to write component output directly from C++ code instead of capturing it as a String.

Example

unit_load

SharedUnit* unit_load(String file_name)

Parameters

file_name : unit source path
return value : native SharedUnit pointer (native runtime internals only)

native-only internal API. unit_load() returns a process-local SharedUnit*, which is not a valid value across the wasm membrane and is not exposed to wasm units.

Use unit-facing APIs such as unit_info(), unit_compile(), unit_call(), unit_render(), or component helpers instead.

unit_render

void unit_render(String file_name)
void unit_render(String file_name, Request& context)

Parameters

file_name : UCE file to load and execute
context : optional request context to pass into the target page

Calls another UCE file and executes its RENDER(Request& context) function.

If context is omitted, the current active request context is used.

Examples:

Regular Expressions

regex_match

bool regex_match(String pattern, String subject)
bool regex_match(String pattern, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern
subject : string to test
flags : optional regex flags
return value : true when the entire subject matches the pattern

Tests whether subject matches pattern from start to end.

This is a full-string match, not a substring search. Use regex_search() when you want to find the first occurrence anywhere in a string.

Examples:

Supported flags:

UCE uses PCRE2 in UTF-8 + Unicode-property mode by default, so patterns such as \\p{L}+ work naturally on Unicode text.

Invalid patterns or invalid flags raise a request-visible runtime error with the PCRE2 diagnostic message.

regex_search

DValue regex_search(String pattern, String subject)
DValue regex_search(String pattern, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern
subject : string to search
flags : optional regex flags
return value : a DValue describing the first match

Searches subject for the first occurrence of pattern and returns structured match data.

Example:

Return shape:

Capture entries contain:

If no match is found, matched is false and match-specific fields are omitted.

regex_search_all

DValue regex_search_all(String pattern, String subject)
DValue regex_search_all(String pattern, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern
subject : string to search
flags : optional regex flags
return value : a DValue containing all non-overlapping matches

Finds every non-overlapping match of pattern in subject.

Example:

Return shape:

Zero-length matches are handled safely; the scanner advances after each zero-length match to avoid infinite loops.

regex_replace

String regex_replace(String pattern, String replacement, String subject)
String regex_replace(String pattern, String replacement, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern
replacement : replacement string
subject : string where replacements should happen
flags : optional regex flags
return value : a new string with all matches replaced

Replaces every match of pattern in subject and returns the transformed string.

Example:

Replacement strings use PCRE2 substitution syntax, including numbered capture references such as $1 and named references such as ${name}.

For simple literal search-and-replace, use replace(). Use regex_replace() when the match condition needs a pattern, captures, character classes, anchors, or flags.

Invalid patterns, invalid flags, or invalid substitution syntax raise a request-visible runtime error.

regex_split

StringList regex_split(String pattern, String subject)
StringList regex_split(String pattern, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern used as the separator
subject : string to split
flags : optional regex flags
return value : a list of string parts

Splits subject wherever pattern matches.

Example:

This is the pattern-aware companion to split().

Behavior notes:

Runtime

backtrace_get_frames

String backtrace_get_frames(void* const* frames, size_t size, u32 skip_frames = 0)

Parameters

frames : frame pointer array returned by native backtrace collection
size : number of frames in the array
skip_frames : number of newest frames to omit
return value : formatted backtrace string

Formats a captured native backtrace frame array.

Most page code should use backtrace_capture() instead. Use this helper when you already have raw frame pointers from lower-level diagnostic code.

backtrace_capture

String backtrace_capture(u32 max_frames = 32, u32 skip_frames = 0)

Parameters

max_frames : maximum number of frames to capture
skip_frames : number of newest frames to omit
return value : formatted backtrace string

Captures and formats a native backtrace for the current call stack.

This helper is for diagnostics. It is used by runtime error reporting paths and can also be useful in local debugging pages.

Example:

Configurable Error Pages

page_compiling=site/errors/compiling.uce
page_compiler_error=site/errors/compiler-error.uce
page_runtime_error=site/errors/runtime-error.uce

Parameters

page_compiling : UCE page rendered (status 503) while the requested page is being built
page_compiler_error : UCE page rendered (status 500) when the requested page fails to build
page_runtime_error : UCE page rendered (status 500) after a recovered fault or uncaught exception

Three optional keys in /etc/uce/settings.cfg route error conditions to developer-defined UCE pages. Each key names a .uce file, either absolute or relative to the server's working directory. When a key is unset, or the named file does not exist, or the error page itself fails, the runtime's built-in plain-text behavior stands.

All three pages receive the error context in context.call["error"]:

A sensible status code is set before the page renders (503 for compiling, 500 for errors); the page may override it with set_status() and set its own headers.

page_compiling

Without this key, a request that hits an uncompiled or changed page blocks until the synchronous build finishes. With it, the runtime responds immediately with your page, hands the build to the proactive compiler, and the page can poll until the build lands:

The compiling page is only used while PROACTIVE_COMPILE_ENABLED is on (the default) — otherwise nothing would finish the build asynchronously, and the runtime waits for the on-request wasm compile.

pagecompilererror

Triggered when the entry page fails to build (components that fail mid-page keep the inline behavior, since the page is already half-rendered). context.call["error"]["compiler_output"] carries the full raw compiler output — show it on development hosts, hide it in production.

pageruntimeerror

Triggered after the worker recovers from a fatal signal or an uncaught exception. The worker has just recovered from a fault, so keep this page simple: static markup and the error fields, no database connections or heavy components.

Recursion safety

While an error page renders, error-page handling is disabled: a compiling, broken, or crashing error page falls back to the built-in behavior instead of looping.

Ready-made examples

site/errors/compiling.uce, site/errors/compiler-error.uce, and site/errors/runtime-error.uce in this repository are working examples — point the config keys at them or copy them into your site.

signal_name

String signal_name(s32 sig)

Parameters

sig : POSIX signal number
return value : signal name such as SIGSEGV, or an empty string when unknown

Returns a readable name for a POSIX signal number.

Example:

This is mostly useful in diagnostics and error reporting code.

unit_info

DValue unit_info(String path = "")

Parameters

path : optional UCE unit path. If empty, uses the current executing unit.
return value : metadata tree for the resolved unit, or an empty tree if the unit cannot be resolved

Returns runtime metadata for a UCE compilation unit.

The returned tree is supplied by the host runtime and may include normalized source/artifact paths, compile/runtime status, ABI/wasm availability, timing counters, mtimes, and exported API declarations. Treat absent fields as unavailable rather than as false.

If path is relative, it is resolved by the same host unit resolver used for unit calls/components.

Because unit metadata lives in worker process memory, request and timing counters reflect the current runtime process, not an aggregate across every worker process.

units_list

std::vector units_list()

Returns the normalized paths of all known .uce units.

This includes the shared known-unit registry plus any units already loaded in the current runtime process.

unit_compile

bool unit_compile(String path = "")

Parameters

path : optional UCE unit path. If empty, recompiles the current executing unit.
return value : true when the host compiler accepted and compiled the unit

Triggers a manual recompile of a UCE compilation unit through the host membrane.

If path is relative, it is resolved by the host unit resolver. The function returns whether compilation succeeded; it does not return or expose a native SharedUnit* to wasm units.

Documentation format

Doc pages are text files in site/doc/pages/*.txt using colon-prefixed sections.

sig : one or more real C++ signatures, exactly as declared

params : name : description rows plus return value : description

content : usage-first prose in 2-5 tight sentences

example : runnable UCE code whose real output is captured by the renderer

see : an area reference (>area) followed by closest sibling page slugs

Doc pages use a small structured text format so the index, detail view, search, and tests can all reason about the same source. Put usage first: describe what the API does and when to reach for it before lower-level implementation notes. Every page should include at least one deterministic :example; the renderer materializes each example as a temporary UCE unit, compiles it, renders it, and shows both the source and captured output. Keep cross-membrane, lock, and PHP/JS equivalence notes short and trailing when they are useful.

Sessions

session_id_create

String session_id_create()

Parameters

return value : a new session ID

Creates and returns a new session ID.

This helper is useful when you need to generate a session token directly rather than starting a full session flow with session_start().

session_destroy

void session_destroy(String session_name = "uce-session")

Parameters

session_name : the name of the session

Deletes the cookie specified by session_name and clears the data stored under the current session ID.

This also empties context.session_id and context.session.

session_start

String session_start(String session_name = "uce-session")

Parameters

session_name : optional name of the session cookie, defaults to "uce-session"
return value : the current session ID

Starts a session or reconnects to an existing one.

If the cookie named by session_name does not exist, UCE creates it and fills it with a new unique session ID. The function then loads the session data for that ID.

After session_start() completes, the following context fields are populated:

Socket Functions

http_request

http_request_async

socket_close

void socket_close(u64 sockfd)

Parameters

sockfd : socket handle

Closes an existing socket connection.

Use this when you are done with a socket opened through socket_connect().

socket_connect

u64 socket_connect(String host, u16 port)

Parameters

host : host name
port : port number
return value : the socket handle

Opens a socket connection to the given host and port.

The returned socket handle is then used with socket_read(), socket_write(), and socket_close().

socket_read

String socket_read(u64 sockfd, u32 max_length = 1024*128, u32 timeout = 1);

Parameters

sockfd : socket handle
max_length : optional maximum data size, defaults to 128kBytes
timeout : optional operation timeout, defaults to one second
return value : string containing the data that was read

Reads data from a socket connection.

max_length limits how much data is read, and timeout controls how long the operation is allowed to wait.

socket_write

bool socket_write(u64 sockfd, String data)

Parameters

sockfd : socket handle
data : a string containing the data to be written to the socket
return value : true if the write operation was successful

Writes data to the given socket.

The function returns true when the write succeeds.

SQLite

sqlite_connect

SQLite* sqlite_connect(String path)

Parameters

path : filesystem path to the SQLite database file
return value : pointer to a SQLite connection struct

Opens an SQLite database file and returns a connection handle.

UCE opens SQLite with serialized/full-mutex connection mode, sets a busy timeout, enables foreign keys, and applies WAL-oriented defaults:

PRAGMA busy_timeout = 5000;
PRAGMA foreign_keys = ON;
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;

SQLite itself handles file locking and one-writer/many-reader concurrency. UCE does not add a separate app-level database lock.

Connections are registered for request cleanup, but explicit sqlite_disconnect() is still preferred when you are done with the handle.

sqlite_disconnect

void sqlite_disconnect(SQLite* db)

Parameters

db : pointer to an active SQLite connection

Closes an SQLite connection and deletes the UCE connection wrapper.

UCE also cleans up SQLite connections that remain open at request end, but explicit disconnects keep resource lifetime local and clear.

sqlite_error

String sqlite_error(SQLite* db)

Parameters

db : pointer to an SQLite connection
return value : latest connector/SQLite status message

Returns the latest SQLite connector status or error message.

Successful calls usually set the message to ok or connected. Failed prepare, bind, step, pragma, or open operations include connector context plus SQLite's own error text.

sqlite_query

DValue sqlite_query(SQLite* db, String q)
DValue sqlite_query(SQLite* db, String q, StringMap params)

Parameters

db : pointer to an active SQLite connection
q : SQL statement
params : optional named parameter map
return value : list of result rows as a DValue

Executes one SQLite statement and returns result rows as a DValue array. Multi-statement SQL strings are rejected so migrations cannot silently run only their first statement.

Use named parameters with :name placeholders only. Positional ? placeholders and SQLite's other named marker forms (@name, $name) are rejected so UCE SQLite queries use the same placeholder style as the MySQL helper. UCE binds parameters with SQLite prepared statements; it does not substitute values into the SQL string.

Result rows are objects keyed by column name. SQLite integer, float, text, blob, and null values are converted to DValue values. Blob values are returned as byte strings.

For statements that do not return rows, inspect sqlite_affected_rows() or sqlite_insert_id() after the call.

sqlite_insert_id

u64 sqlite_insert_id(SQLite* db)

Parameters

db : pointer to an active SQLite connection
return value : last inserted rowid

Returns SQLite's last inserted rowid for the connection after an insert statement.

sqlite_affected_rows

u32 sqlite_affected_rows(SQLite* db)

Parameters

db : pointer to an active SQLite connection
return value : number of rows changed by the most recent statement

Returns the number of rows changed by the most recent insert, update, or delete statement on the connection.

String Functions

ascii_safe_name

String ascii_safe_name(String raw)

Parameters

raw : arbitrary input string
return value : an ASCII-only sanitized name

Like safe_name(), but also restricts the result to ASCII, transliterating or dropping non-ASCII characters. Use it when the consumer (a legacy filesystem, header, or protocol) requires plain ASCII.

base64_decode

String base64_decode(String raw)

Parameters

raw : Base64-encoded text
return value : the decoded bytes (empty on invalid input)

Decodes Base64 text back to bytes. Pairs with base64_encode() for round-tripping binary data through text channels.

base64_encode

String base64_encode(String raw)

Parameters

raw : binary-safe source bytes
return value : the Base64-encoded text

Encodes bytes as Base64 text. UCE strings are binary-safe, so raw may contain NUL and other non-text bytes — handy for embedding random_bytes() or a sha256() digest in headers, cookies, or JSON.

contains

bool contains(String haystack, String needle)

Parameters

haystack : string to search in
needle : substring to look for
return value : true when needle appears in haystack, otherwise false

Returns whether haystack contains needle.

An empty needle always returns true.

filter

StringList filter(StringList items, function f)
vector filter(vector items, function f)

Parameters

items : list of items to be filtered
f : predicate function; items are kept when this returns true
return value : a new list

Returns a new list containing the members of items for which f returned true.

first

String first(String... args)

Parameters

args : a variable number of String arguments
return value : first of the 'args' that was not empty.

Returns the first non-empty string from the provided arguments.

Leading and trailing whitespace are ignored when checking emptiness, so a string containing only whitespace counts as empty.

join

String join(StringList l, String delim = "\n")

Parameters

l : list of strings to be joined
delim : delimiter (defaults to newline character)
return value : a string containing items joined by 'delim'

Joins all strings in l into a single String.

The delimiter is inserted between items. If delim is omitted, the default separator is a newline character.

json_consume_space

void json_consume_space(String s, u32& i)

Parameters

s : JSON source string
i : current byte offset; advanced past JSON whitespace

Advances i past JSON whitespace in s.

This helper is mainly useful when writing a parser that follows UCE's JSON parsing rules. Most page code should call json_decode() instead.

Example:

json_encode

String json_encode(String s)
String json_encode(DValue t)

Parameters

s : string to encode as a JSON string literal
t : DValue object to be serialized
return value : string containing the JSON result

Serializes either a String or a DValue into JSON notation.

When passed a String, json_encode() returns a quoted and escaped JSON string literal.

When passed a DValue, scalar values are serialized directly and nested map values are emitted as JSON objects.

map

StringList map(StringList items, function f)
vector map(vector items, function f)

Parameters

items : list of items to transform
f : a function that returns the transformed value for each item
return value : a new list containing the transformed values

Returns a new list by calling f for each item in items.

Use filter() when you want to keep only matching items, and map() when you want to transform each item.

nibble

String nibble(String& haystack, String delim)

Parameters

haystack : string to be nibbled at
delim : delimiter
return value : string before first occurrence of 'delim'

Returns the part of haystack before the first occurrence of delim.

As a side effect, the consumed portion is removed from haystack, including the delimiter itself.

If delim does not occur in haystack, the entire string is returned and haystack is set to an empty string.

print

void print(...val)

Parameters

...val : one or more values that should be output

Appends data to the current request output stream.

Use print() when you want to emit response content directly from UCE code.

strpos

s64 strpos(String haystack, String needle, s64 offset = 0)

Parameters

haystack : string to search in
needle : substring to search for
offset : optional start offset; negative values count from the end of the string
return value : zero-based position of the first match, or -1 if needle is not found

Finds the first occurrence of needle inside haystack.

This is the closest UCE equivalent to PHP strpos(), but it returns -1 instead of false when no match is found.

If needle is an empty string, strpos() returns the normalized start offset.

str_ends_with

bool str_ends_with(String haystack, String needle)

Parameters

haystack : string to inspect
needle : suffix to compare against the end of haystack
return value : true when haystack ends with needle, otherwise false

Checks whether haystack ends with needle.

str_starts_with

bool str_starts_with(String haystack, String needle)

Parameters

haystack : string to inspect
needle : prefix to compare against the start of haystack
return value : true when haystack begins with needle, otherwise false

Checks whether haystack starts with needle.

substr

String substr(String s, s64 start_pos)
String substr(String s, s64 start_pos, s64 length)

Parameters

s : source string
start_pos : zero-based start position; negative values count from the end of the string
length : optional substring length; negative values trim bytes from the end of the result range
return value : extracted substring, or an empty string if the requested range is outside the source string

Extracts part of a string using PHP-style start and length semantics.

Use the two-argument form to return everything from start_pos to the end of the string.

If start_pos is negative, counting starts from the end of the string.

If length is negative, the returned range stops that many bytes before the end of the string.

split

StringList split(String str, String delim)

Parameters

str : string to be split
delim : delimiter
return value : a list of strings

Splits str into multiple strings using delim as the separator.

Every exact occurrence of delim creates a new entry in the returned StringList.

split_http_headers

StringMap split_http_headers(String s)

Parameters

s : HTTP request or header text
return value : parsed request/header fields

Parses HTTP request/header text into a StringMap.

For a request line, the returned map includes fields such as REQUEST_METHOD, REQUEST_URI, SCRIPT_NAME, QUERY_STRING, and SERVER_PROTOCOL. Header names are normalized to uppercase CGI-style keys, for example Host becomes HTTP_HOST.

Example:

Most page code should read context.params instead. Use this helper when parsing raw HTTP text in tests or protocol helpers.

split_kv

StringMap split_kv(String s, char separator = '=', bool trim_whitespace = true, bool uppercase_keys = false)

Parameters

s : input containing one key/value pair per line
separator : character separating each key from its value
trim_whitespace : trim keys and values when true
uppercase_keys : uppercase keys when true
return value : map of parsed keys and values

Parses simple line-based key/value text into a StringMap.

Each non-empty line is split on the first separator. Lines without the separator are kept with an empty value.

Example:

This is useful for small config files, metadata blocks, and tests that need predictable key/value parsing.

split_space

StringList split_space(String str)

Parameters

str : string to be split
return value : a list of strings

Splits str on runs of whitespace.

Multiple adjacent whitespace characters are treated as a single separator, so repeated spaces, tabs, or line breaks do not create empty entries.

split_utf8

StringList split_utf8(String str, bool compound_characters = false)

Parameters

str : string to be split
compound_characters : optional, if true tries to combine compound characters
return value : a list of Unicode characters

Splits str into its constituent Unicode code points.

If compound_characters is true, split_utf8() also applies a small amount of grouping so some multi-code-point glyphs stay together. The current rules are:

This is useful when simple byte-wise or ASCII splitting would break Unicode text incorrectly.

replace

String replace(String s, String search, String replace_with)

Parameters

s : the string where replacements should happen
search : the string that should be searched for
replace_with : the string that should appear in places where 'search' occurs
return value : a version of 's' where all instances of 'search' have been replaced with 'replace_with'

Replaces every occurrence of search in s with replace_with.

The returned string contains the fully replaced result.

regex_match

bool regex_match(String pattern, String subject)
bool regex_match(String pattern, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern
subject : string to test
flags : optional regex flags
return value : true when the entire subject matches the pattern

Tests whether subject matches pattern from start to end.

This is a full-string match, not a substring search. Use regex_search() when you want to find the first occurrence anywhere in a string.

Examples:

Supported flags:

UCE uses PCRE2 in UTF-8 + Unicode-property mode by default, so patterns such as \\p{L}+ work naturally on Unicode text.

Invalid patterns or invalid flags raise a request-visible runtime error with the PCRE2 diagnostic message.

regex_search

DValue regex_search(String pattern, String subject)
DValue regex_search(String pattern, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern
subject : string to search
flags : optional regex flags
return value : a DValue describing the first match

Searches subject for the first occurrence of pattern and returns structured match data.

Example:

Return shape:

Capture entries contain:

If no match is found, matched is false and match-specific fields are omitted.

regex_search_all

DValue regex_search_all(String pattern, String subject)
DValue regex_search_all(String pattern, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern
subject : string to search
flags : optional regex flags
return value : a DValue containing all non-overlapping matches

Finds every non-overlapping match of pattern in subject.

Example:

Return shape:

Zero-length matches are handled safely; the scanner advances after each zero-length match to avoid infinite loops.

regex_replace

String regex_replace(String pattern, String replacement, String subject)
String regex_replace(String pattern, String replacement, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern
replacement : replacement string
subject : string where replacements should happen
flags : optional regex flags
return value : a new string with all matches replaced

Replaces every match of pattern in subject and returns the transformed string.

Example:

Replacement strings use PCRE2 substitution syntax, including numbered capture references such as $1 and named references such as ${name}.

For simple literal search-and-replace, use replace(). Use regex_replace() when the match condition needs a pattern, captures, character classes, anchors, or flags.

Invalid patterns, invalid flags, or invalid substitution syntax raise a request-visible runtime error.

regex_split

StringList regex_split(String pattern, String subject)
StringList regex_split(String pattern, String subject, String flags)

Parameters

pattern : PCRE2 regular expression pattern used as the separator
subject : string to split
flags : optional regex flags
return value : a list of string parts

Splits subject wherever pattern matches.

Example:

This is the pattern-aware companion to split().

Behavior notes:

to_lower

String to_lower(String s)

Parameters

s : the string to be converted
return value : returns a version of 's' where all upper case characters have been changed into lower case

Returns a lower-case version of s.

This function is not yet Unicode-aware.

to_upper

String to_upper(String s)

Parameters

s : the string to be converted
return value : returns a version of 's' where all lower case characters have been changed into upper case

Returns an upper-case version of s.

This function is not yet Unicode-aware.

trim

String trim(String raw)

Parameters

raw : string to be trimmed
return value : string with leading and trailing whitespace characters removed

Returns raw with leading and trailing whitespace removed.

float_val

f64 float_val(String s)

Parameters

s : string to be converted
return value : a f64 containing the number (0 if no number could be identified).

Extracts a floating point number from a String.

If no usable number can be identified, the result is 0.

int_val

u64 int_val(String s, u32 base = 10)

Parameters

s : string to be converted
base : number system base (default 10)
return value : a u64 containing the number (0 if no number could be identified).

Extracts an integer value from s.

The base argument controls which number system is used while parsing. If no usable number can be identified, the function returns 0.

html_escape

String html_escape(String s)

Parameters

s : string to be escaped
return value : an HTML-safe escaped version of 's'

Returns a version of the input string where special HTML characters are replaced by entities:

safe_name

String safe_name(String raw)

Parameters

raw : arbitrary input string
return value : a sanitized name safe to use as a file or key name

Sanitizes a string into a safe name by normalizing or stripping characters that are unsafe in file names and identifiers (whitespace, separators, control characters). Use it before turning user input into a file name or cache key.

var_dump

String var_dump(StringMap t, String prefix = "", String postfix = "\n")
String var_dump(StringList t, String prefix = "", String postfix = "\n")
String var_dump(DValue t, String prefix = "", String postfix = "\n")

Parameters

t : object to be dumped into a string
return value : string containing a human-friendly representation of 't'

Returns a string representation of t intended for debugging.

json_decode

DValue json_decode(String s)

Parameters

s : string containing JSON data
return value : a DValue object containing the deserialized JSON data

Deserializes s into a DValue structure.

The returned structure is usually consumed through DValue accessors such as:

Current runtime behavior:

File System Functions

basename

String basename(String fn)

Parameters

fn : a path
return value : the final path component

Returns the last component of a path — the file or directory name without its leading directories.

dirname

String dirname(String fn)

Parameters

fn : a path
return value : the directory portion of the path

Returns everything in a path except the final component — i.e. the containing directory.

expand_path

String expand_path(String path, String relative_to_path = "")

Parameters

path : path to expand
relative_to_path : base directory a relative path is resolved against
return value : the expanded path

Expands a path: a relative path is resolved against relative_to_path (or the current unit's directory when that is empty), producing a normalized path you can hand to the file APIs.

file_append

void file_append(String file_name, ...val)

Parameters

file_name : file to append to, created if missing
...val : one or more values appended in order
return value : none

Appends one or more values to a file, creating it if needed. Each call takes an exclusive lock for the append, so concurrent appends are serialized and readers wait for them; you never manage locks yourself.

file_exists

bool file_exists(String path)

Parameters

path : path to check, resolved against the unit's directory
return value : true if a regular file exists at path

Reports whether a regular file exists. Use it to guard reads or to confirm a write or delete took effect. It is file-oriented and returns false for directories — use file_stat() and check is_dir to test for a directory.

file_get_contents

String file_get_contents(String file_name)

Parameters

file_name : file to read, resolved against the unit's directory
return value : the file's contents, or "" if it cannot be read

Reads an entire file and returns it as a String. The read takes a shared lock for its duration, so it waits for any in-progress file_put_contents() / file_append() write to finish; you never manage locks yourself. For large files or random access, use file_open() + file_read().

file_mtime

u64 file_mtime(String file_name)

Parameters

file_name : path to inspect, resolved against the unit's directory
return value : last-modified time as a Unix timestamp, or 0 if missing

Returns a file's last-modified time as a Unix timestamp. Compare two files' mtimes for cache-freshness checks, or test for > 0 to confirm a file exists with a real timestamp.

file_put_contents

bool file_put_contents(String file_name, String content)

Parameters

file_name : file to write, resolved against the unit's directory
content : bytes to write (replaces any existing content)
return value : true on success

Writes content to a file, replacing whatever was there. The write takes an exclusive lock for the truncate-and-write, so concurrent writers are serialized and readers wait for it; you never manage locks yourself.

cwd_get

String cwd_get()

Parameters

return value : the current working directory

Returns the current working directory.

ls

StringList ls(String path)

Parameters

path : directory to list
return value : a StringList of entry names

Returns the names of the entries in a directory as a StringList. For names only this is simpler than dir_list(), which returns full metadata per entry.

mkdir

bool mkdir(String path)

Parameters

path : directory to create
return value : true on success

Creates a single directory and returns whether it succeeded. The parent directory must already exist, so build nested paths one level at a time.

path_join

String path_join(String base, String child)

Parameters

base : base path
child : path to append
return value : the two joined with a single separator

Joins two path fragments with exactly one separator, regardless of whether base ends in a slash or child begins with one. Use it instead of string concatenation to build paths safely.

cwd_set

void cwd_set(String path)

Parameters

path : the new working directory

Sets the host worker process current directory. In wasm this is a hostcall, so restore the previous directory when using it inside request code.

shell_escape

String shell_escape(String raw)

Parameters

raw : string that should be escaped
return value : escaped version of 'raw'

Escapes a parameter so it can be used more safely with shell_exec().

This is the helper to reach for when building shell command lines from dynamic input.

shell_exec

String shell_exec(String cmd)

Parameters

cmd : string that contains the shell command line to be executed
return value : output of the command execution

Executes a Linux shell command and returns the generated output.

When command text includes user-controlled input, escape that input first with shell_escape().

shell_spawn

job_status

job_result

job_await

job_cancel

file_unlink

void file_unlink(String file_name)

Parameters

file_name : file to delete, resolved against the unit's directory
return value : none

Deletes a file. Deleting a path that does not exist is a no-op, so it is safe to call before recreating a file.

zip_create

bool zip_create(String zip_file_name, DValue entries)

Parameters

zip_file_name : path to the archive to create
entries : map or list of archive entries
return value : true when the archive is written

Creates a ZIP archive at zip_file_name.

entries can be a simple map where each key is the archive member name and each value is the file content:

For list-shaped input or when the map key should not be the member name, each child can provide explicit fields:

An entry may also provide file instead of content; UCE reads that source file and stores its contents under name.

Entry names are normalized to forward slashes and rejected when they are absolute paths, drive-qualified paths, empty names, or contain .. path segments.

zip_list

DValue zip_list(String zip_file_name)

Parameters

zip_file_name : path to the ZIP archive to inspect
return value : DValue containing archive metadata and an entries array

Reads the central directory from zip_file_name and returns structured metadata.

The returned tree contains:

Each entry contains:

Example:

zip_read

String zip_read(String zip_file_name, String entry_name)

Parameters

zip_file_name : path to the ZIP archive
entry_name : member name to read from the archive
return value : uncompressed entry contents

Reads one file member from a ZIP archive and returns its uncompressed bytes as a String.

entry_name is normalized to forward slashes and rejected when it is empty, absolute, drive-qualified, or contains a .. path segment.

Use zip_list() when you need to discover entry names before reading them.

zip_extract

bool zip_extract(String zip_file_name, String destination_directory)

Parameters

zip_file_name : path to the ZIP archive
destination_directory : directory that should receive extracted files
return value : true when extraction completes

Extracts every member in a ZIP archive into destination_directory.

UCE creates the destination directory and any needed child directories when they do not already exist.

For safety, every member name is normalized and checked before extraction. Absolute paths, drive-qualified paths, empty names, and .. path segments are rejected so archives cannot write outside the destination directory.

gz_compress

String gz_compress(String src)

Parameters

src : uncompressed input bytes
return value : gzip-format compressed bytes

Compresses src and returns a gzip-format byte string.

The result is binary data. Store it in a file, send it with an appropriate content type/encoding, or pass it directly to gz_uncompress().

UCE writes a standard gzip wrapper around a deflate stream, including CRC32 and uncompressed-size footer fields.

gz_uncompress

String gz_uncompress(String compressed)

Parameters

compressed : gzip-format compressed bytes
return value : uncompressed bytes

Uncompresses a gzip-format byte string and returns the original content.

gz_uncompress() validates the gzip header, CRC32 footer, and uncompressed-size footer. It throws a runtime error when the input is not a supported gzip stream or fails validation.

server_start_http

pid_t server_start_http(String key, String socket_fn_or_port, String call_uce_filename, String call_function = "")

Parameters

key : runtime-wide server key
socket_fn_or_port : TCP port number or Unix socket path to listen on
call_uce_filename : .uce file containing SERVE_HTTP handlers
call_function : optional named SERVE_HTTP:name handler
return value : listener process PID, or 0 when it could not be started

Starts or updates a custom HTTP listener backed by a UCE handler file.

The server key is runtime-wide. Calling server_start_http() again with the same key and the same bind target updates the mapped UCE file/function without restarting the listener. If the bind target changes, UCE stops the old listener and starts a replacement.

socket_fn_or_port may be a numeric TCP port such as "19091" or a Unix socket path.

Handler files use SERVE_HTTP:

SERVE_HTTP(Request* req)
{
    req->header["Content-Type"] = "text/plain; charset=utf-8";
    print("hello from custom HTTP\n");
}

SERVE_HTTP:admin(Request* req)
{
    print("named handler\n");
}

The custom server dispatcher uses the same nonblocking HTTP listener machinery as the built-in HTTP/WebSocket path, and hands request/response data through the normal Request object. Handler code may block in the first implementation; future worker dispatch can be added without changing this API.

server_stop

bool server_stop(String key)

Parameters

key : runtime-wide server key used with server_start_http()
return value : true when no listener remains or a stop signal was sent

Stops a custom server listener by key and removes its registry config.

server_stop() currently targets custom servers started through server_start_http(). The same key model is intended to extend to future server_start_tcp() and server_start_udp() helpers.

file_open

u64 file_open(String path, String mode)

Parameters

path : file to open, resolved against the unit's directory
mode : "r" read, "w" truncate+write, "a" append, "r+" read+write
return value : opaque handle; 0 means open failed (bad path, policy denial, or lock timeout)

Opens a file for streaming, handle-based I/O and returns an opaque handle for file_read(), file_write(), file_seek(), and file_close(). Locks are automatic and scoped to the handle: read opens take a shared lock, write/append/read-write opens take an exclusive lock, and file_close() releases it. Lock waits are bounded by UCE_FILE_LOCK_TIMEOUT_MS (default 2000ms), so a contended open returns 0 instead of blocking forever. For whole-file access prefer file_get_contents() / file_put_contents().

file_read

String file_read(u64 h, u64 len)

Parameters

h : handle from file_open() opened for reading
len : maximum number of bytes to read
return value : up to len bytes from the current offset (shorter at end of file)

Reads up to len bytes starting at the handle's current offset and advances the offset. Returns fewer bytes (or "") at end of file. Use file_seek() to move the offset, or file_pread() to read at an absolute offset without moving it.

file_pread

String file_pread(u64 h, u64 offset, u64 len)

Parameters

h : handle from file_open() opened for reading
offset : absolute byte offset to read from
len : maximum number of bytes to read
return value : up to len bytes read at offset

Reads len bytes from an absolute offset without moving the handle's current offset. Useful for random access reads that interleave with sequential ones.

file_write

u64 file_write(u64 h, String data)

Parameters

h : handle from file_open() opened for writing
data : bytes to write at the current offset
return value : number of bytes written

Writes data at the handle's current offset and advances the offset. The handle must come from file_open() with a writable mode ("w", "a", or "r+"). Binary-safe: data may contain NUL and other non-text bytes.

file_pwrite

u64 file_pwrite(u64 h, u64 offset, String data)

Parameters

h : handle from file_open() opened for writing
offset : absolute byte offset to write at
data : bytes to write
return value : number of bytes written

Writes data at an absolute offset without moving the handle's current offset. The handle must be opened with a writable mode ("r+" for in-place edits).

file_seek

s64 file_seek(u64 h, s64 offset, s64 whence)

Parameters

h : handle from file_open()
offset : byte offset relative to whence
whence : 0 from start, 1 from current, 2 from end
return value : the new absolute offset, or -1 on error

Moves a handle's read/write offset for random access. Combine with file_read() / file_write() to jump around a file; file_tell() reports the current offset.

file_tell

s64 file_tell(u64 h)

Parameters

h : handle from file_open()
return value : the current absolute byte offset

Returns a handle's current read/write offset, as moved by file_read(), file_write(), and file_seek().

file_close

void file_close(u64 h)

Parameters

h : handle returned by file_open()

Closes a file handle and releases the lock that file_open() took. Always close handles you open: locks are scoped to the handle's lifetime, so a leaked handle holds its lock until the worker recycles.

file_stat

DValue file_stat(String path)

Parameters

path : path to inspect, resolved against the unit's directory
return value : a map with exists, isfile, isdir, is_symlink, size, mode, mtime, ctime

Returns metadata about a path as a DValue map. Read fields with the usual accessors, e.g. st["size"].to_u64() and st["is_file"].to_bool(). When the path does not exist, exists is false.

dir_list

DValue dir_list(String path)

Parameters

path : directory to list
return value : a list of entry maps, each with name, type, size, mtime

Lists a directory's entries as a DValue list. Each entry is a map with name, type ("file", "dir", "symlink", or "other"), size, and mtime. Iterate with .each() and read fields with item.key("name")->to_string().

file_rename

bool file_rename(String from, String to)

Parameters

from : source path
to : destination path
return value : true on success

Renames or moves a file. After a successful rename the source path no longer exists. Use it for atomic publish patterns: write a temp file, then rename it into place.

file_copy

bool file_copy(String from, String to)

Parameters

from : source path
to : destination path (overwritten if it exists)
return value : true on success

Copies a file's contents to a new path, overwriting the destination if present.

file_truncate

bool file_truncate(String path, u64 size)

Parameters

path : file to resize
size : new length in bytes
return value : true on success

Truncates (or extends) a file to exactly size bytes. Shrinking discards trailing bytes; growing pads with zero bytes.

dir_remove

bool dir_remove(String path, bool recursive = false)

Parameters

path : directory to remove
recursive : when true, remove the directory and everything inside it
return value : true on success

Removes a directory. By default it must be empty; pass recursive = true to delete the directory and all of its contents.

file_temp

String file_temp(String prefix)

Parameters

prefix : path prefix for the temp file; a unique suffix is appended
return value : the path of the newly created temp file, or "" on failure

Creates a new, uniquely named empty file using prefix as the leading path and returns its full path. Use it for scratch files and the write-then-rename publish pattern.

file_chmod

bool file_chmod(String path, u32 mode)

Parameters

path : file or directory to change
mode : permission bits, e.g. 0644 or 0600 (octal)
return value : true on success

Sets a path's permission bits, like the shell chmod. Pass the mode as an octal literal such as 0600.

file_symlink

bool file_symlink(String target, String linkpath)

Parameters

target : path the symlink should point at
linkpath : symlink to create
return value : true on success

Creates a symbolic link at linkpath pointing to target. Reading through the link reads the target; use path_real() to resolve a link to its canonical destination.

file_fsync

bool file_fsync(u64 h)

Parameters

h : handle from file_open() opened for writing
return value : true if the flush succeeded

Flushes a handle's buffered writes to disk, so the data survives a crash or power loss. Call it before file_close() when durability matters (e.g. after writing a checkpoint).

path_is_within

bool path_is_within(String path, String root)

Parameters

path : path to test
root : directory that should contain it
return value : true if path is inside root

Reports whether path lies inside root. It resolves both paths to their canonical form (like path_real()), so they must exist and .. traversal is collapsed first. Use it to reject path-traversal attempts before opening user-supplied paths.

path_real

String path_real(String path)

Parameters

path : path to resolve
return value : the canonical absolute path, or "" if it cannot be resolved

Resolves a path to its canonical absolute form, following symlinks and collapsing . and .. segments. The path must exist. Combine with path_is_within() to validate that user-supplied paths stay inside an allowed root.

process_start_directory

String process_start_directory()

Parameters

return value : worker process start directory

Returns the directory captured when the native process started. It remains stable even if cwd_set() changes the current working directory.

request_perf

DValue request_perf()

Parameters

return value : performance snapshot for the active request/workspace

Returns a DValue with timing and process metadata such as worker pid, parent pid, request count, request start times, and workspace birth timing when available.

runtime_safe_key

String runtime_safe_key(String key, String label = "runtime key")

Parameters

key : caller-provided key
label : diagnostic label used by native error handling
return value : stable SHA-1 key, or an empty string for empty input in wasm

Trims a runtime key and converts it to a stable SHA-1 identifier suitable for task/runtime file names.

Task API

task

pid_t task(String key, std::function exec_func, u64 timeout = 60*10)

Parameters

key : string uniquely identifying the task across the whole runtime instance
exec_func : function to execute
timeout : maximum run time in seconds; 0 disables the timeout
return value : the process ID of the started (or still running) task, or 0 when the task could not be started

Starts exec_func in a new process and returns that process ID.

If a process with the same key is already running anywhere in the runtime instance, task() does not start a second copy. Instead it returns the PID of the already-running task. Coordination is through a shared task status file under BIN_DIRECTORY, so the key applies across workers, not just the current worker process.

Task keys may contain ordinary user-facing text. UCE hashes the key before using it as an internal lock/status filename so slashes and other path-like characters cannot escape the task state directory.

timeout is enforced in the child process with an alarm. The default is ten minutes. Pass 0 only for tasks that have their own shutdown path.

task_repeat

pid_t task_repeat(String key, f64 interval, std::function exec_func, u64 timeout = 60*10)

Parameters

key : string uniquely identifying the task across the whole runtime instance
interval : repeat interval in seconds
exec_func : function to execute repeatedly
timeout : maximum run time in seconds; 0 disables the timeout
return value : the process ID of the started (or still running) task, or 0 when the task could not be started

Starts a repeating background worker process.

exec_func runs in a loop, and the worker sleeps for interval seconds between executions. interval must be greater than zero.

If a process with the same key is already running anywhere in the runtime instance, task_repeat() does not start a second worker and instead returns the PID of the existing one. Coordination is through the same shared task state used by task().

timeout bounds the lifetime of the repeating worker. The default is ten minutes. Pass 0 only for workers that have another shutdown path.

task_pid

pid_t task_pid(String key)

Parameters

key : string uniquely identifying the task
return value : the process ID of the task

Checks whether a process with the given key is running anywhere in the runtime instance and returns its PID if it is.

Returns 0 when no matching task is active or task state cannot be read safely. Stale task status files are removed when the recorded PID is no longer alive.

New task status records include the Linux process start tick from /proc/<pid>/stat, so task_pid() can reject a stale status file if the PID has exited and the numeric PID has since been reused by another process.

task_kill

int task_kill(pid_t pid, s32 sig = 0)

Parameters

pid : PID of the process
sig : signal number
return value : 0 if signal was sent, -1 otherwise

Wraps the standard POSIX kill() function for positive process IDs.

task_kill() rejects pid <= 0 and returns -1, so callers cannot accidentally use POSIX process-group or broadcast semantics through this helper.

sig may be any supported POSIX signal, including values such as SIGTERM, SIGKILL, SIGINT, SIGUSR1, SIGUSR2, SIGCHLD, SIGCONT, and related process-control signals.

Passing 0 as the signal performs an existence and permission check without actually delivering a signal.

Time and Date Functions

usleep

s32 usleep(u32 usec)

Parameters

usec : microseconds to sleep
return value : 0 after sleeping

Pauses the current request or task for a number of microseconds.

Use this for short waits in local tests, polling loops, or background tasks. Avoid long sleeps in normal HTTP render paths because they hold a worker process for the duration.

Example:

For whole-second waits, use sleep().

time_precise

f64 time_precise()

Parameters

return value : current Unix timestamp

Returns the current Unix timestamp as a 64-bit float with millisecond accuracy or better.

time

u64 time()

Parameters

return value : second-accurate current Unix timestamp

Returns the current Unix timestamp as a 64-bit integer with second precision.

time_format_local

String time_format_local(String format = "", u64 timestamp = 0)

Parameters

format : formatting string specifying the date format
timestamp : optional timestamp value, defaults to current time
return value : a formatted date

Formats a timestamp in the server's local timezone.

This formatter is based on the Linux date command and supports the same core formatting tokens plus UCE's relative-time delta tokens.

Supported format sequences:

Padding and case flags may follow %:

time_format_relative

String time_format_relative(u64 timestamp, String format_very_recent = "", u64 medium_recency_seconds = 0, String format_medium_recent = "", u64 not_recent_seconds = 0, String format_not_recent = "")

Parameters

timestamp : Unix timestamp to compare against the current time
format_very_recent : output format for very recent timestamps, defaults to just now
medium_recency_seconds : cutoff between the very-recent and medium-recent formats, defaults to 90
format_medium_recent : output format for medium-recent timestamps, defaults to %deltaM minutes ago
not_recent_seconds : cutoff between the medium-recent and not-recent formats, defaults to 5400
format_not_recent : output format for older timestamps, defaults to %deltaH hours ago
return value : a formatted relative-time string

Formats a timestamp relative to the current time using the same formatting engine as time_format_local() and time_format_utc().

The formatter chooses one of three output formats:

The relative-time tokens available in all time formatters are:

Default behavior examples:

time_format_utc

String time_format_utc(String format = "", u64 timestamp = 0)

Parameters

format : formatting string specifying the date format
timestamp : optional timestamp value, defaults to current time
return value : a formatted date

Formats a timestamp in the GMT/UTC timezone.

This formatter is based on the Linux date command and supports the same core formatting tokens plus UCE's relative-time delta tokens.

Supported format sequences:

Padding and case flags may follow %:

time_parse

u64 time_parse(String time_string)

Parameters

time_string : a string containing a date and/or time in text form
return value : the interpreted 'time_string' as a Unix timestamp

Attempts to parse time_string into a Unix timestamp.

Types

Request

Request& context

Request& context is the request-local state object passed into every UCE handler:

It is the main bridge between the runtime and page code. It contains incoming request data, response state, output buffers, per-request scratch trees, session/cookie state, WebSocket metadata, and runtime diagnostics.

Handler Lifetime

A fresh Request is created for each HTTP/CLI/custom-server request. Component and unit calls normally share that same object, so state placed on context.call, context.header, context.session, or context.cfg is visible to later components in the same request.

For WebSockets, each incoming message is delivered as its own Request, but context.connection points at broker-owned per-socket state that persists for the lifetime of that WebSocket connection.

ONCE(Request& context) hooks run once per request, per resolved unit file, before the first RENDER, COMPONENT, CLI, or matching entrypoint from that unit.

Incoming Request Maps

context.params — server/runtime parameters

Type: StringMap

This is the low-level parameter map from FastCGI/direct HTTP plus UCE-populated convenience fields. It is closest to PHP $_SERVER.

Common CGI/FastCGI-style keys include:

UCE also populates convenience route/link fields before handlers run:

See request_context_params, request_script_url, request_base_url, request_query_path, request_query_route, and route_path_sanitize.

context.get

Type: StringMap

Parsed query-string key/value parameters. This is populated from context.params["QUERY_STRING"] with parse_query().

For front-controller route URLs such as /?dashboard&theme=dark, the keyless dashboard segment is represented by sanitized ROUTE_PATH; named parameters such as theme=dark are available in context.get.

context.post

Type: StringMap

Parsed request body parameters for ordinary POST requests. URL-encoded bodies are parsed with parse_query(). Multipart form data is parsed with parse_multipart() and uploaded files are listed in context.uploaded_files.

context.cookies

Type: StringMap

Cookies sent by the client, parsed from HTTP_COOKIE. set_cookie() also updates this map after queuing a response cookie, so later code in the same request can observe the new value.

context.in

Type: String

Raw request body. For WebSocket handlers, this is the current message payload.

Use this for JSON APIs:

context.uploaded_files

Type: std::vector<UploadedFile>

Each UploadedFile contains:

Use this with multipart form posts.

Session State

context.session

Type: StringMap

Session data loaded by session_start(). UCE does not load sessions automatically for every request; call session_start() before reading/writing session data.

At the end of a successful request, modified session data is saved automatically if a session is active.

context.session_id and context.session_name

The active session ID and cookie name after session_start().

Related helpers:

Per-request Structured Trees

context.call

Type: DValue

General request-local scratch/configuration tree. It is shared by the page, components, and unit calls participating in the current request. Use it for app-level request state, fragments, router results, page type, page title, and other values that need to be read by later components.

Examples from front-controller style apps:

Prefer clear top-level names when state is app-wide (route, fragments) and nested app names only when the state is truly owned by that app (app/page_title, app/page_type).

context.cfg

Type: DValue

Request-local structured configuration. The runtime does not fill this with application config by default; application code may assign it during boot/setup:

This is separate from context.server->config, which is the runtime/server string config from /etc/uce/settings.cfg.

Use get_by_path() for non-mutating deep reads:

context.props

Type: DValue

Invocation-local props for component(), component_render(), and macro-style unit_call() entrypoints. During a component call, the runtime temporarily replaces context.props with the props passed to that component and restores the previous value after the call returns.

context.connection

Type: DValue

WebSocket connection-local state. Mutations persist across WS(Request& context) calls for the same socket.

Only meaningful for WebSocket handlers.

Response State

context.response_code

Type: String

The raw status line. Usually use context.set_status(...) instead of writing this directly.

context.header

Type: StringMap

Response headers to emit. Header names are case-sensitive as written.

context.set_cookies

Type: StringList

Queued Set-Cookie header lines. Prefer set_cookie() instead of editing this directly.

context.set_status(code[, reason])

Sets the HTTP response status and context.flags.status.

Related helpers:

Output Buffers

context.ob_stack and context.ob

Internal output-buffer stack. Most code should use helpers instead of touching these directly:

Common capture pattern:

context.out and context.err

Runtime output/error artifacts used by some transports and failure paths. Normal page rendering should use print() / output buffers.

Request Flags

context.flags contains runtime booleans and the numeric status:

Most page code only reads flags.status, if anything.

Request Stats

context.stats contains counters/timing for the request:

These are useful for diagnostics, demos, and runtime instrumentation.

Random / Noise State

Used by UCE noise/random helpers to provide request-local deterministic progression.

Related helpers include functions in the noise/hash area such as gen_int, gen_float, gen_noise64, and gen_sha1.

WebSocket Fields

In WS(Request& context), the runtime mirrors WebSocket metadata into context.params and context.resources.

Convenience context.params keys include:

Prefer WebSocket helper functions where possible:

Use context.connection for per-socket structured state.

Runtime / Resource Fields

context.server

Pointer to server state. Useful mainly for low-level/runtime code. Runtime config lives at:

This is a StringMap, separate from app-owned context.cfg.

context.resources

Internal runtime resources and transport state. Includes sockets, MySQL handles, WebSocket state, current unit file, and parser buffers. Application code should normally use public helpers instead of editing this directly.

Notable fields:

Common Patterns

Minimal page

JSON endpoint

Redirect

Component props

Front-controller route

Or use runtime-populated params directly:

array_merge

StringMap array_merge(StringMap a, StringMap b)
DValue array_merge(DValue a, DValue b)

Parameters

a : left-hand source map or tree
b : right-hand source map or tree
return value : merged result

Merges two maps or trees using PHP-like merge behavior.

For StringMap, keys from b overwrite keys from a.

For DValue, string keys from b overwrite keys from a. Numeric keys are appended and reindexed when either side behaves like a list.

This helper is the closest UCE equivalent to PHP array_merge() for common request, config, and JSON-shaped data.

DValue

DValue

DValue is UCE's general-purpose structured value type. It is the runtime's default container for nested data such as configuration trees, call payloads, decoded JSON, connection state, and metadata returned by runtime helpers.

Value Kinds

DValue can hold:

Map-shaped DValue values can also represent list-like data when their keys are numeric strings in sequence.

Where It Appears

You will encounter DValue throughout the runtime, especially in:

Reading Values

All read accessors are const and never modify the tree; they work directly on const DValue& values such as each() callback parameters. Every to_* conversion takes an optional default that is returned when the value is missing or cannot be converted — see the individual pages (2_DValue_to_string, 2_DValue_to_s64, 2_DValue_to_u64, 2_DValue_to_f64, 2_DValue_to_bool) for the exact rules:

operator[] creates missing entries, just like std::map. .has() and .key() are the non-mutating lookup helpers, and .get_by_path() is the non-creating traversal helper.

json_decode() currently stores JSON numbers as string-valued DValue nodes, so typed numeric conversion is the normal way to consume those values.

References are dereferenced automatically in most normal reads.

Conversion Rules

Writing Values

Common mutating helpers include:

Use .set_array() when you want list-style behavior with push() and pop().

Inspection Helpers

Useful inspection helpers include:

each()

each(std::function<void (const DValue& t, String key)> f) iterates over the current tree value (see 2_DValue_each for details).

For map-shaped DValue values, the callback runs once per child entry and receives:

For non-map values, each() still invokes the callback once:

Examples

DValue::filter

DValue DValue::filter(StringList keys) const
DValue DValue::filter(std::function f) const

Parameters

keys : child keys to copy when using the key-list overload
f : predicate returning true for children to keep
return value : filtered copy

filter(keys) copies existing children with the named keys into a new map-shaped DValue.

filter(f) calls the predicate for each item from each(). Kept children from list-shaped input are pushed into a new list and re-indexed from zero; kept children from map-shaped input keep their original keys. Scalar input is passed to the predicate once and, if accepted, is pushed into a list.

DValue::keys

StringList DValue::keys() const

Parameters

return value : child keys for map/list values; empty for scalars

Returns the keys produced by each(). Scalar values have no child key, so the result is empty. List-shaped values return their numeric keys as strings.

DValue::map

DValue DValue::map(std::function f) const

Parameters

f : mapper called for each iterated item
return value : mapped copy

Builds a new DValue by replacing each iterated child with the mapper's returned value. List-shaped input stays list-shaped and is re-indexed by push(). Map-shaped input preserves keys. Scalar input is mapped once and pushed into a list.

DValue::values

DValue DValue::values() const

Parameters

return value : a list-shaped DValue containing each iterated child value

Copies the values produced by each() into a new list-shaped DValue.

DValue::each

void DValue::each(std::function f) const

Parameters

f : callback invoked for each child, or once for a scalar value
return value : none

Iterates a DValue without modifying it. References are dereferenced before iteration.

For map-shaped values, the callback receives each child and its key. List-shaped maps iterate in numeric index order (0, 1, 2, ...); ordinary maps iterate in std::map string-key order. Scalar values invoke the callback once with the current value and an empty key.

DValue::get_by_path

DValue DValue::get_by_path(String path, String delim = "/") const

Parameters

path : delimited child path to traverse
delim : path separator string
return value : resolved child copy, or an empty DValue when traversal fails

Traverses nested map/list children without creating missing nodes. Empty path segments are ignored. If any segment is missing or an intermediate value is not map-shaped, the method returns an empty DValue.

DValue::has

bool DValue::has(String s) const

Parameters

s : child key to test
return value : true when the dereferenced value is map-shaped and contains the key

Checks for a child key without creating it. Returns false for scalars and missing keys.

DValue::is_array

bool DValue::is_array() const

Parameters

return value : true when the dereferenced value is map-shaped

Returns true when the value's current type is M, the map/list container type. It does not require contiguous numeric keys; use is_list() for that.

DValue::is_list

bool DValue::is_list() const

Parameters

return value : true when the value is an array with keys 0..n-1

Returns true for map-shaped values that represent a list. An empty map is a list only if it was explicitly put in list mode with set_array() or by list operations. Non-empty lists must have canonical numeric string keys from 0 through size - 1.

Request::set_status

void Request::set_status(s32 code, String reason = "")

Parameters

code : HTTP status code
reason : optional reason phrase override
return value : none

Sets the request status line and mirrors the numeric status into context.flags.status. When reason is omitted, common HTTP status codes get their standard phrase. FastCGI-style requests use a Status: prefix; other requests use HTTP/1.1.

String

0_String

Primary string type used throughout UCE.

String is an alias for std::string.

It is used for request data, headers, cookie values, file contents, query strings, JSON text, and WebSocket payloads.

Because it is backed by std::string, it is binary-safe and may also contain raw bytes.

For UTF-8-aware splitting, use helpers such as split_utf8() instead of assuming one byte equals one character.

StringList

struct StringList — ordered list of String values

Parameters

return value : use methods such as filter(), map(), keys(), each(), unique(), sort(), some(), every(), and find() to derive or inspect lists

StringList is an ordered container of String values. It inherits normal std::vector<String> behavior and adds list helpers for filtering, mapping, indexes, iteration, deduplication, sorting, and predicate checks.

StringList::filter

template StringList StringList::filter(F f) const

Parameters

f : predicate called with each string
return value : new list containing items where f(item) is true

Returns a new StringList containing the original items for which the predicate returns true. Order is preserved.

StringList::map

template StringList StringList::map(F f) const

Parameters

f : mapper called with each string
return value : new list of mapped strings

Returns a new StringList containing the mapper result for each item, in the same order. Use it for simple string transformations while keeping list shape.

StringList::keys

StringList StringList::keys() const

Parameters

return value : index keys as strings

Returns the list indexes as strings from 0 through size() - 1. Use it when code expects string keys for a list-shaped value.

StringList::each

template void StringList::each(F f) const

Parameters

f : callback called with each string
return value : none

Calls the callback once for each string in order. Use it when you want side effects such as building output or accumulating a separate value.

StringList::unique

StringList StringList::unique() const

Parameters

return value : a new StringList containing each distinct string once

Returns a copy of the list with duplicate strings removed. The first occurrence of each string is kept, so the result preserves first-seen order.

StringList::sort

StringList StringList::sort() const

Parameters

return value : a new StringList sorted in ascending string order

Returns a sorted copy of the list without changing the original. Use it for deterministic output, menus, manifests, and test comparisons.

StringList::some

template bool StringList::some(F f) const

Parameters

f : predicate called with each string
return value : true when at least one item matches

Tests whether any string in the list satisfies the predicate. Use it for concise presence checks when the condition is more specific than direct equality.

StringList::every

template bool StringList::every(F f) const

Parameters

f : predicate called with each string
return value : true when every item matches

Tests whether all strings in the list satisfy the predicate. Use it for validation checks where a list is acceptable only if every member passes the same rule.

StringList::find

template String StringList::find(F f, String fallback = "") const

Parameters

f : predicate called with each string
fallback : value returned when no item matches
return value : the first matching string, or fallback

Returns the first string in the list that satisfies the predicate. Use it when you need the matching value itself, not just a yes/no answer, and when a clear fallback is better than a separate missing-value branch.

StringMap

0_StringMap

Associative container mapping String keys to String values.

StringMap is an alias for std::map<String, String>.

Common Uses

StringMap commonly appears in:

Because it uses std::map, map["key"] will create an empty entry when that key does not already exist.

Helpers such as parse_query() and encode_query() convert between query strings and StringMap values.

DValue::to_bool

bool DValue::to_bool(bool default_value = false) const

Parameters

bool : fallback returned when conversion is not possible
return value : converted value or the fallback

Converts strings, numbers, bools, pointers, and maps to bool. Text such as true, yes, on, 1, false, no, off, 0, and null is recognized; non-empty unparseable strings are truthy; empty strings use the default. Multi-child maps are true when non-empty.

DValue::to_f64

f64 DValue::to_f64(f64 default_value = 0) const

Parameters

f64 : fallback returned when conversion is not possible
return value : converted value or the fallback

Converts strings, f64, bool, pointer, and single-value maps to a finite double. Invalid or empty strings return the default.

DValue::to_json

String DValue::to_json(char quote_char = '"') const

Parameters

quote_char : quote character passed to string escaping
return value : JSON-ish scalar representation

Returns the JSON scalar representation used by this low-level method: strings are escaped and quoted, numbers are emitted with std::to_string, bools as true/false, maps as "(array)", pointers as "(pointer)", and references as "(reference)". For full structured encoding, use the runtime JSON helpers.

DValue::to_s64

s64 DValue::to_s64(s64 default_value = 0) const

Parameters

s64 : fallback returned when conversion is not possible
return value : converted value or the fallback

Converts strings, f64, bool, pointer, and single-value maps to a signed integer. Invalid or empty strings return the default. Values outside the signed range are clamped.

DValue::to_string

String DValue::to_string(String default_value = "") const

Parameters

String : fallback returned when conversion is not possible
return value : converted value or the fallback

Returns the stored string, converts f64/bool/pointer values to text, and returns the default for empty strings, maps, unresolved references, or unknown types. Bool text is (true) or (false).

DValue::to_stringmap

StringMap DValue::to_stringmap() const

Parameters

return value : StringMap copy of the value

Converts a DValue to StringMap. Map children become entries converted with to_string(). Non-empty strings become value=<string>. f64, bool, and pointer values become value=<to_string()>. References that cannot be resolved produce an empty map.

DValue::to_u64

u64 DValue::to_u64(u64 default_value = 0) const

Parameters

u64 : fallback returned when conversion is not possible
return value : converted value or the fallback

Converts strings, f64, bool, pointer, and single-value maps to an unsigned integer. Invalid or empty strings return the default. Negative values clamp to zero and oversized values clamp to u64 max.

to_bool

bool to_bool(String s, bool fallback = false)

Parameters

s : string to parse
fallback : value returned when s is empty or not a recognized boolean token
return value : parsed bool, or fallback.

Parses a trimmed, case-insensitive boolean string.

Truthy tokens are "1", "true", "yes", and "on". Falsey tokens are "0", "false", "no", and "off". Empty or unrecognized strings return the fallback.

to_f64

f64 to_f64(String s, f64 fallback = 0)

Parameters

s : string to parse
fallback : value returned when s is empty or not a complete floating-point number
return value : parsed f64, or fallback.

Parses a trimmed string as a floating-point number.

Unlike float_val(), the whole trimmed string must be consumed by the parser. Empty strings and partially parsed values such as "3.5ms" return the fallback.

to_s64

s64 to_s64(String s, s64 fallback = 0)

Parameters

s : string to parse
fallback : value returned when s is empty or not a complete signed integer
return value : parsed s64, or fallback.

Parses a trimmed string as a base-10 signed integer.

The whole trimmed string must be consumed by the parser. Empty strings and partially parsed values such as "-12px" return the fallback.

to_u64

u64 to_u64(String s, u64 fallback = 0)

Parameters

s : string to parse
fallback : value returned when s is empty or not a complete unsigned integer
return value : parsed u64, or fallback.

Parses a trimmed string as a base-10 unsigned integer.

Unlike int_val(), the whole trimmed string must be consumed by the parser. Empty strings and partially parsed values such as "42px" return the fallback.

ucb_encode

String ucb_encode(DValue value)

Serializes a DValue to UCEB1, UCE's binary DValue wire format for the WASM membrane and future cross-instance calls.

UCEB1 is length-prefixed and binary-safe. It preserves nested maps, list-shaped maps, empty lists, and scalar bytes, including embedded NUL bytes. Use JSON/YAML/XML serializers for human-facing formats; use UCEB1 when UCE code needs the native DValue protocol.

ucb_decode

DValue ucb_decode(String encoded)
bool ucb_decode(String encoded, DValue& out, String* error_out = 0)

Decodes UCEB1 bytes produced by ucb_encode() back into a DValue.

The one-argument form returns an empty DValue on invalid input. The three-argument form reports whether decoding succeeded and can return a human-readable error string.

URI Functions

encode_query

String encode_query(StringMap map)

Parameters

q : StringMap containing URL parameters to be encoded
return value : a string with the encoded parameters

Encodes a StringMap of URL parameters into a single query-string String.

redirect

void redirect(String url, s32 code = 302)

Parameters

url : target URL for the redirect
code : optional HTTP redirect status, defaults to 302

Sets the Location response header and updates the current HTTP status code.

Use this helper instead of manually assigning context.header["Location"] and context.set_status(...) when you want to redirect the current response.

Request Context Params

SCRIPT_URL, BASE_URL, ROUTE_PATH, ROUTE_PAGE, ROUTE_PATH_RAW, ROUTE_VALID, UCE_BIN_DIRECTORY

UCE populates several convenience request parameters before invoking page, component, CLI, custom HTTP, or WebSocket handlers:

ROUTE_PATH is safe to compose under an application-controlled route root. Unsafe route input such as .., ., empty interior segments, backslashes, dots in filenames, or other non route-segment characters is rejected by the runtime and yields an empty ROUTE_PATH with ROUTE_VALID=0.

These are useful for front-controller apps that use URLs like /?dashboard or /?workspace/projects while still accepting ordinary named query parameters.

request_base_url

String request_base_url(Request& context)

Returns the canonical directory base URL for the current script. This is useful for front-controller apps that generate links to sibling assets or query-routed pages.

request_query_path

String request_query_path(Request& context, String default_path = "index")

Returns the first keyless query-string segment as a sanitized route path.

For a request such as /?workspace/projects&theme=dark, this returns workspace/projects.

When no keyless route is supplied, the result is default_path. When unsafe route input is supplied, the result is an empty string. Unsafe route input includes . or .. segments, empty interior segments, backslashes, dots in filenames, or any character outside ASCII letters, digits, _, and -.

The runtime-populated context.params["ROUTE_PATH"] uses the same sanitizer.

request_query_route

DValue request_query_route(Request& context, String default_path = "index")

Builds a small route tree from the first keyless query-string segment.

Fields:

This supports front-controller apps that use URLs such as /?dashboard or /?workspace/projects while still allowing ordinary named query parameters alongside the route. The returned l_path is already sanitized for composing under an application-controlled route root.

request_script_url

String request_script_url(Request& context)

Returns the request script URL from DOCUMENT_URI / SCRIPT_NAME, canonicalizing a front-controller URL ending in /index.uce to the containing directory URL.

route_path_is_safe

bool route_path_is_safe(String path)

Returns whether a normalized route path is safe to use as a route-derived file path segment.

A safe route path contains only non-empty segments made from ASCII letters, digits, _, and -. The segments . and .. are rejected.

Most request code should use runtime-populated context.params["ROUTE_PATH"] or request_query_route() instead of calling this directly.

route_path_normalize

String route_path_normalize(String path)

Trims whitespace and removes leading/trailing / from a route path without deciding whether the path is safe.

For route data that may be used to compose file paths, prefer route_path_sanitize() or runtime-populated context.params["ROUTE_PATH"].

route_path_sanitize

String route_path_sanitize(String path, String default_path = "index")

Normalizes and validates a route path for file-backed routing.

Rules:

Use this instead of manually checking app routes before composing file paths.

request_query_path(), request_query_route(), and the runtime-populated ROUTE_PATH params already use this sanitizer.

session_id_create

String session_id_create()

Parameters

return value : a new session ID

Creates and returns a new session ID.

This helper is useful when you need to generate a session token directly rather than starting a full session flow with session_start().

parse_query

StringMap parse_query(String q)

Parameters

q : string containing URL parameters
return value : a StringMap containing the parameters

Decodes a query-string fragment such as a=b&c=d into a StringMap.

Parsing rules:

Examples:

This is useful when you need to work with URL parameter data outside the normal request parsing flow.

parse_uri

URI parse_uri(String uri_string)

Parameters

uri_string : URI or URL string
return value : URI object with parts and query maps

Parses a URI into its component maps.

return.parts contains the parsed URI fields. return.query contains query parameters decoded with the same rules as parse_query().

Example:

Use parse_uri() when you need to inspect a full URL. Use parse_query() when you only have the query string.

uri_decode

String uri_decode(String s)

Parameters

s : string containing URI encoded data
return value : a string that contains the decoded version of 's'

Decodes a URI-encoded string.

uri_encode

String uri_encode(String s)

Parameters

s : string that should be encoded
return value : an URI-encoded version of 's'

URI-encodes a string.

request_route_from_raw_path

DValue request_route_from_raw_path(String raw_path, String default_path = "index")

Parameters

raw_path : raw route path from a request or query string
default_path : route used for an empty path
return value : route metadata DValue

Normalizes and validates a raw route path. The returned DValue includes route fields used by request context population, including sanitized path and validity metadata.

WebSocket Functions

ws_close

bool ws_close(String connection_id = "")

Parameters

connection_id : optional target client ID, defaults to the current WebSocket client
return value : true if the target connection exists and was scheduled to close

Queues a WebSocket close frame and closes the targeted connection.

If connection_id is omitted, the current connection handled by WS(Request& context) is closed.

ws_connection_count

u64 ws_connection_count(String scope = "")

Parameters

scope : optional scope identifier, defaults to the current WebSocket page scope
return value : number of connected WebSocket clients in that scope

Returns the number of currently connected WebSocket clients for the given scope.

If scope is omitted, the current page scope is used.

ws_connection_id

String ws_connection_id()

Parameters

return value : connection ID of the current WebSocket client

Returns the runtime-generated connection ID of the client whose message is currently being handled.

This ID can be passed to ws_send_to() or ws_close() to target a single connected client.

ws_connections

StringList ws_connections(String scope = "")

Parameters

scope : optional scope identifier, defaults to the current WebSocket page scope
return value : list of connection IDs currently connected to that scope

Returns the currently connected WebSocket client IDs for the given scope.

If scope is omitted, the current page scope is used.

ws_is_binary

bool ws_is_binary()

Parameters

return value : true if the current WebSocket message is binary

Returns whether the message currently being handled by WS(Request& context) arrived as a binary frame.

If this returns false, the current message was delivered as a text frame.

ws_message

String ws_message()

Parameters

return value : payload of the current WebSocket message

Returns the payload of the current WebSocket message being handled by WS(Request& context).

For text frames this is the decoded text payload. For binary frames this String contains the raw message bytes.

Use ws_is_binary() or ws_opcode() to choose how to parse the payload.

ws_opcode

u8 ws_opcode()

Parameters

return value : opcode of the current WebSocket message

Returns the opcode of the message currently being handled by WS(Request& context).

Common values are:

ws_scope

String ws_scope()

Parameters

return value : scope identifier of the current WebSocket endpoint

Returns the runtime's scope identifier for the current WebSocket endpoint.

This is the same default scope used by ws_send(), ws_connections(), and ws_connection_count() when no explicit scope is supplied.

In the current runtime implementation this scope is the page's internal endpoint identifier, typically the absolute SCRIPT_FILENAME of the .uce file that accepted the WebSocket upgrade.

ws_send

bool ws_send(String message, bool binary = false, String scope = "")

Parameters

message : message payload to send
binary : set to true to send a binary frame instead of a text frame
scope : optional scope identifier, defaults to the current WebSocket page scope
return value : true if the message was queued for at least one connected client

Queues a WebSocket message for every client connected to the given scope.

If scope is omitted, the current page scope is used.

ws_send_to

bool ws_send_to(String connection_id, String message, bool binary = false)

Parameters

connection_id : ID of the target WebSocket client
message : message payload to send
binary : set to true to send a binary frame instead of a text frame
return value : true if the target connection exists and the message was queued

Queues a WebSocket message for one specific connected client.

Other Functions and Data Structures

COMPONENT

COMPONENT(Request& context)

Defines the default component entrypoint for the current .uce file.

component() and component_render() call COMPONENT(Request& context) by default. Named component entrypoints use COMPONENT:NAME(Request& context).

If the same file defines ONCE(Request& context), that hook runs once per request before the first COMPONENT() or COMPONENT:NAME() call for that unit.

If the file defines INIT(Request& context), that hook runs once when the worker loads the compiled unit into memory.

Why It Exists

This keeps page rendering and component rendering separate:

A file intended only for component reuse can define COMPONENT() without defining RENDER().

Inside component handlers, props arrive through context.props.

When you call component(":NAME", props, context) or component_render(":NAME", props, context), the runtime resolves :NAME against the current .uce file instead of requiring the file name again.

Example

INIT

INIT(Request& context)

Defines a worker-load hook for the current .uce unit.

When a worker instantiates the unit's compiled wasm module, the runtime checks whether the unit exposes INIT(Request& context). If it does, the hook runs once for that instance before the unit begins serving requests from that worker-local copy.

Because UCE usually loads units on demand during a request, INIT() still receives a valid Request& context. Use it for worker-local initialization, not for request-local state that should reset each request.

Typical Uses

Example

ONCE

ONCE(Request& context)

Defines a request-local one-time hook for the current .uce unit.

When a request first enters a given file through RENDER(Request& context), COMPONENT(Request& context), or any COMPONENT:NAME(Request& context) handler, the runtime checks whether that unit exposes ONCE(Request& context). If it does, the hook runs before the selected render or component handler.

ONCE() is tracked per request and per resolved unit file, so repeated component calls to the same file inside one request do not rerun it.

Typical Uses

Example

WS

WS(Request& context)

Defines the WebSocket message handler for the current .uce page.

Any .uce unit may expose both RENDER(Request& context) and WS(Request& context). RENDER(Request& context) serves the initial HTTP response, while WS(Request& context) is called whenever a complete WebSocket message arrives for that page. Configure nginx/Apache to route WebSocket upgrade requests for .uce paths to the runtime's HTTP/WebSocket listener.

UCE reassembles fragmented messages before calling WS(Request& context). Text and binary frames are both delivered. The current payload is available directly on context.in, message metadata is mirrored into context.params["WS_..."], and connection-local state lives on context.connection.

Connection State

context.connection is a broker-owned DValue for the current socket. It starts empty for a new client and persists across later WS(Request& context) calls on that same connection.

Message Data

The current message payload is available as:

The current message metadata is available as:

Helper wrappers such as ws_message(), ws_connection_id(), ws_scope(), ws_connection_count(), ws_opcode(), and ws_is_binary() are still available when that reads better for the handler.

DValue::operator=

void DValue::operator=(String v)
void DValue::operator=(f64 v)
void DValue::operator=(void* v)
void DValue::operator=(DValue v)
void DValue::operator=(StringMap v)

Parameters

v : assigned value
return value : none

Assignment overloads forward to the matching set(...) overloads. They are the normal concise way to write string, number, pointer, DValue, and StringMap values. Boolean values should use set_bool() to avoid overload ambiguity.

DValue::clear

void DValue::clear()

Parameters

return value : none

Clears the value into an empty map-shaped value and resets its array index. Unlike set_array(), this does not set list mode.

DValue::deref

DValue& DValue::deref()
const DValue& DValue::deref() const

Parameters

return value : referenced target when resolvable, otherwise this value

Returns the value after following internal reference links. Most public accessors call this for you, so direct use is rare in unit code.

DValue::get_or_create

DValue* DValue::get_or_create(String s)

Parameters

s : child key to create or return
return value : pointer to the child node

Ensures the value is map-shaped and returns the named child. If the key does not exist, an empty child is created. Creating a non-numeric key on a list-shaped value clears list mode.

DValue::get_type_name

String DValue::get_type_name() const

Parameters

return value : one of String, f64, bool, array, pointer, reference, or unknown

Returns a human-readable name for the dereferenced value's type tag.

DValue::is_reference

bool DValue::is_reference() const

Parameters

return value : true when this node itself is a reference node

Reports whether the current node's direct type tag is the internal reference tag. Most read methods dereference automatically; this helper is mainly useful when handling reference-aware runtime state.

DValue::key

DValue* DValue::key(String s)
const DValue* DValue::key(String s) const

Parameters

s : child key to find
return value : pointer to existing child, or 0

Looks up one child without creating it. The non-const overload forwards through references; both overloads return 0 for scalars or missing keys.

DValue::operator[]

DValue& DValue::operator[](String s)

Parameters

s : child key to return or create
return value : reference to the child node

Returns a mutable reference to a child, creating the child when it does not already exist. If this value is an internal reference, the operation is forwarded to the target. This has the same creation behavior as get_or_create(), so use has(), key(), or get_by_path() for non-mutating reads.

DValue::pop

DValue DValue::pop()

Parameters

return value : removed child, or an empty DValue when no child exists

Ensures the value is map-shaped, removes the last entry according to std::map reverse key order, and returns it. For list-mode values, the next array index is reset to the new size.

DValue::push

void DValue::push(const DValue& child)

Parameters

child : value to append/copy
return value : none

Appends a child under the next numeric key. Empty values become list-shaped. Existing contiguous lists continue at their size; non-list maps use the next unused numeric key and remain non-list.

DValue::reference_target

DValue* DValue::reference_target()
const DValue* DValue::reference_target() const

Parameters

return value : resolved target pointer, or 0 when this node is not a usable reference

If this node is an internal reference, follows reference links up to the runtime safety limit and returns the final non-reference target. Returns 0 for non-references, null/self references, or chains that still resolve to a reference.

DValue::remove

void DValue::remove(String s)

Parameters

s : child key to erase
return value : none

Ensures the value is map-shaped and erases the named child. Removing the last child resets the next array index to zero.

DValue::set

void DValue::set(String s)
void DValue::set(void* p)
void DValue::set(f64 f)
void DValue::set(DValue source)
void DValue::set(StringMap source)

Parameters

s : string value for the String overload
p : pointer value for the pointer overload
f : floating point value for the f64 overload
source : DValue or StringMap to copy
return value : none

Assigns a new value, forwarding through references when possible. String, pointer, and f64 overloads set scalar nodes. set(DValue) copies the source's current type and payload. set(StringMap) creates a map-shaped value with each string entry as a child.

DValue::set_array

void DValue::set_array()

Parameters

return value : none

Clears the value and makes it an empty list-shaped map. Subsequent push() calls append numeric keys starting at 0.

DValue::set_bool

void DValue::set_bool(bool b)

Parameters

b : boolean value to store
return value : none

Stores a boolean value, forwarding through references when possible.

DValue::set_reference

void DValue::set_reference(DValue* target)

Parameters

target : target node pointer
return value : none

Stores an internal reference to another DValue. Most unit code should not need to create references directly; normal reads and writes generally follow existing references automatically.

DValue::set_type

void DValue::set_type(char t)

Parameters

t : internal type tag such as S, F, B, M, P, or R
return value : none

Changes the node's internal type tag, forwarding through references when possible. Switching to map type clears children, resets list state, and resets the array index.

Prefer the typed setters (set, set_bool, set_array) in normal unit code.

Request::ob_start

void Request::ob_start()

Parameters

return value : none

Starts a new output buffer for the request and makes it the active context.ob. Most unit code should prefer the higher-level output-buffer helpers (ob_start(), ob_get(), ob_get_close(), ob_close()) rather than calling the method directly.

Blocked functions (hostcall blocklist)

UCE units reach the operating system only through a fixed set of uce_host_* membrane hostcalls (see the runtime architecture). A server operator can disable individual hostcalls so a deployment exposes only the capabilities it wants — for example turning off shell_exec or http_request on a hardened host. A unit that calls a disabled function fails at request time with the configurable error page, stating exactly which function was blocked and why.

Configuration

Set UCE_HOSTCALL_BLOCKLIST in /etc/uce/settings.cfg to a comma-separated list of hostcall names. Names may be given bare (shell_exec) or fully qualified (uce_host_shell_exec); whitespace is ignored. Empty (the default) blocks nothing.

Changes take effect on restart (systemctl restart uce). There is no hot reload — the list is parsed once per worker process into a fast lookup, so an empty list has zero runtime cost and a non-empty list costs only a single check per hostcall at workspace birth (never per call).

Behaviour when a blocked function is called

The blocked hostcall resolves to a trap stub instead of its real implementation. When a unit invokes it, the request fails into the runtime error page with:

The worker is unharmed (it is a clean guest trap, like any other), and only the offending request fails. A unit cannot catch this — blocking is enforcement, not a soft signal.

What can and cannot be blocked

Any uce_host_* capability hostcall can be listed — file I/O, shell_exec / shell_spawn, http_request, mysql, sockets, memcache, crypto, the job registry, etc. (the full set is the membrane list in the runtime architecture doc and src/wasm/core_hostcalls.syms).

A small core set the runtime itself needs is exempt and ignored even if listed, so a deployment cannot be bricked by an over-broad blocklist: component_resolve (used for component() / unit rendering).

Notes

C++ Preprocessor

UCE source preprocessing

UCE runs a small custom source-to-source preprocessor before Clang sees a .uce or .ws.uce file.

The template rewriting implementation lives in src/lib/compiler-parser.cpp, with orchestration in src/lib/compiler.cpp. It does not try to parse all of C++. Instead, it performs a narrow character-wise rewrite that understands literal output, inline code islands, #load, and EXPORT harvesting, then writes a generated .cpp file and compiles that file into a WebAssembly side module.

Syntax

Pipeline

Generated Files

For a source file like /some/path/page.uce, the preprocessor produces:

Examples

Literal output with escaped data:

The same thing can also be written with PHP-style literal delimiters:

Roughly becomes:

Literal output with trusted unescaped markup:

Roughly becomes:

Compile-time composition:

The loaded file is resolved relative to the current source file unless the path is already absolute.

One-time worker initialization plus request-local setup:

One-time page assets captured for a template-controlled slot:

The page template can then render context.call["fragments"]["head"] inside <head>.

Rules

Limitations

Debugging

Coming from React, Next, or Remix

UCE orientation for React-framework developers

UCE is server-first C++ with a small template preprocessor. It does not try to be React, but several concepts map cleanly.

Concept Map

Routes and Layouts

UCE does not require a framework-level router. A front controller can keep routing explicit and app-local. The starter example demonstrates this in site/examples/uce-starter/index.uce: it resolves a request path by checking:

  1. views/<path>.uce

  2. views/<path>/index.uce

  3. parent index handlers such as views/workspace/index.uce with the last segment as a route parameter

That keeps file-based and hierarchical routing in normal UCE code instead of hiding it in the runtime.

Data Shaping Near Render Code

The function library includes small collection helpers for common route/menu/card transformations:

Use these when a short transformation is clearer than a loop. Prefer explicit loops for side effects or multi-step validation.

Assets and Islands

UCE core does not provide a global asset or island registry. The starter emits CSS and JavaScript from the owning unit's ONCE(Request& context) hook, with a few shared sibling asset components when multiple components need the same files. The starter's COMPONENT:island helper in components/theme/web_affordances.uce covers small progressive-enhancement modules while keeping app policy in the app.

Debugging

When a unit fails to compile, UCE reports the source path, generated C++ path, compile-output artifact, a source/generated excerpt when it can identify a line, and the raw compiler output. The generated C++ under BIN_DIRECTORY is the source of truth for what the configured compiler actually saw.

What Not To Expect