From 605e68c9b6eeab642179095b8f56d310edc6aae8 Mon Sep 17 00:00:00 2001 From: jow- Date: Wed, 11 Oct 2023 14:50:59 +0000 Subject: [PATCH] deploy: 2b2a47240c089a2cb10223efd4a1f133638f5dd5 --- data/search.json | 2 +- index.html | 4 +- lib.c.html | 105 +- lib_debug.c.html | 18 +- lib_fs.c.html | 154 +-- lib_log.c.html | 4 +- lib_math.c.html | 4 +- lib_struct.c.html | 4 +- lib_uci.c.html | 1874 +++++++++++++++++++++++++++++++++++ module-core.html | 56 +- module-debug.html | 4 +- module-fs.dir.html | 14 +- module-fs.file.html | 18 +- module-fs.html | 56 +- module-fs.proc.html | 16 +- module-log.html | 4 +- module-math.html | 4 +- module-struct.html | 4 +- module-struct.instance.html | 4 +- module-uci.cursor.html | 149 +++ module-uci.html | 16 + tutorial-01-usage.html | 4 +- tutorial-02-syntax.html | 4 +- tutorial-03-memory.html | 4 +- ucode.css | 81 ++ ucode.js | 32 + 26 files changed, 2372 insertions(+), 267 deletions(-) create mode 100644 lib_uci.c.html create mode 100644 module-uci.cursor.html create mode 100644 module-uci.html diff --git a/data/search.json b/data/search.json index 17b601a2..fecf457b 100644 --- a/data/search.json +++ b/data/search.json @@ -1 +1 @@ -{"list":[{"title":"module:core","link":"core","description":"

Builtin functions

\n

The core namespace is not an actual module but refers to the set of\nbuiltin functions and properties available to ucode scripts.

"},{"title":"module:core#arrtoip","link":"arrtoip","description":"

Convert the given input array of byte values to an IP address string.

\n

Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16\nto IPv6 ones. All other lengths are rejected. If any array element is not an\ninteger or exceeds the range 0..255 (inclusive), the array is rejected.

\n

Returns a string containing the formatted IP address.\nReturns null if the input array was invalid.

"},{"title":"module:core#assert","link":"assert","description":"

Raise an exception with the given message parameter when the value in cond\nis not truish.

\n

When message is omitted, the default value is Assertion failed.

"},{"title":"module:core#b64dec","link":"b64dec","description":"

Decodes the given base64 encoded string and returns the decoded result.

\n"},{"title":"module:core#b64enc","link":"b64enc","description":"

Encodes the given string into base64 and returns the resulting string.

\n"},{"title":"module:core#call","link":"call","description":"

Calls the given function value with a modified environment.

\n

The given ctx argument is used as this context for the invoked function\nand the given scope value as global environment. Any further arguments are\npassed to the invoked function as-is.

\n

When ctx is omitted or null, the function will get invoked with this\nbeing null.

\n

When scope is omitted or null, the function will get executed with the\ncurrent global environment of the running program. When scope is set to a\ndictionary, the dictionary is used as global function environment.

\n

When the scope dictionary has no prototype, the current global environment\nwill be set as prototype, means the scope will inherit from it.

\n

When a scope prototype is set, it is kept. This allows passing an isolated\n(sandboxed) function scope without access to the global environment.

\n

Any further argument is forwarded as-is to the invoked function as function\ncall argument.

\n

Returns null if the given function value fn is not callable.

\n

Returns the return value of the invoked function in all other cases.

\n

Forwards exceptions thrown by the invoked function.

"},{"title":"module:core#chr","link":"chr","description":"

Converts each given numeric value to a byte and return the resulting string.\nInvalid numeric values or values < 0 result in \\0 bytes, values larger than\n255 are truncated to 255.

\n

Returns a new strings consisting of the given byte values.

"},{"title":"module:core#clock","link":"clock","description":"

Reads the current second and microsecond value of the system clock.

\n

By default, the realtime clock is queried which might skew forwards or\nbackwards due to NTP changes, system sleep modes etc. If a truish value is\npassed as argument, the monotonic system clock is queried instead, which will\nreturn the monotonically increasing time since some arbitrary point in the\npast (usually the system boot time).

\n

Returns a two element array containing the full seconds as the first element\nand the nanosecond fraction as the second element.

\n

Returns null if a monotonic clock value is requested and the system does\nnot implement this clock type.

"},{"title":"module:core#die","link":"die","description":"

Raise an exception with the given message and abort execution.

"},{"title":"module:core#exists","link":"exists","description":"

Check whether the given key exists within the given object value.

\n

Returns true if the given key is present within the object passed as the\nfirst argument, otherwise false.

"},{"title":"module:core#exit","link":"exit","description":"

Terminate the interpreter with the given exit code.

\n

This function does not return.

"},{"title":"module:core#filter","link":"filter","description":"

Filter the array passed as the first argument by invoking the function\nspecified in the second argument for each array item.

\n

If the invoked function returns a truthy result, the item is retained,\notherwise, it is dropped. The filter function is invoked with three\narguments:

\n
    \n
  1. The array value
  2. \n
  3. The current index
  4. \n
  5. The array being filtered
  6. \n
\n

Returns a new array containing only retainted items, in the same order as\nthe input array.

"},{"title":"module:core#gc","link":"gc","description":"

Interacts with the mark and sweep garbage collector of the running ucode\nvirtual machine.

\n

Depending on the given operation string argument, the meaning of argument\nand the function return value differs.

\n

The following operations are defined:

\n\n

If the operation argument is omitted, the default is collect.

"},{"title":"module:core#getenv","link":"getenv","description":"

Query an environment variable or then entire environment.

\n

Returns the value of the given environment variable, or - if omitted - a\ndictionary containing all environment variables.

"},{"title":"module:core#gmtime","link":"gmtime","description":"

Like localtime() but interpreting the given epoch value as UTC time.

\n

See localtime() for details on the return value.

"},{"title":"module:core#hex","link":"hex","description":"

Converts the given hexadecimal string into a number.

\n

Returns the resulting integer value or NaN if the input value cannot be\ninterpreted as hexadecimal number.

"},{"title":"module:core#hexdec","link":"hexdec","description":"

Decodes the given hexadecimal digit string into a byte string, optionally\nskipping specified characters.

\n

If the characters to skip are not specified, a default of " \\t\\n" is used.

\n

Returns null if the input string contains invalid characters or an uneven\namount of hex digits.

\n

Returns the decoded byte string on success.

"},{"title":"module:core#hexenc","link":"hexenc","description":"

Encodes the given byte string into a hexadecimal digit string, converting\nthe input value to a string if needed.

"},{"title":"module:core#include","link":"include","description":"

Evaluate and include the file at the given path and optionally override the\nexecution scope with the given scope object.

\n

By default, the file is executed within the same scope as the calling\ninclude(), but by passing an object as the second argument, it is possible\nto extend the scope available to the included file.

\n

This is useful to supply additional properties as global variables to the\nincluded code. To sandbox included code, that is giving it only access to\nexplicitly provided properties, the proto() function can be used to create\na scope object with an empty prototype.

"},{"title":"module:core#index","link":"index","description":"

Finds the given value passed as the second argument within the array or\nstring specified in the first argument.

\n

Returns the first matching array index or first matching string offset or\n-1 if the value was not found.

\n

Returns null if the first argument was neither an array nor a string.

"},{"title":"module:core#int","link":"int","description":"

Converts the given value to an integer.

\n

Returns NaN if the value is not convertible.

"},{"title":"module:core#iptoarr","link":"iptoarr","description":"

Convert the given IP address string to an array of byte values.

\n

IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays\ncontaining 16 intergers. The resulting array can be turned back into IP\naddress strings using the inverse arrtoip() function.

\n

Returns an array containing the address byte values.\nReturns null if the given argument is not a string or an invalid IP.

"},{"title":"module:core#join","link":"join","description":"

Joins the array passed as the second argument into a string, using the\nseparator passed in the first argument as glue.

\n

Returns null if the second argument is not an array.

"},{"title":"module:core#json","link":"json","description":"

Parse the given string or resource as JSON and return the resulting value.

\n

If the input argument is a plain string, it is directly parsed as JSON.

\n

If an array, object or resource value is given, this function will attempt to\ninvoke a read() method on it to read chunks of input text to incrementally\nparse as JSON data. Reading will stop if the object's read() method returns\neither null or an empty string.

\n

Throws an exception on parse errors, trailing garbage, or premature EOF.

\n

Returns the parsed JSON data.

"},{"title":"module:core#keys","link":"keys","description":"

Enumerates all object key names.

\n

Returns an array of all key names present in the passed object.\nReturns null if the given argument is not an object.

"},{"title":"module:core#lc","link":"lc","description":"

Convert the given string to lowercase and return the resulting string.

\n

Returns null if the given argument could not be converted to a string.

"},{"title":"module:core#length","link":"length","description":"

Determine the length of the given object, array or string.

\n

Returns the length of the given value.

\n\n

Returns null if the given argument is not an object, array or string.

"},{"title":"module:core#loadfile","link":"loadfile","description":"

Compiles the given file into a ucode program and returns the resulting\nprogram entry function.

\n

See loadstring() for details.

\n

Returns the compiled program entry function.

\n

Throws an exception on compilation or file I/O errors.

"},{"title":"module:core#loadstring","link":"loadstring","description":"

Compiles the given code string into a ucode program and returns the resulting\nprogram entry function.

\n

The optional options dictionary overrides parse and compile options.

\n\n

The following keys in the options dictionary are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
KeyTypeDescription
lstrip_blocksboolStrip leading whitespace before statement template blocks
trim_blocksboolStrip newline after statement template blocks
strict_declarationsboolTreat access to undefined variables as fatal error
raw_modeboolCompile source in script mode, don't treat it as template
module_search_patharrayOverride compile time module search path
force_dynlink_listarrayList of module names to treat as dynamic extensions
\n

Unrecognized keys are ignored, unspecified options default to those of the\nrunning program.

\n

Returns the compiled program entry function.

\n

Throws an exception on compilation errors.

"},{"title":"module:core#localtime","link":"localtime","description":"

Return the given epoch timestamp (or now, if omitted) as a dictionary\ncontaining broken-down date and time information according to the local\nsystem timezone.

\n

The resulting dictionary contains the following fields:

\n\n

Note that in contrast to the underlying localtime(3) C library function,\nthe values for mon, wday, and yday are 1-based, and the year is\n1900-based.

"},{"title":"module:core#ltrim","link":"ltrim","description":"

Trim any of the specified characters from the start of the string.\nIf the second argument is omitted, trims the characters (space), '\\t',\n'\\r', and '\\n'.

\n

Returns the left trimmed string.

"},{"title":"module:core#map","link":"map","description":"

Transform the array passed as the first argument by invoking the function\nspecified in the second argument for each array item.

\n

Returns a new array of the same length as the input array containing the\ntransformed values.

"},{"title":"module:core#match","link":"match","description":"

Match the given string against the regular expression pattern specified as\nthe second argument.

\n

If the passed regular expression uses the g flag, the return value will be\nan array of arrays describing all found occurrences within the string.

\n

Without the g modifier, an array describing the first match is returned.

\n

Returns null if the pattern was not found within the given string.

"},{"title":"module:core#max","link":"max","description":"

Return the largest value among all parameters passed to the function.

"},{"title":"module:core#min","link":"min","description":"

Return the smallest value among all parameters passed to the function.

"},{"title":"module:core#ord","link":"ord","description":"

Without further arguments, this function returns the byte value of the first\ncharacter in the given string.

\n

If an offset argument is supplied, the byte value of the character at this\nposition is returned. If an invalid index is supplied, the function will\nreturn null. Negative index entries are counted towards the end of the\nstring, e.g. -2 will return the value of the second last character.

\n

Returns the byte value of the character.\nReturns null if the offset is invalid or if the input is not a string.

"},{"title":"module:core#pop","link":"pop","description":"

Pops the first item from the given array and returns it.

\n

Returns null if the array was empty or if a non-array argument was passed.

"},{"title":"module:core#print","link":"print","description":"

Print any of the given values to stdout.

\n

The print() function writes a string representation of each given argument\nto stdout and returns the amount of bytes written.

\n

String values are printed as-is, integer and double values are printed in\ndecimal notation, boolean values are printed as true or false while\narrays and objects are converted to their JSON representation before being\nwritten to the standard output. The null value is represented by an empty\nstring so print(null) would print nothing. Resource values are printed in\nthe form <type address>, e.g. <fs.file 0x7f60f0981760>.

\n

If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.

\n

Examples:

\n
print(1 != 2);                       // Will print 'true'\nprint(0xff);                         // Will print '255'\nprint(2e3);                          // Will print '2000'\nprint(null);                         // Will print nothing\nprint({ hello: true, world: 123 });  // Will print '{ "hello": true, "world": 123 }'\nprint([1,2,3]);                      // Will print '[ 1, 2, 3 ]'\n\nprint(proto({ foo: "bar" },          // Will print 'MyObj'\n  { tostring: () => "MyObj" }));     // instead of '{ "foo": "bar" }'\n\n
\n

Returns the amount of bytes printed.

"},{"title":"module:core#printf","link":"printf","description":"

Formats the given arguments according to the given format string and outputs\nthe result to stdout.

\n

Ucode supports a restricted subset of the formats allowed by the underlying\nlibc's printf() implementation, namely it allows the d, i, o, u,\nx, X, e, E, f, F, g, G, c and s conversions.

\n

Additionally, an ucode specific J format is implemented, which causes the\ncorresponding value to be formatted as JSON string. By prefixing the J\nformat letter with a precision specifier, the resulting JSON output will be\npretty printed. A precision of 0 will use tabs for indentation, any other\npositive precision will use that many spaces for indentation while a negative\nor omitted precision specifier will turn off pretty printing.

\n

Other format specifiers such as n or z are not accepted and returned\nverbatim. Format specifiers including * directives are rejected as well.

\n

Returns the number of bytes written to the standard output.

"},{"title":"module:core#proto","link":"proto","description":"

Get or set the prototype of the array or object value val.

\n

When invoked without a second argument, the function returns the current\nprototype of the value in val or null if there is no prototype or if the\ngiven value is neither an object nor an array.

\n

When invoked with a second prototype argument, the given proto value is set\nas the prototype on the array or object in val.

\n

Throws an exception if the given prototype value is not an object.

"},{"title":"module:core#push","link":"push","description":"

Pushes the given argument(s) to the given array.

\n

Returns the last pushed value.

"},{"title":"module:core#regexp","link":"regexp","description":"

Construct a regular expression instance from the given source pattern\nstring and any flags optionally specified by the flags argument.

\n\n

Returns the compiled regular expression value.

"},{"title":"module:core#render","link":"render","description":"

When invoked with a string value as the first argument, the function acts\nlike include() but captures the output of the included file as a string and\nreturns the captured contents.

\n

The second argument is treated as the scope.

\n

When invoked with a function value as the first argument, render() calls\nthe given function and passes all subsequent arguments to it.

\n

Any output produced by the called function is captured and returned as a\nstring. The return value of the called function is discarded.

"},{"title":"module:core#replace","link":"replace","description":"

Replace occurrences of the specified pattern in the string passed as the\nfirst argument.

\n\n

Returns a new string with the pattern replaced.

"},{"title":"module:core#reverse","link":"reverse","description":"

Reverse the order of the given input array or string.

\n

If an array is passed, returns the array in reverse order.\nIf a string is passed, returns the string with the sequence of the characters\nreversed.

\n

Returns the reversed array or string.\nReturns null if neither an array nor a string were passed.

"},{"title":"module:core#rindex","link":"rindex","description":"

Finds the given value passed as the second argument within the array or\nstring specified in the first argument.

\n

Returns the last matching array index or last matching string offset or\n-1 if the value was not found.

\n

Returns null if the first argument was neither an array nor a string.

"},{"title":"module:core#rtrim","link":"rtrim","description":"

Trim any of the specified characters from the end of the string.\nIf the second argument is omitted, trims the characters (space), '\\t',\n'\\r', and '\\n'.

\n

Returns the right trimmed string.

"},{"title":"module:core#shift","link":"shift","description":"

Pops the first item from the given array and returns it.

\n

Returns null if the array was empty or if a non-array argument was passed.

"},{"title":"module:core#signal","link":"signal","description":"

Set or query process signal handler function.

\n

When invoked with two arguments, a signal specification and a signal handler\nvalue, this function configures a new process signal handler.

\n

When invoked with one argument, a signal specification, this function returns\nthe currently configured handler for the given signal.

\n

The signal specification might either be an integer signal number or a string\nvalue containing a signal name (with or without "SIG" prefix). Signal names\nare treated case-insensitively.

\n

The signal handler might be either a callable function value or one of the\ntwo special string values "ignore" and "default". Passing "ignore" will\nmask the given process signal while "default" will restore the operating\nsystems default behaviour for the given signal.

\n

In case a callable handler function is provided, it is invoked at the\nearliest opportunity after receiving the corresponding signal from the\noperating system. The invoked function will receive a single argument, the\nnumber of the signal it is invoked for.

\n

Note that within the ucode VM, process signals are not immediately delivered,\ninstead the VM keeps track of received signals and delivers them to the ucode\nscript environment at the next opportunity, usually before executing the next\nbyte code instruction. This means that if a signal is received while\nperforming a computationally expensive operation in C mode, such as a complex\nregexp match, the corresponding ucode signal handler will only be invoked\nafter that operation concluded and control flow returns to the VM.

\n

Returns the signal handler function or one of the special values "ignore"\nor "default" corresponding to the given signal specification.

\n

Returns null if an invalid signal spec or signal handler was provided.

\n

Returns null if changing the signal action failed, e.g. due to insufficient\npermission, or when attempting to ignore a non-ignorable signal.

"},{"title":"module:core#sleep","link":"sleep","description":"

Pause execution for the given amount of milliseconds.

"},{"title":"module:core#slice","link":"slice","description":"

Performs a shallow copy of a portion of the source array, as specified by\nthe start and end offsets. The original array is not modified.

\n

Returns a new array containing the copied elements, if any.\nReturns null if the given source argument is not an array value.

"},{"title":"module:core#sort","link":"sort","description":"

Sort the given array according to the given sort function.\nIf no sort function is provided, a default ascending sort order is applied.

\n

The input array is sorted in-place, no copy is made.

\n

The custom sort function is repeatedly called until the entire array is\nsorted. It will receive two values as arguments and should return a value\nlower than, larger than or equal to zero depending on whether the first\nargument is smaller, larger or equal to the second argument respectively.

\n

Returns the sorted input array.

"},{"title":"module:core#sourcepath","link":"sourcepath","description":"

Determine the path of the source file currently being executed by ucode.

"},{"title":"module:core#splice","link":"splice","description":"

Removes the elements designated by off and len from the given array,\nand replaces them with the additional arguments passed, if any.

\n

The array grows or shrinks as necessary.

\n

Returns the modified input array.

"},{"title":"module:core#split","link":"split","description":"

Split the given string using the separator passed as the second argument\nand return an array containing the resulting pieces.

\n

If a limit argument is supplied, the resulting array contains no more than\nthe given amount of entries, that means the string is split at most\nlimit - 1 times total.

\n

The separator may either be a plain string or a regular expression.

\n

Returns a new array containing the resulting pieces.

"},{"title":"module:core#sprintf","link":"sprintf","description":"

Formats the given arguments according to the given format string.

\n

See printf() for details.

\n

Returns the formatted string.

"},{"title":"module:core#substr","link":"substr","description":"

Extracts a substring out of str and returns it. First character is at\noffset zero.

\n\n

Returns the extracted substring.

"},{"title":"module:core#system","link":"system","description":"

Executes the given command, waits for completion, and returns the resulting\nexit code.

\n

The command argument may be either a string, in which case it is passed to\n/bin/sh -c, or an array, which is directly converted into an execv()\nargument vector.

\n\n

Omitting the timeout argument or passing 0 disables the command timeout.

\n

Returns the program exit code.

"},{"title":"module:core#time","link":"time","description":"

Returns the current UNIX epoch.

"},{"title":"module:core#timegm","link":"timegm","description":"

Like timelocal() but interpreting the given date time specification as UTC\ntime.

\n

See timelocal() for details.

"},{"title":"module:core#timelocal","link":"timelocal","description":"

Performs the inverse operation of localtime() by taking a broken-down date\nand time dictionary and transforming it into an epoch value according to the\nlocal system timezone.

\n

The wday and yday fields of the given date time specification are\nignored. Field values outside of their valid range are internally normalized,\ne.g. October 40th is interpreted as November 9th.

\n

Returns the resulting epoch value or null if the input date time dictionary\nwas invalid or if the date time specification cannot be represented as epoch\nvalue.

"},{"title":"module:core#trace","link":"trace","description":"

Enables or disables VM opcode tracing.

\n

When invoked with a positive non-zero level, opcode tracing is enabled and\ndebug information is printed to stderr as the program is executed.

\n

Invoking trace() with zero as an argument turns off opcode tracing.

"},{"title":"module:core#trim","link":"trim","description":"

Trim any of the specified characters in c from the start and end of str.\nIf the second argument is omitted, trims the characters, (space), \\t,\n\\r, and \\n.

\n

Returns the trimmed string.

"},{"title":"module:core#type","link":"type","description":"

Query the type of the given value.

\n

Returns the type of the given value as a string which might be one of\n"function", "object", "array", "double", "int", or "bool".

\n

Returns null when no value or null is passed.

"},{"title":"module:core#uc","link":"uc","description":"

Converts the given string to uppercase and returns the resulting string.

\n

Returns null if the given argument could not be converted to a string.

"},{"title":"module:core#uchr","link":"uchr","description":"

Converts each given numeric value to an UTF-8 multibyte sequence and returns\nthe resulting string.

\n

Invalid numeric values or values outside the range 0..0x10FFFF are\nrepresented by the unicode replacement character 0xFFFD.

\n

Returns a new UTF-8 encoded string consisting of unicode characters\ncorresponding to the given numeric codepoints.

"},{"title":"module:core#uniq","link":"uniq","description":"

Returns a new array containing all unique values of the given input array.

\n"},{"title":"module:core#unshift","link":"unshift","description":"

Add the given values to the beginning of the array passed via first argument.

\n

Returns the last value added to the array.

"},{"title":"module:core#values","link":"values","description":"

Returns an array containing all values of the given object.

\n

Returns null if no object was passed.

"},{"title":"module:core#warn","link":"warn","description":"

Print any of the given values to stderr. Arrays and objects are converted to\ntheir JSON representation.

\n

Returns the amount of bytes printed.

"},{"title":"module:core#wildcard","link":"wildcard","description":"

Match the given subject against the supplied wildcard (file glob) pattern.

\n\n

Returns true when the value matched the given pattern, otherwise false.

"},{"title":"module:debug","link":"debug","description":"

Debugger Module

\n

This module provides runtime debug functionality for ucode scripts.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { memdump, traceback } from 'debug';\n\nlet stacktrace = traceback(1);\n\nmemdump("/tmp/dump.txt");\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as debug from 'debug';\n\nlet stacktrace = debug.traceback(1);\n\ndebug.memdump("/tmp/dump.txt");\n
\n

Additionally, the debug module namespace may also be imported by invoking the\nucode interpreter with the -ldebug switch.

\n

Upon loading, the debug module will register a SIGUSR2 signal handler\nwhich, upon receipt of the signal, will write a memory dump of the currently\nrunning program to /tmp/ucode.$timestamp.$pid.memdump. This default\nbehavior can be inhibited by setting the UCODE_DEBUG_MEMDUMP_ENABLED\nenvironment variable to 0 when starting the process. The memory dump signal\nand output directory can be overridden with the UCODE_DEBUG_MEMDUMP_SIGNAL\nand UCODE_DEBUG_MEMDUMP_PATH environment variables respectively.

"},{"title":"module:debug#getinfo","link":"getinfo","description":"

Obtain information about the given value.

\n

The getinfo() function allows querying internal information about the\ngiven ucode value, such as the current reference count, the mark bit state\netc.

\n

Returns a dictionary with value type specific details.

\n

Returns null if a null value was provided.

"},{"title":"module:debug#getlocal","link":"getlocal","description":"

Obtain local variable.

\n

The getlocal() function retrieves information about the specified local\nvariable at the given call stack depth.

\n

The call stack depth specifies the amount of levels up local variables should\nbe queried. A value of 0 refers to this getlocal() function call itself,\n1 to the function calling getlocal() and so on.

\n

The variable to query might be either specified by name or by its index with\nindex numbers following the source code declaration order.

\n

Returns a dictionary holding information about the given variable.

\n

Returns null if the stack depth exceeds the size of the current call stack.

\n

Returns null if the invocation at the given stack depth is a C call.

\n

Returns null if the given variable name is not found or the given variable\nindex is invalid.

"},{"title":"module:debug#getupval","link":"getupval","description":"

Obtain captured variable (upvalue).

\n

The getupval() function retrieves information about the specified captured\nvariable associated with the given function value or the invoked function at\nthe given call stack depth.

\n

The call stack depth specifies the amount of levels up the function should be\nselected to query associated captured variables for. A value of 0 refers to\nthis getupval() function call itself, 1 to the function calling\ngetupval() and so on.

\n

The variable to query might be either specified by name or by its index with\nindex numbers following the source code declaration order.

\n

Returns a dictionary holding information about the given variable.

\n

Returns null if the given function value is not a closure.

\n

Returns null if the stack depth exceeds the size of the current call stack.

\n

Returns null if the invocation at the given stack depth is not a closure.

\n

Returns null if the given variable name is not found or the given variable\nindex is invalid.

"},{"title":"module:debug#memdump","link":"memdump","description":"

Write a memory dump report to the given file.

\n

This function generates a human readable memory dump of ucode values\ncurrently managed by the running VM which is useful to track down logical\nmemory leaks in scripts.

\n

The file parameter can be either a string value containing a file path, in\nwhich case this function tries to create and write the report file at the\ngiven location, or an already open file handle this function should write to.

\n

Returns true if the report has been written.

\n

Returns null if the file could not be opened or if the handle was invalid.

"},{"title":"module:debug#setlocal","link":"setlocal","description":"

Set local variable.

\n

The setlocal() function manipulates the value of the specified local\nvariable at the given call stack depth.

\n

The call stack depth specifies the amount of levels up local variables should\nbe updated. A value of 0 refers to this setlocal() function call itself,\n1 to the function calling setlocal() and so on.

\n

The variable to update might be either specified by name or by its index with\nindex numbers following the source code declaration order.

\n

Returns a dictionary holding information about the updated variable.

\n

Returns null if the stack depth exceeds the size of the current call stack.

\n

Returns null if the invocation at the given stack depth is a C call.

\n

Returns null if the given variable name is not found or the given variable\nindex is invalid.

"},{"title":"module:debug#setupval","link":"setupval","description":"

Set upvalue.

\n

The setupval() function manipulates the value of the specified captured\nvariable associated with the given function value or the invoked function at\nthe given call stack depth.

\n

The call stack depth specifies the amount of levels up the function should be\nselected to update associated captured variables for. A value of 0 refers\nto this setupval() function call itself, 1 to the function calling\nsetupval() and so on.

\n

The variable to update might be either specified by name or by its index with\nindex numbers following the source code declaration order.

\n

Returns a dictionary holding information about the updated variable.

\n

Returns null if the given function value is not a closure.

\n

Returns null if the stack depth exceeds the size of the current call stack.

\n

Returns null if the invocation at the given stack depth is not a closure.

\n

Returns null if the given variable name is not found or the given variable\nindex is invalid.

"},{"title":"module:debug#sourcepos","link":"sourcepos","description":"

Obtain information about the current source position.

\n

The sourcepos() function determines the source code position of the\ncurrent instruction invoking this function.

\n

Returns a dictionary containing the filename, line number and line byte\noffset of the call site.

\n

Returns null if this function was invoked from C code.

"},{"title":"module:debug#traceback","link":"traceback","description":"

Capture call stack trace.

\n

This function captures the current call stack and returns it. The optional\nlevel parameter controls how many calls up the trace should start. It\ndefaults to 1, that is the function calling this traceback() function.

\n

Returns an array of stack trace entries describing the function invocations\nup to the point where traceback() is called.

"},{"title":"module:debug.LocalInfo","link":"LocalInfo"},{"title":"module:debug.SourcePosition","link":"SourcePosition"},{"title":"module:debug.StackTraceEntry","link":"StackTraceEntry"},{"title":"module:debug.UpvalInfo","link":"UpvalInfo"},{"title":"module:debug.UpvalRef","link":"UpvalRef"},{"title":"module:debug.ValueInformation","link":"ValueInformation"},{"title":"module:fs","link":"fs","description":"

Filesystem Access

\n

The fs module provides functions for interacting with the file system.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { readlink, popen } from 'fs';\n\nlet dest = readlink('/sys/class/net/eth0');\nlet proc = popen('ps ww');\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as fs from 'fs';\n\nlet dest = fs.readlink('/sys/class/net/eth0');\nlet proc = fs.popen('ps ww');\n
\n

Additionally, the filesystem module namespace may also be imported by invoking\nthe ucode interpreter with the -lfs switch.

"},{"title":"module:fs#access","link":"access","description":"

Checks the accessibility of a file or directory.

\n

The optional modes argument specifies the access modes which should be\nchecked. A file is only considered accessible if all access modes specified\nin the modes argument are possible.

\n

The following modes are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Tests whether the file is readable.
"w"Tests whether the file is writable.
"x"Tests whether the file is executable.
"f"Tests whether the file exists.
\n

Returns true if the given path is accessible or false when it is not.

\n

Returns null if an error occurred, e.g. due to inaccessible intermediate\npath components, invalid path arguments etc.

"},{"title":"module:fs#basename","link":"basename","description":"

Retrieves the base name of a path.

\n

Returns the base name component of the specified path.

\n

Returns null if the path argument is not a string.

"},{"title":"module:fs#chdir","link":"chdir","description":"

Changes the current working directory to the specified path.

\n

Returns true if the permission change was successful.

\n

Returns null if an error occurred, e.g. due to insufficient permissions or\ninvalid arguments.

"},{"title":"module:fs#chmod","link":"chmod","description":"

Changes the permission mode bits of a file or directory.

\n

Returns true if the permission change was successful.

\n

Returns null if an error occurred, e.g. due to insufficient permissions or\ninvalid arguments.

"},{"title":"module:fs#chown","link":"chown","description":"

Changes the owner and group of a file or directory.

\n

The user and group may be specified either as uid or gid number respectively,\nor as a string containing the user or group name, in which case it is\nresolved to the proper uid/gid first.

\n

If either the user or group parameter is omitted or given as -1,\nit is not changed.

\n

Returns true if the ownership change was successful.

\n

Returns null if an error occurred or if a user/group name cannot be\nresolved to a uid/gid value.

"},{"title":"module:fs#dirname","link":"dirname","description":"

Retrieves the directory name of a path.

\n

Returns the directory name component of the specified path.

\n

Returns null if the path argument is not a string.

"},{"title":"module:fs#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs#fdopen","link":"fdopen","description":"

Associates a file descriptor number with a file handle object.

\n

The mode argument controls how the file handle object is opened\nand must match the open mode of the underlying descriptor.

\n

It may be set to one of the following values:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Opens a file stream for reading. The file descriptor must be valid and opened in read mode.
"w"Opens a file stream for writing. The file descriptor must be valid and opened in write mode.
"a"Opens a file stream for appending. The file descriptor must be valid and opened in write mode.
"r+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"w+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"a+"Opens a file stream for both reading and appending. The file descriptor must be valid and opened in read/write mode.
\n

Returns the file handle object associated with the file descriptor.

"},{"title":"module:fs#getcwd","link":"getcwd","description":"

Retrieves the current working directory.

\n

Returns a string containing the current working directory path.

\n

Returns null if an error occurred.

"},{"title":"module:fs#lsdir","link":"lsdir","description":"

Lists the content of a directory.

\n

Returns a sorted array of the names of files and directories in the specified\ndirectory.

\n

Returns null if an error occurred, e.g. if the specified directory cannot\nbe opened.

"},{"title":"module:fs#lstat","link":"lstat","description":"

Retrieves information about a file or directory, without following symbolic\nlinks.

\n

Returns an object containing information about the file or directory.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#mkdir","link":"mkdir","description":"

Creates a new directory.

\n

Returns true if the directory was successfully created.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#mkstemp","link":"mkstemp","description":"

Creates a unique, ephemeral temporary file.

\n

Creates a new temporary file, opens it in read and write mode, unlinks it and\nreturns a file handle object referring to the yet open but deleted file.

\n

Upon closing the handle, the associated file will automatically vanish from\nthe system.

\n

The optional path template argument may be used to override the path and name\nchosen for the temporary file. If the path template contains no path element,\n/tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is\nappended to it. The XXXXXX sequence is replaced with a random value\nensuring uniqueness of the temporary file name.

\n

Returns a file handle object referring to the ephemeral file on success.

\n

Returns null if an error occurred, e.g. on insufficient permissions or\ninaccessible directory.

"},{"title":"module:fs#open","link":"open","description":"

Opens a file.

\n

The mode argument specifies the way the file is opened, it may\nstart with one of the following values:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Opens a file for reading. The file must exist.
"w"Opens a file for writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a"Opens a file for appending. Data is written at the end of the file. If the file does not exist, it is created.
"r+"Opens a file for both reading and writing. The file must exist.
"w+"Opens a file for both reading and writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a+"Opens a file for both reading and appending. Data can be read and written at the end of the file. If the file does not exist, it is created.
\n

Additionally, the following flag characters may be appended to\nthe mode value:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FlagDescription
"x"Opens a file for exclusive creation. If the file exists, the open call fails.
"e"Opens a file with the O_CLOEXEC flag set, ensuring that the file descriptor is closed on exec calls.
\n

If the mode is one of "w…" or "a…", the permission argument\ncontrols the filesystem permissions bits used when creating\nthe file.

\n

Returns a file handle object associated with the opened file.

"},{"title":"module:fs#opendir","link":"opendir","description":"

Opens a directory and returns a directory handle associated with the open\ndirectory descriptor.

\n

Returns a director handle referring to the open directory.

\n

Returns null if an error occurred.

"},{"title":"module:fs#pipe","link":"pipe","description":"

Creates a pipe and returns file handle objects associated with the read- and\nwrite end of the pipe respectively.

\n

Returns a two element array containing both a file handle object open in read\nmode referring to the read end of the pipe and a file handle object open in\nwrite mode referring to the write end of the pipe.

\n

Returns null if an error occurred.

"},{"title":"module:fs#popen","link":"popen","description":"

Starts a process and returns a handle representing the executed process.

\n

The handle will be connected to the process stdin or stdout, depending on the\nvalue of the mode argument.

\n

The mode argument may be either "r" to open the process for reading (connect\nto its stdin) or "w" to open the process for writing (connect to its stdout).

\n

The mode character "r" or "w" may be optionally followed by "e" to apply the\nFD_CLOEXEC flag onto the open descriptor.

\n

Returns a process handle referring to the executed process.

\n

Returns null if an error occurred.

"},{"title":"module:fs#readfile","link":"readfile","description":"

Reads the content of a file, optionally limited to the given amount of bytes.

\n

Returns a string containing the file contents.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#readlink","link":"readlink","description":"

Reads the target path of a symbolic link.

\n

Returns a string containing the target path.

\n

Returns null if an error occurred.

"},{"title":"module:fs#realpath","link":"realpath","description":"

Resolves the absolute path of a file or directory.

\n

Returns a string containing the resolved path.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#rename","link":"rename","description":"

Renames or moves a file or directory.

\n

Returns true if the rename operation was successful.

\n

Returns null if an error occurred.

"},{"title":"module:fs#rmdir","link":"rmdir","description":"

Removes the specified directory.

\n

Returns true if the directory was successfully removed.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#stat","link":"stat","description":"

Retrieves information about a file or directory.

\n

Returns an object containing information about the file or directory.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#symlink","link":"symlink","description":"

Creates a new symbolic link.

\n

Returns true if the symlink was successfully created.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#unlink","link":"unlink","description":"

Removes the specified file or symbolic link.

\n

Returns true if the unlink operation was successful.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#writefile","link":"writefile","description":"

Writes the given data to a file, optionally truncated to the given amount\nof bytes.

\n

In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written into the file. The null value is\nrepresented by an empty string so writefile(…, null) would write an empty\nfile. Resource values are written in the form <type address>, e.g.\n<fs.file 0x7f60f0981760>.

\n

If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.

\n

If a file already exists at the given path, it is truncated. If no file\nexists, it is created with default permissions 0o666 masked by the currently\neffective umask.

\n

Returns the number of bytes written.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs.FileStatResult","link":"FileStatResult"},{"title":"module:fs.dir","link":"dir","description":"

Represents a handle for interacting with a directory opened by opendir().

"},{"title":"module:fs.dir#close","link":"close","description":"

Closes the directory handle.

\n

Closes the underlying file descriptor referring to the opened directory.

\n

Returns true if the handle was properly closed.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.dir#read","link":"read","description":"

Read the next entry from the open directory.

\n

Returns a string containing the entry name.

\n

Returns null if there are no more entries to read.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#seek","link":"seek","description":"

Set read position.

\n

Sets the read position within the open directory handle to the given offset\nvalue. The offset value should be obtained by a previous call to tell() as\nthe specific integer values are implementation defined.

\n

Returns true if the read position was set.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#tell","link":"tell","description":"

Obtain current read position.

\n

Returns the current read position in the open directory handle which can be\npassed back to the seek() function to return to this position. This is\nmainly useful to read an open directory handle (or specific items) multiple\ntimes.

\n

Returns an integer referring to the current position.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file","link":"file","description":"

Represents a handle for interacting with a file opened by one of the file\nopen functions.

"},{"title":"module:fs.file#close","link":"close","description":"

Closes the file handle.

\n

Upon calling close() on the handle, buffered data is flushed and the\nunderlying file descriptor is closed.

\n

Returns true if the handle was properly closed.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.file#fileno","link":"fileno","description":"

Obtains the number of the handle's underlying file descriptor.

\n

Returns the descriptor number.

\n

Returns null on error.

"},{"title":"module:fs.file#flush","link":"flush","description":"

Forces a write of all buffered data to the underlying handle.

\n

Returns true if the data was successfully flushed.

\n

Returns null on error.

"},{"title":"module:fs.file#isatty","link":"isatty","description":"

Check for TTY.

\n

Checks whether the open file handle refers to a TTY (terminal) device.

\n

Returns true if the handle refers to a terminal.

\n

Returns false if the handle refers to another kind of file.

\n

Returns null on error.

"},{"title":"module:fs.file#read","link":"read","description":"

Reads a chunk of data from the file handle.

\n

The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.

\n\n

Returns a string containing the read data.

\n

Returns an empty string on EOF.

\n

Returns null if a read error occurred.

"},{"title":"module:fs.file#seek","link":"seek","description":"

Set file read position.

\n

Set the read position of the open file handle to the given offset and\nposition.

\n

Returns true if the read position was set.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#tell","link":"tell","description":"

Obtain current read position.

\n

Obtains the current, absolute read position of the open file.

\n

Returns an integer containing the current read offset in bytes.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#write","link":"write","description":"

Writes a chunk of data to the file handle.

\n

In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written. The null value is represented by an\nempty string so file.write(null) would be a no-op. Resource values are\nwritten in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

\n

If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.

\n

Returns the number of bytes written.

\n

Returns null if a write error occurred.

"},{"title":"module:fs.proc","link":"proc","description":"

Represents a handle for interacting with a program launched by popen().

"},{"title":"module:fs.proc#close","link":"close","description":"

Closes the program handle and awaits program termination.

\n

Upon calling close() on the handle, the program's input or output stream\n(depending on the open mode) is closed. Afterwards, the function awaits the\ntermination of the underlying program and returns its exit code.

\n\n

Returns a negative signal number if the program was terminated by a signal.

\n

Returns a positive exit code if the program terminated normally.

\n

Returns null if an error occurred.

"},{"title":"module:fs.proc#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.proc#fileno","link":"fileno","description":"

Obtains the number of the handle's underlying file descriptor.

\n

Returns the descriptor number.

\n

Returns null on error.

"},{"title":"module:fs.proc#flush","link":"flush","description":"

Forces a write of all buffered data to the underlying handle.

\n

Returns true if the data was successfully flushed.

\n

Returns null on error.

"},{"title":"module:fs.proc#read","link":"read","description":"

Reads a chunk of data from the program handle.

\n

The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.

\n\n

Returns a string containing the read data.

\n

Returns an empty string on EOF.

\n

Returns null if a read error occurred.

"},{"title":"module:fs.proc#write","link":"write","description":"

Writes a chunk of data to the program handle.

\n

In case the given data is not a string, it is converted to a string before\nbeing written to the program's stdin. String values are written as-is,\ninteger and double values are written in decimal notation, boolean values are\nwritten as true or false while arrays and objects are converted to their\nJSON representation before being written. The null value is represented by\nan empty string so proc.write(null) would be a no-op. Resource values are\nwritten in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

\n

If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.

\n

Returns the number of bytes written.

\n

Returns null if a write error occurred.

"},{"title":"module:log","link":"log","description":"

System logging functions

\n

The log module provides bindings to the POSIX syslog functions openlog(),\nsyslog() and closelog() as well as - when available - the OpenWrt\nspecific ulog library functions.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';\n\nopenlog("my-log-ident", LOG_PID, LOG_USER);\nsyslog(LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nimport { ulog_open, ulog, ULOG_SYSLOG, LOG_DAEMON, LOG_INFO } from 'log';\n\nulog_open(ULOG_SYSLOG, LOG_DAEMON, "my-log-ident");\nulog(LOG_INFO, "The current epoch is %d", time());\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as log from 'log';\n\nlog.openlog("my-log-ident", log.LOG_PID, log.LOG_USER);\nlog.syslog(log.LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nlog.ulog_open(log.ULOG_SYSLOG, log.LOG_DAEMON, "my-log-ident");\nlog.ulog(log.LOG_INFO, "The current epoch is %d", time());\n
\n

Additionally, the log module namespace may also be imported by invoking the\nucode interpreter with the -llog switch.

\n

Constants

\n

The log module declares a number of numeric constants to specify logging\nfacility, priority and option values, as well as ulog specific channels.

\n

Syslog Options

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_PIDInclude PID with each message.
LOG_CONSLog to console if error occurs while sending to syslog.
LOG_NDELAYOpen the connection to the logger immediately.
LOG_ODELAYDelay open until the first message is logged.
LOG_NOWAITDo not wait for child processes created during logging.
\n

Syslog Facilities

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_AUTHAuthentication/authorization messages.
LOG_AUTHPRIVPrivate authentication messages.
LOG_CRONClock daemon (cron and at commands).
LOG_DAEMONSystem daemons without separate facility values.
LOG_FTPFTP server daemon.
LOG_KERNKernel messages.
LOG_LPRLine printer subsystem.
LOG_MAILMail system.
LOG_NEWSNetwork news subsystem.
LOG_SYSLOGMessages generated internally by syslogd.
LOG_USERGeneric user-level messages.
LOG_UUCPUUCP subsystem.
LOG_LOCAL0Local use 0 (custom facility).
LOG_LOCAL1Local use 1 (custom facility).
LOG_LOCAL2Local use 2 (custom facility).
LOG_LOCAL3Local use 3 (custom facility).
LOG_LOCAL4Local use 4 (custom facility).
LOG_LOCAL5Local use 5 (custom facility).
LOG_LOCAL6Local use 6 (custom facility).
LOG_LOCAL7Local use 7 (custom facility).
\n

Syslog Priorities

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_EMERGSystem is unusable.
LOG_ALERTAction must be taken immediately.
LOG_CRITCritical conditions.
LOG_ERRError conditions.
LOG_WARNINGWarning conditions.
LOG_NOTICENormal, but significant, condition.
LOG_INFOInformational message.
LOG_DEBUGDebug-level message.
\n

Ulog channels

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
ULOG_KMSGLog messages to /dev/kmsg (dmesg).
ULOG_STDIOLog messages to stdout.
ULOG_SYSLOGLog messages to syslog.
"},{"title":"module:log#ERR","link":"ERR","description":"

Invoke ulog with LOG_ERR.

\n

This function is convenience wrapper for ulog(LOG_ERR, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#INFO","link":"INFO","description":"

Invoke ulog with LOG_INFO.

\n

This function is convenience wrapper for ulog(LOG_INFO, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#NOTE","link":"NOTE","description":"

Invoke ulog with LOG_NOTICE.

\n

This function is convenience wrapper for ulog(LOG_NOTICE, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#WARN","link":"WARN","description":"

Invoke ulog with LOG_WARNING.

\n

This function is convenience wrapper for ulog(LOG_WARNING, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#closelog","link":"closelog","description":"

Close connection to system logger.

\n

The usage of this function is optional, and usually an explicit log\nconnection tear down is not required.

"},{"title":"module:log#openlog","link":"openlog","description":"

Open connection to system logger.

\n

The openlog() function instructs the program to establish a connection to\nthe system log service and configures the default facility and identification\nfor use in subsequent log operations. It may be omitted, in which case the\nfirst call to syslog() will implicitly call openlog() with a default\nident value representing the program name and a default LOG_USER facility.

\n

The log option argument may be either a single string value containing an\noption name, an array of option name strings or a numeric value representing\na bitmask of LOG_* option constants.

\n

The facility argument may be either a single string value containing a\nfacility name or one of the numeric LOG_* facility constants in the module\nnamespace.

\n

Returns true if the system openlog() function was invoked.

\n

Returns false if an invalid argument, such as an unrecognized option or\nfacility name, was provided.

"},{"title":"module:log#syslog","link":"syslog","description":"

Log a message to the system logger.

\n

This function logs a message to the system logger. The function behaves in a\nsprintf-like manner, allowing the use of format strings and associated\narguments to construct log messages.

\n

If the openlog function has not been called explicitly before, syslog()\nimplicitly calls openlog(), using a default ident and LOG_USER facility\nvalue before logging the message.

\n

If the format argument is not a string and not null, it will be\nimplicitly converted to a string and logged as-is, without further format\nstring processing.

\n

Returns true if a message was passed to the system syslog() function.

\n

Returns false if an invalid priority value or an empty message was given.

"},{"title":"module:log#ulog","link":"ulog","description":"

Log a message via the ulog mechanism.

\n

The ulog() function outputs the given log message to all configured ulog\nchannels unless the given priority level exceeds the globally configured ulog\npriority threshold. See {@link module:log#ulog_threshold|ulog_threshold()}\nfor details.

\n

The ulog() function is OpenWrt specific and may not be present on other\nsystems. Use syslog() instead for portability to non-OpenWrt environments.

\n

Like syslog(), the function behaves in a sprintf-like manner, allowing the\nuse of format strings and associated arguments to construct log messages.

\n

If the ulog_open() function has not been called explicitly before, ulog()\nimplicitly configures certain defaults, see\n{@link module:log#ulog_open|ulog_open()} for a detailled description.

\n

If the format argument is not a string and not null, it will be\nimplicitly converted to a string and logged as-is, without further format\nstring processing.

\n

Returns true if a message was passed to the underlying ulog() function.

\n

Returns false if an invalid priority value or an empty message was given.

"},{"title":"module:log#ulog_close","link":"ulog_close","description":"

Close ulog logger.

\n

Resets the ulog channels, the default facility and the log ident value to\ndefaults.

\n

In case the "syslog" channel has been configured, the underlying\ncloselog() function will be invoked.

\n

The usage of this function is optional, and usually an explicit ulog teardown\nis not required.

\n

The ulog_close() function is OpenWrt specific and may not be present on\nother systems. Use closelog() in conjunction with syslog() instead for\nportability to non-OpenWrt environments.

"},{"title":"module:log#ulog_open","link":"ulog_open","description":"

Configure ulog logger.

\n

This functions configures the ulog mechanism and is analogeous to using the\nopenlog() function in conjuncton with syslog().

\n

The ulog_open() function is OpenWrt specific and may not be present on\nother systems. Use openlog() and syslog() instead for portability to\nnon-OpenWrt environments.

\n

A program may use multiple channels to simultaneously output messages using\ndifferent means. The channel argument may either be a single string value\ncontaining a channel name, an array of channel names or a numeric value\nrepresenting a bitmask of ULOG_* channel constants.

\n

The facility argument may be either a single string value containing a\nfacility name or one of the numeric LOG_* facility constants in the module\nnamespace.

\n

The default facility value varies, depending on the execution context of the\nprogram. In OpenWrt's preinit boot phase, or when stdout is not connected to\nan interactive terminal, the facility defaults to "daemon" (LOG_DAEMON),\notherwise to "user" (LOG_USER).

\n

Likewise, the default channel is selected depending on the context. During\nOpenWrt's preinit boot phase, the "kmsg" channel is used, for interactive\nterminals the "stdio" one and for all other cases the "syslog" channel\nis selected.

\n

Returns true if ulog was configured.

\n

Returns false if an invalid argument, such as an unrecognized channel or\nfacility name, was provided.

"},{"title":"module:log#ulog_threshold","link":"ulog_threshold","description":"

Set ulog priority threshold.

\n

This function configures the application wide log message threshold for log\nmessages emitted with ulog(). Any message with a priority higher (= less\nsevere) than the threshold priority will be discarded. This is useful to\nimplement application wide verbosity settings without having to wrap ulog()\ninvocations into a helper function or guarding code.

\n

When no explicit threshold has been set, LOG_DEBUG is used by default,\nallowing log messages with all known priorities.

\n

The ulog_threshold() function is OpenWrt specific and may not be present on\nother systems. There is no syslog equivalent to this ulog specific threshold\nmechanism.

\n

The priority argument may be either a string value containing a priority name\nor one of the numeric LOG_* priority constants in the module namespace.

\n

Returns true if a threshold was set.

\n

Returns false if an invalid priority value was given.

"},{"title":"module:log.LogFacility","link":"LogFacility","description":"

The following log facility strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FacilityDescription
"auth"Authentication/authorization messages.
"authpriv"Private authentication messages.
"cron"Clock daemon (cron and at commands).
"daemon"System daemons without separate facility values.
"ftp"FTP server daemon.
"kern"Kernel messages.
"lpr"Line printer subsystem.
"mail"Mail system.
"news"Network news subsystem.
"syslog"Messages generated internally by syslogd.
"user"Generic user-level messages.
"uucp"UUCP subsystem.
"local0"Local use 0 (custom facility).
"local1"Local use 1 (custom facility).
"local2"Local use 2 (custom facility).
"local3"Local use 3 (custom facility).
"local4"Local use 4 (custom facility).
"local5"Local use 5 (custom facility).
"local6"Local use 6 (custom facility).
"local7"Local use 7 (custom facility).
"},{"title":"module:log.LogOption","link":"LogOption","description":"

The following log option strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Log OptionDescription
"pid"Include PID with each message.
"cons"Log to console if an error occurs while sending to syslog.
"ndelay"Open the connection to the logger immediately.
"odelay"Delay open until the first message is logged.
"nowait"Do not wait for child processes created during logging.
"},{"title":"module:log.LogPriority","link":"LogPriority","description":"

The following log priority strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
PriorityDescription
"emerg"System is unusable.
"alert"Action must be taken immediately.
"crit"Critical conditions.
"err"Error conditions.
"warning"Warning conditions.
"notice"Normal, but significant, condition.
"info"Informational message.
"debug"Debug-level message.
"},{"title":"module:log.UlogChannel","link":"UlogChannel","description":"

The following ulog channel strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ChannelDescription
"kmsg"Log to /dev/kmsg, log messages appear in dmesg.
"syslog"Use standard syslog() mechanism.
"stdio"Use stderr for log output.
"},{"title":"module:math","link":"math","description":"

Mathematical Functions

\n

The math module bundles various mathematical and trigonometrical functions.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { pow, rand } from 'math';\n\nlet x = pow(2, 5);\nlet y = rand();\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as math from 'math';\n\nlet x = math.pow(2, 5);\nlet y = math.rand();\n
\n

Additionally, the math module namespace may also be imported by invoking the\nucode interpreter with the -lmath switch.

"},{"title":"module:math#abs","link":"abs","description":"

Returns the absolute value of the given numeric value.

"},{"title":"module:math#atan2","link":"atan2","description":"

Calculates the principal value of the arc tangent of y/x,\nusing the signs of the two arguments to determine the quadrant\nof the result.

\n

On success, this function returns the principal value of the arc\ntangent of y/x in radians; the return value is in the range [-pi, pi].

\n\n

When either x or y can't be converted to a numeric value, NaN is\nreturned.

"},{"title":"module:math#cos","link":"cos","description":"

Calculates the cosine of x, where x is given in radians.

\n

Returns the resulting consine value.

\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#exp","link":"exp","description":"

Calculates the value of e (the base of natural logarithms)\nraised to the power of x.

\n

On success, returns the exponential value of x.

\n\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#isnan","link":"isnan","description":"

Tests whether x is a NaN double.

\n

This functions checks whether the given argument is of type double with\na NaN (not a number) value.

\n

Returns true if the value is NaN, otherwise false.

\n

Note that a value can also be checked for NaN with the expression\nx !== x which only evaluates to true if x is NaN.

"},{"title":"module:math#log","link":"log","description":"

Calculates the natural logarithm of x.

\n

On success, returns the natural logarithm of x.

\n\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#pow","link":"pow","description":"

Calculates the value of x raised to the power of y.

\n

On success, returns the value of x raised to the power of y.

\n\n

Returns NaN if either the x or y value can't be converted to a number.

"},{"title":"module:math#rand","link":"rand","description":"

Produces a pseudo-random positive integer.

\n

Returns the calculated pseuo-random value. The value is within the range\n0 to RAND_MAX inclusive where RAND_MAX is a platform specific value\nguaranteed to be at least 32767.

\n

The {@link module:math~srand srand()} function sets its argument as the\nseed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are\nrepeatable by calling {@link module:math~srand srand()} with the same\nseed value.

\n

If no seed value is explicitly set by calling\n{@link module:math~srand srand()} prior to the first call to rand(),\nthe math module will automatically seed the PRNG once, using the current\ntime of day in milliseconds as seed value.

"},{"title":"module:math#sin","link":"sin","description":"

Calculates the sine of x, where x is given in radians.

\n

Returns the resulting sine value.

\n\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#sqrt","link":"sqrt","description":"

Calculates the nonnegative square root of x.

\n

Returns the resulting square root value.

\n\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#srand","link":"srand","description":"

Seeds the pseudo-random number generator.

\n

This functions seeds the PRNG with the given value and thus affects the\npseudo-random integer sequence produced by subsequent calls to\n{@link module:math~rand rand()}.

\n

Setting the same seed value will result in the same pseudo-random numbers\nproduced by {@link module:math~rand rand()}.

"},{"title":"module:struct","link":"struct","description":"

Handle Packed Binary Data

\n

The struct module provides routines for interpreting byte strings as packed\nbinary data.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { pack, unpack } from 'struct';\n\nlet buffer = pack('bhl', -13, 1234, 444555666);\nlet values = unpack('bhl', buffer);\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as struct from 'struct';\n\nlet buffer = struct.pack('bhl', -13, 1234, 444555666);\nlet values = struct.unpack('bhl', buffer);\n
\n

Additionally, the struct module namespace may also be imported by invoking\nthe ucode interpreter with the -lstruct switch.

\n

Format Strings

\n

Format strings describe the data layout when packing and unpacking data.\nThey are built up from format-characters, which specify the type of data\nbeing packed/unpacked. In addition, special characters control the byte\norder, size and alignment.

\n

Each format string consists of an optional prefix character which describes\nthe overall properties of the data and one or more format characters which\ndescribe the actual data values and padding.

\n

Byte Order, Size, and Alignment

\n

By default, C types are represented in the machine's native format and byte\norder, and properly aligned by skipping pad bytes if necessary (according to\nthe rules used by the C compiler).

\n

This behavior is chosen so that the bytes of a packed struct correspond\nexactly to the memory layout of the corresponding C struct.

\n

Whether to use native byte ordering and padding or standard formats depends\non the application.

\n

Alternatively, the first character of the format string can be used to indicate\nthe byte order, size and alignment of the packed data, according to the\nfollowing table:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
CharacterByte orderSizeAlignment
@nativenativenative
=nativestandardnone
<little-endianstandardnone
>big-endianstandardnone
!network (= big-endian)standardnone
\n

If the first character is not one of these, '@' is assumed.

\n

Native byte order is big-endian or little-endian, depending on the\nhost system. For example, Intel x86, AMD64 (x86-64), and Apple M1 are\nlittle-endian; IBM z and many legacy architectures are big-endian.

\n

Native size and alignment are determined using the C compiler's\nsizeof expression. This is always combined with native byte order.

\n

Standard size depends only on the format character; see the table in\nthe format-characters section.

\n

Note the difference between '@' and '=': both use native byte order,\nbut the size and alignment of the latter is standardized.

\n

The form '!' represents the network byte order which is always big-endian\nas defined in IETF RFC 1700.

\n

There is no way to indicate non-native byte order (force byte-swapping); use\nthe appropriate choice of '<' or '>'.

\n

Notes:

\n

(1) Padding is only automatically added between successive structure members.\nNo padding is added at the beginning or the end of the encoded struct.

\n

(2) No padding is added when using non-native size and alignment, e.g.\nwith '<', '>', '=', and '!'.

\n

(3) To align the end of a structure to the alignment requirement of a\nparticular type, end the format with the code for that type with a repeat\ncount of zero.

\n

Format Characters

\n

Format characters have the following meaning; the conversion between C and\nucode values should be obvious given their types. The 'Standard size' column\nrefers to the size of the packed value in bytes when using standard size;\nthat is, when the format string starts with one of '<', '>', '!' or\n'='. When using native size, the size of the packed value is platform\ndependent.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FormatC TypeUcode typeStandard sizeNotes
xpad byteno value(7)
ccharstring1
bsigned charint1(1), (2)
Bunsigned charint1(2)
?_Boolbool1(1)
hshortint2(2)
Hunsigned shortint2(2)
iintint4(2)
Iunsigned intint4(2)
llongint4(2)
Lunsigned longint4(2)
qlong longint8(2)
Qunsigned long longint8(2)
nssize_tint(3)
Nsize_tint(3)
e(6)double2(4)
ffloatdouble4(4)
ddoubledouble8(4)
schar[]double(9)
pchar[]double(8)
Pvoid *int(5)
*char[]string(10)
\n

Notes:

\n\n

A format character may be preceded by an integral repeat count. For example,\nthe format string '4h' means exactly the same as 'hhhh'.

\n

Whitespace characters between formats are ignored; a count and its format\nmust not contain whitespace though.

\n

When packing a value x using one of the integer formats ('b',\n'B', 'h', 'H', 'i', 'I', 'l', 'L',\n'q', 'Q'), if x is outside the valid range for that format, a type\nerror exception is raised.

\n

For the '?' format character, the return value is either true or false.\nWhen packing, the truish result value of the argument is used. Either 0 or 1\nin the native or standard bool representation will be packed, and any\nnon-zero value will be true when unpacking.

\n

Examples

\n

Note:\nNative byte order examples (designated by the '@' format prefix or\nlack of any prefix character) may not match what the reader's\nmachine produces as\nthat depends on the platform and compiler.

\n

Pack and unpack integers of three different sizes, using big endian\nordering:

\n
import { pack, unpack } from 'struct';\n\npack(">bhl", 1, 2, 3);  // "\\x01\\x00\\x02\\x00\\x00\\x00\\x03"\nunpack(">bhl", "\\x01\\x00\\x02\\x00\\x00\\x00\\x03");  // [ 1, 2, 3 ]\n
\n

Attempt to pack an integer which is too large for the defined field:

\n
$ ucode -lstruct -p 'struct.pack(">h", 99999)'\nType error: Format 'h' requires numeric argument between -32768 and 32767\nIn [-p argument], line 1, byte 24:\n\n `struct.pack(">h", 99999)`\n  Near here -------------^\n
\n

Demonstrate the difference between 's' and 'c' format characters:

\n
import { pack } from 'struct';\n\npack("@ccc", "1", "2", "3");  // "123"\npack("@3s", "123");           // "123"\n
\n

The ordering of format characters may have an impact on size in native\nmode since padding is implicit. In standard mode, the user is\nresponsible for inserting any desired padding.

\n

Note in the first pack() call below that three NUL bytes were added after\nthe packed '#' to align the following integer on a four-byte boundary.\nIn this example, the output was produced on a little endian machine:

\n
import { pack } from 'struct';\n\npack("@ci", "#", 0x12131415);  // "#\\x00\\x00\\x00\\x15\\x14\\x13\\x12"\npack("@ic", 0x12131415, "#");  // "\\x15\\x14\\x13\\x12#"\n
\n

The following format 'ih0i' results in two pad bytes being added at the\nend, assuming the platform's ints are aligned on 4-byte boundaries:

\n
import { pack } from 'struct';\n\npack("ih0i", 0x01010101, 0x0202);  // "\\x01\\x01\\x01\\x01\\x02\\x02\\x00\\x00"\n
\n

Use the wildcard format to extract the remainder of the input data:

\n
import { unpack } from 'struct';\n\nunpack("ccc*", "foobarbaz");   // [ "f", "o", "o", "barbaz" ]\nunpack("ccc3*", "foobarbaz");  // [ "f", "o", "o", "bar" ]\n
\n

Use the wildcard format to pack binary stings as-is into the result data:

\n
import { pack } from 'struct';\n\npack("h*h", 0x0101, "\\x02\\x00\\x03", 0x0404);  // "\\x01\\x01\\x02\\x00\\x03\\x04\\x04"\npack("c3*c", "a", "foobar", "c");  // "afooc"\n
"},{"title":"module:struct#new","link":"new","description":"

Precompile format string.

\n

The new() function precompiles the given format string argument and returns\na struct object instance useful for packing and unpacking multiple items\nwithout having to recompute the internal format each time.

\n

Returns an precompiled struct format instance.

\n

Raises a runtime exception if the format string is invalid.

"},{"title":"module:struct#pack","link":"pack","description":"

Pack given values according to specified format.

\n

The pack() function creates a byte string containing the argument values\npacked according to the given format string.

\n

Returns the packed string.

\n

Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive or if and invalid\nformat string is provided.

"},{"title":"module:struct#unpack","link":"unpack","description":"

Unpack given byte string according to specified format.

\n

The unpack() function interpretes a byte string according to the given\nformat string and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.

\n

Returns an array of unpacked values.

\n

Raises a runtime exception if the format string is invalid or if an invalid\ninput string or offset value is given.

"},{"title":"module:struct.instance","link":"instance","description":"

Represents a struct instance created by new().

"},{"title":"module:struct.instance#pack","link":"pack","description":"

Pack given values.

\n

The pack() function creates a byte string containing the argument values\npacked according to the given format instance.

\n

Returns the packed string.

\n

Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive.

"},{"title":"module:struct.instance#unpack","link":"unpack","description":"

Unpack given byte string.

\n

The unpack() function interpretes a byte string according to the given\nformat instance and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.

\n

Returns an array of unpacked values.

\n

Raises a runtime exception if an invalid input string or offset value is\ngiven.

"}]} \ No newline at end of file +{"list":[{"title":"module:core","link":"core","description":"

Builtin functions

\n

The core namespace is not an actual module but refers to the set of\nbuiltin functions and properties available to ucode scripts.

"},{"title":"module:core#arrtoip","link":"arrtoip","description":"

Convert the given input array of byte values to an IP address string.

\n

Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16\nto IPv6 ones. All other lengths are rejected. If any array element is not an\ninteger or exceeds the range 0..255 (inclusive), the array is rejected.

\n

Returns a string containing the formatted IP address.\nReturns null if the input array was invalid.

"},{"title":"module:core#assert","link":"assert","description":"

Raise an exception with the given message parameter when the value in cond\nis not truish.

\n

When message is omitted, the default value is Assertion failed.

"},{"title":"module:core#b64dec","link":"b64dec","description":"

Decodes the given base64 encoded string and returns the decoded result.

\n"},{"title":"module:core#b64enc","link":"b64enc","description":"

Encodes the given string into base64 and returns the resulting string.

\n"},{"title":"module:core#call","link":"call","description":"

Calls the given function value with a modified environment.

\n

The given ctx argument is used as this context for the invoked function\nand the given scope value as global environment. Any further arguments are\npassed to the invoked function as-is.

\n

When ctx is omitted or null, the function will get invoked with this\nbeing null.

\n

When scope is omitted or null, the function will get executed with the\ncurrent global environment of the running program. When scope is set to a\ndictionary, the dictionary is used as global function environment.

\n

When the scope dictionary has no prototype, the current global environment\nwill be set as prototype, means the scope will inherit from it.

\n

When a scope prototype is set, it is kept. This allows passing an isolated\n(sandboxed) function scope without access to the global environment.

\n

Any further argument is forwarded as-is to the invoked function as function\ncall argument.

\n

Returns null if the given function value fn is not callable.

\n

Returns the return value of the invoked function in all other cases.

\n

Forwards exceptions thrown by the invoked function.

"},{"title":"module:core#chr","link":"chr","description":"

Converts each given numeric value to a byte and return the resulting string.\nInvalid numeric values or values < 0 result in \\0 bytes, values larger than\n255 are truncated to 255.

\n

Returns a new strings consisting of the given byte values.

"},{"title":"module:core#clock","link":"clock","description":"

Reads the current second and microsecond value of the system clock.

\n

By default, the realtime clock is queried which might skew forwards or\nbackwards due to NTP changes, system sleep modes etc. If a truish value is\npassed as argument, the monotonic system clock is queried instead, which will\nreturn the monotonically increasing time since some arbitrary point in the\npast (usually the system boot time).

\n

Returns a two element array containing the full seconds as the first element\nand the nanosecond fraction as the second element.

\n

Returns null if a monotonic clock value is requested and the system does\nnot implement this clock type.

"},{"title":"module:core#die","link":"die","description":"

Raise an exception with the given message and abort execution.

"},{"title":"module:core#exists","link":"exists","description":"

Check whether the given key exists within the given object value.

\n

Returns true if the given key is present within the object passed as the\nfirst argument, otherwise false.

"},{"title":"module:core#exit","link":"exit","description":"

Terminate the interpreter with the given exit code.

\n

This function does not return.

"},{"title":"module:core#filter","link":"filter","description":"

Filter the array passed as the first argument by invoking the function\nspecified in the second argument for each array item.

\n

If the invoked function returns a truthy result, the item is retained,\notherwise, it is dropped. The filter function is invoked with three\narguments:

\n
    \n
  1. The array value
  2. \n
  3. The current index
  4. \n
  5. The array being filtered
  6. \n
\n

Returns a new array containing only retainted items, in the same order as\nthe input array.

"},{"title":"module:core#gc","link":"gc","description":"

Interacts with the mark and sweep garbage collector of the running ucode\nvirtual machine.

\n

Depending on the given operation string argument, the meaning of argument\nand the function return value differs.

\n

The following operations are defined:

\n\n

If the operation argument is omitted, the default is collect.

"},{"title":"module:core#getenv","link":"getenv","description":"

Query an environment variable or then entire environment.

\n

Returns the value of the given environment variable, or - if omitted - a\ndictionary containing all environment variables.

"},{"title":"module:core#gmtime","link":"gmtime","description":"

Like localtime() but interpreting the given epoch value as UTC time.

\n

See {@link module:core#localtime|localtime()} for details on the return value.

"},{"title":"module:core#hex","link":"hex","description":"

Converts the given hexadecimal string into a number.

\n

Returns the resulting integer value or NaN if the input value cannot be\ninterpreted as hexadecimal number.

"},{"title":"module:core#hexdec","link":"hexdec","description":"

Decodes the given hexadecimal digit string into a byte string, optionally\nskipping specified characters.

\n

If the characters to skip are not specified, a default of " \\t\\n" is used.

\n

Returns null if the input string contains invalid characters or an uneven\namount of hex digits.

\n

Returns the decoded byte string on success.

"},{"title":"module:core#hexenc","link":"hexenc","description":"

Encodes the given byte string into a hexadecimal digit string, converting\nthe input value to a string if needed.

"},{"title":"module:core#include","link":"include","description":"

Evaluate and include the file at the given path and optionally override the\nexecution scope with the given scope object.

\n

By default, the file is executed within the same scope as the calling\ninclude(), but by passing an object as the second argument, it is possible\nto extend the scope available to the included file.

\n

This is useful to supply additional properties as global variables to the\nincluded code. To sandbox included code, that is giving it only access to\nexplicitly provided properties, the proto() function can be used to create\na scope object with an empty prototype.

"},{"title":"module:core#index","link":"index","description":"

Finds the given value passed as the second argument within the array or\nstring specified in the first argument.

\n

Returns the first matching array index or first matching string offset or\n-1 if the value was not found.

\n

Returns null if the first argument was neither an array nor a string.

"},{"title":"module:core#int","link":"int","description":"

Converts the given value to an integer.

\n

Returns NaN if the value is not convertible.

"},{"title":"module:core#iptoarr","link":"iptoarr","description":"

Convert the given IP address string to an array of byte values.

\n

IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays\ncontaining 16 intergers. The resulting array can be turned back into IP\naddress strings using the inverse arrtoip() function.

\n

Returns an array containing the address byte values.\nReturns null if the given argument is not a string or an invalid IP.

"},{"title":"module:core#join","link":"join","description":"

Joins the array passed as the second argument into a string, using the\nseparator passed in the first argument as glue.

\n

Returns null if the second argument is not an array.

"},{"title":"module:core#json","link":"json","description":"

Parse the given string or resource as JSON and return the resulting value.

\n

If the input argument is a plain string, it is directly parsed as JSON.

\n

If an array, object or resource value is given, this function will attempt to\ninvoke a read() method on it to read chunks of input text to incrementally\nparse as JSON data. Reading will stop if the object's read() method returns\neither null or an empty string.

\n

Throws an exception on parse errors, trailing garbage, or premature EOF.

\n

Returns the parsed JSON data.

"},{"title":"module:core#keys","link":"keys","description":"

Enumerates all object key names.

\n

Returns an array of all key names present in the passed object.\nReturns null if the given argument is not an object.

"},{"title":"module:core#lc","link":"lc","description":"

Convert the given string to lowercase and return the resulting string.

\n

Returns null if the given argument could not be converted to a string.

"},{"title":"module:core#length","link":"length","description":"

Determine the length of the given object, array or string.

\n

Returns the length of the given value.

\n\n

Returns null if the given argument is not an object, array or string.

"},{"title":"module:core#loadfile","link":"loadfile","description":"

Compiles the given file into a ucode program and returns the resulting\nprogram entry function.

\n

See loadstring() for details.

\n

Returns the compiled program entry function.

\n

Throws an exception on compilation or file I/O errors.

"},{"title":"module:core#loadstring","link":"loadstring","description":"

Compiles the given code string into a ucode program and returns the resulting\nprogram entry function.

\n

The optional options dictionary overrides parse and compile options.

\n\n

The following keys in the options dictionary are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
KeyTypeDescription
lstrip_blocksboolStrip leading whitespace before statement template blocks
trim_blocksboolStrip newline after statement template blocks
strict_declarationsboolTreat access to undefined variables as fatal error
raw_modeboolCompile source in script mode, don't treat it as template
module_search_patharrayOverride compile time module search path
force_dynlink_listarrayList of module names to treat as dynamic extensions
\n

Unrecognized keys are ignored, unspecified options default to those of the\nrunning program.

\n

Returns the compiled program entry function.

\n

Throws an exception on compilation errors.

"},{"title":"module:core#localtime","link":"localtime","description":"

Return the given epoch timestamp (or now, if omitted) as a dictionary\ncontaining broken-down date and time information according to the local\nsystem timezone.

\n

See {@link module:core.TimeSpec|TimeSpec} for a description of the fields.

\n

Note that in contrast to the underlying localtime(3) C library function,\nthe values for mon, wday, and yday are 1-based, and the year is\n1900-based.

"},{"title":"module:core#ltrim","link":"ltrim","description":"

Trim any of the specified characters from the start of the string.\nIf the second argument is omitted, trims the characters (space), '\\t',\n'\\r', and '\\n'.

\n

Returns the left trimmed string.

"},{"title":"module:core#map","link":"map","description":"

Transform the array passed as the first argument by invoking the function\nspecified in the second argument for each array item.

\n

Returns a new array of the same length as the input array containing the\ntransformed values.

"},{"title":"module:core#match","link":"match","description":"

Match the given string against the regular expression pattern specified as\nthe second argument.

\n

If the passed regular expression uses the g flag, the return value will be\nan array of arrays describing all found occurrences within the string.

\n

Without the g modifier, an array describing the first match is returned.

\n

Returns null if the pattern was not found within the given string.

"},{"title":"module:core#max","link":"max","description":"

Return the largest value among all parameters passed to the function.

"},{"title":"module:core#min","link":"min","description":"

Return the smallest value among all parameters passed to the function.

"},{"title":"module:core#ord","link":"ord","description":"

Without further arguments, this function returns the byte value of the first\ncharacter in the given string.

\n

If an offset argument is supplied, the byte value of the character at this\nposition is returned. If an invalid index is supplied, the function will\nreturn null. Negative index entries are counted towards the end of the\nstring, e.g. -2 will return the value of the second last character.

\n

Returns the byte value of the character.\nReturns null if the offset is invalid or if the input is not a string.

"},{"title":"module:core#pop","link":"pop","description":"

Pops the first item from the given array and returns it.

\n

Returns null if the array was empty or if a non-array argument was passed.

"},{"title":"module:core#print","link":"print","description":"

Print any of the given values to stdout.

\n

The print() function writes a string representation of each given argument\nto stdout and returns the amount of bytes written.

\n

String values are printed as-is, integer and double values are printed in\ndecimal notation, boolean values are printed as true or false while\narrays and objects are converted to their JSON representation before being\nwritten to the standard output. The null value is represented by an empty\nstring so print(null) would print nothing. Resource values are printed in\nthe form <type address>, e.g. <fs.file 0x7f60f0981760>.

\n

If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.

\n

Examples:

\n
print(1 != 2);                       // Will print 'true'\nprint(0xff);                         // Will print '255'\nprint(2e3);                          // Will print '2000'\nprint(null);                         // Will print nothing\nprint({ hello: true, world: 123 });  // Will print '{ "hello": true, "world": 123 }'\nprint([1,2,3]);                      // Will print '[ 1, 2, 3 ]'\n\nprint(proto({ foo: "bar" },          // Will print 'MyObj'\n  { tostring: () => "MyObj" }));     // instead of '{ "foo": "bar" }'\n\n
\n

Returns the amount of bytes printed.

"},{"title":"module:core#printf","link":"printf","description":"

Formats the given arguments according to the given format string and outputs\nthe result to stdout.

\n

Ucode supports a restricted subset of the formats allowed by the underlying\nlibc's printf() implementation, namely it allows the d, i, o, u,\nx, X, e, E, f, F, g, G, c and s conversions.

\n

Additionally, an ucode specific J format is implemented, which causes the\ncorresponding value to be formatted as JSON string. By prefixing the J\nformat letter with a precision specifier, the resulting JSON output will be\npretty printed. A precision of 0 will use tabs for indentation, any other\npositive precision will use that many spaces for indentation while a negative\nor omitted precision specifier will turn off pretty printing.

\n

Other format specifiers such as n or z are not accepted and returned\nverbatim. Format specifiers including * directives are rejected as well.

\n

Returns the number of bytes written to the standard output.

"},{"title":"module:core#proto","link":"proto","description":"

Get or set the prototype of the array or object value val.

\n

When invoked without a second argument, the function returns the current\nprototype of the value in val or null if there is no prototype or if the\ngiven value is neither an object nor an array.

\n

When invoked with a second prototype argument, the given proto value is set\nas the prototype on the array or object in val.

\n

Throws an exception if the given prototype value is not an object.

"},{"title":"module:core#push","link":"push","description":"

Pushes the given argument(s) to the given array.

\n

Returns the last pushed value.

"},{"title":"module:core#regexp","link":"regexp","description":"

Construct a regular expression instance from the given source pattern\nstring and any flags optionally specified by the flags argument.

\n\n

Returns the compiled regular expression value.

"},{"title":"module:core#render","link":"render","description":"

When invoked with a string value as the first argument, the function acts\nlike include() but captures the output of the included file as a string and\nreturns the captured contents.

\n

The second argument is treated as the scope.

\n

When invoked with a function value as the first argument, render() calls\nthe given function and passes all subsequent arguments to it.

\n

Any output produced by the called function is captured and returned as a\nstring. The return value of the called function is discarded.

"},{"title":"module:core#replace","link":"replace","description":"

Replace occurrences of the specified pattern in the string passed as the\nfirst argument.

\n\n

Returns a new string with the pattern replaced.

"},{"title":"module:core#reverse","link":"reverse","description":"

Reverse the order of the given input array or string.

\n

If an array is passed, returns the array in reverse order.\nIf a string is passed, returns the string with the sequence of the characters\nreversed.

\n

Returns the reversed array or string.\nReturns null if neither an array nor a string were passed.

"},{"title":"module:core#rindex","link":"rindex","description":"

Finds the given value passed as the second argument within the array or\nstring specified in the first argument.

\n

Returns the last matching array index or last matching string offset or\n-1 if the value was not found.

\n

Returns null if the first argument was neither an array nor a string.

"},{"title":"module:core#rtrim","link":"rtrim","description":"

Trim any of the specified characters from the end of the string.\nIf the second argument is omitted, trims the characters (space), '\\t',\n'\\r', and '\\n'.

\n

Returns the right trimmed string.

"},{"title":"module:core#shift","link":"shift","description":"

Pops the first item from the given array and returns it.

\n

Returns null if the array was empty or if a non-array argument was passed.

"},{"title":"module:core#signal","link":"signal","description":"

Set or query process signal handler function.

\n

When invoked with two arguments, a signal specification and a signal handler\nvalue, this function configures a new process signal handler.

\n

When invoked with one argument, a signal specification, this function returns\nthe currently configured handler for the given signal.

\n

The signal specification might either be an integer signal number or a string\nvalue containing a signal name (with or without "SIG" prefix). Signal names\nare treated case-insensitively.

\n

The signal handler might be either a callable function value or one of the\ntwo special string values "ignore" and "default". Passing "ignore" will\nmask the given process signal while "default" will restore the operating\nsystems default behaviour for the given signal.

\n

In case a callable handler function is provided, it is invoked at the\nearliest opportunity after receiving the corresponding signal from the\noperating system. The invoked function will receive a single argument, the\nnumber of the signal it is invoked for.

\n

Note that within the ucode VM, process signals are not immediately delivered,\ninstead the VM keeps track of received signals and delivers them to the ucode\nscript environment at the next opportunity, usually before executing the next\nbyte code instruction. This means that if a signal is received while\nperforming a computationally expensive operation in C mode, such as a complex\nregexp match, the corresponding ucode signal handler will only be invoked\nafter that operation concluded and control flow returns to the VM.

\n

Returns the signal handler function or one of the special values "ignore"\nor "default" corresponding to the given signal specification.

\n

Returns null if an invalid signal spec or signal handler was provided.

\n

Returns null if changing the signal action failed, e.g. due to insufficient\npermission, or when attempting to ignore a non-ignorable signal.

"},{"title":"module:core#sleep","link":"sleep","description":"

Pause execution for the given amount of milliseconds.

"},{"title":"module:core#slice","link":"slice","description":"

Performs a shallow copy of a portion of the source array, as specified by\nthe start and end offsets. The original array is not modified.

\n

Returns a new array containing the copied elements, if any.\nReturns null if the given source argument is not an array value.

"},{"title":"module:core#sort","link":"sort","description":"

Sort the given array according to the given sort function.\nIf no sort function is provided, a default ascending sort order is applied.

\n

The input array is sorted in-place, no copy is made.

\n

The custom sort function is repeatedly called until the entire array is\nsorted. It will receive two values as arguments and should return a value\nlower than, larger than or equal to zero depending on whether the first\nargument is smaller, larger or equal to the second argument respectively.

\n

Returns the sorted input array.

"},{"title":"module:core#sourcepath","link":"sourcepath","description":"

Determine the path of the source file currently being executed by ucode.

"},{"title":"module:core#splice","link":"splice","description":"

Removes the elements designated by off and len from the given array,\nand replaces them with the additional arguments passed, if any.

\n

The array grows or shrinks as necessary.

\n

Returns the modified input array.

"},{"title":"module:core#split","link":"split","description":"

Split the given string using the separator passed as the second argument\nand return an array containing the resulting pieces.

\n

If a limit argument is supplied, the resulting array contains no more than\nthe given amount of entries, that means the string is split at most\nlimit - 1 times total.

\n

The separator may either be a plain string or a regular expression.

\n

Returns a new array containing the resulting pieces.

"},{"title":"module:core#sprintf","link":"sprintf","description":"

Formats the given arguments according to the given format string.

\n

See printf() for details.

\n

Returns the formatted string.

"},{"title":"module:core#substr","link":"substr","description":"

Extracts a substring out of str and returns it. First character is at\noffset zero.

\n\n

Returns the extracted substring.

"},{"title":"module:core#system","link":"system","description":"

Executes the given command, waits for completion, and returns the resulting\nexit code.

\n

The command argument may be either a string, in which case it is passed to\n/bin/sh -c, or an array, which is directly converted into an execv()\nargument vector.

\n\n

Omitting the timeout argument or passing 0 disables the command timeout.

\n

Returns the program exit code.

"},{"title":"module:core#time","link":"time","description":"

Returns the current UNIX epoch.

"},{"title":"module:core#timegm","link":"timegm","description":"

Like timelocal() but interpreting the given date time specification as UTC\ntime.

\n

See {@link module:core#timelocal|timelocal()} for details.

"},{"title":"module:core#timelocal","link":"timelocal","description":"

Performs the inverse operation of {@link module:core#localtime|localtime()}\nby taking a broken-down date and time dictionary and transforming it into an\nepoch value according to the local system timezone.

\n

The wday and yday fields of the given date time specification are\nignored. Field values outside of their valid range are internally normalized,\ne.g. October 40th is interpreted as November 9th.

\n

Returns the resulting epoch value or null if the input date time dictionary\nwas invalid or if the date time specification cannot be represented as epoch\nvalue.

"},{"title":"module:core#trace","link":"trace","description":"

Enables or disables VM opcode tracing.

\n

When invoked with a positive non-zero level, opcode tracing is enabled and\ndebug information is printed to stderr as the program is executed.

\n

Invoking trace() with zero as an argument turns off opcode tracing.

"},{"title":"module:core#trim","link":"trim","description":"

Trim any of the specified characters in c from the start and end of str.\nIf the second argument is omitted, trims the characters, (space), \\t,\n\\r, and \\n.

\n

Returns the trimmed string.

"},{"title":"module:core#type","link":"type","description":"

Query the type of the given value.

\n

Returns the type of the given value as a string which might be one of\n"function", "object", "array", "double", "int", or "bool".

\n

Returns null when no value or null is passed.

"},{"title":"module:core#uc","link":"uc","description":"

Converts the given string to uppercase and returns the resulting string.

\n

Returns null if the given argument could not be converted to a string.

"},{"title":"module:core#uchr","link":"uchr","description":"

Converts each given numeric value to an UTF-8 multibyte sequence and returns\nthe resulting string.

\n

Invalid numeric values or values outside the range 0..0x10FFFF are\nrepresented by the unicode replacement character 0xFFFD.

\n

Returns a new UTF-8 encoded string consisting of unicode characters\ncorresponding to the given numeric codepoints.

"},{"title":"module:core#uniq","link":"uniq","description":"

Returns a new array containing all unique values of the given input array.

\n"},{"title":"module:core#unshift","link":"unshift","description":"

Add the given values to the beginning of the array passed via first argument.

\n

Returns the last value added to the array.

"},{"title":"module:core#values","link":"values","description":"

Returns an array containing all values of the given object.

\n

Returns null if no object was passed.

"},{"title":"module:core#warn","link":"warn","description":"

Print any of the given values to stderr. Arrays and objects are converted to\ntheir JSON representation.

\n

Returns the amount of bytes printed.

"},{"title":"module:core#wildcard","link":"wildcard","description":"

Match the given subject against the supplied wildcard (file glob) pattern.

\n\n

Returns true when the value matched the given pattern, otherwise false.

"},{"title":"module:core.TimeSpec","link":"TimeSpec","description":"

A time spec is a plain object describing a point in time, it is returned by\nthe {@link module:core#gmtime|gmtime()} and\n{@link module:core#localtime|localtime()} functions and expected as parameter\nby the complementary {@link module:core#timegm|timegm()} and\n{@link module:core#timelocal|timelocal()} functions.

\n

When returned by gmtime() or localtime(), all members of the object will\nbe initialized, when passed as argument to timegm() or timelocal(), most\nmember values are optional.

"},{"title":"module:debug","link":"debug","description":"

Debugger Module

\n

This module provides runtime debug functionality for ucode scripts.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { memdump, traceback } from 'debug';\n\nlet stacktrace = traceback(1);\n\nmemdump("/tmp/dump.txt");\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as debug from 'debug';\n\nlet stacktrace = debug.traceback(1);\n\ndebug.memdump("/tmp/dump.txt");\n
\n

Additionally, the debug module namespace may also be imported by invoking the\nucode interpreter with the -ldebug switch.

\n

Upon loading, the debug module will register a SIGUSR2 signal handler\nwhich, upon receipt of the signal, will write a memory dump of the currently\nrunning program to /tmp/ucode.$timestamp.$pid.memdump. This default\nbehavior can be inhibited by setting the UCODE_DEBUG_MEMDUMP_ENABLED\nenvironment variable to 0 when starting the process. The memory dump signal\nand output directory can be overridden with the UCODE_DEBUG_MEMDUMP_SIGNAL\nand UCODE_DEBUG_MEMDUMP_PATH environment variables respectively.

"},{"title":"module:debug#getinfo","link":"getinfo","description":"

Obtain information about the given value.

\n

The getinfo() function allows querying internal information about the\ngiven ucode value, such as the current reference count, the mark bit state\netc.

\n

Returns a dictionary with value type specific details.

\n

Returns null if a null value was provided.

"},{"title":"module:debug#getlocal","link":"getlocal","description":"

Obtain local variable.

\n

The getlocal() function retrieves information about the specified local\nvariable at the given call stack depth.

\n

The call stack depth specifies the amount of levels up local variables should\nbe queried. A value of 0 refers to this getlocal() function call itself,\n1 to the function calling getlocal() and so on.

\n

The variable to query might be either specified by name or by its index with\nindex numbers following the source code declaration order.

\n

Returns a dictionary holding information about the given variable.

\n

Returns null if the stack depth exceeds the size of the current call stack.

\n

Returns null if the invocation at the given stack depth is a C call.

\n

Returns null if the given variable name is not found or the given variable\nindex is invalid.

"},{"title":"module:debug#getupval","link":"getupval","description":"

Obtain captured variable (upvalue).

\n

The getupval() function retrieves information about the specified captured\nvariable associated with the given function value or the invoked function at\nthe given call stack depth.

\n

The call stack depth specifies the amount of levels up the function should be\nselected to query associated captured variables for. A value of 0 refers to\nthis getupval() function call itself, 1 to the function calling\ngetupval() and so on.

\n

The variable to query might be either specified by name or by its index with\nindex numbers following the source code declaration order.

\n

Returns a dictionary holding information about the given variable.

\n

Returns null if the given function value is not a closure.

\n

Returns null if the stack depth exceeds the size of the current call stack.

\n

Returns null if the invocation at the given stack depth is not a closure.

\n

Returns null if the given variable name is not found or the given variable\nindex is invalid.

"},{"title":"module:debug#memdump","link":"memdump","description":"

Write a memory dump report to the given file.

\n

This function generates a human readable memory dump of ucode values\ncurrently managed by the running VM which is useful to track down logical\nmemory leaks in scripts.

\n

The file parameter can be either a string value containing a file path, in\nwhich case this function tries to create and write the report file at the\ngiven location, or an already open file handle this function should write to.

\n

Returns true if the report has been written.

\n

Returns null if the file could not be opened or if the handle was invalid.

"},{"title":"module:debug#setlocal","link":"setlocal","description":"

Set local variable.

\n

The setlocal() function manipulates the value of the specified local\nvariable at the given call stack depth.

\n

The call stack depth specifies the amount of levels up local variables should\nbe updated. A value of 0 refers to this setlocal() function call itself,\n1 to the function calling setlocal() and so on.

\n

The variable to update might be either specified by name or by its index with\nindex numbers following the source code declaration order.

\n

Returns a dictionary holding information about the updated variable.

\n

Returns null if the stack depth exceeds the size of the current call stack.

\n

Returns null if the invocation at the given stack depth is a C call.

\n

Returns null if the given variable name is not found or the given variable\nindex is invalid.

"},{"title":"module:debug#setupval","link":"setupval","description":"

Set upvalue.

\n

The setupval() function manipulates the value of the specified captured\nvariable associated with the given function value or the invoked function at\nthe given call stack depth.

\n

The call stack depth specifies the amount of levels up the function should be\nselected to update associated captured variables for. A value of 0 refers\nto this setupval() function call itself, 1 to the function calling\nsetupval() and so on.

\n

The variable to update might be either specified by name or by its index with\nindex numbers following the source code declaration order.

\n

Returns a dictionary holding information about the updated variable.

\n

Returns null if the given function value is not a closure.

\n

Returns null if the stack depth exceeds the size of the current call stack.

\n

Returns null if the invocation at the given stack depth is not a closure.

\n

Returns null if the given variable name is not found or the given variable\nindex is invalid.

"},{"title":"module:debug#sourcepos","link":"sourcepos","description":"

Obtain information about the current source position.

\n

The sourcepos() function determines the source code position of the\ncurrent instruction invoking this function.

\n

Returns a dictionary containing the filename, line number and line byte\noffset of the call site.

\n

Returns null if this function was invoked from C code.

"},{"title":"module:debug#traceback","link":"traceback","description":"

Capture call stack trace.

\n

This function captures the current call stack and returns it. The optional\nlevel parameter controls how many calls up the trace should start. It\ndefaults to 1, that is the function calling this traceback() function.

\n

Returns an array of stack trace entries describing the function invocations\nup to the point where traceback() is called.

"},{"title":"module:debug.LocalInfo","link":"LocalInfo"},{"title":"module:debug.SourcePosition","link":"SourcePosition"},{"title":"module:debug.StackTraceEntry","link":"StackTraceEntry"},{"title":"module:debug.UpvalInfo","link":"UpvalInfo"},{"title":"module:debug.UpvalRef","link":"UpvalRef"},{"title":"module:debug.ValueInformation","link":"ValueInformation"},{"title":"module:fs","link":"fs","description":"

Filesystem Access

\n

The fs module provides functions for interacting with the file system.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { readlink, popen } from 'fs';\n\nlet dest = readlink('/sys/class/net/eth0');\nlet proc = popen('ps ww');\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as fs from 'fs';\n\nlet dest = fs.readlink('/sys/class/net/eth0');\nlet proc = fs.popen('ps ww');\n
\n

Additionally, the filesystem module namespace may also be imported by invoking\nthe ucode interpreter with the -lfs switch.

"},{"title":"module:fs#access","link":"access","description":"

Checks the accessibility of a file or directory.

\n

The optional modes argument specifies the access modes which should be\nchecked. A file is only considered accessible if all access modes specified\nin the modes argument are possible.

\n

The following modes are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Tests whether the file is readable.
"w"Tests whether the file is writable.
"x"Tests whether the file is executable.
"f"Tests whether the file exists.
\n

Returns true if the given path is accessible or false when it is not.

\n

Returns null if an error occurred, e.g. due to inaccessible intermediate\npath components, invalid path arguments etc.

"},{"title":"module:fs#basename","link":"basename","description":"

Retrieves the base name of a path.

\n

Returns the base name component of the specified path.

\n

Returns null if the path argument is not a string.

"},{"title":"module:fs#chdir","link":"chdir","description":"

Changes the current working directory to the specified path.

\n

Returns true if the permission change was successful.

\n

Returns null if an error occurred, e.g. due to insufficient permissions or\ninvalid arguments.

"},{"title":"module:fs#chmod","link":"chmod","description":"

Changes the permission mode bits of a file or directory.

\n

Returns true if the permission change was successful.

\n

Returns null if an error occurred, e.g. due to insufficient permissions or\ninvalid arguments.

"},{"title":"module:fs#chown","link":"chown","description":"

Changes the owner and group of a file or directory.

\n

The user and group may be specified either as uid or gid number respectively,\nor as a string containing the user or group name, in which case it is\nresolved to the proper uid/gid first.

\n

If either the user or group parameter is omitted or given as -1,\nit is not changed.

\n

Returns true if the ownership change was successful.

\n

Returns null if an error occurred or if a user/group name cannot be\nresolved to a uid/gid value.

"},{"title":"module:fs#dirname","link":"dirname","description":"

Retrieves the directory name of a path.

\n

Returns the directory name component of the specified path.

\n

Returns null if the path argument is not a string.

"},{"title":"module:fs#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs#fdopen","link":"fdopen","description":"

Associates a file descriptor number with a file handle object.

\n

The mode argument controls how the file handle object is opened\nand must match the open mode of the underlying descriptor.

\n

It may be set to one of the following values:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Opens a file stream for reading. The file descriptor must be valid and opened in read mode.
"w"Opens a file stream for writing. The file descriptor must be valid and opened in write mode.
"a"Opens a file stream for appending. The file descriptor must be valid and opened in write mode.
"r+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"w+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"a+"Opens a file stream for both reading and appending. The file descriptor must be valid and opened in read/write mode.
\n

Returns the file handle object associated with the file descriptor.

"},{"title":"module:fs#getcwd","link":"getcwd","description":"

Retrieves the current working directory.

\n

Returns a string containing the current working directory path.

\n

Returns null if an error occurred.

"},{"title":"module:fs#lsdir","link":"lsdir","description":"

Lists the content of a directory.

\n

Returns a sorted array of the names of files and directories in the specified\ndirectory.

\n

Returns null if an error occurred, e.g. if the specified directory cannot\nbe opened.

"},{"title":"module:fs#lstat","link":"lstat","description":"

Retrieves information about a file or directory, without following symbolic\nlinks.

\n

Returns an object containing information about the file or directory.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#mkdir","link":"mkdir","description":"

Creates a new directory.

\n

Returns true if the directory was successfully created.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#mkstemp","link":"mkstemp","description":"

Creates a unique, ephemeral temporary file.

\n

Creates a new temporary file, opens it in read and write mode, unlinks it and\nreturns a file handle object referring to the yet open but deleted file.

\n

Upon closing the handle, the associated file will automatically vanish from\nthe system.

\n

The optional path template argument may be used to override the path and name\nchosen for the temporary file. If the path template contains no path element,\n/tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is\nappended to it. The XXXXXX sequence is replaced with a random value\nensuring uniqueness of the temporary file name.

\n

Returns a file handle object referring to the ephemeral file on success.

\n

Returns null if an error occurred, e.g. on insufficient permissions or\ninaccessible directory.

"},{"title":"module:fs#open","link":"open","description":"

Opens a file.

\n

The mode argument specifies the way the file is opened, it may\nstart with one of the following values:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Opens a file for reading. The file must exist.
"w"Opens a file for writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a"Opens a file for appending. Data is written at the end of the file. If the file does not exist, it is created.
"r+"Opens a file for both reading and writing. The file must exist.
"w+"Opens a file for both reading and writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a+"Opens a file for both reading and appending. Data can be read and written at the end of the file. If the file does not exist, it is created.
\n

Additionally, the following flag characters may be appended to\nthe mode value:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FlagDescription
"x"Opens a file for exclusive creation. If the file exists, the open call fails.
"e"Opens a file with the O_CLOEXEC flag set, ensuring that the file descriptor is closed on exec calls.
\n

If the mode is one of "w…" or "a…", the permission argument\ncontrols the filesystem permissions bits used when creating\nthe file.

\n

Returns a file handle object associated with the opened file.

"},{"title":"module:fs#opendir","link":"opendir","description":"

Opens a directory and returns a directory handle associated with the open\ndirectory descriptor.

\n

Returns a director handle referring to the open directory.

\n

Returns null if an error occurred.

"},{"title":"module:fs#pipe","link":"pipe","description":"

Creates a pipe and returns file handle objects associated with the read- and\nwrite end of the pipe respectively.

\n

Returns a two element array containing both a file handle object open in read\nmode referring to the read end of the pipe and a file handle object open in\nwrite mode referring to the write end of the pipe.

\n

Returns null if an error occurred.

"},{"title":"module:fs#popen","link":"popen","description":"

Starts a process and returns a handle representing the executed process.

\n

The handle will be connected to the process stdin or stdout, depending on the\nvalue of the mode argument.

\n

The mode argument may be either "r" to open the process for reading (connect\nto its stdin) or "w" to open the process for writing (connect to its stdout).

\n

The mode character "r" or "w" may be optionally followed by "e" to apply the\nFD_CLOEXEC flag onto the open descriptor.

\n

Returns a process handle referring to the executed process.

\n

Returns null if an error occurred.

"},{"title":"module:fs#readfile","link":"readfile","description":"

Reads the content of a file, optionally limited to the given amount of bytes.

\n

Returns a string containing the file contents.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#readlink","link":"readlink","description":"

Reads the target path of a symbolic link.

\n

Returns a string containing the target path.

\n

Returns null if an error occurred.

"},{"title":"module:fs#realpath","link":"realpath","description":"

Resolves the absolute path of a file or directory.

\n

Returns a string containing the resolved path.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#rename","link":"rename","description":"

Renames or moves a file or directory.

\n

Returns true if the rename operation was successful.

\n

Returns null if an error occurred.

"},{"title":"module:fs#rmdir","link":"rmdir","description":"

Removes the specified directory.

\n

Returns true if the directory was successfully removed.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#stat","link":"stat","description":"

Retrieves information about a file or directory.

\n

Returns an object containing information about the file or directory.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#symlink","link":"symlink","description":"

Creates a new symbolic link.

\n

Returns true if the symlink was successfully created.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#unlink","link":"unlink","description":"

Removes the specified file or symbolic link.

\n

Returns true if the unlink operation was successful.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#writefile","link":"writefile","description":"

Writes the given data to a file, optionally truncated to the given amount\nof bytes.

\n

In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written into the file. The null value is\nrepresented by an empty string so writefile(…, null) would write an empty\nfile. Resource values are written in the form <type address>, e.g.\n<fs.file 0x7f60f0981760>.

\n

If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.

\n

If a file already exists at the given path, it is truncated. If no file\nexists, it is created with default permissions 0o666 masked by the currently\neffective umask.

\n

Returns the number of bytes written.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs.FileStatResult","link":"FileStatResult"},{"title":"module:fs.dir","link":"dir","description":"

Represents a handle for interacting with a directory opened by opendir().

"},{"title":"module:fs.dir#close","link":"close","description":"

Closes the directory handle.

\n

Closes the underlying file descriptor referring to the opened directory.

\n

Returns true if the handle was properly closed.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.dir#read","link":"read","description":"

Read the next entry from the open directory.

\n

Returns a string containing the entry name.

\n

Returns null if there are no more entries to read.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#seek","link":"seek","description":"

Set read position.

\n

Sets the read position within the open directory handle to the given offset\nvalue. The offset value should be obtained by a previous call to tell() as\nthe specific integer values are implementation defined.

\n

Returns true if the read position was set.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#tell","link":"tell","description":"

Obtain current read position.

\n

Returns the current read position in the open directory handle which can be\npassed back to the seek() function to return to this position. This is\nmainly useful to read an open directory handle (or specific items) multiple\ntimes.

\n

Returns an integer referring to the current position.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file","link":"file","description":"

Represents a handle for interacting with a file opened by one of the file\nopen functions.

"},{"title":"module:fs.file#close","link":"close","description":"

Closes the file handle.

\n

Upon calling close() on the handle, buffered data is flushed and the\nunderlying file descriptor is closed.

\n

Returns true if the handle was properly closed.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.file#fileno","link":"fileno","description":"

Obtains the number of the handle's underlying file descriptor.

\n

Returns the descriptor number.

\n

Returns null on error.

"},{"title":"module:fs.file#flush","link":"flush","description":"

Forces a write of all buffered data to the underlying handle.

\n

Returns true if the data was successfully flushed.

\n

Returns null on error.

"},{"title":"module:fs.file#isatty","link":"isatty","description":"

Check for TTY.

\n

Checks whether the open file handle refers to a TTY (terminal) device.

\n

Returns true if the handle refers to a terminal.

\n

Returns false if the handle refers to another kind of file.

\n

Returns null on error.

"},{"title":"module:fs.file#read","link":"read","description":"

Reads a chunk of data from the file handle.

\n

The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.

\n\n

Returns a string containing the read data.

\n

Returns an empty string on EOF.

\n

Returns null if a read error occurred.

"},{"title":"module:fs.file#seek","link":"seek","description":"

Set file read position.

\n

Set the read position of the open file handle to the given offset and\nposition.

\n

Returns true if the read position was set.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#tell","link":"tell","description":"

Obtain current read position.

\n

Obtains the current, absolute read position of the open file.

\n

Returns an integer containing the current read offset in bytes.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#write","link":"write","description":"

Writes a chunk of data to the file handle.

\n

In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written. The null value is represented by an\nempty string so file.write(null) would be a no-op. Resource values are\nwritten in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

\n

If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.

\n

Returns the number of bytes written.

\n

Returns null if a write error occurred.

"},{"title":"module:fs.proc","link":"proc","description":"

Represents a handle for interacting with a program launched by popen().

"},{"title":"module:fs.proc#close","link":"close","description":"

Closes the program handle and awaits program termination.

\n

Upon calling close() on the handle, the program's input or output stream\n(depending on the open mode) is closed. Afterwards, the function awaits the\ntermination of the underlying program and returns its exit code.

\n\n

Returns a negative signal number if the program was terminated by a signal.

\n

Returns a positive exit code if the program terminated normally.

\n

Returns null if an error occurred.

"},{"title":"module:fs.proc#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.proc#fileno","link":"fileno","description":"

Obtains the number of the handle's underlying file descriptor.

\n

Returns the descriptor number.

\n

Returns null on error.

"},{"title":"module:fs.proc#flush","link":"flush","description":"

Forces a write of all buffered data to the underlying handle.

\n

Returns true if the data was successfully flushed.

\n

Returns null on error.

"},{"title":"module:fs.proc#read","link":"read","description":"

Reads a chunk of data from the program handle.

\n

The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.

\n\n

Returns a string containing the read data.

\n

Returns an empty string on EOF.

\n

Returns null if a read error occurred.

"},{"title":"module:fs.proc#write","link":"write","description":"

Writes a chunk of data to the program handle.

\n

In case the given data is not a string, it is converted to a string before\nbeing written to the program's stdin. String values are written as-is,\ninteger and double values are written in decimal notation, boolean values are\nwritten as true or false while arrays and objects are converted to their\nJSON representation before being written. The null value is represented by\nan empty string so proc.write(null) would be a no-op. Resource values are\nwritten in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

\n

If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.

\n

Returns the number of bytes written.

\n

Returns null if a write error occurred.

"},{"title":"module:log","link":"log","description":"

System logging functions

\n

The log module provides bindings to the POSIX syslog functions openlog(),\nsyslog() and closelog() as well as - when available - the OpenWrt\nspecific ulog library functions.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';\n\nopenlog("my-log-ident", LOG_PID, LOG_USER);\nsyslog(LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nimport { ulog_open, ulog, ULOG_SYSLOG, LOG_DAEMON, LOG_INFO } from 'log';\n\nulog_open(ULOG_SYSLOG, LOG_DAEMON, "my-log-ident");\nulog(LOG_INFO, "The current epoch is %d", time());\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as log from 'log';\n\nlog.openlog("my-log-ident", log.LOG_PID, log.LOG_USER);\nlog.syslog(log.LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nlog.ulog_open(log.ULOG_SYSLOG, log.LOG_DAEMON, "my-log-ident");\nlog.ulog(log.LOG_INFO, "The current epoch is %d", time());\n
\n

Additionally, the log module namespace may also be imported by invoking the\nucode interpreter with the -llog switch.

\n

Constants

\n

The log module declares a number of numeric constants to specify logging\nfacility, priority and option values, as well as ulog specific channels.

\n

Syslog Options

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_PIDInclude PID with each message.
LOG_CONSLog to console if error occurs while sending to syslog.
LOG_NDELAYOpen the connection to the logger immediately.
LOG_ODELAYDelay open until the first message is logged.
LOG_NOWAITDo not wait for child processes created during logging.
\n

Syslog Facilities

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_AUTHAuthentication/authorization messages.
LOG_AUTHPRIVPrivate authentication messages.
LOG_CRONClock daemon (cron and at commands).
LOG_DAEMONSystem daemons without separate facility values.
LOG_FTPFTP server daemon.
LOG_KERNKernel messages.
LOG_LPRLine printer subsystem.
LOG_MAILMail system.
LOG_NEWSNetwork news subsystem.
LOG_SYSLOGMessages generated internally by syslogd.
LOG_USERGeneric user-level messages.
LOG_UUCPUUCP subsystem.
LOG_LOCAL0Local use 0 (custom facility).
LOG_LOCAL1Local use 1 (custom facility).
LOG_LOCAL2Local use 2 (custom facility).
LOG_LOCAL3Local use 3 (custom facility).
LOG_LOCAL4Local use 4 (custom facility).
LOG_LOCAL5Local use 5 (custom facility).
LOG_LOCAL6Local use 6 (custom facility).
LOG_LOCAL7Local use 7 (custom facility).
\n

Syslog Priorities

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_EMERGSystem is unusable.
LOG_ALERTAction must be taken immediately.
LOG_CRITCritical conditions.
LOG_ERRError conditions.
LOG_WARNINGWarning conditions.
LOG_NOTICENormal, but significant, condition.
LOG_INFOInformational message.
LOG_DEBUGDebug-level message.
\n

Ulog channels

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
ULOG_KMSGLog messages to /dev/kmsg (dmesg).
ULOG_STDIOLog messages to stdout.
ULOG_SYSLOGLog messages to syslog.
"},{"title":"module:log#ERR","link":"ERR","description":"

Invoke ulog with LOG_ERR.

\n

This function is convenience wrapper for ulog(LOG_ERR, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#INFO","link":"INFO","description":"

Invoke ulog with LOG_INFO.

\n

This function is convenience wrapper for ulog(LOG_INFO, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#NOTE","link":"NOTE","description":"

Invoke ulog with LOG_NOTICE.

\n

This function is convenience wrapper for ulog(LOG_NOTICE, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#WARN","link":"WARN","description":"

Invoke ulog with LOG_WARNING.

\n

This function is convenience wrapper for ulog(LOG_WARNING, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#closelog","link":"closelog","description":"

Close connection to system logger.

\n

The usage of this function is optional, and usually an explicit log\nconnection tear down is not required.

"},{"title":"module:log#openlog","link":"openlog","description":"

Open connection to system logger.

\n

The openlog() function instructs the program to establish a connection to\nthe system log service and configures the default facility and identification\nfor use in subsequent log operations. It may be omitted, in which case the\nfirst call to syslog() will implicitly call openlog() with a default\nident value representing the program name and a default LOG_USER facility.

\n

The log option argument may be either a single string value containing an\noption name, an array of option name strings or a numeric value representing\na bitmask of LOG_* option constants.

\n

The facility argument may be either a single string value containing a\nfacility name or one of the numeric LOG_* facility constants in the module\nnamespace.

\n

Returns true if the system openlog() function was invoked.

\n

Returns false if an invalid argument, such as an unrecognized option or\nfacility name, was provided.

"},{"title":"module:log#syslog","link":"syslog","description":"

Log a message to the system logger.

\n

This function logs a message to the system logger. The function behaves in a\nsprintf-like manner, allowing the use of format strings and associated\narguments to construct log messages.

\n

If the openlog function has not been called explicitly before, syslog()\nimplicitly calls openlog(), using a default ident and LOG_USER facility\nvalue before logging the message.

\n

If the format argument is not a string and not null, it will be\nimplicitly converted to a string and logged as-is, without further format\nstring processing.

\n

Returns true if a message was passed to the system syslog() function.

\n

Returns false if an invalid priority value or an empty message was given.

"},{"title":"module:log#ulog","link":"ulog","description":"

Log a message via the ulog mechanism.

\n

The ulog() function outputs the given log message to all configured ulog\nchannels unless the given priority level exceeds the globally configured ulog\npriority threshold. See {@link module:log#ulog_threshold|ulog_threshold()}\nfor details.

\n

The ulog() function is OpenWrt specific and may not be present on other\nsystems. Use syslog() instead for portability to non-OpenWrt environments.

\n

Like syslog(), the function behaves in a sprintf-like manner, allowing the\nuse of format strings and associated arguments to construct log messages.

\n

If the ulog_open() function has not been called explicitly before, ulog()\nimplicitly configures certain defaults, see\n{@link module:log#ulog_open|ulog_open()} for a detailled description.

\n

If the format argument is not a string and not null, it will be\nimplicitly converted to a string and logged as-is, without further format\nstring processing.

\n

Returns true if a message was passed to the underlying ulog() function.

\n

Returns false if an invalid priority value or an empty message was given.

"},{"title":"module:log#ulog_close","link":"ulog_close","description":"

Close ulog logger.

\n

Resets the ulog channels, the default facility and the log ident value to\ndefaults.

\n

In case the "syslog" channel has been configured, the underlying\ncloselog() function will be invoked.

\n

The usage of this function is optional, and usually an explicit ulog teardown\nis not required.

\n

The ulog_close() function is OpenWrt specific and may not be present on\nother systems. Use closelog() in conjunction with syslog() instead for\nportability to non-OpenWrt environments.

"},{"title":"module:log#ulog_open","link":"ulog_open","description":"

Configure ulog logger.

\n

This functions configures the ulog mechanism and is analogeous to using the\nopenlog() function in conjuncton with syslog().

\n

The ulog_open() function is OpenWrt specific and may not be present on\nother systems. Use openlog() and syslog() instead for portability to\nnon-OpenWrt environments.

\n

A program may use multiple channels to simultaneously output messages using\ndifferent means. The channel argument may either be a single string value\ncontaining a channel name, an array of channel names or a numeric value\nrepresenting a bitmask of ULOG_* channel constants.

\n

The facility argument may be either a single string value containing a\nfacility name or one of the numeric LOG_* facility constants in the module\nnamespace.

\n

The default facility value varies, depending on the execution context of the\nprogram. In OpenWrt's preinit boot phase, or when stdout is not connected to\nan interactive terminal, the facility defaults to "daemon" (LOG_DAEMON),\notherwise to "user" (LOG_USER).

\n

Likewise, the default channel is selected depending on the context. During\nOpenWrt's preinit boot phase, the "kmsg" channel is used, for interactive\nterminals the "stdio" one and for all other cases the "syslog" channel\nis selected.

\n

Returns true if ulog was configured.

\n

Returns false if an invalid argument, such as an unrecognized channel or\nfacility name, was provided.

"},{"title":"module:log#ulog_threshold","link":"ulog_threshold","description":"

Set ulog priority threshold.

\n

This function configures the application wide log message threshold for log\nmessages emitted with ulog(). Any message with a priority higher (= less\nsevere) than the threshold priority will be discarded. This is useful to\nimplement application wide verbosity settings without having to wrap ulog()\ninvocations into a helper function or guarding code.

\n

When no explicit threshold has been set, LOG_DEBUG is used by default,\nallowing log messages with all known priorities.

\n

The ulog_threshold() function is OpenWrt specific and may not be present on\nother systems. There is no syslog equivalent to this ulog specific threshold\nmechanism.

\n

The priority argument may be either a string value containing a priority name\nor one of the numeric LOG_* priority constants in the module namespace.

\n

Returns true if a threshold was set.

\n

Returns false if an invalid priority value was given.

"},{"title":"module:log.LogFacility","link":"LogFacility","description":"

The following log facility strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FacilityDescription
"auth"Authentication/authorization messages.
"authpriv"Private authentication messages.
"cron"Clock daemon (cron and at commands).
"daemon"System daemons without separate facility values.
"ftp"FTP server daemon.
"kern"Kernel messages.
"lpr"Line printer subsystem.
"mail"Mail system.
"news"Network news subsystem.
"syslog"Messages generated internally by syslogd.
"user"Generic user-level messages.
"uucp"UUCP subsystem.
"local0"Local use 0 (custom facility).
"local1"Local use 1 (custom facility).
"local2"Local use 2 (custom facility).
"local3"Local use 3 (custom facility).
"local4"Local use 4 (custom facility).
"local5"Local use 5 (custom facility).
"local6"Local use 6 (custom facility).
"local7"Local use 7 (custom facility).
"},{"title":"module:log.LogOption","link":"LogOption","description":"

The following log option strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Log OptionDescription
"pid"Include PID with each message.
"cons"Log to console if an error occurs while sending to syslog.
"ndelay"Open the connection to the logger immediately.
"odelay"Delay open until the first message is logged.
"nowait"Do not wait for child processes created during logging.
"},{"title":"module:log.LogPriority","link":"LogPriority","description":"

The following log priority strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
PriorityDescription
"emerg"System is unusable.
"alert"Action must be taken immediately.
"crit"Critical conditions.
"err"Error conditions.
"warning"Warning conditions.
"notice"Normal, but significant, condition.
"info"Informational message.
"debug"Debug-level message.
"},{"title":"module:log.UlogChannel","link":"UlogChannel","description":"

The following ulog channel strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ChannelDescription
"kmsg"Log to /dev/kmsg, log messages appear in dmesg.
"syslog"Use standard syslog() mechanism.
"stdio"Use stderr for log output.
"},{"title":"module:math","link":"math","description":"

Mathematical Functions

\n

The math module bundles various mathematical and trigonometrical functions.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { pow, rand } from 'math';\n\nlet x = pow(2, 5);\nlet y = rand();\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as math from 'math';\n\nlet x = math.pow(2, 5);\nlet y = math.rand();\n
\n

Additionally, the math module namespace may also be imported by invoking the\nucode interpreter with the -lmath switch.

"},{"title":"module:math#abs","link":"abs","description":"

Returns the absolute value of the given numeric value.

"},{"title":"module:math#atan2","link":"atan2","description":"

Calculates the principal value of the arc tangent of y/x,\nusing the signs of the two arguments to determine the quadrant\nof the result.

\n

On success, this function returns the principal value of the arc\ntangent of y/x in radians; the return value is in the range [-pi, pi].

\n\n

When either x or y can't be converted to a numeric value, NaN is\nreturned.

"},{"title":"module:math#cos","link":"cos","description":"

Calculates the cosine of x, where x is given in radians.

\n

Returns the resulting consine value.

\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#exp","link":"exp","description":"

Calculates the value of e (the base of natural logarithms)\nraised to the power of x.

\n

On success, returns the exponential value of x.

\n\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#isnan","link":"isnan","description":"

Tests whether x is a NaN double.

\n

This functions checks whether the given argument is of type double with\na NaN (not a number) value.

\n

Returns true if the value is NaN, otherwise false.

\n

Note that a value can also be checked for NaN with the expression\nx !== x which only evaluates to true if x is NaN.

"},{"title":"module:math#log","link":"log","description":"

Calculates the natural logarithm of x.

\n

On success, returns the natural logarithm of x.

\n\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#pow","link":"pow","description":"

Calculates the value of x raised to the power of y.

\n

On success, returns the value of x raised to the power of y.

\n\n

Returns NaN if either the x or y value can't be converted to a number.

"},{"title":"module:math#rand","link":"rand","description":"

Produces a pseudo-random positive integer.

\n

Returns the calculated pseuo-random value. The value is within the range\n0 to RAND_MAX inclusive where RAND_MAX is a platform specific value\nguaranteed to be at least 32767.

\n

The {@link module:math~srand srand()} function sets its argument as the\nseed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are\nrepeatable by calling {@link module:math~srand srand()} with the same\nseed value.

\n

If no seed value is explicitly set by calling\n{@link module:math~srand srand()} prior to the first call to rand(),\nthe math module will automatically seed the PRNG once, using the current\ntime of day in milliseconds as seed value.

"},{"title":"module:math#sin","link":"sin","description":"

Calculates the sine of x, where x is given in radians.

\n

Returns the resulting sine value.

\n\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#sqrt","link":"sqrt","description":"

Calculates the nonnegative square root of x.

\n

Returns the resulting square root value.

\n\n

Returns NaN if the x value can't be converted to a number.

"},{"title":"module:math#srand","link":"srand","description":"

Seeds the pseudo-random number generator.

\n

This functions seeds the PRNG with the given value and thus affects the\npseudo-random integer sequence produced by subsequent calls to\n{@link module:math~rand rand()}.

\n

Setting the same seed value will result in the same pseudo-random numbers\nproduced by {@link module:math~rand rand()}.

"},{"title":"module:struct","link":"struct","description":"

Handle Packed Binary Data

\n

The struct module provides routines for interpreting byte strings as packed\nbinary data.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { pack, unpack } from 'struct';\n\nlet buffer = pack('bhl', -13, 1234, 444555666);\nlet values = unpack('bhl', buffer);\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as struct from 'struct';\n\nlet buffer = struct.pack('bhl', -13, 1234, 444555666);\nlet values = struct.unpack('bhl', buffer);\n
\n

Additionally, the struct module namespace may also be imported by invoking\nthe ucode interpreter with the -lstruct switch.

\n

Format Strings

\n

Format strings describe the data layout when packing and unpacking data.\nThey are built up from format-characters, which specify the type of data\nbeing packed/unpacked. In addition, special characters control the byte\norder, size and alignment.

\n

Each format string consists of an optional prefix character which describes\nthe overall properties of the data and one or more format characters which\ndescribe the actual data values and padding.

\n

Byte Order, Size, and Alignment

\n

By default, C types are represented in the machine's native format and byte\norder, and properly aligned by skipping pad bytes if necessary (according to\nthe rules used by the C compiler).

\n

This behavior is chosen so that the bytes of a packed struct correspond\nexactly to the memory layout of the corresponding C struct.

\n

Whether to use native byte ordering and padding or standard formats depends\non the application.

\n

Alternatively, the first character of the format string can be used to indicate\nthe byte order, size and alignment of the packed data, according to the\nfollowing table:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
CharacterByte orderSizeAlignment
@nativenativenative
=nativestandardnone
<little-endianstandardnone
>big-endianstandardnone
!network (= big-endian)standardnone
\n

If the first character is not one of these, '@' is assumed.

\n

Native byte order is big-endian or little-endian, depending on the\nhost system. For example, Intel x86, AMD64 (x86-64), and Apple M1 are\nlittle-endian; IBM z and many legacy architectures are big-endian.

\n

Native size and alignment are determined using the C compiler's\nsizeof expression. This is always combined with native byte order.

\n

Standard size depends only on the format character; see the table in\nthe format-characters section.

\n

Note the difference between '@' and '=': both use native byte order,\nbut the size and alignment of the latter is standardized.

\n

The form '!' represents the network byte order which is always big-endian\nas defined in IETF RFC 1700.

\n

There is no way to indicate non-native byte order (force byte-swapping); use\nthe appropriate choice of '<' or '>'.

\n

Notes:

\n

(1) Padding is only automatically added between successive structure members.\nNo padding is added at the beginning or the end of the encoded struct.

\n

(2) No padding is added when using non-native size and alignment, e.g.\nwith '<', '>', '=', and '!'.

\n

(3) To align the end of a structure to the alignment requirement of a\nparticular type, end the format with the code for that type with a repeat\ncount of zero.

\n

Format Characters

\n

Format characters have the following meaning; the conversion between C and\nucode values should be obvious given their types. The 'Standard size' column\nrefers to the size of the packed value in bytes when using standard size;\nthat is, when the format string starts with one of '<', '>', '!' or\n'='. When using native size, the size of the packed value is platform\ndependent.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FormatC TypeUcode typeStandard sizeNotes
xpad byteno value(7)
ccharstring1
bsigned charint1(1), (2)
Bunsigned charint1(2)
?_Boolbool1(1)
hshortint2(2)
Hunsigned shortint2(2)
iintint4(2)
Iunsigned intint4(2)
llongint4(2)
Lunsigned longint4(2)
qlong longint8(2)
Qunsigned long longint8(2)
nssize_tint(3)
Nsize_tint(3)
e(6)double2(4)
ffloatdouble4(4)
ddoubledouble8(4)
schar[]double(9)
pchar[]double(8)
Pvoid *int(5)
*char[]string(10)
\n

Notes:

\n\n

A format character may be preceded by an integral repeat count. For example,\nthe format string '4h' means exactly the same as 'hhhh'.

\n

Whitespace characters between formats are ignored; a count and its format\nmust not contain whitespace though.

\n

When packing a value x using one of the integer formats ('b',\n'B', 'h', 'H', 'i', 'I', 'l', 'L',\n'q', 'Q'), if x is outside the valid range for that format, a type\nerror exception is raised.

\n

For the '?' format character, the return value is either true or false.\nWhen packing, the truish result value of the argument is used. Either 0 or 1\nin the native or standard bool representation will be packed, and any\nnon-zero value will be true when unpacking.

\n

Examples

\n

Note:\nNative byte order examples (designated by the '@' format prefix or\nlack of any prefix character) may not match what the reader's\nmachine produces as\nthat depends on the platform and compiler.

\n

Pack and unpack integers of three different sizes, using big endian\nordering:

\n
import { pack, unpack } from 'struct';\n\npack(">bhl", 1, 2, 3);  // "\\x01\\x00\\x02\\x00\\x00\\x00\\x03"\nunpack(">bhl", "\\x01\\x00\\x02\\x00\\x00\\x00\\x03");  // [ 1, 2, 3 ]\n
\n

Attempt to pack an integer which is too large for the defined field:

\n
$ ucode -lstruct -p 'struct.pack(">h", 99999)'\nType error: Format 'h' requires numeric argument between -32768 and 32767\nIn [-p argument], line 1, byte 24:\n\n `struct.pack(">h", 99999)`\n  Near here -------------^\n
\n

Demonstrate the difference between 's' and 'c' format characters:

\n
import { pack } from 'struct';\n\npack("@ccc", "1", "2", "3");  // "123"\npack("@3s", "123");           // "123"\n
\n

The ordering of format characters may have an impact on size in native\nmode since padding is implicit. In standard mode, the user is\nresponsible for inserting any desired padding.

\n

Note in the first pack() call below that three NUL bytes were added after\nthe packed '#' to align the following integer on a four-byte boundary.\nIn this example, the output was produced on a little endian machine:

\n
import { pack } from 'struct';\n\npack("@ci", "#", 0x12131415);  // "#\\x00\\x00\\x00\\x15\\x14\\x13\\x12"\npack("@ic", 0x12131415, "#");  // "\\x15\\x14\\x13\\x12#"\n
\n

The following format 'ih0i' results in two pad bytes being added at the\nend, assuming the platform's ints are aligned on 4-byte boundaries:

\n
import { pack } from 'struct';\n\npack("ih0i", 0x01010101, 0x0202);  // "\\x01\\x01\\x01\\x01\\x02\\x02\\x00\\x00"\n
\n

Use the wildcard format to extract the remainder of the input data:

\n
import { unpack } from 'struct';\n\nunpack("ccc*", "foobarbaz");   // [ "f", "o", "o", "barbaz" ]\nunpack("ccc3*", "foobarbaz");  // [ "f", "o", "o", "bar" ]\n
\n

Use the wildcard format to pack binary stings as-is into the result data:

\n
import { pack } from 'struct';\n\npack("h*h", 0x0101, "\\x02\\x00\\x03", 0x0404);  // "\\x01\\x01\\x02\\x00\\x03\\x04\\x04"\npack("c3*c", "a", "foobar", "c");  // "afooc"\n
"},{"title":"module:struct#new","link":"new","description":"

Precompile format string.

\n

The new() function precompiles the given format string argument and returns\na struct object instance useful for packing and unpacking multiple items\nwithout having to recompute the internal format each time.

\n

Returns an precompiled struct format instance.

\n

Raises a runtime exception if the format string is invalid.

"},{"title":"module:struct#pack","link":"pack","description":"

Pack given values according to specified format.

\n

The pack() function creates a byte string containing the argument values\npacked according to the given format string.

\n

Returns the packed string.

\n

Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive or if and invalid\nformat string is provided.

"},{"title":"module:struct#unpack","link":"unpack","description":"

Unpack given byte string according to specified format.

\n

The unpack() function interpretes a byte string according to the given\nformat string and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.

\n

Returns an array of unpacked values.

\n

Raises a runtime exception if the format string is invalid or if an invalid\ninput string or offset value is given.

"},{"title":"module:struct.instance","link":"instance","description":"

Represents a struct instance created by new().

"},{"title":"module:struct.instance#pack","link":"pack","description":"

Pack given values.

\n

The pack() function creates a byte string containing the argument values\npacked according to the given format instance.

\n

Returns the packed string.

\n

Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive.

"},{"title":"module:struct.instance#unpack","link":"unpack","description":"

Unpack given byte string.

\n

The unpack() function interpretes a byte string according to the given\nformat instance and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.

\n

Returns an array of unpacked values.

\n

Raises a runtime exception if an invalid input string or offset value is\ngiven.

"},{"title":"module:uci","link":"uci","description":"

OpenWrt UCI configuration

\n

The uci module provides access to the native OpenWrt\n{@link https://github.com/openwrt/uci libuci} API for reading and\nmanipulating UCI configuration files.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { cursor } from 'uci';\n\nlet ctx = cursor();\nlet hostname = ctx.get_first('system', 'system', 'hostname');\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as uci from 'uci';\n\nlet ctx = uci.cursor();\nlet hostname = ctx.get_first('system', 'system', 'hostname');\n
\n

Additionally, the uci module namespace may also be imported by invoking\nthe ucode interpreter with the -luci switch.

"},{"title":"module:uci#cursor","link":"cursor","description":"

Instantiate uci cursor.

\n

A uci cursor is a context for interacting with uci configuration files. It's\npurpose is to cache and hold changes made to loaded configuration states\nuntil those changes are written out to disk or discared.

\n

Unsaved and uncommitted changes in a cursor instance are private and not\nvisible to other cursor instances instantiated by the same program or other\nprocesses on the system.

\n

Returns the instantiated cursor on success.

\n

Returns null on error, e.g. if an invalid path argument was provided.

"},{"title":"module:uci#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:uci.cursor","link":"cursor","description":"

Represents a context for interacting with uci configuration files.

\n

Operations on uci configurations are performed through a uci cursor object\nwhich operates on in-memory representations of loaded configuration files.

\n

Any changes made to configuration values are local to the cursor object and\nheld in memory only until they're written out to the filesystem using the\nsave() and commit() methods.

\n

Changes performed in one cursor instance are not reflected in another, unless\nthe first instance writes those changes to the filesystem and the other\ninstance explicitly (re)loads the affected configuration files.

"},{"title":"module:uci.cursor#add","link":"add","description":"

Add anonymous section to given configuration.

\n

Adds a new anonymous (unnamed) section of the specified type to the given\nconfiguration. In order to add a named section, the three argument form of\nset() should be used instead.

\n

In contrast to other query functions, add() will not implicitly load the\nconfiguration into the cursor. The configuration either needs to be loaded\nexplicitly through load() beforehand, or implicitly by querying it through\none of the get(), get_all(), get_first() or foreach() functions.

\n

Returns the autogenerated, ephemeral name of the added unnamed section\non success.

\n

Returns null on error, e.g. if the targeted configuration was not loaded or\nif an invalid section type value was passed.

"},{"title":"module:uci.cursor#changes","link":"changes","description":"

Enumerate pending changes.

\n

The changes() function returns a list of change records for currently\nloaded configuration files, originating both from the cursors associated\ndelta directory and yet unsaved cursor changes.

\n

When the optional "config" parameter is specified, the requested\nconfiguration is implicitly loaded if it not already loaded into the cursor.

\n

Returns a dictionary of change record arrays, keyed by configuration name.

\n

Returns null on error, e.g. if the requested configuration could not be\nloaded.

"},{"title":"module:uci.cursor#commit","link":"commit","description":"

Update configuration files with accumulated cursor changes.

\n

The commit() function merges changes made to in-memory copies of loaded\nconfiguration files as well as existing delta records in the cursors\nconfigured delta directory and writes them back into the underlying\nconfiguration files, persistently committing changes to the file system.

\n

When the optional "config" parameter is omitted, all currently loaded\nconfiguration files with either present delta records or yet unsaved\ncursor changes are updated.

\n

Returns the true if operation completed successfully.

\n

Returns null on error, e.g. if the requested configuration was not loaded\nor when a file system error occurred.

"},{"title":"module:uci.cursor#configs","link":"configs","description":"

Enumerate existing configurations.

\n

The configs() function yields an array of configuration files present in\nthe cursors associated configuration directory, /etc/config/ by default.

\n

Returns an array of configuration names on success.

\n

Returns null on error, e.g. due to filesystem errors.

"},{"title":"module:uci.cursor#delete","link":"delete","description":"

Delete an option or section from given configuration.

\n

When invoked with three arguments, the function deletes the given option\nwithin the specified section of the given configuration.

\n

When invoked with two arguments, the function deletes the entire specified\nsection within the given configuration.

\n

In either case, the given configuration is implicitly loaded into the cursor\nif not already present.

\n

Returns the true if specified option or section has been deleted.

\n

Returns null on error, e.g. if the targeted configuration was not found or\nif an invalid value was passed.

"},{"title":"module:uci.cursor#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:uci.cursor#foreach","link":"foreach","description":"

Iterate configuration sections.

\n

The foreach() function iterates all sections of the given configuration,\noptionally filtered by type, and invokes the given callback function for\neach encountered section.

\n

When the optional "type" parameter is specified, the callback is only invoked\nfor sections of the given type, otherwise it is invoked for all sections.

\n

The requested configuration is implicitly loaded into the cursor.

\n

Returns true if the callback was executed successfully at least once.

\n

Returns false if the callback was never invoked, e.g. when the\nconfiguration is empty or contains no sections of the given type.

\n

Returns null on error, e.g. when an invalid callback was passed or the\nrequested configuration not found.

"},{"title":"module:uci.cursor#get","link":"get","description":"

Query a single option value or section type.

\n

When invoked with three arguments, the function returns the value of the\ngiven option, within the specified section of the given configuration.

\n

When invoked with just a config and section argument, the function returns\nthe type of the specified section.

\n

In either case, the given configuration is implicitly loaded into the cursor\nif not already present.

\n

Returns the configuration value or section type on success.

\n

Returns null on error, e.g. if the requested configuration does not exist\nor if an invalid argument was passed.

"},{"title":"module:uci.cursor#get_all","link":"get_all","description":"

Query a complete section or configuration.

\n

When invoked with two arguments, the function returns all values of the\nspecified section within the given configuration as dictionary.

\n

When invoked with just a config argument, the function returns a nested\ndictionary of all sections present within the given configuration.

\n

In either case, the given configuration is implicitly loaded into the cursor\nif not already present.

\n

Returns the section or configuration dictionary on success.

\n

Returns null on error, e.g. if the requested configuration does not exist\nor if an invalid argument was passed.

"},{"title":"module:uci.cursor#get_first","link":"get_first","description":"

Query option value or name of first section of given type.

\n

When invoked with three arguments, the function returns the value of the\ngiven option within the first found section of the specified type in the\ngiven configuration.

\n

When invoked with just a config and section type argument, the function\nreturns the name of the first found section of the given type.

\n

In either case, the given configuration is implicitly loaded into the cursor\nif not already present.

\n

Returns the configuration value or section name on success.

\n

Returns null on error, e.g. if the requested configuration does not exist\nor if an invalid argument was passed.

"},{"title":"module:uci.cursor#load","link":"load","description":"

Explicitly reload configuration file.

\n

Usually, any attempt to query or modify a value within a given configuration\nwill implicitly load the underlying file into memory. By invoking load()\nexplicitly, a potentially loaded stale configuration is discarded and\nreloaded from the file system, ensuring that the latest state is reflected in\nthe cursor.

\n

Returns true if the configuration was successfully loaded.

\n

Returns null on error, e.g. if the requested configuration does not exist.

"},{"title":"module:uci.cursor#rename","link":"rename","description":"

Rename an option or section in given configuration.

\n

When invoked with four arguments, the function renames the given option\nwithin the specified section of the given configuration to the provided\nvalue.

\n

When invoked with three arguments, the function renames the entire specified\nsection to the provided value.

\n

In either case, the given configuration is implicitly loaded into the cursor\nif not already present.

\n

Returns the true if specified option or section has been renamed.

\n

Returns null on error, e.g. if the targeted configuration was not found or\nif an invalid value was passed.

"},{"title":"module:uci.cursor#reorder","link":"reorder","description":"

Reorder sections in given configuration.

\n

The reorder() function moves a single section by repositioning it to the\ngiven index within the configurations section list.

\n

The given configuration is implicitly loaded into the cursor if not already\npresent.

\n

Returns the true if specified section has been moved.

\n

Returns null on error, e.g. if the targeted configuration was not found or\nif an invalid value was passed.

"},{"title":"module:uci.cursor#revert","link":"revert","description":"

Revert accumulated cursor changes and associated delta records.

\n

The revert() function discards any changes made to in-memory copies of\nloaded configuration files and discards any related existing delta records in\nthe cursors configured delta directory.

\n

When the optional "config" parameter is omitted, all currently loaded\nconfiguration files with either present delta records or yet unsaved\ncursor changes are reverted.

\n

Returns the true if operation completed successfully.

\n

Returns null on error, e.g. if the requested configuration was not loaded\nor when a file system error occurred.

"},{"title":"module:uci.cursor#save","link":"save","description":"

Save accumulated cursor changes to delta directory.

\n

The save() function writes consolidated changes made to in-memory copies of\nloaded configuration files to the uci delta directory which effectively makes\nthem available to other processes using the same delta directory path as well\nas the uci changes cli command when using the default delta directory.

\n

Note that uci deltas are overlayed over the actual configuration file values\nso they're reflected by get(), foreach() etc. even if the underlying\nconfiguration files are not actually changed (yet). The delta records may be\neither permanently merged into the configuration by invoking commit() or\nreverted through revert() in order to restore the current state of the\nunderlying configuration file.

\n

When the optional "config" parameter is omitted, delta records for all\ncurrently loaded configuration files are written.

\n

In case that neither sharing changes with other processes nor any revert\nfunctionality is required, changes may be committed directly using commit()\ninstead, bypassing any delta record creation.

\n

Returns the true if operation completed successfully.

\n

Returns null on error, e.g. if the requested configuration was not loaded\nor when a file system error occurred.

"},{"title":"module:uci.cursor#set","link":"set","description":"

Set option value or add named section in given configuration.

\n

When invoked with four arguments, the function sets the value of the given\noption within the specified section of the given configuration to the\nprovided value. A value of "" (empty string) can be used to delete an\nexisting option.

\n

When invoked with three arguments, the function adds a new named section to\nthe given configuration, using the specified type.

\n

In either case, the given configuration is implicitly loaded into the cursor\nif not already present.

\n

Returns the true if the named section was added or the specified option was\nset.

\n

Returns null on error, e.g. if the targeted configuration was not found or\nif an invalid value was passed.

"},{"title":"module:uci.cursor#unload","link":"unload","description":"

Explicitly unload configuration file.

\n

The unload() function forcibly discards a loaded configuration state from\nthe cursor so that the next attempt to read or modify that configuration\nwill load it anew from the file system.

\n

Returns true if the configuration was successfully unloaded.

\n

Returns false if the configuration was not loaded to begin with.

\n

Returns null on error, e.g. if the requested configuration does not exist.

"},{"title":"module:uci.cursor.ChangeRecord","link":"ChangeRecord","description":"

A uci change record is a plain array containing the change operation name as\nfirst element, the affected section ID as second argument and an optional\nthird and fourth argument whose meanings depend on the operation.

"},{"title":"module:uci.cursor.SectionCallback","link":"SectionCallback","description":"

The sections callback is invoked for each section found within the given\nconfiguration and receives the section object and its associated name as\narguments.

"},{"title":"module:uci.cursor.SectionObject","link":"SectionObject","description":"

A section object represents the options and their corresponding values\nenclosed within a configuration section, as well as some additional meta data\nsuch as sort indexes and internal ID.

\n

Any internal metadata fields are prefixed with a dot which isn't an allowed\ncharacter for normal option names.

"}]} \ No newline at end of file diff --git a/index.html b/index.html index 16fc6a80..2f07d629 100644 --- a/index.html +++ b/index.html @@ -1,6 +1,6 @@ ucode - Reference Documentation
On this page

The ucode Language

The ucode language is a tiny general purpose scripting language featuring a syntax closely resembling ECMAScript. It can be used in a stand-alone manner by using the ucode command line interpreter or embedded into host applications by linking libucode and utilizing its C language API. Additionally, ucode can be invoked in template mode where control flow and expression logic statements are embedded in Jinja-like markup blocks.

Besides aiming for small size, the major design goals of ucode are the ability to trivially read and write JSON data, good embeddability into C applications, template capabilities for output formatting, extensiblity through loadable native extension modules and a straightforward set of built-in functions mimicking those found in the Perl 5 language.

History and Motivation

In spring 2021 it has been decided to rewrite the OpenWrt firewall framework on top of nftables with the goal to replace the then current C application with a kind of preprocessor generating nftables rulesets using a set of templates instead of relying on built-in hardcoded rules like its predecessor.

That decision spurred the development of ucode, initially meant to be a simple template processor solely for the OpenWrt nftables firewall but quickly evolving into a general purpose scripting language suitable for a wider range of system scripting tasks.

Despite OpenWrt predominantly relying on POSIX shell and Lua as system scripting languages already, a new solution was needed to accomodate the needs of the new firewall implementation; mainly the ability to efficiently deal with JSON data and complex data structures such as arrays and dictionaries and the ability to closely interface with OpenWrt's ubus message bus system.

Throughout the design process of the new firewall and its template processor, the following design goals were defined for the ucode scripting language:

  • Ability to embed code logic fragments such as control flow statements, function calls or arithmetic expressions into plain text templates, using a block syntax and functionality roughly inspired by Jinja templates
  • Built-in support for JSON data parsing and serialization, without the need for external libraries
  • Distinct array and object types (compared to Lua's single table datatype)
  • Distinct integer and float types and guaranteed 64bit integer range
  • Built-in support for bit operations
  • Built-in support for (POSIX) regular expressions
  • A comprehensive set of built-in standard functions, inspired by the core functions found in the Perl 5 interpreter
  • Staying as close to ECMAScript syntax as possible due to higher developer familiarity and to be able to reuse existing tooling such as editor syntax highlighting
  • Bindings for all relevant Linux and OpenWrt APIs, such as ubus, uci, uloop, netlink etc.
  • Procedural, synchronous programming flow
  • Very small executable size (the interpreter and runtime is currently around 64KB on ARM Cortex A9)
  • Embeddability into C host applications

Summarized, ucode can be described as synchronous ECMAScript without the object oriented standard library.

Installation

OpenWrt

In OpenWrt 22.03 and later, ucode should already be preinstalled. If not, it can be installed via the package manager, using the opkg install ucode command.

MacOS

To build on MacOS, first install cmake and json-c via Homebrew, then clone the ucode repository and execute cmake followed by make:

$ brew install cmake json-c
+    
On this page

The ucode Language

The ucode language is a tiny general purpose scripting language featuring a syntax closely resembling ECMAScript. It can be used in a stand-alone manner by using the ucode command line interpreter or embedded into host applications by linking libucode and utilizing its C language API. Additionally, ucode can be invoked in template mode where control flow and expression logic statements are embedded in Jinja-like markup blocks.

Besides aiming for small size, the major design goals of ucode are the ability to trivially read and write JSON data, good embeddability into C applications, template capabilities for output formatting, extensiblity through loadable native extension modules and a straightforward set of built-in functions mimicking those found in the Perl 5 language.

History and Motivation

In spring 2021 it has been decided to rewrite the OpenWrt firewall framework on top of nftables with the goal to replace the then current C application with a kind of preprocessor generating nftables rulesets using a set of templates instead of relying on built-in hardcoded rules like its predecessor.

That decision spurred the development of ucode, initially meant to be a simple template processor solely for the OpenWrt nftables firewall but quickly evolving into a general purpose scripting language suitable for a wider range of system scripting tasks.

Despite OpenWrt predominantly relying on POSIX shell and Lua as system scripting languages already, a new solution was needed to accomodate the needs of the new firewall implementation; mainly the ability to efficiently deal with JSON data and complex data structures such as arrays and dictionaries and the ability to closely interface with OpenWrt's ubus message bus system.

Throughout the design process of the new firewall and its template processor, the following design goals were defined for the ucode scripting language:

  • Ability to embed code logic fragments such as control flow statements, function calls or arithmetic expressions into plain text templates, using a block syntax and functionality roughly inspired by Jinja templates
  • Built-in support for JSON data parsing and serialization, without the need for external libraries
  • Distinct array and object types (compared to Lua's single table datatype)
  • Distinct integer and float types and guaranteed 64bit integer range
  • Built-in support for bit operations
  • Built-in support for (POSIX) regular expressions
  • A comprehensive set of built-in standard functions, inspired by the core functions found in the Perl 5 interpreter
  • Staying as close to ECMAScript syntax as possible due to higher developer familiarity and to be able to reuse existing tooling such as editor syntax highlighting
  • Bindings for all relevant Linux and OpenWrt APIs, such as ubus, uci, uloop, netlink etc.
  • Procedural, synchronous programming flow
  • Very small executable size (the interpreter and runtime is currently around 64KB on ARM Cortex A9)
  • Embeddability into C host applications

Summarized, ucode can be described as synchronous ECMAScript without the object oriented standard library.

Installation

OpenWrt

In OpenWrt 22.03 and later, ucode should already be preinstalled. If not, it can be installed via the package manager, using the opkg install ucode command.

MacOS

To build on MacOS, first install cmake and json-c via Homebrew, then clone the ucode repository and execute cmake followed by make:

$ brew install cmake json-c
 $ git clone https://github.com/jow-/ucode.git
 $ cd ucode/
 $ cmake -DUBUS_SUPPORT=OFF -DUCI_SUPPORT=OFF -DULOOP_SUPPORT=OFF .
@@ -16,4 +16,4 @@
 $ cmake -DUBUS_SUPPORT=OFF -DUCI_SUPPORT=OFF -DULOOP_SUPPORT=OFF .
 $ make
 $ sudo make install
-
\ No newline at end of file +
\ No newline at end of file diff --git a/lib.c.html b/lib.c.html index 5cd0be69..816b4de8 100644 --- a/lib.c.html +++ b/lib.c.html @@ -1,6 +1,6 @@ Source: lib.c
On this page

lib.c

/*
+    
On this page

lib.c

/*
  * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -367,7 +367,7 @@
  *
  * @param {Object|Array|string} x - The input object, array, or string.
  *
- * @returns {number|null} - The length of the input.
+ * @returns {?number} - The length of the input.
  *
  * @example
  * length("test")                             // 4
@@ -486,7 +486,7 @@
  * @param {*} needle
  * The value to find within the array or string.
  *
- * @returns {number|null}
+ * @returns {?number}
  *
  * @example
  * index("Hello hello hello", "ll")          // 2
@@ -518,7 +518,7 @@
  * @param {*} needle
  * The value to find within the array or string.
  *
- * @returns {number|null}
+ * @returns {?number}
  *
  * @example
  * rindex("Hello hello hello", "ll")          // 14
@@ -846,7 +846,7 @@
  * @param {string} [name]
  * The name of the environment variable.
  *
- * @returns {string|object}
+ * @returns {string|Object<string, string>}
  */
 static uc_value_t *
 uc_getenv(uc_vm_t *vm, size_t nargs)
@@ -1039,7 +1039,7 @@
  * @param {Array} arr
  * The array to be joined into a string.
  *
- * @returns {string|null}
+ * @returns {?string}
  */
 static uc_value_t *
 uc_join(uc_vm_t *vm, size_t nargs)
@@ -1075,7 +1075,7 @@
  * @param {object} obj
  * The object from which to retrieve the key names.
  *
- * @returns {Array|null}
+ * @returns {?Array}
  */
 static uc_value_t *
 uc_keys(uc_vm_t *vm, size_t nargs)
@@ -1106,7 +1106,7 @@
  * @param {string} s
  * The input string.
  *
- * @returns {string|null}
+ * @returns {?string}
  * The lowercase string.
  *
  * @example
@@ -1213,7 +1213,7 @@
  * @param {number} [offset]
  * The offset of the character.
  *
- * @returns {number|null}
+ * @returns {?number}
  *
  * @example
  * ord("Abc");         // 65
@@ -1267,7 +1267,7 @@
  * @param {*} x
  * The value to determine the type of.
  *
- * @returns {string|null}
+ * @returns {?string}
  */
 static uc_value_t *
 uc_type(uc_vm_t *vm, size_t nargs)
@@ -1309,7 +1309,7 @@
  * @param {Array|string} arr_or_str
  * The input array or string.
  *
- * @returns {Array|string|null}
+ * @returns {?(Array|string)}
  *
  * @example
  * reverse([1, 2, 3]);   // [ 3, 2, 1 ]
@@ -1940,7 +1940,7 @@
  * @param {*} str
  * The string to be converted to uppercase.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * uc("hello");   // "HELLO"
@@ -2042,7 +2042,7 @@
  * @param {*} obj
  * The object from which to extract values.
  *
- * @returns {Array|null}
+ * @returns {?Array}
  *
  * @example
  * values({ foo: true, bar: false });   // [true, false]
@@ -2776,7 +2776,7 @@
  * @param {string} address
  * The IP address string to convert.
  *
- * @returns {number[]|null}
+ * @returns {?number[]}
  *
  * @example
  * iptoarr("192.168.1.1")              // [ 192, 168, 1, 1 ]
@@ -2853,7 +2853,7 @@
  * @param {number[]} arr
  * The byte array to convert into an IP address string.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * arrtoip([ 192, 168, 1, 1 ])   // "192.168.1.1"
@@ -2930,7 +2930,7 @@
  * @param {RegExp} pattern
  * The regular expression pattern.
  *
- * @returns {Array|null}
+ * @returns {?Array}
  *
  * @example
  * match("foobarbaz", /b.(.)/)   // ["bar", "r"]
@@ -3978,7 +3978,7 @@
  * @param {Object} [proto]
  * The optional prototype object.
  *
- * @returns {Object|null}
+ * @returns {?Object}
  *
  * @example
  * const arr = [1, 2, 3];
@@ -4224,7 +4224,7 @@
  * @param {boolean} [dironly]
  * Whether to return only the directory portion of the source file path.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * sourcepath();         // Returns the path of the currently executed file
@@ -4428,7 +4428,7 @@
  * @param {string} str
  * The base64 encoded string to decode.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * b64dec("VGhpcyBpcyBhIHRlc3Q=");         // Returns "This is a test"
@@ -4578,7 +4578,7 @@
  * @param {string} str
  * The string to encode.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * b64enc("This is a test");  // Returns "VGhpcyBpcyBhIHRlc3Q="
@@ -4715,7 +4715,7 @@
  * @param {Array} array
  * The input array.
  *
- * @returns {Array|null}
+ * @returns {?Array}
  *
  * @example
  * uniq([1, true, "foo", 2, true, "bar", "foo"]);       // Returns [1, true, "foo", 2, "bar"]
@@ -4754,6 +4754,28 @@
 	return uniq;
 }
 
+/**
+ * A time spec is a plain object describing a point in time, it is returned by
+ * the {@link module:core#gmtime|gmtime()} and
+ * {@link module:core#localtime|localtime()} functions and expected as parameter
+ * by the complementary {@link module:core#timegm|timegm()} and
+ * {@link module:core#timelocal|timelocal()} functions.
+ *
+ * When returned by `gmtime()` or `localtime()`, all members of the object will
+ * be initialized, when passed as argument to `timegm()` or `timelocal()`, most
+ * member values are optional.
+ *
+ * @typedef {Object} module:core.TimeSpec
+ * @property {number} sec - Seconds (0..60)
+ * @property {number} min - Minutes (0..59)
+ * @property {number} hour - Hours (0..23)
+ * @property {number} mday - Day of month (1..31)
+ * @property {number} mon - Month (1..12)
+ * @property {number} year - Year (>= 1900)
+ * @property {number} wday - Day of week (1..7, Sunday = 7)
+ * @property {number} yday - Day of year (1-366, Jan 1st = 1)
+ * @property {number} isdst - Daylight saving time in effect (yes = 1)
+ */
 static uc_value_t *
 uc_gettime_common(uc_vm_t *vm, size_t nargs, bool local)
 {
@@ -4784,16 +4806,7 @@
  * containing broken-down date and time information according to the local
  * system timezone.
  *
- * The resulting dictionary contains the following fields:
- * - `sec`    Seconds (0-60)
- * - `min`    Minutes (0-59)
- * - `hour`   Hours (0-23)
- * - `mday`   Day of month (1-31)
- * - `mon`    Month (1-12)
- * - `year`   Year (>= 1900)
- * - `wday`   Day of the week (1-7, Sunday = 7)
- * - `yday`   Day of the year (1-366, Jan 1st = 1)
- * - `isdst`  Daylight saving time in effect (yes = 1)
+ * See {@link module:core.TimeSpec|TimeSpec} for a description of the fields.
  *
  * Note that in contrast to the underlying `localtime(3)` C library function,
  * the values for `mon`, `wday`, and `yday` are 1-based, and the `year` is
@@ -4804,7 +4817,7 @@
  * @param {number} [epoch]
  * The epoch timestamp.
  *
- * @returns {Object}
+ * @returns {module:core.TimeSpec}
  *
  * @example
  * localtime(1647953502);
@@ -4830,14 +4843,14 @@
 /**
  * Like `localtime()` but interpreting the given epoch value as UTC time.
  *
- * See `localtime()` for details on the return value.
+ * See {@link module:core#localtime|localtime()} for details on the return value.
  *
  * @function module:core#gmtime
  *
  * @param {number} [epoch]
  * The epoch timestamp.
  *
- * @returns {Object}
+ * @returns {module:core.TimeSpec}
  *
  * @example
  * gmtime(1647953502);
@@ -4910,9 +4923,9 @@
 }
 
 /**
- * Performs the inverse operation of `localtime()` by taking a broken-down date
- * and time dictionary and transforming it into an epoch value according to the
- * local system timezone.
+ * Performs the inverse operation of {@link module:core#localtime|localtime()}
+ * by taking a broken-down date and time dictionary and transforming it into an
+ * epoch value according to the local system timezone.
  *
  * The `wday` and `yday` fields of the given date time specification are
  * ignored. Field values outside of their valid range are internally normalized,
@@ -4924,10 +4937,10 @@
  *
  * @function module:core#timelocal
  *
- * @param {Object} datetimespec
+ * @param {module:core.TimeSpec} datetimespec
  * The broken-down date and time dictionary.
  *
- * @returns {number|null}
+ * @returns {?number}
  *
  * @example
  * timelocal({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
@@ -4943,14 +4956,14 @@
  * Like `timelocal()` but interpreting the given date time specification as UTC
  * time.
  *
- * See `timelocal()` for details.
+ * See {@link module:core#timelocal|timelocal()} for details.
  *
  * @function module:core#timegm
  *
- * @param {Object} datetimespec
+ * @param {module:core.TimeSpec} datetimespec
  * The broken-down date and time dictionary.
  *
- * @returns {number|null}
+ * @returns {?number}
  *
  * @example
  * timegm({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
@@ -4982,7 +4995,7 @@
  * @param {boolean} [monotonic]
  * Whether to query the monotonic system clock.
  *
- * @returns {Array<number>|null}
+ * @returns {?number[]}
  *
  * @example
  * clock();        // [ 1647954926, 798269464 ]
@@ -5080,7 +5093,7 @@
  * @param {string} [skipchars]
  * The characters to skip during decoding.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * hexdec("48656c6c6f20776f726c64210a");  // "Hello world!\n"
@@ -5167,7 +5180,7 @@
  * @param {*} [argument]
  * The argument for the operation.
  *
- * @returns {boolean|number|null}
+ * @returns {?(boolean|number)}
  *
  * @example
  * gc();         // true
@@ -5792,4 +5805,4 @@
 
 	return NULL;
 }
-
\ No newline at end of file +
\ No newline at end of file diff --git a/lib_debug.c.html b/lib_debug.c.html index a19dfac5..6b67d949 100644 --- a/lib_debug.c.html +++ b/lib_debug.c.html @@ -1,6 +1,6 @@ Source: lib/debug.c
On this page

lib_debug.c

/*
+    
On this page

lib_debug.c

/*
  * Copyright (C) 2023 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -669,7 +669,7 @@
  * @param {string|module:fs.file|module:fs.proc} file
  * The file path or open file handle to write report to.
  *
- * @return {boolean|null}
+ * @return {?boolean}
  */
 static uc_value_t *
 uc_memdump(uc_vm_t *vm, size_t nargs)
@@ -820,7 +820,7 @@
  *
  * @function module:debug#sourcepos
  *
- * @return {module:debug.SourcePosition|null}
+ * @return {?module:debug.SourcePosition}
  */
 
 /**
@@ -957,7 +957,7 @@
  * @param {*} value
  * The value to query information for.
  *
- * @return {module:debug.ValueInformation|null}
+ * @return {?module:debug.ValueInformation}
  */
 
 /**
@@ -1364,7 +1364,7 @@
  * @param {string|number} variable
  * The variable index or variable name to obtain information for.
  *
- * @returns {module:debug.LocalInfo|null}
+ * @returns {?module:debug.LocalInfo}
  */
 static uc_value_t *
 uc_getlocal(uc_vm_t *vm, size_t nargs)
@@ -1408,7 +1408,7 @@
  * @param {*} [value=null]
  * The value to set the local variable to.
  *
- * @returns {module:debug.LocalInfo|null}
+ * @returns {?module:debug.LocalInfo}
  */
 static uc_value_t *
 uc_setlocal(uc_vm_t *vm, size_t nargs)
@@ -1554,7 +1554,7 @@
  * @param {string|number} variable
  * The variable index or variable name to obtain information for.
  *
- * @returns {module:debug.UpvalInfo|null}
+ * @returns {?module:debug.UpvalInfo}
  */
 static uc_value_t *
 uc_getupval(uc_vm_t *vm, size_t nargs)
@@ -1603,7 +1603,7 @@
  * @param {*} value
  * The value to set the variable to.
  *
- * @returns {module:debug.UpvalInfo|null}
+ * @returns {?module:debug.UpvalInfo}
  */
 static uc_value_t *
 uc_setupval(uc_vm_t *vm, size_t nargs)
@@ -1633,4 +1633,4 @@
 
 	debug_setup(vm);
 }
-
\ No newline at end of file +
\ No newline at end of file diff --git a/lib_fs.c.html b/lib_fs.c.html index 627ca098..b63bfc7e 100644 --- a/lib_fs.c.html +++ b/lib_fs.c.html @@ -1,6 +1,6 @@ Source: lib/fs.c
On this page

lib_fs.c

/*
+    
On this page

lib_fs.c

/*
  * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -81,7 +81,7 @@
  * @function module:fs#error
  *
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * // Trigger file system error
@@ -260,6 +260,8 @@
  * @class module:fs.proc
  * @hideconstructor
  *
+ * @borrows module:fs#error as module:fs.proc#error
+ *
  * @see {@link module:fs#popen|popen()}
  *
  * @example
@@ -277,26 +279,6 @@
  * handle.error();
  */
 
-/**
- * Query error information.
- *
- * Returns a string containing a description of the last occurred error or
- * `null` if there is no error information.
- *
- * @function module:fs.proc#error
- *
- * @returns {string|null}
- *
- * @example
- * // Trigger error
- * const fp = popen("command");
- * fp.close();
- * fp.close(); // already closed
- *
- * // Print error (should yield "Bad file descriptor")
- * print(fp.error(), "\n");
- */
-
 /**
  * Closes the program handle and awaits program termination.
  *
@@ -318,7 +300,7 @@
  *
  * @function module:fs.proc#close
  *
- * @returns {number|null}
+ * @returns {?number}
  */
 static uc_value_t *
 uc_fs_pclose(uc_vm_t *vm, size_t nargs)
@@ -380,7 +362,7 @@
  * The length of data to read. Can be a number, the string "line", the string
  * "all", or a single character string.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * const fp = popen("command", "r");
@@ -428,7 +410,7 @@
  * @param {*} data
  * The data to be written.
  *
- * @returns {number|null}
+ * @returns {?number}
  *
  * @example
  * const fp = popen("command", "w");
@@ -450,7 +432,7 @@
  *
  * @function module:fs.proc#flush
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  */
 static uc_value_t *
@@ -468,7 +450,7 @@
  *
  * @function module:fs.proc#fileno
  *
- * @returns {number|null}
+ * @returns {?number}
  */
 static uc_value_t *
 uc_fs_pfileno(uc_vm_t *vm, size_t nargs)
@@ -500,7 +482,7 @@
  * @param {string} [mode="r"]
  * The open mode of the process handle.
  *
- * @returns {module:fs.proc|null}
+ * @returns {?module:fs.proc}
  *
  * @example
  * // Open a process
@@ -533,6 +515,8 @@
  * @class module:fs.file
  * @hideconstructor
  *
+ * @borrows module:fs#error as module:fs.file#error
+ *
  * @see {@link module:fs#open|open()}
  * @see {@link module:fs#fdopen|fdopen()}
  * @see {@link module:fs#mkstemp|mkstemp()}
@@ -557,26 +541,6 @@
  * handle.error();
  */
 
-/**
- * Query error information.
- *
- * Returns a string containing a description of the last occurred error or
- * `null` if there is no error information.
- *
- * @function module:fs.file#error
- *
- * @returns {string|null}
- *
- * @example
- * // Trigger error
- * const fp = open("file.txt");
- * fp.close();
- * fp.close(); // already closed
- *
- * // Print error (should yield "Bad file descriptor")
- * print(fp.error(), "\n");
- */
-
 /**
  * Closes the file handle.
  *
@@ -589,7 +553,7 @@
  *
  * @function module:fs.file#close
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  */
 static uc_value_t *
 uc_fs_close(uc_vm_t *vm, size_t nargs)
@@ -641,7 +605,7 @@
  * The length of data to read. Can be a number, the string "line", the string
  * "all", or a single character string.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * const fp = open("file.txt", "r");
@@ -689,7 +653,7 @@
  * @param {*} data
  * The data to be written.
  *
- * @returns {number|null}
+ * @returns {?number}
  *
  * @example
  * const fp = open("file.txt", "w");
@@ -726,7 +690,7 @@
  * | `1`      | The given offset is relative to the current read position.                                   |
  * | `2`      | The given offset is relative to the end of the file.                                         |
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * const fp = open("file.txt", "r");
@@ -787,7 +751,7 @@
  *
  * @function module:fs.file#tell
  *
- * @returns {number|null}
+ * @returns {?number}
  */
 static uc_value_t *
 uc_fs_tell(uc_vm_t *vm, size_t nargs)
@@ -820,7 +784,7 @@
  *
  * @function module:fs.file#isatty
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  */
 static uc_value_t *
@@ -849,7 +813,7 @@
  *
  * @function module:fs.file#flush
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  */
 static uc_value_t *
@@ -867,7 +831,7 @@
  *
  * @function module:fs.file#fileno
  *
- * @returns {number|null}
+ * @returns {?number}
  */
 static uc_value_t *
 uc_fs_fileno(uc_vm_t *vm, size_t nargs)
@@ -915,7 +879,7 @@
  * @param {number} [perm=0o666]
  * The file creation permissions (for modes `w…` and `a…`)
  *
- * @returns {module:fs.file|null}
+ * @returns {?module:fs.file}
  *
  * @example
  * // Open a file in read-only mode
@@ -1060,6 +1024,8 @@
  * @class module:fs.dir
  * @hideconstructor
  *
+ * @borrows module:fs#error as module:fs.dir#error
+ *
  * @see {@link module:fs#opendir|opendir()}
  *
  * @example
@@ -1076,26 +1042,6 @@
  * handle.error();
  */
 
-/**
- * Query error information.
- *
- * Returns a string containing a description of the last occurred error or
- * `null` if there is no error information.
- *
- * @function module:fs.dir#error
- *
- * @returns {string|null}
- *
- * @example
- * // Trigger error
- * const fp = opendir("/tmp");
- * fp.close();
- * fp.close(); // already closed
- *
- * // Print error (should yield "Bad file descriptor")
- * print(fp.error(), "\n");
- */
-
 /**
  * Read the next entry from the open directory.
  *
@@ -1107,7 +1053,7 @@
  *
  * @function module:fs.dir#read
  *
- * @returns {string|null}
+ * @returns {?string}
  */
 static uc_value_t *
 uc_fs_readdir(uc_vm_t *vm, size_t nargs)
@@ -1141,7 +1087,7 @@
  *
  * @function module:fs.dir#tell
  *
- * @returns {number|null}
+ * @returns {?number}
  */
 static uc_value_t *
 uc_fs_telldir(uc_vm_t *vm, size_t nargs)
@@ -1176,7 +1122,7 @@
  * @param {number} offset
  * Position value obtained by `tell()`.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  *
@@ -1220,7 +1166,7 @@
  *
  * @function module:fs.dir#close
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  */
 static uc_value_t *
 uc_fs_closedir(uc_vm_t *vm, size_t nargs)
@@ -1249,7 +1195,7 @@
  * @param {string} path
  * The path to the directory.
  *
- * @returns {module:fs.dir|null}
+ * @returns {?module:fs.dir}
  *
  * @example
  * // Open a directory
@@ -1284,7 +1230,7 @@
  * @param {string} path
  * The path to the symbolic link.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * // Read the value of a symbolic link
@@ -1458,7 +1404,7 @@
  * @param {string} path
  * The path to the file or directory.
  *
- * @returns {module:fs.FileStatResult|null}
+ * @returns {?module:fs.FileStatResult}
  *
  * @example
  * // Get information about a file
@@ -1483,7 +1429,7 @@
  * @param {string} path
  * The path to the file or directory.
  *
- * @returns {module:fs.FileStatResult|null}
+ * @returns {?module:fs.FileStatResult}
  *
  * @example
  * // Get information about a directory
@@ -1507,7 +1453,7 @@
  * @param {string} path
  * The path to the new directory.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Create a directory
@@ -1541,7 +1487,7 @@
  * @param {string} path
  * The path to the directory to be removed.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Remove a directory
@@ -1576,7 +1522,7 @@
  * @param {string} path
  * The path of the symbolic link.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Create a symbolic link
@@ -1610,7 +1556,7 @@
  * @param {string} path
  * The path to the file or symbolic link.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Remove a file
@@ -1639,7 +1585,7 @@
  *
  * @function module:fs#getcwd
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * // Get the current working directory
@@ -1694,7 +1640,7 @@
  * @param {string} path
  * The path to the new working directory.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Change the current working directory
@@ -1730,7 +1676,7 @@
  * @param {number} mode
  * The new mode (permissions).
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Change the mode of a file
@@ -1874,7 +1820,7 @@
  * The new group's ID. When given as number, it is used as-is, when given as
  * string, the group name is resolved to the corresponding gid first.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Change the owner of a file
@@ -1920,7 +1866,7 @@
  * @param {string} newPath
  * The new path of the file or directory.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Rename a file
@@ -1982,7 +1928,7 @@
  * @param {string} path
  * The path to extract the directory name from.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * // Get the directory name of a path
@@ -2031,7 +1977,7 @@
  * @param {string} path
  * The path to extract the base name from.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * // Get the base name of a path
@@ -2085,7 +2031,7 @@
  * @param {string} path
  * The path to the directory.
  *
- * @returns {string[]|null}
+ * @returns {?string[]}
  *
  * @example
  * // List the content of a directory
@@ -2171,7 +2117,7 @@
  * @param {string} [template="/tmp/XXXXXX"]
  * The path template to use when forming the temporary file name.
  *
- * @returns {module:fs.file|null}
+ * @returns {?module:fs.file}
  *
  * @example
  * // Create a unique temporary file in the current working directory
@@ -2263,7 +2209,7 @@
  * @param {number} [mode="f"]
  * Optional access mode.
  *
- * @returns {boolean|null}
+ * @returns {?boolean}
  *
  * @example
  * // Check file read and write accessibility
@@ -2331,7 +2277,7 @@
  * Number of bytes to limit the result to. When omitted, the entire content is
  * returned.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * // Read first 100 bytes of content
@@ -2443,7 +2389,7 @@
  * Truncates the amount of data to be written to the specified amount of bytes.
  * When omitted, the entire content is written.
  *
- * @returns {number|null}
+ * @returns {?number}
  *
  * @example
  * // Write string to a file
@@ -2524,7 +2470,7 @@
  * @param {string} path
  * The path to the file or directory.
  *
- * @returns {string|null}
+ * @returns {?string}
  *
  * @example
  * // Resolve the absolute path of a file
@@ -2563,7 +2509,7 @@
  *
  * @function module:fs#pipe
  *
- * @returns {module:fs.file[]|null}
+ * @returns {?module:fs.file[]}
  *
  * @example
  * // Create a pipe
@@ -2707,4 +2653,4 @@
 	ucv_object_add(scope, "stdout", uc_resource_new(file_type, stdout));
 	ucv_object_add(scope, "stderr", uc_resource_new(file_type, stderr));
 }
-
\ No newline at end of file +
\ No newline at end of file diff --git a/lib_log.c.html b/lib_log.c.html index ff82309d..6b38e7b5 100644 --- a/lib_log.c.html +++ b/lib_log.c.html @@ -1,6 +1,6 @@ Source: lib/log.c
On this page

lib_log.c

/*
+    
On this page

lib_log.c

/*
  * Copyright (C) 2023 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -1074,4 +1074,4 @@
 	ADD_CONST(ULOG_STDIO);
 #endif
 }
-
\ No newline at end of file +
\ No newline at end of file diff --git a/lib_math.c.html b/lib_math.c.html index 21162a0a..270ea7ca 100644 --- a/lib_math.c.html +++ b/lib_math.c.html @@ -1,6 +1,6 @@ Source: lib/math.c
On this page

lib_math.c

/*
+    
On this page

lib_math.c

/*
  * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -480,4 +480,4 @@
 {
 	uc_function_list_register(scope, math_fns);
 }
-
\ No newline at end of file +
\ No newline at end of file diff --git a/lib_struct.c.html b/lib_struct.c.html index 99dcbfeb..df45f4b3 100644 --- a/lib_struct.c.html +++ b/lib_struct.c.html @@ -1,6 +1,6 @@ Source: lib/struct.c
On this page

lib_struct.c

/*
+    
On this page

lib_struct.c

/*
  * Binary data packing/unpacking module for ucode.
  * Copyright (C) 2021 Jo-Philipp Wich <jo@mein.io>
  *
@@ -2953,4 +2953,4 @@
 
 	struct_type = uc_type_declare(vm, "struct", struct_inst_fns, uc_struct_gc);
 }
-
\ No newline at end of file +
\ No newline at end of file diff --git a/lib_uci.c.html b/lib_uci.c.html new file mode 100644 index 00000000..3b2adff2 --- /dev/null +++ b/lib_uci.c.html @@ -0,0 +1,1874 @@ +Source: lib/uci.c
On this page

lib_uci.c

/*
+ * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/**
+ * # OpenWrt UCI configuration
+ *
+ * The `uci` module provides access to the native OpenWrt
+ * {@link https://github.com/openwrt/uci libuci} API for reading and
+ * manipulating UCI configuration files.
+ *
+ * Functions can be individually imported and directly accessed using the
+ * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}
+ * syntax:
+ *
+ *   ```
+ *   import { cursor } from 'uci';
+ *
+ *   let ctx = cursor();
+ *   let hostname = ctx.get_first('system', 'system', 'hostname');
+ *   ```
+ *
+ * Alternatively, the module namespace can be imported
+ * using a wildcard import statement:
+ *
+ *   ```
+ *   import * as uci from 'uci';
+ *
+ *   let ctx = uci.cursor();
+ *   let hostname = ctx.get_first('system', 'system', 'hostname');
+ *   ```
+ *
+ * Additionally, the uci module namespace may also be imported by invoking
+ * the `ucode` interpreter with the `-luci` switch.
+ *
+ * @module uci
+ */
+
+#include <string.h>
+#include <uci.h>
+
+#include "ucode/module.h"
+
+#define err_return(err) do { last_error = err; return NULL; } while(0)
+
+static int last_error = 0;
+static uc_resource_type_t *cursor_type;
+
+enum pkg_cmd {
+	CMD_SAVE,
+	CMD_COMMIT,
+	CMD_REVERT
+};
+
+/**
+ * Query error information.
+ *
+ * Returns a string containing a description of the last occurred error or
+ * `null` if there is no error information.
+ *
+ * @function module:uci#error
+ *
+ * @returns {?string}
+ *
+ * @example
+ * // Trigger error
+ * const ctx = cursor();
+ * ctx.set("not_existing_config", "test", "1");
+ *
+ * // Print error (should yield "Entry not found")
+ * print(ctx.error(), "\n");
+ */
+static uc_value_t *
+uc_uci_error(uc_vm_t *vm, size_t nargs)
+{
+	char buf[sizeof("Unknown error: -9223372036854775808")];
+	uc_value_t *errmsg;
+
+	const char *errstr[] = {
+		[UCI_ERR_MEM] =       "Out of memory",
+		[UCI_ERR_INVAL] =     "Invalid argument",
+		[UCI_ERR_NOTFOUND] =  "Entry not found",
+		[UCI_ERR_IO] =        "I/O error",
+		[UCI_ERR_PARSE] =     "Parse error",
+		[UCI_ERR_DUPLICATE] = "Duplicate entry",
+		[UCI_ERR_UNKNOWN] =   "Unknown error",
+	};
+
+	if (last_error == 0)
+		return NULL;
+
+	if (last_error >= 0 && (unsigned)last_error < ARRAY_SIZE(errstr)) {
+		errmsg = ucv_string_new(errstr[last_error]);
+	}
+	else {
+		snprintf(buf, sizeof(buf), "Unknown error: %d", last_error);
+		errmsg = ucv_string_new(buf);
+	}
+
+	last_error = 0;
+
+	return errmsg;
+}
+
+
+/**
+ * Instantiate uci cursor.
+ *
+ * A uci cursor is a context for interacting with uci configuration files. It's
+ * purpose is to cache and hold changes made to loaded configuration states
+ * until those changes are written out to disk or discared.
+ *
+ * Unsaved and uncommitted changes in a cursor instance are private and not
+ * visible to other cursor instances instantiated by the same program or other
+ * processes on the system.
+ *
+ * Returns the instantiated cursor on success.
+ *
+ * Returns `null` on error, e.g. if an invalid path argument was provided.
+ *
+ * @function module:uci#cursor
+ *
+ * @param {string} [config_dir=/etc/config]
+ * The directory to search for configuration files. It defaults to the well
+ * known uci configuration directory `/etc/config` but may be set to a different
+ * path for special purpose applications.
+ *
+ * @param {string} [delta_dir=/tmp/.uci]
+ * The directory to save delta records in. It defaults to the well known
+ * `/tmp/.uci` path which is used as default by the uci command line tool.
+ *
+ * By changing this path to a different location, it is possible to isolate
+ * uncommitted application changes from the uci cli or other processes on the
+ * system.
+ *
+ * @returns {?module:uci.cursor}
+ */
+static uc_value_t *
+uc_uci_cursor(uc_vm_t *vm, size_t nargs)
+{
+	uc_value_t *cdir = uc_fn_arg(0);
+	uc_value_t *sdir = uc_fn_arg(1);
+	struct uci_context *c;
+	int rv;
+
+	if ((cdir && ucv_type(cdir) != UC_STRING) ||
+	    (sdir && ucv_type(sdir) != UC_STRING))
+		err_return(UCI_ERR_INVAL);
+
+	c = uci_alloc_context();
+
+	if (!c)
+		err_return(UCI_ERR_MEM);
+
+	if (cdir) {
+		rv = uci_set_confdir(c, ucv_string_get(cdir));
+
+		if (rv)
+			err_return(rv);
+	}
+
+	if (sdir) {
+		rv = uci_set_savedir(c, ucv_string_get(sdir));
+
+		if (rv)
+			err_return(rv);
+	}
+
+	return uc_resource_new(cursor_type, c);
+}
+
+
+/**
+ * Represents a context for interacting with uci configuration files.
+ *
+ * Operations on uci configurations are performed through a uci cursor object
+ * which operates on in-memory representations of loaded configuration files.
+ *
+ * Any changes made to configuration values are local to the cursor object and
+ * held in memory only until they're written out to the filesystem using the
+ * `save()` and `commit()` methods.
+ *
+ * Changes performed in one cursor instance are not reflected in another, unless
+ * the first instance writes those changes to the filesystem and the other
+ * instance explicitly (re)loads the affected configuration files.
+ *
+ * @class module:uci.cursor
+ * @hideconstructor
+ *
+ * @borrows module:uci#error as module.uci.cursor#error
+ *
+ * @see {@link module:uci#cursor|cursor()}
+ *
+ * @example
+ *
+ * const ctx = cursor(…);
+ *
+ * // Enumerate configuration files
+ * ctx.configs();
+ *
+ * // Load configuration files
+ * ctx.load(…);
+ * ctx.unload(…);
+ *
+ * // Query values
+ * ctx.get(…);
+ * ctx.get_all(…);
+ * ctx.get_first(…);
+ * ctx.foreach(…);
+ *
+ * // Modify values
+ * ctx.add(…);
+ * ctx.set(…);
+ * ctx.rename(…);
+ * ctx.reorder(…);
+ * ctx.delete(…);
+ *
+ * // Stage, revert, save changes
+ * ctx.changes(…);
+ * ctx.save(…);
+ * ctx.revert(…);
+ * ctx.commit(…);
+ */
+
+/**
+ * A uci change record is a plain array containing the change operation name as
+ * first element, the affected section ID as second argument and an optional
+ * third and fourth argument whose meanings depend on the operation.
+ *
+ * @typedef {string[]} ChangeRecord
+ * @memberof module:uci.cursor
+ *
+ * @property {string} 0
+ * The operation name - may be one of `add`, `set`, `remove`, `order`,
+ * `list-add`, `list-del` or `rename`.
+ *
+ * @property {string} 1
+ * The section ID targeted by the operation.
+ *
+ * @property {string} 2
+ * The meaning of the third element depends on the operation.
+ * - For `add` it is type of the section that has been added
+ * - For `set` it either is the option name if a fourth element exists, or the
+ *   type of a named section which has been added when the change entry only
+ *   contains three elements.
+ * - For `remove` it contains the name of the option that has been removed.
+ * - For `order` it specifies the new sort index of the section.
+ * - For `list-add` it contains the name of the list option a new value has been
+ *   added to.
+ * - For `list-del` it contains the name of the list option a value has been
+ *   removed from.
+ * - For `rename` it contains the name of the option that has been renamed if a
+ *   fourth element exists, else it contains the new name a section has been
+ *   renamed to if the change entry only contains three elements.
+ *
+ * @property {string} 4
+ * The meaning of the fourth element depends on the operation.
+ * - For `set` it is the value an option has been set to.
+ * - For `list-add` it is the new value that has been added to a list option.
+ * - For `rename` it is the new name of an option that has been renamed.
+ */
+
+/**
+ * A section object represents the options and their corresponding values
+ * enclosed within a configuration section, as well as some additional meta data
+ * such as sort indexes and internal ID.
+ *
+ * Any internal metadata fields are prefixed with a dot which isn't an allowed
+ * character for normal option names.
+ *
+ * @typedef {Object<string, boolean|number|string|string[]>} SectionObject
+ * @memberof module:uci.cursor
+ *
+ * @property {boolean} .anonymous
+ * The `.anonymous` property specifies whether the configuration is
+ * anonymous (`true`) or named (`false`).
+ *
+ * @property {number} .index
+ * The `.index` property specifies the sort order of the section.
+ *
+ * @property {string} .name
+ * The `.name` property holds the name of the section object. It may be either
+ * an anonymous ID in the form `cfgXXXXXX` with `X` being a hexadecimal digit or
+ * a string holding the name of the section.
+ *
+ * @property {string} .type
+ * The `.type` property contains the type of the corresponding uci
+ * section.
+ *
+ * @property {string|string[]} *
+ * A section object may contain an arbitrary number of further properties
+ * representing the uci option enclosed in the section.
+ *
+ * All option property names will be in the form `[A-Za-z0-9_]+` and either
+ * contain a string value or an array of strings, in case the underlying option
+ * is an UCI list.
+ */
+
+/**
+ * The sections callback is invoked for each section found within the given
+ * configuration and receives the section object and its associated name as
+ * arguments.
+ *
+ * @callback module:uci.cursor.SectionCallback
+ *
+ * @param {module:uci.cursor.SectionObject} section
+ * The section object.
+ */
+
+/**
+ * Explicitly reload configuration file.
+ *
+ * Usually, any attempt to query or modify a value within a given configuration
+ * will implicitly load the underlying file into memory. By invoking `load()`
+ * explicitly, a potentially loaded stale configuration is discarded and
+ * reloaded from the file system, ensuring that the latest state is reflected in
+ * the cursor.
+ *
+ * Returns `true` if the configuration was successfully loaded.
+ *
+ * Returns `null` on error, e.g. if the requested configuration does not exist.
+ *
+ * @function module:uci.cursor#load
+ *
+ * @param {string} config
+ * The name of the configuration file to load, e.g. `"system"` to load
+ * `/etc/config/system` into the cursor.
+ *
+ * @returns {?boolean}
+ */
+static uc_value_t *
+uc_uci_load(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	struct uci_element *e;
+	char *s;
+
+	if (!c || !*c)
+		err_return(UCI_ERR_INVAL);
+
+	if (ucv_type(conf) != UC_STRING)
+		err_return(UCI_ERR_INVAL);
+
+	s = ucv_string_get(conf);
+
+	uci_foreach_element(&(*c)->root, e) {
+		if (!strcmp(e->name, s)) {
+			uci_unload(*c, uci_to_package(e));
+			break;
+		}
+	}
+
+	if (uci_load(*c, s, NULL))
+		err_return((*c)->err);
+
+	return ucv_boolean_new(true);
+}
+
+/**
+ * Explicitly unload configuration file.
+ *
+ * The `unload()` function forcibly discards a loaded configuration state from
+ * the cursor so that the next attempt to read or modify that configuration
+ * will load it anew from the file system.
+ *
+ * Returns `true` if the configuration was successfully unloaded.
+ *
+ * Returns `false` if the configuration was not loaded to begin with.
+ *
+ * Returns `null` on error, e.g. if the requested configuration does not exist.
+ *
+ * @function module:uci.cursor#unload
+ *
+ * @param {string} config
+ * The name of the configuration file to unload.
+ *
+ * @returns {?boolean}
+ */
+static uc_value_t *
+uc_uci_unload(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	struct uci_element *e;
+
+	if (!c || !*c)
+		err_return(UCI_ERR_INVAL);
+
+	if (ucv_type(conf) != UC_STRING)
+		err_return(UCI_ERR_INVAL);
+
+	uci_foreach_element(&(*c)->root, e) {
+		if (!strcmp(e->name, ucv_string_get(conf))) {
+			uci_unload(*c, uci_to_package(e));
+
+			return ucv_boolean_new(true);
+		}
+	}
+
+	return ucv_boolean_new(false);
+}
+
+static int
+lookup_extended(struct uci_context *ctx, struct uci_ptr *ptr, bool extended)
+{
+	int rv;
+	struct uci_ptr lookup;
+
+	/* use a copy of the passed ptr since failing lookups will
+	 * clobber the state */
+	lookup = *ptr;
+	lookup.flags |= UCI_LOOKUP_EXTENDED;
+
+	rv = uci_lookup_ptr(ctx, &lookup, NULL, extended);
+
+	/* copy to passed ptr on success */
+	if (!rv)
+		*ptr = lookup;
+
+	return rv;
+}
+
+static int
+lookup_ptr(struct uci_context *ctx, struct uci_ptr *ptr, bool extended)
+{
+	if (ptr && !ptr->s && ptr->section && *ptr->section == '@')
+		return lookup_extended(ctx, ptr, extended);
+
+	return uci_lookup_ptr(ctx, ptr, NULL, extended);
+}
+
+static uc_value_t *
+option_to_uval(uc_vm_t *vm, struct uci_option *o)
+{
+	struct uci_element *e;
+	uc_value_t *arr;
+
+	switch (o->type) {
+	case UCI_TYPE_STRING:
+		return ucv_string_new(o->v.string);
+
+	case UCI_TYPE_LIST:
+		arr = ucv_array_new(vm);
+
+		if (arr)
+			uci_foreach_element(&o->v.list, e)
+				ucv_array_push(arr, ucv_string_new(e->name));
+
+		return arr;
+
+	default:
+		return NULL;
+	}
+}
+
+static uc_value_t *
+section_to_uval(uc_vm_t *vm, struct uci_section *s, int index)
+{
+	uc_value_t *so = ucv_object_new(vm);
+	struct uci_element *e;
+	struct uci_option *o;
+
+	if (!so)
+		return NULL;
+
+	ucv_object_add(so, ".anonymous", ucv_boolean_new(s->anonymous));
+	ucv_object_add(so, ".type", ucv_string_new(s->type));
+	ucv_object_add(so, ".name", ucv_string_new(s->e.name));
+
+	if (index >= 0)
+		ucv_object_add(so, ".index", ucv_int64_new(index));
+
+	uci_foreach_element(&s->options, e) {
+		o = uci_to_option(e);
+		ucv_object_add(so, o->e.name, option_to_uval(vm, o));
+	}
+
+	return so;
+}
+
+static uc_value_t *
+package_to_uval(uc_vm_t *vm, struct uci_package *p)
+{
+	uc_value_t *po = ucv_object_new(vm);
+	uc_value_t *so;
+	struct uci_element *e;
+	int i = 0;
+
+	if (!po)
+		return NULL;
+
+	uci_foreach_element(&p->sections, e) {
+		so = section_to_uval(vm, uci_to_section(e), i++);
+		ucv_object_add(po, e->name, so);
+	}
+
+	return po;
+}
+
+static uc_value_t *
+uc_uci_get_any(uc_vm_t *vm, size_t nargs, bool all)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *sect = uc_fn_arg(1);
+	uc_value_t *opt = uc_fn_arg(2);
+	struct uci_ptr ptr = { 0 };
+	int rv;
+
+	if (!c || !*c)
+		err_return(UCI_ERR_INVAL);
+
+	if ((ucv_type(conf) != UC_STRING) ||
+	    (sect && ucv_type(sect) != UC_STRING) ||
+	    (opt && ucv_type(opt) != UC_STRING))
+		err_return(UCI_ERR_INVAL);
+
+	if ((!sect && !all) || (opt && all))
+		err_return(UCI_ERR_INVAL);
+
+	ptr.package = ucv_string_get(conf);
+	ptr.section = sect ? ucv_string_get(sect) : NULL;
+	ptr.option = opt ? ucv_string_get(opt) : NULL;
+
+	rv = lookup_ptr(*c, &ptr, true);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	if (!(ptr.flags & UCI_LOOKUP_COMPLETE))
+		err_return(UCI_ERR_NOTFOUND);
+
+	if (all) {
+		if (ptr.section) {
+			if (!ptr.s)
+				err_return(UCI_ERR_NOTFOUND);
+
+			return section_to_uval(vm, ptr.s, -1);
+		}
+
+		if (!ptr.p)
+			err_return(UCI_ERR_NOTFOUND);
+
+		return package_to_uval(vm, ptr.p);
+	}
+
+	if (ptr.option) {
+		if (!ptr.o)
+			err_return(UCI_ERR_NOTFOUND);
+
+		return option_to_uval(vm, ptr.o);
+	}
+
+	if (!ptr.s)
+		err_return(UCI_ERR_NOTFOUND);
+
+	return ucv_string_new(ptr.s->type);
+}
+
+/**
+ * Query a single option value or section type.
+ *
+ * When invoked with three arguments, the function returns the value of the
+ * given option, within the specified section of the given configuration.
+ *
+ * When invoked with just a config and section argument, the function returns
+ * the type of the specified section.
+ *
+ * In either case, the given configuration is implicitly loaded into the cursor
+ * if not already present.
+ *
+ * Returns the configuration value or section type on success.
+ *
+ * Returns `null` on error, e.g. if the requested configuration does not exist
+ * or if an invalid argument was passed.
+ *
+ * @function module:uci.cursor#get
+ *
+ * @param {string} config
+ * The name of the configuration file to query, e.g. `"system"` to query values
+ * in `/etc/config/system`.
+ *
+ * @param {string} section
+ * The name of the section to query within the configuration.
+ *
+ * @param {string} [option]
+ * The name of the option to query within the section. If omitted, the type of
+ * the section is returned instead.
+ *
+ * @returns {?(string|string[])}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Query an option, extended section notation is supported
+ * ctx.get('system', '@system[0]', 'hostname');
+ *
+ * // Query a section type (should yield 'interface')
+ * ctx.get('network', 'lan');
+ */
+static uc_value_t *
+uc_uci_get(uc_vm_t *vm, size_t nargs)
+{
+	return uc_uci_get_any(vm, nargs, false);
+}
+
+/**
+ * Query a complete section or configuration.
+ *
+ * When invoked with two arguments, the function returns all values of the
+ * specified section within the given configuration as dictionary.
+ *
+ * When invoked with just a config argument, the function returns a nested
+ * dictionary of all sections present within the given configuration.
+ *
+ * In either case, the given configuration is implicitly loaded into the cursor
+ * if not already present.
+ *
+ * Returns the section or configuration dictionary on success.
+ *
+ * Returns `null` on error, e.g. if the requested configuration does not exist
+ * or if an invalid argument was passed.
+ *
+ * @function module:uci.cursor#get_all
+ *
+ * @param {string} config
+ * The name of the configuration file to query, e.g. `"system"` to query values
+ * in `/etc/config/system`.
+ *
+ * @param {string} [section]
+ * The name of the section to query within the configuration. If omitted a
+ * nested dictionary containing all section values is returned.
+ *
+ * @returns {?(Object<string, module:uci.cursor.SectionObject>|module:uci.cursor.SectionObject)}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Query all lan interface details
+ * ctx.get_all('network', 'lan');
+ *
+ * // Dump the entire dhcp configuration
+ * ctx.get_all('dhcp');
+ */
+static uc_value_t *
+uc_uci_get_all(uc_vm_t *vm, size_t nargs)
+{
+	return uc_uci_get_any(vm, nargs, true);
+}
+
+/**
+ * Query option value or name of first section of given type.
+ *
+ * When invoked with three arguments, the function returns the value of the
+ * given option within the first found section of the specified type in the
+ * given configuration.
+ *
+ * When invoked with just a config and section type argument, the function
+ * returns the name of the first found section of the given type.
+ *
+ * In either case, the given configuration is implicitly loaded into the cursor
+ * if not already present.
+ *
+ * Returns the configuration value or section name on success.
+ *
+ * Returns `null` on error, e.g. if the requested configuration does not exist
+ * or if an invalid argument was passed.
+ *
+ * @function module:uci.cursor#get_first
+ *
+ * @param {string} config
+ * The name of the configuration file to query, e.g. `"system"` to query values
+ * in `/etc/config/system`.
+ *
+ * @param {string} type
+ * The section type to find the first section for within the configuration.
+ *
+ * @param {string} [option]
+ * The name of the option to query within the section. If omitted, the name of
+ * the section is returned instead.
+ *
+ * @returns {?(string|string[])}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Query hostname in first anonymous "system" section of /etc/config/system
+ * ctx.get_first('system', 'system', 'hostname');
+ *
+ * // Figure out name of first network interface section (usually "loopback")
+ * ctx.get_first('network', 'interface');
+ */
+static uc_value_t *
+uc_uci_get_first(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *type = uc_fn_arg(1);
+	uc_value_t *opt = uc_fn_arg(2);
+	struct uci_package *p = NULL;
+	struct uci_section *sc;
+	struct uci_element *e;
+	struct uci_ptr ptr = { 0 };
+	int rv;
+
+	if (ucv_type(conf) != UC_STRING ||
+	    ucv_type(type) != UC_STRING ||
+	    (opt && ucv_type(opt) != UC_STRING))
+		err_return(UCI_ERR_INVAL);
+
+	uci_foreach_element(&(*c)->root, e) {
+		if (strcmp(e->name, ucv_string_get(conf)))
+			continue;
+
+		p = uci_to_package(e);
+		break;
+	}
+
+	if (!p && uci_load(*c, ucv_string_get(conf), &p))
+		err_return((*c)->err);
+
+	uci_foreach_element(&p->sections, e) {
+		sc = uci_to_section(e);
+
+		if (strcmp(sc->type, ucv_string_get(type)))
+			continue;
+
+		if (!opt)
+			return ucv_string_new(sc->e.name);
+
+		ptr.package = ucv_string_get(conf);
+		ptr.section = sc->e.name;
+		ptr.option = ucv_string_get(opt);
+		ptr.p = p;
+		ptr.s = sc;
+
+		rv = lookup_ptr(*c, &ptr, false);
+
+		if (rv != UCI_OK)
+			err_return(rv);
+
+		if (!(ptr.flags & UCI_LOOKUP_COMPLETE))
+			err_return(UCI_ERR_NOTFOUND);
+
+		return option_to_uval(vm, ptr.o);
+	}
+
+	err_return(UCI_ERR_NOTFOUND);
+}
+
+/**
+ * Add anonymous section to given configuration.
+ *
+ * Adds a new anonymous (unnamed) section of the specified type to the given
+ * configuration. In order to add a named section, the three argument form of
+ * `set()` should be used instead.
+ *
+ * In contrast to other query functions, `add()` will not implicitly load the
+ * configuration into the cursor. The configuration either needs to be loaded
+ * explicitly through `load()` beforehand, or implicitly by querying it through
+ * one of the `get()`, `get_all()`, `get_first()` or `foreach()` functions.
+ *
+ * Returns the autogenerated, ephemeral name of the added unnamed section
+ * on success.
+ *
+ * Returns `null` on error, e.g. if the targeted configuration was not loaded or
+ * if an invalid section type value was passed.
+ *
+ * @function module:uci.cursor#add
+ *
+ * @param {string} config
+ * The name of the configuration file to add the section to, e.g. `"system"` to
+ * modify `/etc/config/system`.
+ *
+ * @param {string} type
+ * The type value to use for the added section.
+ *
+ * @returns {?string}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Load firewall configuration
+ * ctx.load('firewall');
+ *
+ * // Add unnamed `config rule` section
+ * const sid = ctx.add('firewall', 'rule');
+ *
+ * // Set values on the newly added section
+ * ctx.set('firewall', sid, 'name', 'A test');
+ * ctx.set('firewall', sid, 'target', 'ACCEPT');
+ * …
+ */
+static uc_value_t *
+uc_uci_add(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *type = uc_fn_arg(1);
+	struct uci_element *e = NULL;
+	struct uci_package *p = NULL;
+	struct uci_section *sc = NULL;
+	int rv;
+
+	if (ucv_type(conf) != UC_STRING ||
+	    ucv_type(type) != UC_STRING)
+	    err_return(UCI_ERR_INVAL);
+
+	uci_foreach_element(&(*c)->root, e) {
+		if (!strcmp(e->name, ucv_string_get(conf))) {
+			p = uci_to_package(e);
+			break;
+		}
+	}
+
+	if (!p)
+		err_return(UCI_ERR_NOTFOUND);
+
+	rv = uci_add_section(*c, p, ucv_string_get(type), &sc);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+	else if (!sc)
+		err_return(UCI_ERR_NOTFOUND);
+
+	return ucv_string_new(sc->e.name);
+}
+
+static bool
+uval_to_uci(uc_vm_t *vm, uc_value_t *val, const char **p, bool *is_list)
+{
+	uc_value_t *item;
+
+	*p = NULL;
+
+	if (is_list)
+		*is_list = false;
+
+	switch (ucv_type(val)) {
+	case UC_ARRAY:
+		if (ucv_array_length(val) == 0)
+			return false;
+
+		item = ucv_array_get(val, 0);
+
+		/* don't recurse */
+		if (ucv_type(item) == UC_ARRAY)
+			return false;
+
+		if (is_list)
+			*is_list = true;
+
+		return uval_to_uci(vm, item, p, NULL);
+
+	case UC_BOOLEAN:
+		*p = xstrdup(ucv_boolean_get(val) ? "1" : "0");
+
+		return true;
+
+	case UC_DOUBLE:
+	case UC_INTEGER:
+	case UC_STRING:
+		*p = ucv_to_string(vm, val);
+		/* fall through */
+
+	case UC_NULL:
+		return true;
+
+	default:
+		return false;
+	}
+}
+
+/**
+ * Set option value or add named section in given configuration.
+ *
+ * When invoked with four arguments, the function sets the value of the given
+ * option within the specified section of the given configuration to the
+ * provided value. A value of `""` (empty string) can be used to delete an
+ * existing option.
+ *
+ * When invoked with three arguments, the function adds a new named section to
+ * the given configuration, using the specified type.
+ *
+ * In either case, the given configuration is implicitly loaded into the cursor
+ * if not already present.
+ *
+ * Returns the `true` if the named section was added or the specified option was
+ * set.
+ *
+ * Returns `null` on error, e.g. if the targeted configuration was not found or
+ * if an invalid value was passed.
+ *
+ * @function module:uci.cursor#set
+ *
+ * @param {string} config
+ * The name of the configuration file to set values in, e.g. `"system"` to
+ * modify `/etc/config/system`.
+ *
+ * @param {string} section
+ * The section name to create or set a value in.
+ *
+ * @param {string} option_or_type
+ * The option name to set within the section or, when the subsequent value
+ * argument is omitted, the type of the section to create within the
+ * configuration.
+ *
+ * @param {(Array<string|boolean|number>|string|boolean|number)} [value]
+ * The option value to set.
+ *
+ * @returns {?boolean}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Add named `config interface guest` section
+ * ctx.set('network', 'guest', 'interface');
+ *
+ * // Set values on the newly added section
+ * ctx.set('network', 'guest', 'proto', 'static');
+ * ctx.set('network', 'guest', 'ipaddr', '10.0.0.1/24');
+ * ctx.set('network', 'guest', 'dns', ['8.8.4.4', '8.8.8.8']);
+ * …
+ *
+ * // Delete 'disabled' option in first wifi-iface section
+ * ctx.set('wireless', '@wifi-iface[0]', 'disabled', '');
+ */
+static uc_value_t *
+uc_uci_set(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *sect = uc_fn_arg(1);
+	uc_value_t *opt = NULL, *val = NULL;
+	struct uci_ptr ptr = { 0 };
+	bool is_list = false;
+	size_t i;
+	int rv;
+
+	if (ucv_type(conf) != UC_STRING ||
+	    ucv_type(sect) != UC_STRING)
+	    err_return(UCI_ERR_INVAL);
+
+	switch (nargs) {
+	/* conf, sect, opt, val */
+	case 4:
+		opt = uc_fn_arg(2);
+		val = uc_fn_arg(3);
+
+		if (ucv_type(opt) != UC_STRING)
+			err_return(UCI_ERR_INVAL);
+
+		break;
+
+	/* conf, sect, type */
+	case 3:
+		val = uc_fn_arg(2);
+
+		if (ucv_type(val) != UC_STRING)
+			err_return(UCI_ERR_INVAL);
+
+		break;
+
+	default:
+		err_return(UCI_ERR_INVAL);
+	}
+
+	ptr.package = ucv_string_get(conf);
+	ptr.section = ucv_string_get(sect);
+	ptr.option = opt ? ucv_string_get(opt) : NULL;
+
+	rv = lookup_ptr(*c, &ptr, true);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	if (!ptr.s && ptr.option)
+		err_return(UCI_ERR_NOTFOUND);
+
+	if (!uval_to_uci(vm, val, &ptr.value, &is_list))
+		err_return(UCI_ERR_INVAL);
+
+	if (is_list) {
+		/* if we got a one-element array, delete existing option (if any)
+		 * and iterate array at offset 0 */
+		if (ucv_array_length(val) == 1) {
+			i = 0;
+
+			free((char *)ptr.value);
+			ptr.value = NULL;
+
+			if (ptr.o) {
+				rv = uci_delete(*c, &ptr);
+
+				if (rv != UCI_OK)
+					err_return(rv);
+			}
+		}
+		/* if we get a multi element array, overwrite existing option (if any)
+		 * with first value and iterate remaining array at offset 1 */
+		else {
+			i = 1;
+
+			rv = uci_set(*c, &ptr);
+			free((char *)ptr.value);
+
+			if (rv != UCI_OK)
+				err_return(rv);
+		}
+
+		for (; i < ucv_array_length(val); i++) {
+			if (!uval_to_uci(vm, ucv_array_get(val, i), &ptr.value, NULL))
+				continue;
+
+			rv = uci_add_list(*c, &ptr);
+			free((char *)ptr.value);
+
+			if (rv != UCI_OK)
+				err_return(rv);
+		}
+	}
+	else {
+		rv = uci_set(*c, &ptr);
+		free((char *)ptr.value);
+
+		if (rv != UCI_OK)
+			err_return(rv);
+	}
+
+	return ucv_boolean_new(true);
+}
+
+/**
+ * Delete an option or section from given configuration.
+ *
+ * When invoked with three arguments, the function deletes the given option
+ * within the specified section of the given configuration.
+ *
+ * When invoked with two arguments, the function deletes the entire specified
+ * section within the given configuration.
+ *
+ * In either case, the given configuration is implicitly loaded into the cursor
+ * if not already present.
+ *
+ * Returns the `true` if specified option or section has been deleted.
+ *
+ * Returns `null` on error, e.g. if the targeted configuration was not found or
+ * if an invalid value was passed.
+ *
+ * @function module:uci.cursor#delete
+ *
+ * @param {string} config
+ * The name of the configuration file to delete values in, e.g. `"system"` to
+ * modify `/etc/config/system`.
+ *
+ * @param {string} section
+ * The section name to remove the specified option in or, when the subsequent
+ * argument is omitted, the section to remove entirely.
+ *
+ * @param {string} [option]
+ * The option name to remove within the section.
+ *
+ * @returns {?boolean}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Delete 'disabled' option in first wifi-iface section
+ * ctx.delete('wireless', '@wifi-iface[0]', 'disabled');
+ *
+ * // Delete 'wan' interface
+ * ctx.delete('network', 'lan');
+ *
+ * // Delete last firewall rule
+ * ctx.delete('firewall', '@rule[-1]');
+ */
+static uc_value_t *
+uc_uci_delete(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *sect = uc_fn_arg(1);
+	uc_value_t *opt = uc_fn_arg(2);
+	struct uci_ptr ptr = { 0 };
+	int rv;
+
+	if (ucv_type(conf) != UC_STRING ||
+	    ucv_type(sect) != UC_STRING ||
+	    (opt && ucv_type(opt) != UC_STRING))
+	    err_return(UCI_ERR_INVAL);
+
+	ptr.package = ucv_string_get(conf);
+	ptr.section = ucv_string_get(sect);
+	ptr.option = opt ? ucv_string_get(opt) : NULL;
+
+	rv = lookup_ptr(*c, &ptr, true);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	if (opt ? !ptr.o : !ptr.s)
+		err_return(UCI_ERR_NOTFOUND);
+
+	rv = uci_delete(*c, &ptr);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	return ucv_boolean_new(true);
+}
+
+/**
+ * Rename an option or section in given configuration.
+ *
+ * When invoked with four arguments, the function renames the given option
+ * within the specified section of the given configuration to the provided
+ * value.
+ *
+ * When invoked with three arguments, the function renames the entire specified
+ * section to the provided value.
+ *
+ * In either case, the given configuration is implicitly loaded into the cursor
+ * if not already present.
+ *
+ * Returns the `true` if specified option or section has been renamed.
+ *
+ * Returns `null` on error, e.g. if the targeted configuration was not found or
+ * if an invalid value was passed.
+ *
+ * @function module:uci.cursor#rename
+ *
+ * @param {string} config
+ * The name of the configuration file to rename values in, e.g. `"system"` to
+ * modify `/etc/config/system`.
+ *
+ * @param {string} section
+ * The section name to rename or to rename an option in.
+ *
+ * @param {string} option_or_name
+ * The option name to rename within the section or, when the subsequent name
+ * argument is omitted, the new name of the renamed section within the
+ * configuration.
+ *
+ * @param {string} [name]
+ * The new name of the option to rename.
+ *
+ * @returns {?boolean}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Assign explicit name to last anonymous firewall rule section
+ * ctx.rename('firewall', '@rule[-1]', 'my_block_rule');
+ *
+ * // Rename 'server' to 'orig_server_list' in ntp section of system config
+ * ctx.rename('system', 'ntp', 'server', 'orig_server_list');
+ *
+ * // Rename 'wan' interface to 'external'
+ * ctx.rename('network', 'wan', 'external');
+ */
+static uc_value_t *
+uc_uci_rename(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *sect = uc_fn_arg(1);
+	uc_value_t *opt = NULL, *val = NULL;
+	struct uci_ptr ptr = { 0 };
+	int rv;
+
+	if (ucv_type(conf) != UC_STRING ||
+	    ucv_type(sect) != UC_STRING)
+	    err_return(UCI_ERR_INVAL);
+
+	switch (nargs) {
+	/* conf, sect, opt, val */
+	case 4:
+		opt = uc_fn_arg(2);
+		val = uc_fn_arg(3);
+
+		if (ucv_type(opt) != UC_STRING ||
+		    ucv_type(val) != UC_STRING)
+			err_return(UCI_ERR_INVAL);
+
+		break;
+
+	/* conf, sect, type */
+	case 3:
+		val = uc_fn_arg(2);
+
+		if (ucv_type(val) != UC_STRING)
+			err_return(UCI_ERR_INVAL);
+
+		break;
+
+	default:
+		err_return(UCI_ERR_INVAL);
+	}
+
+	ptr.package = ucv_string_get(conf);
+	ptr.section = ucv_string_get(sect);
+	ptr.option = opt ? ucv_string_get(opt) : NULL;
+	ptr.value = ucv_string_get(val);
+
+	rv = lookup_ptr(*c, &ptr, true);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	if (!ptr.s && ptr.option)
+		err_return(UCI_ERR_NOTFOUND);
+
+	rv = uci_rename(*c, &ptr);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	return ucv_boolean_new(true);
+}
+
+/**
+ * Reorder sections in given configuration.
+ *
+ * The `reorder()` function moves a single section by repositioning it to the
+ * given index within the configurations section list.
+ *
+ * The given configuration is implicitly loaded into the cursor if not already
+ * present.
+ *
+ * Returns the `true` if specified section has been moved.
+ *
+ * Returns `null` on error, e.g. if the targeted configuration was not found or
+ * if an invalid value was passed.
+ *
+ * @function module:uci.cursor#reorder
+ *
+ * @param {string} config
+ * The name of the configuration file to move the section in, e.g. `"system"` to
+ * modify `/etc/config/system`.
+ *
+ * @param {string} section
+ * The section name to move.
+ *
+ * @param {number} index
+ * The target index to move the section to, starting from `0`.
+ *
+ * @param {string} [name]
+ * The new name of the option to rename.
+ *
+ * @returns {?boolean}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Query whole firewall config and reorder resulting dict by type and name
+ * const type_order = ['defaults', 'zone', 'forwarding', 'redirect', 'rule'];
+ * const values = ctx.get_all('firewall');
+ *
+ * sort(values, (k1, k2, s1, s2) => {
+ *     // Get weight from type_order array
+ *     let w1 = index(type_order, s1['.type']);
+ *     let w2 = index(type_order, s2['.type']);
+ *
+ *     // For unknown type orders, use type value itself as weight
+ *     if (w1 == -1) w1 = s1['.type'];
+ *     if (w2 == -1) w2 = s2['.type'];
+ *
+ *     // Get name from name option, fallback to section name
+ *     let n1 = s1.name ?? k1;
+ *     let n2 = s2.name ?? k2;
+ *
+ *     // Order by weight
+ *     if (w1 < w2) return -1;
+ *     if (w1 > w2) return 1;
+ *
+ *     // For same weight order by name
+ *     if (n1 < n2) return -1;
+ *     if (n1 > n2) return 1;
+ *
+ *     return 0;
+ * });
+ *
+ * // Sequentially reorder sorted sections in firewall configuration
+ * let position = 0;
+ *
+ * for (let sid in values)
+ *   ctx.reorder('firewall', sid, position++);
+ */
+static uc_value_t *
+uc_uci_reorder(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *sect = uc_fn_arg(1);
+	uc_value_t *val = uc_fn_arg(2);
+	struct uci_ptr ptr = { 0 };
+	int64_t n;
+	int rv;
+
+	if (ucv_type(conf) != UC_STRING ||
+	    ucv_type(sect) != UC_STRING ||
+	    ucv_type(val) != UC_INTEGER)
+	    err_return(UCI_ERR_INVAL);
+
+	n = ucv_int64_get(val);
+
+	if (n < 0)
+		err_return(UCI_ERR_INVAL);
+
+	ptr.package = ucv_string_get(conf);
+	ptr.section = ucv_string_get(sect);
+
+	rv = lookup_ptr(*c, &ptr, true);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	if (!ptr.s)
+		err_return(UCI_ERR_NOTFOUND);
+
+	rv = uci_reorder_section(*c, ptr.s, n);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	return ucv_boolean_new(true);
+}
+
+static int
+uc_uci_pkg_command_single(struct uci_context *ctx, enum pkg_cmd cmd,
+                          struct uci_package *pkg)
+{
+	struct uci_ptr ptr = { 0 };
+
+	switch (cmd) {
+	case CMD_COMMIT:
+		return uci_commit(ctx, &pkg, false);
+
+	case CMD_SAVE:
+		return uci_save(ctx, pkg);
+
+	case CMD_REVERT:
+		ptr.p = pkg;
+
+		return uci_revert(ctx, &ptr);
+
+	default:
+		return UCI_ERR_INVAL;
+	}
+}
+
+static uc_value_t *
+uc_uci_pkg_command(uc_vm_t *vm, size_t nargs, enum pkg_cmd cmd)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	struct uci_package *p;
+	char **configs = NULL;
+	int rv, res = UCI_OK;
+	size_t i;
+
+	if (conf) {
+		if (ucv_type(conf) != UC_STRING)
+			err_return(UCI_ERR_INVAL);
+
+		if (!(p = uci_lookup_package(*c, ucv_string_get(conf))))
+			err_return(UCI_ERR_NOTFOUND);
+
+		res = uc_uci_pkg_command_single(*c, cmd, p);
+	}
+	else {
+		if (uci_list_configs(*c, &configs))
+			err_return((*c)->err);
+
+		if (!configs || !configs[0])
+			err_return(UCI_ERR_NOTFOUND);
+
+		for (i = 0; configs[i]; i++) {
+			if (!(p = uci_lookup_package(*c, configs[i])))
+				continue;
+
+			rv = uc_uci_pkg_command_single(*c, cmd, p);
+
+			if (rv != UCI_OK)
+				res = rv;
+		}
+
+		free(configs);
+	}
+
+	if (res != UCI_OK)
+		err_return(res);
+
+	return ucv_boolean_new(true);
+}
+
+/**
+ * Save accumulated cursor changes to delta directory.
+ *
+ * The `save()` function writes consolidated changes made to in-memory copies of
+ * loaded configuration files to the uci delta directory which effectively makes
+ * them available to other processes using the same delta directory path as well
+ * as the `uci changes` cli command when using the default delta directory.
+ *
+ * Note that uci deltas are overlayed over the actual configuration file values
+ * so they're reflected by `get()`, `foreach()` etc. even if the underlying
+ * configuration files are not actually changed (yet). The delta records may be
+ * either permanently merged into the configuration by invoking `commit()` or
+ * reverted through `revert()` in order to restore the current state of the
+ * underlying configuration file.
+ *
+ * When the optional "config" parameter is omitted, delta records for all
+ * currently loaded configuration files are written.
+ *
+ * In case that neither sharing changes with other processes nor any revert
+ * functionality is required, changes may be committed directly using `commit()`
+ * instead, bypassing any delta record creation.
+ *
+ * Returns the `true` if operation completed successfully.
+ *
+ * Returns `null` on error, e.g. if the requested configuration was not loaded
+ * or when a file system error occurred.
+ *
+ * @function module:uci.cursor#save
+ *
+ * @param {string} [config]
+ * The name of the configuration file to save delta records for, e.g. `"system"`
+ * to store changes for `/etc/config/system`.
+ *
+ * @returns {?boolean}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * ctx.set('wireless', '@wifi-iface[0]', 'disabled', '1');
+ * ctx.save('wireless');
+ *
+ * @see {@link module:uci.cursor#commit|commit()}
+ * @see {@link module:uci.cursor#revert|revert()}
+ */
+static uc_value_t *
+uc_uci_save(uc_vm_t *vm, size_t nargs)
+{
+	return uc_uci_pkg_command(vm, nargs, CMD_SAVE);
+}
+
+/**
+ * Update configuration files with accumulated cursor changes.
+ *
+ * The `commit()` function merges changes made to in-memory copies of loaded
+ * configuration files as well as existing delta records in the cursors
+ * configured delta directory and writes them back into the underlying
+ * configuration files, persistently committing changes to the file system.
+ *
+ * When the optional "config" parameter is omitted, all currently loaded
+ * configuration files with either present delta records or yet unsaved
+ * cursor changes are updated.
+ *
+ * Returns the `true` if operation completed successfully.
+ *
+ * Returns `null` on error, e.g. if the requested configuration was not loaded
+ * or when a file system error occurred.
+ *
+ * @function module:uci.cursor#commit
+ *
+ * @param {string} [config]
+ * The name of the configuration file to commit, e.g. `"system"` to update the
+ * `/etc/config/system` file.
+ *
+ * @returns {?boolean}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * ctx.set('system', '@system[0]', 'hostname', 'example.org');
+ * ctx.commit('system');
+ */
+static uc_value_t *
+uc_uci_commit(uc_vm_t *vm, size_t nargs)
+{
+	return uc_uci_pkg_command(vm, nargs, CMD_COMMIT);
+}
+
+/**
+ * Revert accumulated cursor changes and associated delta records.
+ *
+ * The `revert()` function discards any changes made to in-memory copies of
+ * loaded configuration files and discards any related existing delta records in
+ * the  cursors configured delta directory.
+ *
+ * When the optional "config" parameter is omitted, all currently loaded
+ * configuration files with either present delta records or yet unsaved
+ * cursor changes are reverted.
+ *
+ * Returns the `true` if operation completed successfully.
+ *
+ * Returns `null` on error, e.g. if the requested configuration was not loaded
+ * or when a file system error occurred.
+ *
+ * @function module:uci.cursor#revert
+ *
+ * @param {string} [config]
+ * The name of the configuration file to revert, e.g. `"system"` to discard any
+ * changes for the `/etc/config/system` file.
+ *
+ * @returns {?boolean}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * ctx.set('system', '@system[0]', 'hostname', 'example.org');
+ * ctx.revert('system');
+ *
+ * @see {@link module:uci.cursor#save|save()}
+ */
+static uc_value_t *
+uc_uci_revert(uc_vm_t *vm, size_t nargs)
+{
+	return uc_uci_pkg_command(vm, nargs, CMD_REVERT);
+}
+
+static uc_value_t *
+change_to_uval(uc_vm_t *vm, struct uci_delta *d)
+{
+	const char *types[] = {
+		[UCI_CMD_REORDER]  = "order",
+		[UCI_CMD_REMOVE]   = "remove",
+		[UCI_CMD_RENAME]   = "rename",
+		[UCI_CMD_ADD]      = "add",
+		[UCI_CMD_LIST_ADD] = "list-add",
+		[UCI_CMD_LIST_DEL] = "list-del",
+		[UCI_CMD_CHANGE]   = "set",
+	};
+
+	uc_value_t *a;
+
+	if (!d->section)
+		return NULL;
+
+	a = ucv_array_new(vm);
+
+	if (!a)
+		return NULL;
+
+	ucv_array_push(a, ucv_string_new(types[d->cmd]));
+	ucv_array_push(a, ucv_string_new(d->section));
+
+	if (d->e.name)
+		ucv_array_push(a, ucv_string_new(d->e.name));
+
+	if (d->value) {
+		if (d->cmd == UCI_CMD_REORDER)
+			ucv_array_push(a, ucv_int64_new(strtoul(d->value, NULL, 10)));
+		else
+			ucv_array_push(a, ucv_string_new(d->value));
+	}
+
+	return a;
+}
+
+static uc_value_t *
+changes_to_uval(uc_vm_t *vm, struct uci_context *ctx, const char *package)
+{
+	uc_value_t *a = NULL, *c;
+	struct uci_package *p = NULL;
+	struct uci_element *e;
+	bool unload = false;
+
+	uci_foreach_element(&ctx->root, e) {
+		if (strcmp(e->name, package))
+			continue;
+
+		p = uci_to_package(e);
+	}
+
+	if (!p) {
+		unload = true;
+		uci_load(ctx, package, &p);
+	}
+
+	if (!p)
+		return NULL;
+
+	if (!uci_list_empty(&p->delta) || !uci_list_empty(&p->saved_delta)) {
+		a = ucv_array_new(vm);
+
+		if (!a)
+			err_return(UCI_ERR_MEM);
+
+		uci_foreach_element(&p->saved_delta, e) {
+			c = change_to_uval(vm, uci_to_delta(e));
+
+			if (c)
+				ucv_array_push(a, c);
+		}
+
+		uci_foreach_element(&p->delta, e) {
+			c = change_to_uval(vm, uci_to_delta(e));
+
+			if (c)
+				ucv_array_push(a, c);
+		}
+	}
+
+	if (unload)
+		uci_unload(ctx, p);
+
+	return a;
+}
+
+/**
+ * Enumerate pending changes.
+ *
+ * The `changes()` function returns a list of change records for currently
+ * loaded configuration files, originating both from the cursors associated
+ * delta directory and yet unsaved cursor changes.
+ *
+ * When the optional "config" parameter is specified, the requested
+ * configuration is implicitly loaded if it not already loaded into the cursor.
+ *
+ * Returns a dictionary of change record arrays, keyed by configuration name.
+ *
+ * Returns `null` on error, e.g. if the requested configuration could not be
+ * loaded.
+ *
+ * @function module:uci.cursor#changes
+ *
+ * @param {string} [config]
+ * The name of the configuration file to enumerate changes for, e.g. `"system"`
+ * to query pending changes for the `/etc/config/system` file.
+ *
+ * @returns {?Object<string, module:uci.cursor.ChangeRecord[]>}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Enumerate changes for all currently loaded configurations
+ * const deltas = ctx.changes();
+ *
+ * // Explicitly load and enumerate changes for the "system" configuration
+ * const deltas = ctx.changes('system');
+ */
+static uc_value_t *
+uc_uci_changes(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *res, *chg;
+	char **configs;
+	int rv, i;
+
+	if (conf && ucv_type(conf) != UC_STRING)
+		err_return(UCI_ERR_INVAL);
+
+	rv = uci_list_configs(*c, &configs);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	res = ucv_object_new(vm);
+
+	for (i = 0; configs[i]; i++) {
+		if (conf && strcmp(configs[i], ucv_string_get(conf)))
+			continue;
+
+		chg = changes_to_uval(vm, *c, configs[i]);
+
+		if (chg)
+			ucv_object_add(res, configs[i], chg);
+	}
+
+	free(configs);
+
+	return res;
+}
+
+/**
+ * Iterate configuration sections.
+ *
+ * The `foreach()` function iterates all sections of the given configuration,
+ * optionally filtered by type, and invokes the given callback function for
+ * each encountered section.
+ *
+ * When the optional "type" parameter is specified, the callback is only invoked
+ * for sections of the given type, otherwise it is invoked for all sections.
+ *
+ * The requested configuration is implicitly loaded into the cursor.
+ *
+ * Returns `true` if the callback was executed successfully at least once.
+ *
+ * Returns `false` if the callback was never invoked, e.g. when the
+ * configuration is empty or contains no sections of the given type.
+ *
+ * Returns `null` on error, e.g. when an invalid callback was passed or the
+ * requested configuration not found.
+ *
+ * @function module:uci.cursor#foreach
+ *
+ * @param {string} config
+ * The configuration to iterate sections for, e.g. `"system"` to read the
+ * `/etc/config/system` file.
+ *
+ * @param {?string} type
+ * Invoke the callback only for sections of the specified type.
+ *
+ * @param {module:uci.cursor.SectionCallback} callback
+ * The callback to invoke for each section, will receive a section dictionary
+ * as sole argument.
+ *
+ * @returns {?boolean}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Iterate all network interfaces
+ * ctx.foreach('network', 'interface',
+ * 	   section => print(`Have interface ${section[".name"]}\n`));
+ */
+static uc_value_t *
+uc_uci_foreach(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *conf = uc_fn_arg(0);
+	uc_value_t *type = uc_fn_arg(1);
+	uc_value_t *func = uc_fn_arg(2);
+	uc_value_t *rv = NULL;
+	struct uci_package *p = NULL;
+	struct uci_element *e, *tmp;
+	struct uci_section *sc;
+	uc_exception_type_t ex;
+	bool stop = false;
+	bool ret = false;
+	int i = 0;
+
+	if (ucv_type(conf) != UC_STRING ||
+	    (type && ucv_type(type) != UC_STRING))
+	    err_return(UCI_ERR_INVAL);
+
+	uci_foreach_element(&(*c)->root, e) {
+		if (strcmp(e->name, ucv_string_get(conf)))
+			continue;
+
+		p = uci_to_package(e);
+		break;
+	}
+
+	if (!p && uci_load(*c, ucv_string_get(conf), &p))
+		err_return((*c)->err);
+
+	uci_foreach_element_safe(&p->sections, tmp, e) {
+		sc = uci_to_section(e);
+		i++;
+
+		if (type && strcmp(sc->type, ucv_string_get(type)))
+			continue;
+
+		uc_value_push(ucv_get(func));
+		uc_value_push(section_to_uval(vm, sc, i - 1));
+
+		ex = uc_call(1);
+
+		/* stop on exception in callback */
+		if (ex)
+			break;
+
+		ret = true;
+		rv = uc_value_pop();
+		stop = (ucv_type(rv) == UC_BOOLEAN && !ucv_boolean_get(rv));
+
+		ucv_put(rv);
+
+		if (stop)
+			break;
+	}
+
+	return ucv_boolean_new(ret);
+}
+
+/**
+ * Enumerate existing configurations.
+ *
+ * The `configs()` function yields an array of configuration files present in
+ * the cursors associated configuration directory, `/etc/config/` by default.
+ *
+ * Returns an array of configuration names on success.
+ *
+ * Returns `null` on error, e.g. due to filesystem errors.
+ *
+ * @function module:uci.cursor#configs
+ *
+ * @returns {?string[]}
+ *
+ * @example
+ * const ctx = cursor(…);
+ *
+ * // Enumerate all present configuration file names
+ * const configurations = ctx.configs();
+ */
+static uc_value_t *
+uc_uci_configs(uc_vm_t *vm, size_t nargs)
+{
+	struct uci_context **c = uc_fn_this("uci.cursor");
+	uc_value_t *a;
+	char **configs;
+	int i, rv;
+
+	rv = uci_list_configs(*c, &configs);
+
+	if (rv != UCI_OK)
+		err_return(rv);
+
+	a = ucv_array_new(vm);
+
+	for (i = 0; configs[i]; i++)
+		ucv_array_push(a, ucv_string_new(configs[i]));
+
+	free(configs);
+
+	return a;
+}
+
+
+static const uc_function_list_t cursor_fns[] = {
+	{ "load",		uc_uci_load },
+	{ "unload",		uc_uci_unload },
+	{ "get",		uc_uci_get },
+	{ "get_all",	uc_uci_get_all },
+	{ "get_first",	uc_uci_get_first },
+	{ "add",		uc_uci_add },
+	{ "set",		uc_uci_set },
+	{ "rename",		uc_uci_rename },
+	{ "save",		uc_uci_save },
+	{ "delete",		uc_uci_delete },
+	{ "commit",		uc_uci_commit },
+	{ "revert",		uc_uci_revert },
+	{ "reorder",	uc_uci_reorder },
+	{ "changes",	uc_uci_changes },
+	{ "foreach",	uc_uci_foreach },
+	{ "configs",	uc_uci_configs },
+	{ "error",		uc_uci_error },
+};
+
+static const uc_function_list_t global_fns[] = {
+	{ "error",		uc_uci_error },
+	{ "cursor",		uc_uci_cursor },
+};
+
+
+static void close_uci(void *ud) {
+	uci_free_context((struct uci_context *)ud);
+}
+
+void uc_module_init(uc_vm_t *vm, uc_value_t *scope)
+{
+	uc_function_list_register(scope, global_fns);
+
+	cursor_type = uc_type_declare(vm, "uci.cursor", cursor_fns, close_uci);
+}
+
\ No newline at end of file diff --git a/module-core.html b/module-core.html index 01ee8bbd..8f460af5 100644 --- a/module-core.html +++ b/module-core.html @@ -1,15 +1,15 @@ Module: core
On this page

Builtin functions

The core namespace is not an actual module but refers to the set of builtin functions and properties available to ucode scripts.

Source

Methods

arrtoip(arr) → {string|null}

Convert the given input array of byte values to an IP address string.

Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16 to IPv6 ones. All other lengths are rejected. If any array element is not an integer or exceeds the range 0..255 (inclusive), the array is rejected.

Returns a string containing the formatted IP address. Returns null if the input array was invalid.

Parameters:
NameTypeDescription
arrArray.<number>

The byte array to convert into an IP address string.

Returns:
Type: 
string | null
Example
arrtoip([ 192, 168, 1, 1 ])   // "192.168.1.1"
+    
On this page

Builtin functions

The core namespace is not an actual module but refers to the set of builtin functions and properties available to ucode scripts.

Source

Methods

arrtoip(arr) → (nullable) {string}

Convert the given input array of byte values to an IP address string.

Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16 to IPv6 ones. All other lengths are rejected. If any array element is not an integer or exceeds the range 0..255 (inclusive), the array is rejected.

Returns a string containing the formatted IP address. Returns null if the input array was invalid.

Parameters:
NameTypeDescription
arrArray.<number>

The byte array to convert into an IP address string.

Returns:
Type: 
string
Example
arrtoip([ 192, 168, 1, 1 ])   // "192.168.1.1"
 arrtoip([ 254, 128, 0, 0, 0, 0, 0, 0, 252, 84, 0, 255, 254, 130, 171, 189 ])
                               // "fe80::fc54:ff:fe82:abbd"
 arrtoip([ 1, 2, 3])           // null (invalid length)
 arrtoip([ 1, "2", -5, 300 ])  // null (invalid values)
 arrtoip("123")                // null (not an array)

assert(cond, messageopt)

Raise an exception with the given message parameter when the value in cond is not truish.

When message is omitted, the default value is Assertion failed.

Parameters:
NameTypeAttributesDescription
cond*

The value to check for truthiness.

messagestring<optional>

The message to include in the exception.

Throws:

When the condition is falsy.

Type
Error
Example
assert(true, "This is true");  // No exception is raised
-assert(false);                 // Exception is raised with the default message "Assertion failed"

b64dec(str) → {string|null}

Decodes the given base64 encoded string and returns the decoded result.

  • If non-whitespace, non-base64 characters are encountered, if invalid padding or trailing garbage is found, the function returns null.
  • If a non-string argument is given, the function returns null.
Parameters:
NameTypeDescription
strstring

The base64 encoded string to decode.

Returns:
Type: 
string | null
Example
b64dec("VGhpcyBpcyBhIHRlc3Q=");         // Returns "This is a test"
+assert(false);                 // Exception is raised with the default message "Assertion failed"

b64dec(str) → (nullable) {string}

Decodes the given base64 encoded string and returns the decoded result.

  • If non-whitespace, non-base64 characters are encountered, if invalid padding or trailing garbage is found, the function returns null.
  • If a non-string argument is given, the function returns null.
Parameters:
NameTypeDescription
strstring

The base64 encoded string to decode.

Returns:
Type: 
string
Example
b64dec("VGhpcyBpcyBhIHRlc3Q=");         // Returns "This is a test"
 b64dec(123);                           // Returns null
-b64dec("XXX");                         // Returns null

b64enc(str) → {string|null}

Encodes the given string into base64 and returns the resulting string.

  • If a non-string argument is given, the function returns null.
Parameters:
NameTypeDescription
strstring

The string to encode.

Returns:
Type: 
string | null
Example
b64enc("This is a test");  // Returns "VGhpcyBpcyBhIHRlc3Q="
-b64enc(123);               // Returns null

call(fn, ctxopt, scopeopt, …argopt) → {*}

Calls the given function value with a modified environment.

The given ctx argument is used as this context for the invoked function and the given scope value as global environment. Any further arguments are passed to the invoked function as-is.

When ctx is omitted or null, the function will get invoked with this being null.

When scope is omitted or null, the function will get executed with the current global environment of the running program. When scope is set to a dictionary, the dictionary is used as global function environment.

When the scope dictionary has no prototype, the current global environment will be set as prototype, means the scope will inherit from it.

When a scope prototype is set, it is kept. This allows passing an isolated (sandboxed) function scope without access to the global environment.

Any further argument is forwarded as-is to the invoked function as function call argument.

Returns null if the given function value fn is not callable.

Returns the return value of the invoked function in all other cases.

Forwards exceptions thrown by the invoked function.

Parameters:
NameTypeAttributesDefaultDescription
fnfunction

Function value to call.

ctx*<optional>
null

this context for the invoked function.

scopeObject<optional>
null

Global environment for the invoked function.

arg*<optional>
<repeatable>

Additional arguments to pass to the invoked function.

Returns:
Type: 
*
Example
// Override this context
+b64dec("XXX");                         // Returns null

b64enc(str) → (nullable) {string}

Encodes the given string into base64 and returns the resulting string.

  • If a non-string argument is given, the function returns null.
Parameters:
NameTypeDescription
strstring

The string to encode.

Returns:
Type: 
string
Example
b64enc("This is a test");  // Returns "VGhpcyBpcyBhIHRlc3Q="
+b64enc(123);               // Returns null

call(fn, ctxopt, scopeopt, …argopt) → {*}

Calls the given function value with a modified environment.

The given ctx argument is used as this context for the invoked function and the given scope value as global environment. Any further arguments are passed to the invoked function as-is.

When ctx is omitted or null, the function will get invoked with this being null.

When scope is omitted or null, the function will get executed with the current global environment of the running program. When scope is set to a dictionary, the dictionary is used as global function environment.

When the scope dictionary has no prototype, the current global environment will be set as prototype, means the scope will inherit from it.

When a scope prototype is set, it is kept. This allows passing an isolated (sandboxed) function scope without access to the global environment.

Any further argument is forwarded as-is to the invoked function as function call argument.

Returns null if the given function value fn is not callable.

Returns the return value of the invoked function in all other cases.

Forwards exceptions thrown by the invoked function.

Parameters:
NameTypeAttributesDefaultDescription
fnfunction

Function value to call.

ctx*<optional>
null

this context for the invoked function.

scopeObject<optional>
null

Global environment for the invoked function.

arg*<optional>
<repeatable>

Additional arguments to pass to the invoked function.

Returns:
Type: 
*
Example
// Override this context
 call(function() { printf("%J\n", this) });            // null
 call(function() { printf("%J\n", this) }, null);      // null
 call(function() { printf("%J\n", this) }, { x: 1 });  // { "x": 1 }
@@ -32,7 +32,7 @@
 
 // Forward arguments
 x = call((x, y, z) => x * y * z, null, null, 2, 3, 4);   // x = 24

chr(…n1) → {string}

Converts each given numeric value to a byte and return the resulting string. Invalid numeric values or values < 0 result in \0 bytes, values larger than 255 are truncated to 255.

Returns a new strings consisting of the given byte values.

Parameters:
NameTypeAttributesDescription
n1number<repeatable>

The numeric values.

Returns:
Type: 
string
Example
chr(65, 98, 99);  // "Abc"
-chr(-1, 300);     // string consisting of an `0x0` and a `0xff` byte

clock(monotonicopt) → {Array.<number>|null}

Reads the current second and microsecond value of the system clock.

By default, the realtime clock is queried which might skew forwards or backwards due to NTP changes, system sleep modes etc. If a truish value is passed as argument, the monotonic system clock is queried instead, which will return the monotonically increasing time since some arbitrary point in the past (usually the system boot time).

Returns a two element array containing the full seconds as the first element and the nanosecond fraction as the second element.

Returns null if a monotonic clock value is requested and the system does not implement this clock type.

Parameters:
NameTypeAttributesDescription
monotonicboolean<optional>

Whether to query the monotonic system clock.

Returns:
Type: 
Array.<number> | null
Example
clock();        // [ 1647954926, 798269464 ]
+chr(-1, 300);     // string consisting of an `0x0` and a `0xff` byte

clock(monotonicopt) → (nullable) {Array.<number>}

Reads the current second and microsecond value of the system clock.

By default, the realtime clock is queried which might skew forwards or backwards due to NTP changes, system sleep modes etc. If a truish value is passed as argument, the monotonic system clock is queried instead, which will return the monotonically increasing time since some arbitrary point in the past (usually the system boot time).

Returns a two element array containing the full seconds as the first element and the nanosecond fraction as the second element.

Returns null if a monotonic clock value is requested and the system does not implement this clock type.

Parameters:
NameTypeAttributesDescription
monotonicboolean<optional>

Whether to query the monotonic system clock.

Returns:
Type: 
Array.<number>
Example
clock();        // [ 1647954926, 798269464 ]
 clock(true);    // [ 474751, 527959975 ]

die(msg)

Raise an exception with the given message and abort execution.

Parameters:
NameTypeDescription
msgstring

The error message.

Throws:

The error with the given message.

Type
Error
Example
die(msg);

exists(obj, key) → {boolean}

Check whether the given key exists within the given object value.

Returns true if the given key is present within the object passed as the first argument, otherwise false.

Parameters:
NameTypeDescription
objObject

The input object.

keystring

The key to check for existence.

Returns:
Type: 
boolean
Example
let x = { foo: true, bar: false, qrx: null };
 exists(x, 'foo');  // true
 exists(x, 'qrx');  // true
@@ -45,9 +45,9 @@
 a = filter(["foo", 1, true, null, 2.2], function(v) {
     return (type(v) == "int" || type(v) == "double");
 });
-// a = [1, 2.2]

gc(operationopt, argumentopt) → {boolean|number|null}

Interacts with the mark and sweep garbage collector of the running ucode virtual machine.

Depending on the given operation string argument, the meaning of argument and the function return value differs.

The following operations are defined:

  • collect - Perform a complete garbage collection cycle, returns true.
  • start - (Re-)start periodic garbage collection, argument is an optional integer in the range 1..65535 specifying the interval. Defaults to 1000 if omitted. Returns true if the periodic GC was previously stopped and is now started or if the interval changed. Returns false otherwise.
  • stop - Stop periodic garbage collection. Returns true if the periodic GC was previously started and is now stopped, false otherwise.
  • count - Count the amount of active complex object references in the VM context, returns the counted amount.

If the operation argument is omitted, the default is collect.

Parameters:
NameTypeAttributesDescription
operationstring<optional>

The operation to perform.

argument*<optional>

The argument for the operation.

Returns:
Type: 
boolean | number | null
Example
gc();         // true
+// a = [1, 2.2]

gc(operationopt, argumentopt) → (nullable) {boolean|number}

Interacts with the mark and sweep garbage collector of the running ucode virtual machine.

Depending on the given operation string argument, the meaning of argument and the function return value differs.

The following operations are defined:

  • collect - Perform a complete garbage collection cycle, returns true.
  • start - (Re-)start periodic garbage collection, argument is an optional integer in the range 1..65535 specifying the interval. Defaults to 1000 if omitted. Returns true if the periodic GC was previously stopped and is now started or if the interval changed. Returns false otherwise.
  • stop - Stop periodic garbage collection. Returns true if the periodic GC was previously started and is now stopped, false otherwise.
  • count - Count the amount of active complex object references in the VM context, returns the counted amount.

If the operation argument is omitted, the default is collect.

Parameters:
NameTypeAttributesDescription
operationstring<optional>

The operation to perform.

argument*<optional>

The argument for the operation.

Returns:
Type: 
boolean | number
Example
gc();         // true
 gc("start");  // true
-gc("count");  // 42

getenv(nameopt) → {string|object}

Query an environment variable or then entire environment.

Returns the value of the given environment variable, or - if omitted - a dictionary containing all environment variables.

Parameters:
NameTypeAttributesDescription
namestring<optional>

The name of the environment variable.

Returns:
Type: 
string | object

gmtime(epochopt) → {Object}

Like localtime() but interpreting the given epoch value as UTC time.

See localtime() for details on the return value.

Parameters:
NameTypeAttributesDescription
epochnumber<optional>

The epoch timestamp.

Returns:
Type: 
Object
Example
gmtime(1647953502);
+gc("count");  // 42

getenv(nameopt) → {string|Object.<string, string>}

Query an environment variable or then entire environment.

Returns the value of the given environment variable, or - if omitted - a dictionary containing all environment variables.

Parameters:
NameTypeAttributesDescription
namestring<optional>

The name of the environment variable.

Returns:
Type: 
string | Object.<string, string>

gmtime(epochopt) → {module:core.TimeSpec}

Like localtime() but interpreting the given epoch value as UTC time.

See localtime() for details on the return value.

Parameters:
NameTypeAttributesDescription
epochnumber<optional>

The epoch timestamp.

Returns:
Type: 
module:core.TimeSpec
Example
gmtime(1647953502);
 // Returns:
 // {
 //     sec: 42,
@@ -59,8 +59,8 @@
 //     wday: 2,
 //     yday: 81,
 //     isdst: 0
-// }

hex(x) → {number}

Converts the given hexadecimal string into a number.

Returns the resulting integer value or NaN if the input value cannot be interpreted as hexadecimal number.

Parameters:
NameTypeDescription
x*

The hexadecimal string to be converted.

Returns:
Type: 
number

hexdec(hexstring, skipcharsopt) → {string|null}

Decodes the given hexadecimal digit string into a byte string, optionally skipping specified characters.

If the characters to skip are not specified, a default of " \t\n" is used.

Returns null if the input string contains invalid characters or an uneven amount of hex digits.

Returns the decoded byte string on success.

Parameters:
NameTypeAttributesDescription
hexstringstring

The hexadecimal digit string to decode.

skipcharsstring<optional>

The characters to skip during decoding.

Returns:
Type: 
string | null
Example
hexdec("48656c6c6f20776f726c64210a");  // "Hello world!\n"
-hexdec("44:55:66:77:33:44", ":");      // "DUfw3D"

hexenc(val) → {string}

Encodes the given byte string into a hexadecimal digit string, converting the input value to a string if needed.

Parameters:
NameTypeDescription
valstring

The byte string to encode.

Returns:
Type: 
string
Example
hexenc("Hello world!\n");   // "48656c6c6f20776f726c64210a"

include(path, scopeopt)

Evaluate and include the file at the given path and optionally override the execution scope with the given scope object.

By default, the file is executed within the same scope as the calling include(), but by passing an object as the second argument, it is possible to extend the scope available to the included file.

This is useful to supply additional properties as global variables to the included code. To sandbox included code, that is giving it only access to explicitly provided properties, the proto() function can be used to create a scope object with an empty prototype.

Parameters:
NameTypeAttributesDescription
pathstring

The path to the file to be included.

scopeObject<optional>

The optional scope object to override the execution scope.

Example
// Load and execute "foo.uc" immediately
+// }

hex(x) → {number}

Converts the given hexadecimal string into a number.

Returns the resulting integer value or NaN if the input value cannot be interpreted as hexadecimal number.

Parameters:
NameTypeDescription
x*

The hexadecimal string to be converted.

Returns:
Type: 
number

hexdec(hexstring, skipcharsopt) → (nullable) {string}

Decodes the given hexadecimal digit string into a byte string, optionally skipping specified characters.

If the characters to skip are not specified, a default of " \t\n" is used.

Returns null if the input string contains invalid characters or an uneven amount of hex digits.

Returns the decoded byte string on success.

Parameters:
NameTypeAttributesDescription
hexstringstring

The hexadecimal digit string to decode.

skipcharsstring<optional>

The characters to skip during decoding.

Returns:
Type: 
string
Example
hexdec("48656c6c6f20776f726c64210a");  // "Hello world!\n"
+hexdec("44:55:66:77:33:44", ":");      // "DUfw3D"

hexenc(val) → {string}

Encodes the given byte string into a hexadecimal digit string, converting the input value to a string if needed.

Parameters:
NameTypeDescription
valstring

The byte string to encode.

Returns:
Type: 
string
Example
hexenc("Hello world!\n");   // "48656c6c6f20776f726c64210a"

include(path, scopeopt)

Evaluate and include the file at the given path and optionally override the execution scope with the given scope object.

By default, the file is executed within the same scope as the calling include(), but by passing an object as the second argument, it is possible to extend the scope available to the included file.

This is useful to supply additional properties as global variables to the included code. To sandbox included code, that is giving it only access to explicitly provided properties, the proto() function can be used to create a scope object with an empty prototype.

Parameters:
NameTypeAttributesDescription
pathstring

The path to the file to be included.

scopeObject<optional>

The optional scope object to override the execution scope.

Example
// Load and execute "foo.uc" immediately
 include("./foo.uc")
 
 // Execute the "supplemental.ucode" in an extended scope and make the "foo"
@@ -78,15 +78,15 @@
   foo: true,
   bar: 123,
   print: print
-}, {}))

index(arr_or_str, needle) → {number|null}

Finds the given value passed as the second argument within the array or string specified in the first argument.

Returns the first matching array index or first matching string offset or -1 if the value was not found.

Returns null if the first argument was neither an array nor a string.

Parameters:
NameTypeDescription
arr_or_strArray | string

The array or string to search for the value.

needle*

The value to find within the array or string.

Returns:
Type: 
number | null
Example
index("Hello hello hello", "ll")          // 2
+}, {}))

index(arr_or_str, needle) → (nullable) {number}

Finds the given value passed as the second argument within the array or string specified in the first argument.

Returns the first matching array index or first matching string offset or -1 if the value was not found.

Returns null if the first argument was neither an array nor a string.

Parameters:
NameTypeDescription
arr_or_strArray | string

The array or string to search for the value.

needle*

The value to find within the array or string.

Returns:
Type: 
number
Example
index("Hello hello hello", "ll")          // 2
 index([ 1, 2, 3, 1, 2, 3, 1, 2, 3 ], 2)   // 1
 index("foo", "bar")                       // -1
 index(["Red", "Blue", "Green"], "Brown")  // -1
-index(123, 2)                             // null

int(x) → {number}

Converts the given value to an integer.

Returns NaN if the value is not convertible.

Parameters:
NameTypeDescription
x*

The value to be converted to an integer.

Returns:
Type: 
number

iptoarr(address) → {Array.<number>|null}

Convert the given IP address string to an array of byte values.

IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays containing 16 intergers. The resulting array can be turned back into IP address strings using the inverse arrtoip() function.

Returns an array containing the address byte values. Returns null if the given argument is not a string or an invalid IP.

Parameters:
NameTypeDescription
addressstring

The IP address string to convert.

Returns:
Type: 
Array.<number> | null
Example
iptoarr("192.168.1.1")              // [ 192, 168, 1, 1 ]
+index(123, 2)                             // null

int(x) → {number}

Converts the given value to an integer.

Returns NaN if the value is not convertible.

Parameters:
NameTypeDescription
x*

The value to be converted to an integer.

Returns:
Type: 
number

iptoarr(address) → (nullable) {Array.<number>}

Convert the given IP address string to an array of byte values.

IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays containing 16 intergers. The resulting array can be turned back into IP address strings using the inverse arrtoip() function.

Returns an array containing the address byte values. Returns null if the given argument is not a string or an invalid IP.

Parameters:
NameTypeDescription
addressstring

The IP address string to convert.

Returns:
Type: 
Array.<number>
Example
iptoarr("192.168.1.1")              // [ 192, 168, 1, 1 ]
 iptoarr("fe80::fc54:ff:fe82:abbd")  // [ 254, 128, 0, 0, 0, 0, 0, 0, 252, 84,
                                     //   0, 255, 254, 130, 171, 189 ])
 iptoarr("foo")                      // null (invalid address)
-iptoarr(123)                        // null (not a string)

join(sep, arr) → {string|null}

Joins the array passed as the second argument into a string, using the separator passed in the first argument as glue.

Returns null if the second argument is not an array.

Parameters:
NameTypeDescription
sepstring

The separator to be used in joining the array elements.

arrArray

The array to be joined into a string.

Returns:
Type: 
string | null

json(str_or_resource) → {*}

Parse the given string or resource as JSON and return the resulting value.

If the input argument is a plain string, it is directly parsed as JSON.

If an array, object or resource value is given, this function will attempt to invoke a read() method on it to read chunks of input text to incrementally parse as JSON data. Reading will stop if the object's read() method returns either null or an empty string.

Throws an exception on parse errors, trailing garbage, or premature EOF.

Returns the parsed JSON data.

Parameters:
NameTypeDescription
str_or_resourcestring

The string or resource object to be parsed as JSON.

Returns:
Type: 
*
Example
json('{"a":true, "b":123}')   // { "a": true, "b": 123 }
+iptoarr(123)                        // null (not a string)

join(sep, arr) → (nullable) {string}

Joins the array passed as the second argument into a string, using the separator passed in the first argument as glue.

Returns null if the second argument is not an array.

Parameters:
NameTypeDescription
sepstring

The separator to be used in joining the array elements.

arrArray

The array to be joined into a string.

Returns:
Type: 
string

json(str_or_resource) → {*}

Parse the given string or resource as JSON and return the resulting value.

If the input argument is a plain string, it is directly parsed as JSON.

If an array, object or resource value is given, this function will attempt to invoke a read() method on it to read chunks of input text to incrementally parse as JSON data. Reading will stop if the object's read() method returns either null or an empty string.

Throws an exception on parse errors, trailing garbage, or premature EOF.

Returns the parsed JSON data.

Parameters:
NameTypeDescription
str_or_resourcestring

The string or resource object to be parsed as JSON.

Returns:
Type: 
*
Example
json('{"a":true, "b":123}')   // { "a": true, "b": 123 }
 json('[1,2,')                 // Throws an exception
 
 import { open } from 'fs';
@@ -99,19 +99,19 @@
     { read: function() { return shift(this) } }
 );
 json(x);                      // will keep invoking `x.read()` until array
-                              // is empty incrementally parse each piece

keys(obj) → {Array|null}

Enumerates all object key names.

Returns an array of all key names present in the passed object. Returns null if the given argument is not an object.

Parameters:
NameTypeDescription
objobject

The object from which to retrieve the key names.

Returns:
Type: 
Array | null

lc(s) → {string|null}

Convert the given string to lowercase and return the resulting string.

Returns null if the given argument could not be converted to a string.

Parameters:
NameTypeDescription
sstring

The input string.

Returns:

The lowercase string.

Type: 
string | null
Example
lc("HeLLo WoRLd!");  // "hello world!"

length(x) → {number|null}

Determine the length of the given object, array or string.

Returns the length of the given value.

  • For strings, the length is the amount of bytes within the string
  • For arrays, the length is the amount of array elements
  • For objects, the length is defined as the amount of keys

Returns null if the given argument is not an object, array or string.

Parameters:
NameTypeDescription
xObject | Array | string

The input object, array, or string.

Returns:
  • The length of the input.
Type: 
number | null
Example
length("test")                             // 4
+                              // is empty incrementally parse each piece

keys(obj) → (nullable) {Array}

Enumerates all object key names.

Returns an array of all key names present in the passed object. Returns null if the given argument is not an object.

Parameters:
NameTypeDescription
objobject

The object from which to retrieve the key names.

Returns:
Type: 
Array

lc(s) → (nullable) {string}

Convert the given string to lowercase and return the resulting string.

Returns null if the given argument could not be converted to a string.

Parameters:
NameTypeDescription
sstring

The input string.

Returns:

The lowercase string.

Type: 
string
Example
lc("HeLLo WoRLd!");  // "hello world!"

length(x) → (nullable) {number}

Determine the length of the given object, array or string.

Returns the length of the given value.

  • For strings, the length is the amount of bytes within the string
  • For arrays, the length is the amount of array elements
  • For objects, the length is defined as the amount of keys

Returns null if the given argument is not an object, array or string.

Parameters:
NameTypeDescription
xObject | Array | string

The input object, array, or string.

Returns:
  • The length of the input.
Type: 
number
Example
length("test")                             // 4
 length([true, false, null, 123, "test"])   // 5
 length({foo: true, bar: 123, baz: "test"}) // 3
 length({})                                 // 0
 length(true)                               // null
-length(10.0)                               // null

loadfile(path, optionsopt) → {function}

Compiles the given file into a ucode program and returns the resulting program entry function.

See loadstring() for details.

Returns the compiled program entry function.

Throws an exception on compilation or file I/O errors.

Parameters:
NameTypeAttributesDescription
pathstring

The path of the file to compile.

optionsObject<optional>

The options for compilation.

Returns:
Type: 
function
Example
loadfile("./templates/example.uc");  // function main() { ... }

loadstring(code, optionsopt) → {function}

Compiles the given code string into a ucode program and returns the resulting program entry function.

The optional options dictionary overrides parse and compile options.

  • If a non-string code argument is given, it is implicitly converted to a string value first.
  • If options is omitted or a non-object value, the compile options of the running ucode program are reused.

The following keys in the options dictionary are recognized:

KeyTypeDescription
lstrip_blocksboolStrip leading whitespace before statement template blocks
trim_blocksboolStrip newline after statement template blocks
strict_declarationsboolTreat access to undefined variables as fatal error
raw_modeboolCompile source in script mode, don't treat it as template
module_search_patharrayOverride compile time module search path
force_dynlink_listarrayList of module names to treat as dynamic extensions

Unrecognized keys are ignored, unspecified options default to those of the running program.

Returns the compiled program entry function.

Throws an exception on compilation errors.

Parameters:
NameTypeAttributesDescription
codestring

The code string to compile.

optionsObject<optional>

The options for compilation.

Returns:
Type: 
function
Example
let fn1 = loadstring("Hello, {{ name }}", { raw_mode: false });
+length(10.0)                               // null

loadfile(path, optionsopt) → {function}

Compiles the given file into a ucode program and returns the resulting program entry function.

See loadstring() for details.

Returns the compiled program entry function.

Throws an exception on compilation or file I/O errors.

Parameters:
NameTypeAttributesDescription
pathstring

The path of the file to compile.

optionsObject<optional>

The options for compilation.

Returns:
Type: 
function
Example
loadfile("./templates/example.uc");  // function main() { ... }

loadstring(code, optionsopt) → {function}

Compiles the given code string into a ucode program and returns the resulting program entry function.

The optional options dictionary overrides parse and compile options.

  • If a non-string code argument is given, it is implicitly converted to a string value first.
  • If options is omitted or a non-object value, the compile options of the running ucode program are reused.

The following keys in the options dictionary are recognized:

KeyTypeDescription
lstrip_blocksboolStrip leading whitespace before statement template blocks
trim_blocksboolStrip newline after statement template blocks
strict_declarationsboolTreat access to undefined variables as fatal error
raw_modeboolCompile source in script mode, don't treat it as template
module_search_patharrayOverride compile time module search path
force_dynlink_listarrayList of module names to treat as dynamic extensions

Unrecognized keys are ignored, unspecified options default to those of the running program.

Returns the compiled program entry function.

Throws an exception on compilation errors.

Parameters:
NameTypeAttributesDescription
codestring

The code string to compile.

optionsObject<optional>

The options for compilation.

Returns:
Type: 
function
Example
let fn1 = loadstring("Hello, {{ name }}", { raw_mode: false });
 
 global.name = "Alice";
 fn1(); // prints `Hello, Alice`
 
 
 let fn2 = loadstring("return 1 + 2;", { raw_mode: true });
-fn2(); // 3

localtime(epochopt) → {Object}

Return the given epoch timestamp (or now, if omitted) as a dictionary containing broken-down date and time information according to the local system timezone.

The resulting dictionary contains the following fields:

  • sec Seconds (0-60)
  • min Minutes (0-59)
  • hour Hours (0-23)
  • mday Day of month (1-31)
  • mon Month (1-12)
  • year Year (>= 1900)
  • wday Day of the week (1-7, Sunday = 7)
  • yday Day of the year (1-366, Jan 1st = 1)
  • isdst Daylight saving time in effect (yes = 1)

Note that in contrast to the underlying localtime(3) C library function, the values for mon, wday, and yday are 1-based, and the year is 1900-based.

Parameters:
NameTypeAttributesDescription
epochnumber<optional>

The epoch timestamp.

Returns:
Type: 
Object
Example
localtime(1647953502);
+fn2(); // 3

localtime(epochopt) → {module:core.TimeSpec}

Return the given epoch timestamp (or now, if omitted) as a dictionary containing broken-down date and time information according to the local system timezone.

See TimeSpec for a description of the fields.

Note that in contrast to the underlying localtime(3) C library function, the values for mon, wday, and yday are 1-based, and the year is 1900-based.

Parameters:
NameTypeAttributesDescription
epochnumber<optional>

The epoch timestamp.

Returns:
Type: 
module:core.TimeSpec
Example
localtime(1647953502);
 // Returns:
 // {
 //     sec: 42,
@@ -130,7 +130,7 @@
 
 // map to type names:
 a = map(["foo", 1, true, null, 2.2], type);
-// a = ["string", "int", "bool", null, "double"]

match(str, pattern) → {Array|null}

Match the given string against the regular expression pattern specified as the second argument.

If the passed regular expression uses the g flag, the return value will be an array of arrays describing all found occurrences within the string.

Without the g modifier, an array describing the first match is returned.

Returns null if the pattern was not found within the given string.

Parameters:
NameTypeDescription
strstring

The string to be matched against the pattern.

patternRegExp

The regular expression pattern.

Returns:
Type: 
Array | null
Example
match("foobarbaz", /b.(.)/)   // ["bar", "r"]
+// a = ["string", "int", "bool", null, "double"]

match(str, pattern) → (nullable) {Array}

Match the given string against the regular expression pattern specified as the second argument.

If the passed regular expression uses the g flag, the return value will be an array of arrays describing all found occurrences within the string.

Without the g modifier, an array describing the first match is returned.

Returns null if the pattern was not found within the given string.

Parameters:
NameTypeDescription
strstring

The string to be matched against the pattern.

patternRegExp

The regular expression pattern.

Returns:
Type: 
Array
Example
match("foobarbaz", /b.(.)/)   // ["bar", "r"]
 match("foobarbaz", /b.(.)/g)  // [["bar", "r"], ["baz", "z"]]

max(…valopt) → {*}

Return the largest value among all parameters passed to the function.

Parameters:
NameTypeAttributesDescription
val*<optional>
<repeatable>

The values to compare.

Returns:
Type: 
*
Example
max(5, 2.1, 3, "abc", 0.3);            // Returns 5
 max(1, "abc");                         // Returns 1 (!)
 max("1", "abc");                       // Returns "abc"
@@ -139,7 +139,7 @@
 min(1, "abc");                         // Returns 1
 min("1", "abc");                       // Returns "1"
 min("def", "abc", "ghi");              // Returns "abc"
-min(true, false);                      // Returns false

ord(s, offsetopt) → {number|null}

Without further arguments, this function returns the byte value of the first character in the given string.

If an offset argument is supplied, the byte value of the character at this position is returned. If an invalid index is supplied, the function will return null. Negative index entries are counted towards the end of the string, e.g. -2 will return the value of the second last character.

Returns the byte value of the character. Returns null if the offset is invalid or if the input is not a string.

Parameters:
NameTypeAttributesDescription
sstring

The input string.

offsetnumber<optional>

The offset of the character.

Returns:
Type: 
number | null
Example
ord("Abc");         // 65
+min(true, false);                      // Returns false

ord(s, offsetopt) → (nullable) {number}

Without further arguments, this function returns the byte value of the first character in the given string.

If an offset argument is supplied, the byte value of the character at this position is returned. If an invalid index is supplied, the function will return null. Negative index entries are counted towards the end of the string, e.g. -2 will return the value of the second last character.

Returns the byte value of the character. Returns null if the offset is invalid or if the input is not a string.

Parameters:
NameTypeAttributesDescription
sstring

The input string.

offsetnumber<optional>

The offset of the character.

Returns:
Type: 
number
Example
ord("Abc");         // 65
 ord("Abc", 0);      // 65
 ord("Abc", 1);      // 98
 ord("Abc", 2);      // 99
@@ -178,7 +178,7 @@
   //   2,
   //   3
   // ]
-%}

proto(val, protoopt) → {Object|null}

Get or set the prototype of the array or object value val.

When invoked without a second argument, the function returns the current prototype of the value in val or null if there is no prototype or if the given value is neither an object nor an array.

When invoked with a second prototype argument, the given proto value is set as the prototype on the array or object in val.

Throws an exception if the given prototype value is not an object.

Parameters:
NameTypeAttributesDescription
valArray | Object

The array or object value.

protoObject<optional>

The optional prototype object.

Returns:
Type: 
Object | null
Example
const arr = [1, 2, 3];
+%}

proto(val, protoopt) → (nullable) {Object}

Get or set the prototype of the array or object value val.

When invoked without a second argument, the function returns the current prototype of the value in val or null if there is no prototype or if the given value is neither an object nor an array.

When invoked with a second prototype argument, the given proto value is set as the prototype on the array or object in val.

Throws an exception if the given prototype value is not an object.

Parameters:
NameTypeAttributesDescription
valArray | Object

The array or object value.

protoObject<optional>

The optional prototype object.

Returns:
Type: 
Object
Example
const arr = [1, 2, 3];
 proto(arr);                 // Returns the current prototype of the array (null by default)
 proto(arr, { foo: true });  // Sets the given object as the prototype of the array

push(arr, …valuesopt) → {*}

Pushes the given argument(s) to the given array.

Returns the last pushed value.

Parameters:
NameTypeAttributesDescription
arrArray

The array to push values to.

values*<optional>
<repeatable>

The values to push.

Returns:
Type: 
*
Example
let x = [ 1, 2, 3 ];
 push(x, 4, 5, 6);    // 6
@@ -197,15 +197,15 @@
     return c3 + c2 + c1;
 })                                                          // raboofzab
 replace("aaaaa", "a", "x", 3)                               // xxxaa
-replace("foo bar baz", /[ao]/g, "x", 3)                     // fxx bxr baz

reverse(arr_or_str) → {Array|string|null}

Reverse the order of the given input array or string.

If an array is passed, returns the array in reverse order. If a string is passed, returns the string with the sequence of the characters reversed.

Returns the reversed array or string. Returns null if neither an array nor a string were passed.

Parameters:
NameTypeDescription
arr_or_strArray | string

The input array or string.

Returns:
Type: 
Array | string | null
Example
reverse([1, 2, 3]);   // [ 3, 2, 1 ]
-reverse("Abc");       // "cbA"

rindex(arr_or_str, needle) → {number|null}

Finds the given value passed as the second argument within the array or string specified in the first argument.

Returns the last matching array index or last matching string offset or -1 if the value was not found.

Returns null if the first argument was neither an array nor a string.

Parameters:
NameTypeDescription
arr_or_strArray | string

The array or string to search for the value.

needle*

The value to find within the array or string.

Returns:
Type: 
number | null
Example
rindex("Hello hello hello", "ll")          // 14
+replace("foo bar baz", /[ao]/g, "x", 3)                     // fxx bxr baz

reverse(arr_or_str) → (nullable) {Array|string}

Reverse the order of the given input array or string.

If an array is passed, returns the array in reverse order. If a string is passed, returns the string with the sequence of the characters reversed.

Returns the reversed array or string. Returns null if neither an array nor a string were passed.

Parameters:
NameTypeDescription
arr_or_strArray | string

The input array or string.

Returns:
Type: 
Array | string
Example
reverse([1, 2, 3]);   // [ 3, 2, 1 ]
+reverse("Abc");       // "cbA"

rindex(arr_or_str, needle) → (nullable) {number}

Finds the given value passed as the second argument within the array or string specified in the first argument.

Returns the last matching array index or last matching string offset or -1 if the value was not found.

Returns null if the first argument was neither an array nor a string.

Parameters:
NameTypeDescription
arr_or_strArray | string

The array or string to search for the value.

needle*

The value to find within the array or string.

Returns:
Type: 
number
Example
rindex("Hello hello hello", "ll")          // 14
 rindex([ 1, 2, 3, 1, 2, 3, 1, 2, 3 ], 2)   //  7
 rindex("foo", "bar")                       // -1
 rindex(["Red", "Blue", "Green"], "Brown")  // -1
 rindex(123, 2)                             // null

rtrim(str, copt) → {string}

Trim any of the specified characters from the end of the string. If the second argument is omitted, trims the characters (space), '\t', '\r', and '\n'.

Returns the right trimmed string.

Parameters:
NameTypeAttributesDescription
strstring

The input string.

cstring<optional>

The characters to trim.

Returns:
Type: 
string
Example
rtrim("  foo  \n")     // "  foo"
 rtrim("--bar--", "-")  // "--bar"

shift(arr) → {*}

Pops the first item from the given array and returns it.

Returns null if the array was empty or if a non-array argument was passed.

Parameters:
NameTypeDescription
arrArray

The array from which to pop the first item.

Returns:
Type: 
*
Example
let x = [ 1, 2, 3 ];
 shift(x);        // 1
-print(x, "\n");  // [ 2, 3 ]

signal(signal, handleropt) → {function|string}

Set or query process signal handler function.

When invoked with two arguments, a signal specification and a signal handler value, this function configures a new process signal handler.

When invoked with one argument, a signal specification, this function returns the currently configured handler for the given signal.

The signal specification might either be an integer signal number or a string value containing a signal name (with or without "SIG" prefix). Signal names are treated case-insensitively.

The signal handler might be either a callable function value or one of the two special string values "ignore" and "default". Passing "ignore" will mask the given process signal while "default" will restore the operating systems default behaviour for the given signal.

In case a callable handler function is provided, it is invoked at the earliest opportunity after receiving the corresponding signal from the operating system. The invoked function will receive a single argument, the number of the signal it is invoked for.

Note that within the ucode VM, process signals are not immediately delivered, instead the VM keeps track of received signals and delivers them to the ucode script environment at the next opportunity, usually before executing the next byte code instruction. This means that if a signal is received while performing a computationally expensive operation in C mode, such as a complex regexp match, the corresponding ucode signal handler will only be invoked after that operation concluded and control flow returns to the VM.

Returns the signal handler function or one of the special values "ignore" or "default" corresponding to the given signal specification.

Returns null if an invalid signal spec or signal handler was provided.

Returns null if changing the signal action failed, e.g. due to insufficient permission, or when attempting to ignore a non-ignorable signal.

Parameters:
NameTypeAttributesDescription
signalnumber | string

The signal to query/set handler for.

handlerfunction | string<optional>

The signal handler to install for the given signal.

Returns:
Type: 
function | string
Example
// Ignore signals
+print(x, "\n");  // [ 2, 3 ]

signal(signal, handleropt) → {function|string}

Set or query process signal handler function.

When invoked with two arguments, a signal specification and a signal handler value, this function configures a new process signal handler.

When invoked with one argument, a signal specification, this function returns the currently configured handler for the given signal.

The signal specification might either be an integer signal number or a string value containing a signal name (with or without "SIG" prefix). Signal names are treated case-insensitively.

The signal handler might be either a callable function value or one of the two special string values "ignore" and "default". Passing "ignore" will mask the given process signal while "default" will restore the operating systems default behaviour for the given signal.

In case a callable handler function is provided, it is invoked at the earliest opportunity after receiving the corresponding signal from the operating system. The invoked function will receive a single argument, the number of the signal it is invoked for.

Note that within the ucode VM, process signals are not immediately delivered, instead the VM keeps track of received signals and delivers them to the ucode script environment at the next opportunity, usually before executing the next byte code instruction. This means that if a signal is received while performing a computationally expensive operation in C mode, such as a complex regexp match, the corresponding ucode signal handler will only be invoked after that operation concluded and control flow returns to the VM.

Returns the signal handler function or one of the special values "ignore" or "default" corresponding to the given signal specification.

Returns null if an invalid signal spec or signal handler was provided.

Returns null if changing the signal action failed, e.g. due to insufficient permission, or when attempting to ignore a non-ignorable signal.

Parameters:
NameTypeAttributesDescription
signalnumber | string

The signal to query/set handler for.

handlerfunction | string<optional>

The signal handler to install for the given signal.

Returns:
Type: 
function | string
Example
// Ignore signals
 signal('INT', 'ignore');      // "ignore"
 signal('SIGINT', 'ignore');   // "ignore" (equivalent to 'INT')
 signal('sigterm', 'ignore');  // "ignore" (signal names are case insensitive)
@@ -232,7 +232,7 @@
 slice("invalid", 1, 2)    // null

sort(arr, fnopt) → {Array}

Sort the given array according to the given sort function. If no sort function is provided, a default ascending sort order is applied.

The input array is sorted in-place, no copy is made.

The custom sort function is repeatedly called until the entire array is sorted. It will receive two values as arguments and should return a value lower than, larger than or equal to zero depending on whether the first argument is smaller, larger or equal to the second argument respectively.

Returns the sorted input array.

Parameters:
NameTypeAttributesDescription
arrArray

The input array to be sorted.

fnfunction<optional>

The sort function.

Returns:
Type: 
Array
Example
sort([8, 1, 5, 9]) // [1, 5, 8, 9]
 sort(["Bean", "Orange", "Apple"], function(a, b) {
    return length(a) - length(b);
-}) // ["Bean", "Apple", "Orange"]

sourcepath(depthopt, dironlyopt) → {string|null}

Determine the path of the source file currently being executed by ucode.

Parameters:
NameTypeAttributesDefaultDescription
depthnumber<optional>
0

The depth to walk up the call stack.

dironlyboolean<optional>

Whether to return only the directory portion of the source file path.

Returns:
Type: 
string | null
Example
sourcepath();         // Returns the path of the currently executed file
+}) // ["Bean", "Apple", "Orange"]

sourcepath(depthopt, dironlyopt) → (nullable) {string}

Determine the path of the source file currently being executed by ucode.

Parameters:
NameTypeAttributesDefaultDescription
depthnumber<optional>
0

The depth to walk up the call stack.

dironlyboolean<optional>

Whether to return only the directory portion of the source file path.

Returns:
Type: 
string
Example
sourcepath();         // Returns the path of the currently executed file
 sourcepath(1);        // Returns the path of the parent source file
 sourcepath(2, true);  // Returns the directory portion of the grandparent source file path

splice(arr, off, lenopt, …elementsopt) → {*}

Removes the elements designated by off and len from the given array, and replaces them with the additional arguments passed, if any.

The array grows or shrinks as necessary.

Returns the modified input array.

Parameters:
NameTypeAttributesDescription
arrArray

The input array to be modified.

offnumber

The index to start removing elements.

lennumber<optional>

The number of elements to remove.

elements*<optional>
<repeatable>

The elements to insert.

Returns:
Type: 
*
Example
let x = [ 1, 2, 3, 4 ];
 splice(x, 1, 2, "a", "b", "c");  // [ 1, "a", "b", "c", 4 ]
@@ -259,15 +259,15 @@
 
 // Apply a timeout
 // returns -9
-system("sleep 3 && echo 'Success'", 1000);

time() → {number}

Returns the current UNIX epoch.

Returns:
Type: 
number
Example
time();     // 1598043054

timegm(datetimespec) → {number|null}

Like timelocal() but interpreting the given date time specification as UTC time.

See timelocal() for details.

Parameters:
NameTypeDescription
datetimespecObject

The broken-down date and time dictionary.

Returns:
Type: 
number | null
Example
timegm({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
-// Returns 1647953502

timelocal(datetimespec) → {number|null}

Performs the inverse operation of localtime() by taking a broken-down date and time dictionary and transforming it into an epoch value according to the local system timezone.

The wday and yday fields of the given date time specification are ignored. Field values outside of their valid range are internally normalized, e.g. October 40th is interpreted as November 9th.

Returns the resulting epoch value or null if the input date time dictionary was invalid or if the date time specification cannot be represented as epoch value.

Parameters:
NameTypeDescription
datetimespecObject

The broken-down date and time dictionary.

Returns:
Type: 
number | null
Example
timelocal({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
+system("sleep 3 && echo 'Success'", 1000);

time() → {number}

Returns the current UNIX epoch.

Returns:
Type: 
number
Example
time();     // 1598043054

timegm(datetimespec) → (nullable) {number}

Like timelocal() but interpreting the given date time specification as UTC time.

See timelocal() for details.

Parameters:
NameTypeDescription
datetimespecmodule:core.TimeSpec

The broken-down date and time dictionary.

Returns:
Type: 
number
Example
timegm({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
+// Returns 1647953502

timelocal(datetimespec) → (nullable) {number}

Performs the inverse operation of localtime() by taking a broken-down date and time dictionary and transforming it into an epoch value according to the local system timezone.

The wday and yday fields of the given date time specification are ignored. Field values outside of their valid range are internally normalized, e.g. October 40th is interpreted as November 9th.

Returns the resulting epoch value or null if the input date time dictionary was invalid or if the date time specification cannot be represented as epoch value.

Parameters:
NameTypeDescription
datetimespecmodule:core.TimeSpec

The broken-down date and time dictionary.

Returns:
Type: 
number
Example
timelocal({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
 // Returns 1647953502

trace(level)

Enables or disables VM opcode tracing.

When invoked with a positive non-zero level, opcode tracing is enabled and debug information is printed to stderr as the program is executed.

Invoking trace() with zero as an argument turns off opcode tracing.

Parameters:
NameTypeDescription
levelnumber

The level of tracing to enable.

Example
trace(1);   // Enables opcode tracing
-trace(0);   // Disables opcode tracing

trim(str, copt) → {string}

Trim any of the specified characters in c from the start and end of str. If the second argument is omitted, trims the characters, (space), \t, \r, and \n.

Returns the trimmed string.

Parameters:
NameTypeAttributesDescription
strstring

The string to be trimmed.

cstring<optional>

The characters to be trimmed from the start and end of the string.

Returns:
Type: 
string

type(x) → {string|null}

Query the type of the given value.

Returns the type of the given value as a string which might be one of "function", "object", "array", "double", "int", or "bool".

Returns null when no value or null is passed.

Parameters:
NameTypeDescription
x*

The value to determine the type of.

Returns:
Type: 
string | null

uc(str) → {string|null}

Converts the given string to uppercase and returns the resulting string.

Returns null if the given argument could not be converted to a string.

Parameters:
NameTypeDescription
str*

The string to be converted to uppercase.

Returns:
Type: 
string | null
Example
uc("hello");   // "HELLO"
+trace(0);   // Disables opcode tracing

trim(str, copt) → {string}

Trim any of the specified characters in c from the start and end of str. If the second argument is omitted, trims the characters, (space), \t, \r, and \n.

Returns the trimmed string.

Parameters:
NameTypeAttributesDescription
strstring

The string to be trimmed.

cstring<optional>

The characters to be trimmed from the start and end of the string.

Returns:
Type: 
string

type(x) → (nullable) {string}

Query the type of the given value.

Returns the type of the given value as a string which might be one of "function", "object", "array", "double", "int", or "bool".

Returns null when no value or null is passed.

Parameters:
NameTypeDescription
x*

The value to determine the type of.

Returns:
Type: 
string

uc(str) → (nullable) {string}

Converts the given string to uppercase and returns the resulting string.

Returns null if the given argument could not be converted to a string.

Parameters:
NameTypeDescription
str*

The string to be converted to uppercase.

Returns:
Type: 
string
Example
uc("hello");   // "HELLO"
 uc(123);       // null

uchr(…Numeric) → {string}

Converts each given numeric value to an UTF-8 multibyte sequence and returns the resulting string.

Invalid numeric values or values outside the range 0..0x10FFFF are represented by the unicode replacement character 0xFFFD.

Returns a new UTF-8 encoded string consisting of unicode characters corresponding to the given numeric codepoints.

Parameters:
NameTypeAttributesDescription
Numericnumber<repeatable>

values to convert.

Returns:
Type: 
string
Example
uchr(0x2600, 0x26C6, 0x2601);  // "☀⛆☁"
-uchr(-1, 0x20ffff, "foo");     // "���"

uniq(array) → {Array|null}

Returns a new array containing all unique values of the given input array.

  • The order is preserved, and subsequent duplicate values are skipped.
  • If a non-array argument is given, the function returns null.
Parameters:
NameTypeDescription
arrayArray

The input array.

Returns:
Type: 
Array | null
Example
uniq([1, true, "foo", 2, true, "bar", "foo"]);       // Returns [1, true, "foo", 2, "bar"]
+uchr(-1, 0x20ffff, "foo");     // "���"

uniq(array) → (nullable) {Array}

Returns a new array containing all unique values of the given input array.

  • The order is preserved, and subsequent duplicate values are skipped.
  • If a non-array argument is given, the function returns null.
Parameters:
NameTypeDescription
arrayArray

The input array.

Returns:
Type: 
Array
Example
uniq([1, true, "foo", 2, true, "bar", "foo"]);       // Returns [1, true, "foo", 2, "bar"]
 uniq("test");                                        // Returns null

unshift(arr, …Values) → {*}

Add the given values to the beginning of the array passed via first argument.

Returns the last value added to the array.

Parameters:
NameTypeAttributesDescription
arrArray

The array to which the values will be added.

Values*<repeatable>

to add.

Returns:
Type: 
*
Example
let x = [ 3, 4, 5 ];
 unshift(x, 1, 2);  // 2
-print(x, "\n");    // [ 1, 2, 3, 4, 5 ]

values(obj) → {Array|null}

Returns an array containing all values of the given object.

Returns null if no object was passed.

Parameters:
NameTypeDescription
obj*

The object from which to extract values.

Returns:
Type: 
Array | null
Example
values({ foo: true, bar: false });   // [true, false]

warn(…x) → {number}

Print any of the given values to stderr. Arrays and objects are converted to their JSON representation.

Returns the amount of bytes printed.

Parameters:
NameTypeAttributesDescription
x*<repeatable>

The values to be printed.

Returns:
Type: 
number
Example
warn("Hello", "world");  // Print "Helloworld" to stderr
+print(x, "\n");    // [ 1, 2, 3, 4, 5 ]

values(obj) → (nullable) {Array}

Returns an array containing all values of the given object.

Returns null if no object was passed.

Parameters:
NameTypeDescription
obj*

The object from which to extract values.

Returns:
Type: 
Array
Example
values({ foo: true, bar: false });   // [true, false]

warn(…x) → {number}

Print any of the given values to stderr. Arrays and objects are converted to their JSON representation.

Returns the amount of bytes printed.

Parameters:
NameTypeAttributesDescription
x*<repeatable>

The values to be printed.

Returns:
Type: 
number
Example
warn("Hello", "world");  // Print "Helloworld" to stderr
 warn({ key: "value" });  // Print JSON representation of the object to stderr

wildcard(subject, pattern, nocaseopt) → {boolean}

Match the given subject against the supplied wildcard (file glob) pattern.

  • If a truthy value is supplied as the third argument, case-insensitive matching is performed.
  • If a non-string value is supplied as the subject, it is converted into a string before being matched.

Returns true when the value matched the given pattern, otherwise false.

Parameters:
NameTypeAttributesDescription
subject*

The subject to match against the wildcard pattern.

patternstring

The wildcard pattern.

nocaseboolean<optional>

Whether to perform case-insensitive matching.

Returns:
Type: 
boolean
Example
wildcard("file.txt", "*.txt");        // Returns true
 wildcard("file.txt", "*.TXT", true);  // Returns true (case-insensitive match)
-wildcard("file.txt", "*.jpg");        // Returns false
\ No newline at end of file +wildcard("file.txt", "*.jpg"); // Returns false

Type Definitions

TimeSpec

A time spec is a plain object describing a point in time, it is returned by the gmtime() and localtime() functions and expected as parameter by the complementary timegm() and timelocal() functions.

When returned by gmtime() or localtime(), all members of the object will be initialized, when passed as argument to timegm() or timelocal(), most member values are optional.

Type:
  • Object
Properties
NameTypeDescription
secnumber

Seconds (0..60)

minnumber

Minutes (0..59)

hournumber

Hours (0..23)

mdaynumber

Day of month (1..31)

monnumber

Month (1..12)

yearnumber

Year (>= 1900)

wdaynumber

Day of week (1..7, Sunday = 7)

ydaynumber

Day of year (1-366, Jan 1st = 1)

isdstnumber

Daylight saving time in effect (yes = 1)

\ No newline at end of file diff --git a/module-debug.html b/module-debug.html index 6fb46358..dcd07875 100644 --- a/module-debug.html +++ b/module-debug.html @@ -1,6 +1,6 @@ Module: debug
On this page

Debugger Module

This module provides runtime debug functionality for ucode scripts.

Functions can be individually imported and directly accessed using the named import syntax:

import { memdump, traceback } from 'debug';
+    
On this page

Debugger Module

This module provides runtime debug functionality for ucode scripts.

Functions can be individually imported and directly accessed using the named import syntax:

import { memdump, traceback } from 'debug';
 
 let stacktrace = traceback(1);
 
@@ -10,4 +10,4 @@
 let stacktrace = debug.traceback(1);
 
 debug.memdump("/tmp/dump.txt");
-

Additionally, the debug module namespace may also be imported by invoking the ucode interpreter with the -ldebug switch.

Upon loading, the debug module will register a SIGUSR2 signal handler which, upon receipt of the signal, will write a memory dump of the currently running program to /tmp/ucode.$timestamp.$pid.memdump. This default behavior can be inhibited by setting the UCODE_DEBUG_MEMDUMP_ENABLED environment variable to 0 when starting the process. The memory dump signal and output directory can be overridden with the UCODE_DEBUG_MEMDUMP_SIGNAL and UCODE_DEBUG_MEMDUMP_PATH environment variables respectively.

Methods

getinfo(value) → {module:debug.ValueInformation|null}

Obtain information about the given value.

The getinfo() function allows querying internal information about the given ucode value, such as the current reference count, the mark bit state etc.

Returns a dictionary with value type specific details.

Returns null if a null value was provided.

Parameters:
NameTypeDescription
value*

The value to query information for.

Returns:
Type: 
module:debug.ValueInformation | null

getlocal(levelopt, variable) → {module:debug.LocalInfo|null}

Obtain local variable.

The getlocal() function retrieves information about the specified local variable at the given call stack depth.

The call stack depth specifies the amount of levels up local variables should be queried. A value of 0 refers to this getlocal() function call itself, 1 to the function calling getlocal() and so on.

The variable to query might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the given variable.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is a C call.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
1

The amount of call stack levels up local variables should be queried.

variablestring | number

The variable index or variable name to obtain information for.

Returns:
Type: 
module:debug.LocalInfo | null

getupval(target, variable) → {module:debug.UpvalInfo|null}

Obtain captured variable (upvalue).

The getupval() function retrieves information about the specified captured variable associated with the given function value or the invoked function at the given call stack depth.

The call stack depth specifies the amount of levels up the function should be selected to query associated captured variables for. A value of 0 refers to this getupval() function call itself, 1 to the function calling getupval() and so on.

The variable to query might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the given variable.

Returns null if the given function value is not a closure.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is not a closure.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeDescription
targetfunction | number

Either a function value referring to a closure to query upvalues for or a stack depth number selecting a closure that many levels up.

variablestring | number

The variable index or variable name to obtain information for.

Returns:
Type: 
module:debug.UpvalInfo | null

memdump(file) → {boolean|null}

Write a memory dump report to the given file.

This function generates a human readable memory dump of ucode values currently managed by the running VM which is useful to track down logical memory leaks in scripts.

The file parameter can be either a string value containing a file path, in which case this function tries to create and write the report file at the given location, or an already open file handle this function should write to.

Returns true if the report has been written.

Returns null if the file could not be opened or if the handle was invalid.

Parameters:
NameTypeDescription
filestring | module:fs.file | module:fs.proc

The file path or open file handle to write report to.

Returns:
Type: 
boolean | null

setlocal(levelopt, variable, valueopt) → {module:debug.LocalInfo|null}

Set local variable.

The setlocal() function manipulates the value of the specified local variable at the given call stack depth.

The call stack depth specifies the amount of levels up local variables should be updated. A value of 0 refers to this setlocal() function call itself, 1 to the function calling setlocal() and so on.

The variable to update might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the updated variable.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is a C call.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
1

The amount of call stack levels up local variables should be updated.

variablestring | number

The variable index or variable name to update.

value*<optional>
null

The value to set the local variable to.

Returns:
Type: 
module:debug.LocalInfo | null

setupval(target, variable, value) → {module:debug.UpvalInfo|null}

Set upvalue.

The setupval() function manipulates the value of the specified captured variable associated with the given function value or the invoked function at the given call stack depth.

The call stack depth specifies the amount of levels up the function should be selected to update associated captured variables for. A value of 0 refers to this setupval() function call itself, 1 to the function calling setupval() and so on.

The variable to update might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the updated variable.

Returns null if the given function value is not a closure.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is not a closure.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeDescription
targetfunction | number

Either a function value referring to a closure to update upvalues for or a stack depth number selecting a closure that many levels up.

variablestring | number

The variable index or variable name to update.

value*

The value to set the variable to.

Returns:
Type: 
module:debug.UpvalInfo | null

sourcepos() → {module:debug.SourcePosition|null}

Obtain information about the current source position.

The sourcepos() function determines the source code position of the current instruction invoking this function.

Returns a dictionary containing the filename, line number and line byte offset of the call site.

Returns null if this function was invoked from C code.

Returns:
Type: 
module:debug.SourcePosition | null

traceback(levelopt) → {Array.<module:debug.StackTraceEntry>}

Capture call stack trace.

This function captures the current call stack and returns it. The optional level parameter controls how many calls up the trace should start. It defaults to 1, that is the function calling this traceback() function.

Returns an array of stack trace entries describing the function invocations up to the point where traceback() is called.

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
1

The number of callframes up the call trace should start, 0 is this function itself, 1 the function calling it and so on.

Returns:
Type: 
Array.<module:debug.StackTraceEntry>

Type Definitions

LocalInfo

Type:
  • Object
Properties
NameTypeDescription
indexnumber

The index of the local variable.

namestring

The name of the local variable.

value*

The current value of the local variable.

linefromnumber

The source line number of the local variable declaration.

bytefromnumber

The source line offset of the local variable declaration.

linetonumber

The source line number where the local variable goes out of scope.

bytetonumber

The source line offset where the local vatiable goes out of scope.

SourcePosition

Type:
  • Object
Properties
NameTypeDescription
filenamestring

The name of the source file that called this function.

linenumber

The source line of the function call.

bytenumber

The source line offset of the function call.

StackTraceEntry

Type:
  • Object
Properties
NameTypeAttributesDescription
calleefunction

The function that was called.

this*

The this context the function was called with.

mcallboolean

Indicates whether the function was invoked as a method.

strictboolean<optional>

Indicates whether the VM was running in strict mode when the function was called (only applicable to non-C, pure ucode calls).

filenamestring<optional>

The name of the source file that called the function (only applicable to non-C, pure ucode calls).

linenumber<optional>

The source line of the function call (only applicable to non-C, pure ucode calls).

bytenumber<optional>

The source line offset of the function call (only applicable to non-C, pure ucode calls).

contextstring<optional>

The surrounding source code context formatted as human-readable string, useful for generating debug messages (only applicable to non-C, pure ucode calls).

UpvalInfo

Type:
  • Object
Properties
NameTypeDescription
indexnumber

The index of the captured variable (upvalue).

namestring

The name of the captured variable.

closedboolean

Indicates whether the captured variable is closed or not. A closed upvalue means that the function outlived the declaration scope of the captured variable.

value*

The current value of the captured variable.

UpvalRef

Type:
  • Object
Properties
NameTypeAttributesDescription
namestring

The name of the captured variable.

closedboolean

Indicates whether the captured variable (upvalue) is closed or not. A closed upvalue means that the function value outlived the declaration scope of the captured variable.

value*

The current value of the captured variable.

slotnumber<optional>

The stack slot of the captured variable. Only applicable to open (non-closed) captured variables.

ValueInformation

Type:
  • Object
Properties
NameTypeAttributesDescription
typestring

The name of the value type, one of integer, boolean, string, double, array, object, regexp, cfunction, closure, upvalue or resource.

value*

The value itself.

taggedboolean

Indicates whether the given value is internally stored as tagged pointer without an additional heap allocation.

markboolean<optional>

Indicates whether the value has it's mark bit set, which is used for loop detection during recursive object traversal on garbage collection cycles or complex value stringification. Only applicable to non-tagged values.

refcountnumber<optional>

The current reference count of the value. Note that the getinfo() function places a reference to the value into the value field of the resulting information dictionary, so the ref count will always be at least 2 - one reference for the function call argument and one for the value property in the result dictionary. Only applicable to non-tagged values.

unsignedboolean<optional>

Whether the number value is internally stored as unsigned integer. Only applicable to non-tagged integer values.

addressnumber<optional>

The address of the underlying C heap memory. Only applicable to non-tagged string, array, object, cfunction or resource values.

lengthnumber<optional>

The length of the underlying string memory. Only applicable to non-tagged string values.

countnumber<optional>

The amount of elements in the underlying memory structure. Only applicable to array and object values.

constantboolean<optional>

Indicates whether the value is constant (immutable). Only applicable to array and object values.

prototype*<optional>

The associated prototype value, if any. Only applicable to array, object and prototype values.

sourcestring<optional>

The original regex source pattern. Only applicable to regexp values.

icaseboolean<optional>

Whether the compiled regex has the i (ignore case) flag set. Only applicable to regexp values.

globalboolean<optional>

Whether the compiled regex has the g (global) flag set. Only applicable to regexp values.

newlineboolean<optional>

Whether the compiled regex has the s (single line) flag set. Only applicable to regexp values.

nsubnumber<optional>

The amount of capture groups within the regular expression. Only applicable to regexp values.

namestring<optional>

The name of the non-anonymous function. Only applicable to cfunction and closure values. Set to null for anonymous function values.

arrowboolean<optional>

Indicates whether the ucode function value is an arrow function. Only applicable to closure values.

moduleboolean<optional>

Indicates whether the ucode function value is a module entry point. Only applicable to closure values.

strictboolean<optional>

Indicates whether the function body will be executed in strict mode. Only applicable to closure values.

varargboolean<optional>

Indicates whether the ucode function takes a variable number of arguments. Only applicable to closure values.

nargsnumber<optional>

The number of arguments expected by the ucode function, excluding a potential final variable argument ellipsis. Only applicable to closure values.

argnamesArray.<string><optional>

The names of the function arguments in their declaration order. Only applicable to closure values.

nupvalsnumber<optional>

The number of upvalues associated with the ucode function. Only applicable to closure values.

upvalsArray.<module:debug.UpvalRef><optional>

An array of upvalue information objects. Only applicable to closure values.

filenamestring<optional>

The path of the source file the function was declared in. Only applicable to closure values.

linenumber<optional>

The source line number the function was declared at. Only applicable to closure values.

bytenumber<optional>

The source line offset the function was declared at. Only applicable to closure values.

typestring<optional>

The resource type name. Only applicable to resource values.

\ No newline at end of file +

Additionally, the debug module namespace may also be imported by invoking the ucode interpreter with the -ldebug switch.

Upon loading, the debug module will register a SIGUSR2 signal handler which, upon receipt of the signal, will write a memory dump of the currently running program to /tmp/ucode.$timestamp.$pid.memdump. This default behavior can be inhibited by setting the UCODE_DEBUG_MEMDUMP_ENABLED environment variable to 0 when starting the process. The memory dump signal and output directory can be overridden with the UCODE_DEBUG_MEMDUMP_SIGNAL and UCODE_DEBUG_MEMDUMP_PATH environment variables respectively.

Methods

getinfo(value) → (nullable) {module:debug.ValueInformation}

Obtain information about the given value.

The getinfo() function allows querying internal information about the given ucode value, such as the current reference count, the mark bit state etc.

Returns a dictionary with value type specific details.

Returns null if a null value was provided.

Parameters:
NameTypeDescription
value*

The value to query information for.

getlocal(levelopt, variable) → (nullable) {module:debug.LocalInfo}

Obtain local variable.

The getlocal() function retrieves information about the specified local variable at the given call stack depth.

The call stack depth specifies the amount of levels up local variables should be queried. A value of 0 refers to this getlocal() function call itself, 1 to the function calling getlocal() and so on.

The variable to query might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the given variable.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is a C call.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
1

The amount of call stack levels up local variables should be queried.

variablestring | number

The variable index or variable name to obtain information for.

Returns:
Type: 
module:debug.LocalInfo

getupval(target, variable) → (nullable) {module:debug.UpvalInfo}

Obtain captured variable (upvalue).

The getupval() function retrieves information about the specified captured variable associated with the given function value or the invoked function at the given call stack depth.

The call stack depth specifies the amount of levels up the function should be selected to query associated captured variables for. A value of 0 refers to this getupval() function call itself, 1 to the function calling getupval() and so on.

The variable to query might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the given variable.

Returns null if the given function value is not a closure.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is not a closure.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeDescription
targetfunction | number

Either a function value referring to a closure to query upvalues for or a stack depth number selecting a closure that many levels up.

variablestring | number

The variable index or variable name to obtain information for.

Returns:
Type: 
module:debug.UpvalInfo

memdump(file) → (nullable) {boolean}

Write a memory dump report to the given file.

This function generates a human readable memory dump of ucode values currently managed by the running VM which is useful to track down logical memory leaks in scripts.

The file parameter can be either a string value containing a file path, in which case this function tries to create and write the report file at the given location, or an already open file handle this function should write to.

Returns true if the report has been written.

Returns null if the file could not be opened or if the handle was invalid.

Parameters:
NameTypeDescription
filestring | module:fs.file | module:fs.proc

The file path or open file handle to write report to.

Returns:
Type: 
boolean

setlocal(levelopt, variable, valueopt) → (nullable) {module:debug.LocalInfo}

Set local variable.

The setlocal() function manipulates the value of the specified local variable at the given call stack depth.

The call stack depth specifies the amount of levels up local variables should be updated. A value of 0 refers to this setlocal() function call itself, 1 to the function calling setlocal() and so on.

The variable to update might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the updated variable.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is a C call.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
1

The amount of call stack levels up local variables should be updated.

variablestring | number

The variable index or variable name to update.

value*<optional>
null

The value to set the local variable to.

Returns:
Type: 
module:debug.LocalInfo

setupval(target, variable, value) → (nullable) {module:debug.UpvalInfo}

Set upvalue.

The setupval() function manipulates the value of the specified captured variable associated with the given function value or the invoked function at the given call stack depth.

The call stack depth specifies the amount of levels up the function should be selected to update associated captured variables for. A value of 0 refers to this setupval() function call itself, 1 to the function calling setupval() and so on.

The variable to update might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the updated variable.

Returns null if the given function value is not a closure.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is not a closure.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeDescription
targetfunction | number

Either a function value referring to a closure to update upvalues for or a stack depth number selecting a closure that many levels up.

variablestring | number

The variable index or variable name to update.

value*

The value to set the variable to.

Returns:
Type: 
module:debug.UpvalInfo

sourcepos() → (nullable) {module:debug.SourcePosition}

Obtain information about the current source position.

The sourcepos() function determines the source code position of the current instruction invoking this function.

Returns a dictionary containing the filename, line number and line byte offset of the call site.

Returns null if this function was invoked from C code.

traceback(levelopt) → {Array.<module:debug.StackTraceEntry>}

Capture call stack trace.

This function captures the current call stack and returns it. The optional level parameter controls how many calls up the trace should start. It defaults to 1, that is the function calling this traceback() function.

Returns an array of stack trace entries describing the function invocations up to the point where traceback() is called.

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
1

The number of callframes up the call trace should start, 0 is this function itself, 1 the function calling it and so on.

Returns:
Type: 
Array.<module:debug.StackTraceEntry>

Type Definitions

LocalInfo

Type:
  • Object
Properties
NameTypeDescription
indexnumber

The index of the local variable.

namestring

The name of the local variable.

value*

The current value of the local variable.

linefromnumber

The source line number of the local variable declaration.

bytefromnumber

The source line offset of the local variable declaration.

linetonumber

The source line number where the local variable goes out of scope.

bytetonumber

The source line offset where the local vatiable goes out of scope.

SourcePosition

Type:
  • Object
Properties
NameTypeDescription
filenamestring

The name of the source file that called this function.

linenumber

The source line of the function call.

bytenumber

The source line offset of the function call.

StackTraceEntry

Type:
  • Object
Properties
NameTypeAttributesDescription
calleefunction

The function that was called.

this*

The this context the function was called with.

mcallboolean

Indicates whether the function was invoked as a method.

strictboolean<optional>

Indicates whether the VM was running in strict mode when the function was called (only applicable to non-C, pure ucode calls).

filenamestring<optional>

The name of the source file that called the function (only applicable to non-C, pure ucode calls).

linenumber<optional>

The source line of the function call (only applicable to non-C, pure ucode calls).

bytenumber<optional>

The source line offset of the function call (only applicable to non-C, pure ucode calls).

contextstring<optional>

The surrounding source code context formatted as human-readable string, useful for generating debug messages (only applicable to non-C, pure ucode calls).

UpvalInfo

Type:
  • Object
Properties
NameTypeDescription
indexnumber

The index of the captured variable (upvalue).

namestring

The name of the captured variable.

closedboolean

Indicates whether the captured variable is closed or not. A closed upvalue means that the function outlived the declaration scope of the captured variable.

value*

The current value of the captured variable.

UpvalRef

Type:
  • Object
Properties
NameTypeAttributesDescription
namestring

The name of the captured variable.

closedboolean

Indicates whether the captured variable (upvalue) is closed or not. A closed upvalue means that the function value outlived the declaration scope of the captured variable.

value*

The current value of the captured variable.

slotnumber<optional>

The stack slot of the captured variable. Only applicable to open (non-closed) captured variables.

ValueInformation

Type:
  • Object
Properties
NameTypeAttributesDescription
typestring

The name of the value type, one of integer, boolean, string, double, array, object, regexp, cfunction, closure, upvalue or resource.

value*

The value itself.

taggedboolean

Indicates whether the given value is internally stored as tagged pointer without an additional heap allocation.

markboolean<optional>

Indicates whether the value has it's mark bit set, which is used for loop detection during recursive object traversal on garbage collection cycles or complex value stringification. Only applicable to non-tagged values.

refcountnumber<optional>

The current reference count of the value. Note that the getinfo() function places a reference to the value into the value field of the resulting information dictionary, so the ref count will always be at least 2 - one reference for the function call argument and one for the value property in the result dictionary. Only applicable to non-tagged values.

unsignedboolean<optional>

Whether the number value is internally stored as unsigned integer. Only applicable to non-tagged integer values.

addressnumber<optional>

The address of the underlying C heap memory. Only applicable to non-tagged string, array, object, cfunction or resource values.

lengthnumber<optional>

The length of the underlying string memory. Only applicable to non-tagged string values.

countnumber<optional>

The amount of elements in the underlying memory structure. Only applicable to array and object values.

constantboolean<optional>

Indicates whether the value is constant (immutable). Only applicable to array and object values.

prototype*<optional>

The associated prototype value, if any. Only applicable to array, object and prototype values.

sourcestring<optional>

The original regex source pattern. Only applicable to regexp values.

icaseboolean<optional>

Whether the compiled regex has the i (ignore case) flag set. Only applicable to regexp values.

globalboolean<optional>

Whether the compiled regex has the g (global) flag set. Only applicable to regexp values.

newlineboolean<optional>

Whether the compiled regex has the s (single line) flag set. Only applicable to regexp values.

nsubnumber<optional>

The amount of capture groups within the regular expression. Only applicable to regexp values.

namestring<optional>

The name of the non-anonymous function. Only applicable to cfunction and closure values. Set to null for anonymous function values.

arrowboolean<optional>

Indicates whether the ucode function value is an arrow function. Only applicable to closure values.

moduleboolean<optional>

Indicates whether the ucode function value is a module entry point. Only applicable to closure values.

strictboolean<optional>

Indicates whether the function body will be executed in strict mode. Only applicable to closure values.

varargboolean<optional>

Indicates whether the ucode function takes a variable number of arguments. Only applicable to closure values.

nargsnumber<optional>

The number of arguments expected by the ucode function, excluding a potential final variable argument ellipsis. Only applicable to closure values.

argnamesArray.<string><optional>

The names of the function arguments in their declaration order. Only applicable to closure values.

nupvalsnumber<optional>

The number of upvalues associated with the ucode function. Only applicable to closure values.

upvalsArray.<module:debug.UpvalRef><optional>

An array of upvalue information objects. Only applicable to closure values.

filenamestring<optional>

The path of the source file the function was declared in. Only applicable to closure values.

linenumber<optional>

The source line number the function was declared at. Only applicable to closure values.

bytenumber<optional>

The source line offset the function was declared at. Only applicable to closure values.

typestring<optional>

The resource type name. Only applicable to resource values.

\ No newline at end of file diff --git a/module-fs.dir.html b/module-fs.dir.html index a84ec596..1b9236de 100644 --- a/module-fs.dir.html +++ b/module-fs.dir.html @@ -1,6 +1,6 @@ Class: dir
On this page

fs. dir

Represents a handle for interacting with a directory opened by opendir().

Example
const handle = opendir(…);
+    
On this page

fs. dir

Represents a handle for interacting with a directory opened by opendir().

Example
const handle = opendir(…);
 
 handle.read();
 
@@ -9,17 +9,15 @@
 
 handle.close();
 
-handle.error();

Methods

close() → {boolean|null}

Closes the directory handle.

Closes the underlying file descriptor referring to the opened directory.

Returns true if the handle was properly closed.

Returns null if an error occurred.

Returns:
Type: 
boolean | null

error() → {string|null}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string | null
Example
// Trigger error
-const fp = opendir("/tmp");
-fp.close();
-fp.close(); // already closed
+handle.error();

Methods

close() → (nullable) {boolean}

Closes the directory handle.

Closes the underlying file descriptor referring to the opened directory.

Returns true if the handle was properly closed.

Returns null if an error occurred.

Returns:
Type: 
boolean

error() → (nullable) {string}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string
Example
// Trigger file system error
+unlink('/path/does/not/exist');
 
-// Print error (should yield "Bad file descriptor")
-print(fp.error(), "\n");

read() → {string|null}

Read the next entry from the open directory.

Returns a string containing the entry name.

Returns null if there are no more entries to read.

Returns null if an error occurred.

Returns:
Type: 
string | null

seek(offset) → {boolean|null}

Set read position.

Sets the read position within the open directory handle to the given offset value. The offset value should be obtained by a previous call to tell() as the specific integer values are implementation defined.

Returns true if the read position was set.

Returns null if an error occurred.

Parameters:
NameTypeDescription
offsetnumber

Position value obtained by tell().

Returns:
Type: 
boolean | null
Example
const handle = opendir("/tmp");
+// Print error (should yield "No such file or directory")
+print(error(), "\n");

read() → (nullable) {string}

Read the next entry from the open directory.

Returns a string containing the entry name.

Returns null if there are no more entries to read.

Returns null if an error occurred.

Returns:
Type: 
string

seek(offset) → (nullable) {boolean}

Set read position.

Sets the read position within the open directory handle to the given offset value. The offset value should be obtained by a previous call to tell() as the specific integer values are implementation defined.

Returns true if the read position was set.

Returns null if an error occurred.

Parameters:
NameTypeDescription
offsetnumber

Position value obtained by tell().

Returns:
Type: 
boolean
Example
const handle = opendir("/tmp");
 const begin = handle.tell();
 
 print(handle.read(), "\n");
 
 handle.seek(begin);
 
-print(handle.read(), "\n");  // prints the first entry again

tell() → {number|null}

Obtain current read position.

Returns the current read position in the open directory handle which can be passed back to the seek() function to return to this position. This is mainly useful to read an open directory handle (or specific items) multiple times.

Returns an integer referring to the current position.

Returns null if an error occurred.

Returns:
Type: 
number | null
\ No newline at end of file +print(handle.read(), "\n"); // prints the first entry again

tell() → (nullable) {number}

Obtain current read position.

Returns the current read position in the open directory handle which can be passed back to the seek() function to return to this position. This is mainly useful to read an open directory handle (or specific items) multiple times.

Returns an integer referring to the current position.

Returns null if an error occurred.

Returns:
Type: 
number
\ No newline at end of file diff --git a/module-fs.file.html b/module-fs.file.html index 3acb5464..abf73fb7 100644 --- a/module-fs.file.html +++ b/module-fs.file.html @@ -1,6 +1,6 @@ Class: file
On this page

fs. file

Represents a handle for interacting with a file opened by one of the file open functions.

Example
const handle = open(…);
+    
On this page

fs. file

Represents a handle for interacting with a file opened by one of the file open functions.

Example
const handle = open(…);
 
 handle.read(…);
 handle.write(…);
@@ -14,13 +14,11 @@
 
 handle.close();
 
-handle.error();

Methods

close() → {boolean|null}

Closes the file handle.

Upon calling close() on the handle, buffered data is flushed and the underlying file descriptor is closed.

Returns true if the handle was properly closed.

Returns null if an error occurred.

Returns:
Type: 
boolean | null

error() → {string|null}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string | null
Example
// Trigger error
-const fp = open("file.txt");
-fp.close();
-fp.close(); // already closed
+handle.error();

Methods

close() → (nullable) {boolean}

Closes the file handle.

Upon calling close() on the handle, buffered data is flushed and the underlying file descriptor is closed.

Returns true if the handle was properly closed.

Returns null if an error occurred.

Returns:
Type: 
boolean

error() → (nullable) {string}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string
Example
// Trigger file system error
+unlink('/path/does/not/exist');
 
-// Print error (should yield "Bad file descriptor")
-print(fp.error(), "\n");

fileno() → {number|null}

Obtains the number of the handle's underlying file descriptor.

Returns the descriptor number.

Returns null on error.

Returns:
Type: 
number | null

flush() → {boolean|null}

Forces a write of all buffered data to the underlying handle.

Returns true if the data was successfully flushed.

Returns null on error.

Returns:
Type: 
boolean | null

isatty() → {boolean|null}

Check for TTY.

Checks whether the open file handle refers to a TTY (terminal) device.

Returns true if the handle refers to a terminal.

Returns false if the handle refers to another kind of file.

Returns null on error.

Returns:
Type: 
boolean | null

read(length) → {string|null}

Reads a chunk of data from the file handle.

The length argument may be either a positive number of bytes to read, in which case the read call returns up to that many bytes, or a string to specify a dynamic read size.

  • If length is a number, the method will read the specified number of bytes from the handle. Reading stops after the given amount of bytes or after encountering EOF, whatever comes first.

  • If length is the string "line", the method will read an entire line, terminated by "\n" (a newline), from the handle. Reading stops at the next newline or when encountering EOF. The returned data will contain the terminating newline character if one was read.

  • If length is the string "all", the method will read from the handle until encountering EOF and return the complete contents.

  • If length is a single character string, the method will read from the handle until encountering the specified character or upon encountering EOF. The returned data will contain the terminating character if one was read.

Returns a string containing the read data.

Returns an empty string on EOF.

Returns null if a read error occurred.

Parameters:
NameTypeDescription
lengthnumber | string

The length of data to read. Can be a number, the string "line", the string "all", or a single character string.

Returns:
Type: 
string | null
Example
const fp = open("file.txt", "r");
+// Print error (should yield "No such file or directory")
+print(error(), "\n");

fileno() → (nullable) {number}

Obtains the number of the handle's underlying file descriptor.

Returns the descriptor number.

Returns null on error.

Returns:
Type: 
number

flush() → (nullable) {boolean}

Forces a write of all buffered data to the underlying handle.

Returns true if the data was successfully flushed.

Returns null on error.

Returns:
Type: 
boolean

isatty() → (nullable) {boolean}

Check for TTY.

Checks whether the open file handle refers to a TTY (terminal) device.

Returns true if the handle refers to a terminal.

Returns false if the handle refers to another kind of file.

Returns null on error.

Returns:
Type: 
boolean

read(length) → (nullable) {string}

Reads a chunk of data from the file handle.

The length argument may be either a positive number of bytes to read, in which case the read call returns up to that many bytes, or a string to specify a dynamic read size.

  • If length is a number, the method will read the specified number of bytes from the handle. Reading stops after the given amount of bytes or after encountering EOF, whatever comes first.

  • If length is the string "line", the method will read an entire line, terminated by "\n" (a newline), from the handle. Reading stops at the next newline or when encountering EOF. The returned data will contain the terminating newline character if one was read.

  • If length is the string "all", the method will read from the handle until encountering EOF and return the complete contents.

  • If length is a single character string, the method will read from the handle until encountering the specified character or upon encountering EOF. The returned data will contain the terminating character if one was read.

Returns a string containing the read data.

Returns an empty string on EOF.

Returns null if a read error occurred.

Parameters:
NameTypeDescription
lengthnumber | string

The length of data to read. Can be a number, the string "line", the string "all", or a single character string.

Returns:
Type: 
string
Example
const fp = open("file.txt", "r");
 
 // Example 1: Read 10 bytes from the handle
 const chunk = fp.read(10);
@@ -33,7 +31,7 @@
 const content = fp.read("all");
 
 // Example 4: Read until encountering the character ':'
-const field = fp.read(":");

seek(offsetopt, positionopt) → {boolean|null}

Set file read position.

Set the read position of the open file handle to the given offset and position.

Returns true if the read position was set.

Returns null if an error occurred.

Parameters:
NameTypeAttributesDefaultDescription
offsetnumber<optional>
0

The offset in bytes.

positionnumber<optional>
0

The position of the offset.

PositionDescription
0The given offset is relative to the start of the file. This is the default value if omitted.
1The given offset is relative to the current read position.
2The given offset is relative to the end of the file.
Returns:
Type: 
boolean | null
Example
const fp = open("file.txt", "r");
+const field = fp.read(":");

seek(offsetopt, positionopt) → (nullable) {boolean}

Set file read position.

Set the read position of the open file handle to the given offset and position.

Returns true if the read position was set.

Returns null if an error occurred.

Parameters:
NameTypeAttributesDefaultDescription
offsetnumber<optional>
0

The offset in bytes.

positionnumber<optional>
0

The position of the offset.

PositionDescription
0The given offset is relative to the start of the file. This is the default value if omitted.
1The given offset is relative to the current read position.
2The given offset is relative to the end of the file.
Returns:
Type: 
boolean
Example
const fp = open("file.txt", "r");
 
 print(fp.read(100), "\n");  // read 100 bytes...
 fp.seek(0, 0);              // ... and reset position to start of file
@@ -43,6 +41,6 @@
 fp.tell();       // ... position is at 110 now
 
 fp.seek(-10, 2);            // set position to ten bytes before EOF ...
-print(fp.read(100), "\n");  // ... reads 10 bytes at most

tell() → {number|null}

Obtain current read position.

Obtains the current, absolute read position of the open file.

Returns an integer containing the current read offset in bytes.

Returns null if an error occurred.

Returns:
Type: 
number | null

write(data) → {number|null}

Writes a chunk of data to the file handle.

In case the given data is not a string, it is converted to a string before being written into the file. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written. The null value is represented by an empty string so file.write(null) would be a no-op. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

Returns the number of bytes written.

Returns null if a write error occurred.

Parameters:
NameTypeDescription
data*

The data to be written.

Returns:
Type: 
number | null
Example
const fp = open("file.txt", "w");
+print(fp.read(100), "\n");  // ... reads 10 bytes at most

tell() → (nullable) {number}

Obtain current read position.

Obtains the current, absolute read position of the open file.

Returns an integer containing the current read offset in bytes.

Returns null if an error occurred.

Returns:
Type: 
number

write(data) → (nullable) {number}

Writes a chunk of data to the file handle.

In case the given data is not a string, it is converted to a string before being written into the file. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written. The null value is represented by an empty string so file.write(null) would be a no-op. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

Returns the number of bytes written.

Returns null if a write error occurred.

Parameters:
NameTypeDescription
data*

The data to be written.

Returns:
Type: 
number
Example
const fp = open("file.txt", "w");
 
-fp.write("Hello world!\n");
\ No newline at end of file +fp.write("Hello world!\n");
\ No newline at end of file diff --git a/module-fs.html b/module-fs.html index 41b28b64..230129d4 100644 --- a/module-fs.html +++ b/module-fs.html @@ -1,6 +1,6 @@ Module: fs
On this page

Filesystem Access

The fs module provides functions for interacting with the file system.

Functions can be individually imported and directly accessed using the named import syntax:

import { readlink, popen } from 'fs';
+    
On this page

Filesystem Access

The fs module provides functions for interacting with the file system.

Functions can be individually imported and directly accessed using the named import syntax:

import { readlink, popen } from 'fs';
 
 let dest = readlink('/sys/class/net/eth0');
 let proc = popen('ps ww');
@@ -8,49 +8,49 @@
 
 let dest = fs.readlink('/sys/class/net/eth0');
 let proc = fs.popen('ps ww');
-

Additionally, the filesystem module namespace may also be imported by invoking the ucode interpreter with the -lfs switch.

Classes

dir
file
proc

Methods

access(path, modeopt) → {boolean|null}

Checks the accessibility of a file or directory.

The optional modes argument specifies the access modes which should be checked. A file is only considered accessible if all access modes specified in the modes argument are possible.

The following modes are recognized:

ModeDescription
"r"Tests whether the file is readable.
"w"Tests whether the file is writable.
"x"Tests whether the file is executable.
"f"Tests whether the file exists.

Returns true if the given path is accessible or false when it is not.

Returns null if an error occurred, e.g. due to inaccessible intermediate path components, invalid path arguments etc.

Parameters:
NameTypeAttributesDefaultDescription
pathstring

The path to the file or directory.

modenumber<optional>
"f"

Optional access mode.

Returns:
Type: 
boolean | null
Example
// Check file read and write accessibility
+

Additionally, the filesystem module namespace may also be imported by invoking the ucode interpreter with the -lfs switch.

Classes

dir
file
proc

Methods

access(path, modeopt) → (nullable) {boolean}

Checks the accessibility of a file or directory.

The optional modes argument specifies the access modes which should be checked. A file is only considered accessible if all access modes specified in the modes argument are possible.

The following modes are recognized:

ModeDescription
"r"Tests whether the file is readable.
"w"Tests whether the file is writable.
"x"Tests whether the file is executable.
"f"Tests whether the file exists.

Returns true if the given path is accessible or false when it is not.

Returns null if an error occurred, e.g. due to inaccessible intermediate path components, invalid path arguments etc.

Parameters:
NameTypeAttributesDefaultDescription
pathstring

The path to the file or directory.

modenumber<optional>
"f"

Optional access mode.

Returns:
Type: 
boolean
Example
// Check file read and write accessibility
 const isAccessible = access('path/to/file', 'rw');
 
 // Check execute permissions
-const mayExecute = access('/usr/bin/example', 'x');

basename(path) → {string|null}

Retrieves the base name of a path.

Returns the base name component of the specified path.

Returns null if the path argument is not a string.

Parameters:
NameTypeDescription
pathstring

The path to extract the base name from.

Returns:
Type: 
string | null
Example
// Get the base name of a path
-const baseName = basename('/path/to/file.txt');

chdir(path) → {boolean|null}

Changes the current working directory to the specified path.

Returns true if the permission change was successful.

Returns null if an error occurred, e.g. due to insufficient permissions or invalid arguments.

Parameters:
NameTypeDescription
pathstring

The path to the new working directory.

Returns:
Type: 
boolean | null
Example
// Change the current working directory
-chdir('new-directory');

chmod(path, mode) → {boolean|null}

Changes the permission mode bits of a file or directory.

Returns true if the permission change was successful.

Returns null if an error occurred, e.g. due to insufficient permissions or invalid arguments.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

modenumber

The new mode (permissions).

Returns:
Type: 
boolean | null
Example
// Change the mode of a file
-chmod('path/to/file', 0o644);

chown(path, uidopt, gidopt) → {boolean|null}

Changes the owner and group of a file or directory.

The user and group may be specified either as uid or gid number respectively, or as a string containing the user or group name, in which case it is resolved to the proper uid/gid first.

If either the user or group parameter is omitted or given as -1, it is not changed.

Returns true if the ownership change was successful.

Returns null if an error occurred or if a user/group name cannot be resolved to a uid/gid value.

Parameters:
NameTypeAttributesDefaultDescription
pathstring

The path to the file or directory.

uidnumber | string<optional>
-1

The new owner's user ID. When given as number, it is used as-is, when given as string, the user name is resolved to the corresponding uid first.

gidnumber | string<optional>
-1

The new group's ID. When given as number, it is used as-is, when given as string, the group name is resolved to the corresponding gid first.

Returns:
Type: 
boolean | null
Example
// Change the owner of a file
+const mayExecute = access('/usr/bin/example', 'x');

basename(path) → (nullable) {string}

Retrieves the base name of a path.

Returns the base name component of the specified path.

Returns null if the path argument is not a string.

Parameters:
NameTypeDescription
pathstring

The path to extract the base name from.

Returns:
Type: 
string
Example
// Get the base name of a path
+const baseName = basename('/path/to/file.txt');

chdir(path) → (nullable) {boolean}

Changes the current working directory to the specified path.

Returns true if the permission change was successful.

Returns null if an error occurred, e.g. due to insufficient permissions or invalid arguments.

Parameters:
NameTypeDescription
pathstring

The path to the new working directory.

Returns:
Type: 
boolean
Example
// Change the current working directory
+chdir('new-directory');

chmod(path, mode) → (nullable) {boolean}

Changes the permission mode bits of a file or directory.

Returns true if the permission change was successful.

Returns null if an error occurred, e.g. due to insufficient permissions or invalid arguments.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

modenumber

The new mode (permissions).

Returns:
Type: 
boolean
Example
// Change the mode of a file
+chmod('path/to/file', 0o644);

chown(path, uidopt, gidopt) → (nullable) {boolean}

Changes the owner and group of a file or directory.

The user and group may be specified either as uid or gid number respectively, or as a string containing the user or group name, in which case it is resolved to the proper uid/gid first.

If either the user or group parameter is omitted or given as -1, it is not changed.

Returns true if the ownership change was successful.

Returns null if an error occurred or if a user/group name cannot be resolved to a uid/gid value.

Parameters:
NameTypeAttributesDefaultDescription
pathstring

The path to the file or directory.

uidnumber | string<optional>
-1

The new owner's user ID. When given as number, it is used as-is, when given as string, the user name is resolved to the corresponding uid first.

gidnumber | string<optional>
-1

The new group's ID. When given as number, it is used as-is, when given as string, the group name is resolved to the corresponding gid first.

Returns:
Type: 
boolean
Example
// Change the owner of a file
 chown('path/to/file', 1000);
 
 // Change the group of a directory
-chown('/htdocs/', null, 'www-data');

dirname(path) → {string|null}

Retrieves the directory name of a path.

Returns the directory name component of the specified path.

Returns null if the path argument is not a string.

Parameters:
NameTypeDescription
pathstring

The path to extract the directory name from.

Returns:
Type: 
string | null
Example
// Get the directory name of a path
-const directoryName = dirname('/path/to/file.txt');

error() → {string|null}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string | null
Example
// Trigger file system error
+chown('/htdocs/', null, 'www-data');

dirname(path) → (nullable) {string}

Retrieves the directory name of a path.

Returns the directory name component of the specified path.

Returns null if the path argument is not a string.

Parameters:
NameTypeDescription
pathstring

The path to extract the directory name from.

Returns:
Type: 
string
Example
// Get the directory name of a path
+const directoryName = dirname('/path/to/file.txt');

error() → (nullable) {string}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string
Example
// Trigger file system error
 unlink('/path/does/not/exist');
 
 // Print error (should yield "No such file or directory")
-print(error(), "\n");

fdopen(fd, modeopt) → {Object}

Associates a file descriptor number with a file handle object.

The mode argument controls how the file handle object is opened and must match the open mode of the underlying descriptor.

It may be set to one of the following values:

ModeDescription
"r"Opens a file stream for reading. The file descriptor must be valid and opened in read mode.
"w"Opens a file stream for writing. The file descriptor must be valid and opened in write mode.
"a"Opens a file stream for appending. The file descriptor must be valid and opened in write mode.
"r+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"w+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"a+"Opens a file stream for both reading and appending. The file descriptor must be valid and opened in read/write mode.

Returns the file handle object associated with the file descriptor.

Parameters:
NameTypeAttributesDefaultDescription
fdnumber

The file descriptor.

modestring<optional>
"r"

The open mode.

Returns:
Type: 
Object
Example
// Associate file descriptors of stdin and stdout with handles
+print(error(), "\n");

fdopen(fd, modeopt) → {Object}

Associates a file descriptor number with a file handle object.

The mode argument controls how the file handle object is opened and must match the open mode of the underlying descriptor.

It may be set to one of the following values:

ModeDescription
"r"Opens a file stream for reading. The file descriptor must be valid and opened in read mode.
"w"Opens a file stream for writing. The file descriptor must be valid and opened in write mode.
"a"Opens a file stream for appending. The file descriptor must be valid and opened in write mode.
"r+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"w+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"a+"Opens a file stream for both reading and appending. The file descriptor must be valid and opened in read/write mode.

Returns the file handle object associated with the file descriptor.

Parameters:
NameTypeAttributesDefaultDescription
fdnumber

The file descriptor.

modestring<optional>
"r"

The open mode.

Returns:
Type: 
Object
Example
// Associate file descriptors of stdin and stdout with handles
 const stdinHandle = fdopen(0, 'r');
-const stdoutHandle = fdopen(1, 'w');

getcwd() → {string|null}

Retrieves the current working directory.

Returns a string containing the current working directory path.

Returns null if an error occurred.

Returns:
Type: 
string | null
Example
// Get the current working directory
-const cwd = getcwd();

lsdir(path) → {Array.<string>|null}

Lists the content of a directory.

Returns a sorted array of the names of files and directories in the specified directory.

Returns null if an error occurred, e.g. if the specified directory cannot be opened.

Parameters:
NameTypeDescription
pathstring

The path to the directory.

Returns:
Type: 
Array.<string> | null
Example
// List the content of a directory
-const fileList = lsdir('/path/to/directory');

lstat(path) → {module:fs.FileStatResult|null}

Retrieves information about a file or directory, without following symbolic links.

Returns an object containing information about the file or directory.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Returns:
Type: 
module:fs.FileStatResult | null
Example
// Get information about a directory
-const dirInfo = lstat('path/to/directory');

mkdir(path) → {boolean|null}

Creates a new directory.

Returns true if the directory was successfully created.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the new directory.

Returns:
Type: 
boolean | null
Example
// Create a directory
-mkdir('path/to/new-directory');

mkstemp(templateopt) → {module:fs.file|null}

Creates a unique, ephemeral temporary file.

Creates a new temporary file, opens it in read and write mode, unlinks it and returns a file handle object referring to the yet open but deleted file.

Upon closing the handle, the associated file will automatically vanish from the system.

The optional path template argument may be used to override the path and name chosen for the temporary file. If the path template contains no path element, /tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is appended to it. The XXXXXX sequence is replaced with a random value ensuring uniqueness of the temporary file name.

Returns a file handle object referring to the ephemeral file on success.

Returns null if an error occurred, e.g. on insufficient permissions or inaccessible directory.

Parameters:
NameTypeAttributesDefaultDescription
templatestring<optional>
"/tmp/XXXXXX"

The path template to use when forming the temporary file name.

Returns:
Type: 
module:fs.file | null
Example
// Create a unique temporary file in the current working directory
-const tempFile = mkstemp('./data-XXXXXX');

open(path, modeopt, permopt) → {module:fs.file|null}

Opens a file.

The mode argument specifies the way the file is opened, it may start with one of the following values:

ModeDescription
"r"Opens a file for reading. The file must exist.
"w"Opens a file for writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a"Opens a file for appending. Data is written at the end of the file. If the file does not exist, it is created.
"r+"Opens a file for both reading and writing. The file must exist.
"w+"Opens a file for both reading and writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a+"Opens a file for both reading and appending. Data can be read and written at the end of the file. If the file does not exist, it is created.

Additionally, the following flag characters may be appended to the mode value:

FlagDescription
"x"Opens a file for exclusive creation. If the file exists, the open call fails.
"e"Opens a file with the O_CLOEXEC flag set, ensuring that the file descriptor is closed on exec calls.

If the mode is one of "w…" or "a…", the permission argument controls the filesystem permissions bits used when creating the file.

Returns a file handle object associated with the opened file.

Parameters:
NameTypeAttributesDefaultDescription
pathstring

The path to the file.

modestring<optional>
"r"

The file opening mode.

permnumber<optional>
0o666

The file creation permissions (for modes w… and a…)

Returns:
Type: 
module:fs.file | null
Example
// Open a file in read-only mode
-const fileHandle = open('file.txt', 'r');

opendir(path) → {module:fs.dir|null}

Opens a directory and returns a directory handle associated with the open directory descriptor.

Returns a director handle referring to the open directory.

Returns null if an error occurred.

Parameters:
NameTypeDescription
pathstring

The path to the directory.

Returns:
Type: 
module:fs.dir | null
Example
// Open a directory
-const directory = opendir('path/to/directory');

pipe() → {Array.<module:fs.file>|null}

Creates a pipe and returns file handle objects associated with the read- and write end of the pipe respectively.

Returns a two element array containing both a file handle object open in read mode referring to the read end of the pipe and a file handle object open in write mode referring to the write end of the pipe.

Returns null if an error occurred.

Returns:
Type: 
Array.<module:fs.file> | null
Example
// Create a pipe
+const stdoutHandle = fdopen(1, 'w');

getcwd() → (nullable) {string}

Retrieves the current working directory.

Returns a string containing the current working directory path.

Returns null if an error occurred.

Returns:
Type: 
string
Example
// Get the current working directory
+const cwd = getcwd();

lsdir(path) → (nullable) {Array.<string>}

Lists the content of a directory.

Returns a sorted array of the names of files and directories in the specified directory.

Returns null if an error occurred, e.g. if the specified directory cannot be opened.

Parameters:
NameTypeDescription
pathstring

The path to the directory.

Returns:
Type: 
Array.<string>
Example
// List the content of a directory
+const fileList = lsdir('/path/to/directory');

lstat(path) → (nullable) {module:fs.FileStatResult}

Retrieves information about a file or directory, without following symbolic links.

Returns an object containing information about the file or directory.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Example
// Get information about a directory
+const dirInfo = lstat('path/to/directory');

mkdir(path) → (nullable) {boolean}

Creates a new directory.

Returns true if the directory was successfully created.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the new directory.

Returns:
Type: 
boolean
Example
// Create a directory
+mkdir('path/to/new-directory');

mkstemp(templateopt) → (nullable) {module:fs.file}

Creates a unique, ephemeral temporary file.

Creates a new temporary file, opens it in read and write mode, unlinks it and returns a file handle object referring to the yet open but deleted file.

Upon closing the handle, the associated file will automatically vanish from the system.

The optional path template argument may be used to override the path and name chosen for the temporary file. If the path template contains no path element, /tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is appended to it. The XXXXXX sequence is replaced with a random value ensuring uniqueness of the temporary file name.

Returns a file handle object referring to the ephemeral file on success.

Returns null if an error occurred, e.g. on insufficient permissions or inaccessible directory.

Parameters:
NameTypeAttributesDefaultDescription
templatestring<optional>
"/tmp/XXXXXX"

The path template to use when forming the temporary file name.

Returns:
Type: 
module:fs.file
Example
// Create a unique temporary file in the current working directory
+const tempFile = mkstemp('./data-XXXXXX');

open(path, modeopt, permopt) → (nullable) {module:fs.file}

Opens a file.

The mode argument specifies the way the file is opened, it may start with one of the following values:

ModeDescription
"r"Opens a file for reading. The file must exist.
"w"Opens a file for writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a"Opens a file for appending. Data is written at the end of the file. If the file does not exist, it is created.
"r+"Opens a file for both reading and writing. The file must exist.
"w+"Opens a file for both reading and writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a+"Opens a file for both reading and appending. Data can be read and written at the end of the file. If the file does not exist, it is created.

Additionally, the following flag characters may be appended to the mode value:

FlagDescription
"x"Opens a file for exclusive creation. If the file exists, the open call fails.
"e"Opens a file with the O_CLOEXEC flag set, ensuring that the file descriptor is closed on exec calls.

If the mode is one of "w…" or "a…", the permission argument controls the filesystem permissions bits used when creating the file.

Returns a file handle object associated with the opened file.

Parameters:
NameTypeAttributesDefaultDescription
pathstring

The path to the file.

modestring<optional>
"r"

The file opening mode.

permnumber<optional>
0o666

The file creation permissions (for modes w… and a…)

Returns:
Type: 
module:fs.file
Example
// Open a file in read-only mode
+const fileHandle = open('file.txt', 'r');

opendir(path) → (nullable) {module:fs.dir}

Opens a directory and returns a directory handle associated with the open directory descriptor.

Returns a director handle referring to the open directory.

Returns null if an error occurred.

Parameters:
NameTypeDescription
pathstring

The path to the directory.

Returns:
Type: 
module:fs.dir
Example
// Open a directory
+const directory = opendir('path/to/directory');

pipe() → (nullable) {Array.<module:fs.file>}

Creates a pipe and returns file handle objects associated with the read- and write end of the pipe respectively.

Returns a two element array containing both a file handle object open in read mode referring to the read end of the pipe and a file handle object open in write mode referring to the write end of the pipe.

Returns null if an error occurred.

Returns:
Type: 
Array.<module:fs.file>
Example
// Create a pipe
 const pipeHandles = pipe();
 pipeHandles[1].write("Hello world\n");
-print(pipeHandles[0].read("line"));

popen(command, modeopt) → {module:fs.proc|null}

Starts a process and returns a handle representing the executed process.

The handle will be connected to the process stdin or stdout, depending on the value of the mode argument.

The mode argument may be either "r" to open the process for reading (connect to its stdin) or "w" to open the process for writing (connect to its stdout).

The mode character "r" or "w" may be optionally followed by "e" to apply the FD_CLOEXEC flag onto the open descriptor.

Returns a process handle referring to the executed process.

Returns null if an error occurred.

Parameters:
NameTypeAttributesDefaultDescription
commandstring

The command to be executed.

modestring<optional>
"r"

The open mode of the process handle.

Returns:
Type: 
module:fs.proc | null
Example
// Open a process
-const process = popen('command', 'r');

readfile(path, limitopt) → {string|null}

Reads the content of a file, optionally limited to the given amount of bytes.

Returns a string containing the file contents.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeAttributesDescription
pathstring

The path to the file.

limitnumber<optional>

Number of bytes to limit the result to. When omitted, the entire content is returned.

Returns:
Type: 
string | null
Example
// Read first 100 bytes of content
+print(pipeHandles[0].read("line"));

popen(command, modeopt) → (nullable) {module:fs.proc}

Starts a process and returns a handle representing the executed process.

The handle will be connected to the process stdin or stdout, depending on the value of the mode argument.

The mode argument may be either "r" to open the process for reading (connect to its stdin) or "w" to open the process for writing (connect to its stdout).

The mode character "r" or "w" may be optionally followed by "e" to apply the FD_CLOEXEC flag onto the open descriptor.

Returns a process handle referring to the executed process.

Returns null if an error occurred.

Parameters:
NameTypeAttributesDefaultDescription
commandstring

The command to be executed.

modestring<optional>
"r"

The open mode of the process handle.

Returns:
Type: 
module:fs.proc
Example
// Open a process
+const process = popen('command', 'r');

readfile(path, limitopt) → (nullable) {string}

Reads the content of a file, optionally limited to the given amount of bytes.

Returns a string containing the file contents.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeAttributesDescription
pathstring

The path to the file.

limitnumber<optional>

Number of bytes to limit the result to. When omitted, the entire content is returned.

Returns:
Type: 
string
Example
// Read first 100 bytes of content
 const content = readfile('path/to/file', 100);
 
 // Read entire file content
-const content = readfile('path/to/file');

Reads the target path of a symbolic link.

Returns a string containing the target path.

Returns null if an error occurred.

Parameters:
NameTypeDescription
pathstring

The path to the symbolic link.

Returns:
Type: 
string | null
Example
// Read the value of a symbolic link
-const targetPath = readlink('symbolicLink');

realpath(path) → {string|null}

Resolves the absolute path of a file or directory.

Returns a string containing the resolved path.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Returns:
Type: 
string | null
Example
// Resolve the absolute path of a file
-const absolutePath = realpath('path/to/file', 'utf8');

rename(oldPath, newPath) → {boolean|null}

Renames or moves a file or directory.

Returns true if the rename operation was successful.

Returns null if an error occurred.

Parameters:
NameTypeDescription
oldPathstring

The current path of the file or directory.

newPathstring

The new path of the file or directory.

Returns:
Type: 
boolean | null
Example
// Rename a file
-rename('old-name.txt', 'new-name.txt');

rmdir(path) → {boolean|null}

Removes the specified directory.

Returns true if the directory was successfully removed.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the directory to be removed.

Returns:
Type: 
boolean | null
Example
// Remove a directory
-rmdir('path/to/directory');

stat(path) → {module:fs.FileStatResult|null}

Retrieves information about a file or directory.

Returns an object containing information about the file or directory.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Returns:
Type: 
module:fs.FileStatResult | null
Example
// Get information about a file
-const fileInfo = stat('path/to/file');

Creates a new symbolic link.

Returns true if the symlink was successfully created.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
targetstring

The target of the symbolic link.

pathstring

The path of the symbolic link.

Returns:
Type: 
boolean | null
Example
// Create a symbolic link
-symlink('target', 'path/to/symlink');

Removes the specified file or symbolic link.

Returns true if the unlink operation was successful.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the file or symbolic link.

Returns:
Type: 
boolean | null
Example
// Remove a file
-unlink('path/to/file');

writefile(path, data, limitopt) → {number|null}

Writes the given data to a file, optionally truncated to the given amount of bytes.

In case the given data is not a string, it is converted to a string before being written into the file. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written into the file. The null value is represented by an empty string so writefile(…, null) would write an empty file. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

If a file already exists at the given path, it is truncated. If no file exists, it is created with default permissions 0o666 masked by the currently effective umask.

Returns the number of bytes written.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeAttributesDescription
pathstring

The path to the file.

data*

The data to be written.

limitnumber<optional>

Truncates the amount of data to be written to the specified amount of bytes. When omitted, the entire content is written.

Returns:
Type: 
number | null
Example
// Write string to a file
+const content = readfile('path/to/file');

Reads the target path of a symbolic link.

Returns a string containing the target path.

Returns null if an error occurred.

Parameters:
NameTypeDescription
pathstring

The path to the symbolic link.

Returns:
Type: 
string
Example
// Read the value of a symbolic link
+const targetPath = readlink('symbolicLink');

realpath(path) → (nullable) {string}

Resolves the absolute path of a file or directory.

Returns a string containing the resolved path.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Returns:
Type: 
string
Example
// Resolve the absolute path of a file
+const absolutePath = realpath('path/to/file', 'utf8');

rename(oldPath, newPath) → (nullable) {boolean}

Renames or moves a file or directory.

Returns true if the rename operation was successful.

Returns null if an error occurred.

Parameters:
NameTypeDescription
oldPathstring

The current path of the file or directory.

newPathstring

The new path of the file or directory.

Returns:
Type: 
boolean
Example
// Rename a file
+rename('old-name.txt', 'new-name.txt');

rmdir(path) → (nullable) {boolean}

Removes the specified directory.

Returns true if the directory was successfully removed.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the directory to be removed.

Returns:
Type: 
boolean
Example
// Remove a directory
+rmdir('path/to/directory');

stat(path) → (nullable) {module:fs.FileStatResult}

Retrieves information about a file or directory.

Returns an object containing information about the file or directory.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Example
// Get information about a file
+const fileInfo = stat('path/to/file');

Creates a new symbolic link.

Returns true if the symlink was successfully created.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
targetstring

The target of the symbolic link.

pathstring

The path of the symbolic link.

Returns:
Type: 
boolean
Example
// Create a symbolic link
+symlink('target', 'path/to/symlink');

Removes the specified file or symbolic link.

Returns true if the unlink operation was successful.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the file or symbolic link.

Returns:
Type: 
boolean
Example
// Remove a file
+unlink('path/to/file');

writefile(path, data, limitopt) → (nullable) {number}

Writes the given data to a file, optionally truncated to the given amount of bytes.

In case the given data is not a string, it is converted to a string before being written into the file. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written into the file. The null value is represented by an empty string so writefile(…, null) would write an empty file. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

If a file already exists at the given path, it is truncated. If no file exists, it is created with default permissions 0o666 masked by the currently effective umask.

Returns the number of bytes written.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeAttributesDescription
pathstring

The path to the file.

data*

The data to be written.

limitnumber<optional>

Truncates the amount of data to be written to the specified amount of bytes. When omitted, the entire content is written.

Returns:
Type: 
number
Example
// Write string to a file
 const bytesWritten = writefile('path/to/file', 'Hello, World!');
 
 // Write object as JSON to a file and limit to 1024 bytes at most
 const obj = { foo: "Hello world", bar: true, baz: 123 };
-const bytesWritten = writefile('debug.txt', obj, 1024);

Type Definitions

FileStatResult

Type:
  • Object
Properties
NameTypeDescription
devObject

The device information.

Properties
NameTypeDescription
majornumber

The major device number.

minornumber

The minor device number.

permObject

The file permissions.

Properties
NameTypeDescription
setuidboolean

Whether the setuid bit is set.

setgidboolean

Whether the setgid bit is set.

stickyboolean

Whether the sticky bit is set.

user_readboolean

Whether the file is readable by the owner.

user_writeboolean

Whether the file is writable by the owner.

user_execboolean

Whether the file is executable by the owner.

group_readboolean

Whether the file is readable by the group.

group_writeboolean

Whether the file is writable by the group.

group_execboolean

Whether the file is executable by the group.

other_readboolean

Whether the file is readable by others.

other_writeboolean

Whether the file is writable by others.

other_execboolean

Whether the file is executable by others.

inodenumber

The inode number.

modenumber

The file mode.

nlinknumber

The number of hard links.

uidnumber

The user ID of the owner.

gidnumber

The group ID of the owner.

sizenumber

The file size in bytes.

blksizenumber

The block size for file system I/O.

blocksnumber

The number of 512-byte blocks allocated for the file.

atimenumber

The timestamp when the file was last accessed.

mtimenumber

The timestamp when the file was last modified.

ctimenumber

The timestamp when the file status was last changed.

typestring

The type of the file ("directory", "file", etc.).

\ No newline at end of file +const bytesWritten = writefile('debug.txt', obj, 1024);

Type Definitions

FileStatResult

Type:
  • Object
Properties
NameTypeDescription
devObject

The device information.

Properties
NameTypeDescription
majornumber

The major device number.

minornumber

The minor device number.

permObject

The file permissions.

Properties
NameTypeDescription
setuidboolean

Whether the setuid bit is set.

setgidboolean

Whether the setgid bit is set.

stickyboolean

Whether the sticky bit is set.

user_readboolean

Whether the file is readable by the owner.

user_writeboolean

Whether the file is writable by the owner.

user_execboolean

Whether the file is executable by the owner.

group_readboolean

Whether the file is readable by the group.

group_writeboolean

Whether the file is writable by the group.

group_execboolean

Whether the file is executable by the group.

other_readboolean

Whether the file is readable by others.

other_writeboolean

Whether the file is writable by others.

other_execboolean

Whether the file is executable by others.

inodenumber

The inode number.

modenumber

The file mode.

nlinknumber

The number of hard links.

uidnumber

The user ID of the owner.

gidnumber

The group ID of the owner.

sizenumber

The file size in bytes.

blksizenumber

The block size for file system I/O.

blocksnumber

The number of 512-byte blocks allocated for the file.

atimenumber

The timestamp when the file was last accessed.

mtimenumber

The timestamp when the file was last modified.

ctimenumber

The timestamp when the file status was last changed.

typestring

The type of the file ("directory", "file", etc.).

\ No newline at end of file diff --git a/module-fs.proc.html b/module-fs.proc.html index 0a96aece..b5eb6c68 100644 --- a/module-fs.proc.html +++ b/module-fs.proc.html @@ -1,6 +1,6 @@ Class: proc
On this page

fs. proc

Represents a handle for interacting with a program launched by popen().

Example
const handle = popen(…);
+    
On this page

fs. proc

Represents a handle for interacting with a program launched by popen().

Example
const handle = popen(…);
 
 handle.read(…);
 handle.write(…);
@@ -10,13 +10,11 @@
 
 handle.close();
 
-handle.error();

Methods

close() → {number|null}

Closes the program handle and awaits program termination.

Upon calling close() on the handle, the program's input or output stream (depending on the open mode) is closed. Afterwards, the function awaits the termination of the underlying program and returns its exit code.

  • When the program was terminated by a signal, the return value will be the negative signal number, e.g. -9 for SIGKILL.

  • When the program terminated normally, the return value will be the positive exit code of the program.

Returns a negative signal number if the program was terminated by a signal.

Returns a positive exit code if the program terminated normally.

Returns null if an error occurred.

Returns:
Type: 
number | null

error() → {string|null}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string | null
Example
// Trigger error
-const fp = popen("command");
-fp.close();
-fp.close(); // already closed
+handle.error();

Methods

close() → (nullable) {number}

Closes the program handle and awaits program termination.

Upon calling close() on the handle, the program's input or output stream (depending on the open mode) is closed. Afterwards, the function awaits the termination of the underlying program and returns its exit code.

  • When the program was terminated by a signal, the return value will be the negative signal number, e.g. -9 for SIGKILL.

  • When the program terminated normally, the return value will be the positive exit code of the program.

Returns a negative signal number if the program was terminated by a signal.

Returns a positive exit code if the program terminated normally.

Returns null if an error occurred.

Returns:
Type: 
number

error() → (nullable) {string}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string
Example
// Trigger file system error
+unlink('/path/does/not/exist');
 
-// Print error (should yield "Bad file descriptor")
-print(fp.error(), "\n");

fileno() → {number|null}

Obtains the number of the handle's underlying file descriptor.

Returns the descriptor number.

Returns null on error.

Returns:
Type: 
number | null

flush() → {boolean|null}

Forces a write of all buffered data to the underlying handle.

Returns true if the data was successfully flushed.

Returns null on error.

Returns:
Type: 
boolean | null

read(length) → {string|null}

Reads a chunk of data from the program handle.

The length argument may be either a positive number of bytes to read, in which case the read call returns up to that many bytes, or a string to specify a dynamic read size.

  • If length is a number, the method will read the specified number of bytes from the handle. Reading stops after the given amount of bytes or after encountering EOF, whatever comes first.

  • If length is the string "line", the method will read an entire line, terminated by "\n" (a newline), from the handle. Reading stops at the next newline or when encountering EOF. The returned data will contain the terminating newline character if one was read.

  • If length is the string "all", the method will read from the handle until encountering EOF and return the complete contents.

  • If length is a single character string, the method will read from the handle until encountering the specified character or upon encountering EOF. The returned data will contain the terminating character if one was read.

Returns a string containing the read data.

Returns an empty string on EOF.

Returns null if a read error occurred.

Parameters:
NameTypeDescription
lengthnumber | string

The length of data to read. Can be a number, the string "line", the string "all", or a single character string.

Returns:
Type: 
string | null
Example
const fp = popen("command", "r");
+// Print error (should yield "No such file or directory")
+print(error(), "\n");

fileno() → (nullable) {number}

Obtains the number of the handle's underlying file descriptor.

Returns the descriptor number.

Returns null on error.

Returns:
Type: 
number

flush() → (nullable) {boolean}

Forces a write of all buffered data to the underlying handle.

Returns true if the data was successfully flushed.

Returns null on error.

Returns:
Type: 
boolean

read(length) → (nullable) {string}

Reads a chunk of data from the program handle.

The length argument may be either a positive number of bytes to read, in which case the read call returns up to that many bytes, or a string to specify a dynamic read size.

  • If length is a number, the method will read the specified number of bytes from the handle. Reading stops after the given amount of bytes or after encountering EOF, whatever comes first.

  • If length is the string "line", the method will read an entire line, terminated by "\n" (a newline), from the handle. Reading stops at the next newline or when encountering EOF. The returned data will contain the terminating newline character if one was read.

  • If length is the string "all", the method will read from the handle until encountering EOF and return the complete contents.

  • If length is a single character string, the method will read from the handle until encountering the specified character or upon encountering EOF. The returned data will contain the terminating character if one was read.

Returns a string containing the read data.

Returns an empty string on EOF.

Returns null if a read error occurred.

Parameters:
NameTypeDescription
lengthnumber | string

The length of data to read. Can be a number, the string "line", the string "all", or a single character string.

Returns:
Type: 
string
Example
const fp = popen("command", "r");
 
 // Example 1: Read 10 bytes from the handle
 const chunk = fp.read(10);
@@ -29,6 +27,6 @@
 const content = fp.read("all");
 
 // Example 4: Read until encountering the character ':'
-const field = fp.read(":");

write(data) → {number|null}

Writes a chunk of data to the program handle.

In case the given data is not a string, it is converted to a string before being written to the program's stdin. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written. The null value is represented by an empty string so proc.write(null) would be a no-op. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

Returns the number of bytes written.

Returns null if a write error occurred.

Parameters:
NameTypeDescription
data*

The data to be written.

Returns:
Type: 
number | null
Example
const fp = popen("command", "w");
+const field = fp.read(":");

write(data) → (nullable) {number}

Writes a chunk of data to the program handle.

In case the given data is not a string, it is converted to a string before being written to the program's stdin. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written. The null value is represented by an empty string so proc.write(null) would be a no-op. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

Returns the number of bytes written.

Returns null if a write error occurred.

Parameters:
NameTypeDescription
data*

The data to be written.

Returns:
Type: 
number
Example
const fp = popen("command", "w");
 
-fp.write("Hello world!\n");
\ No newline at end of file +fp.write("Hello world!\n");
\ No newline at end of file diff --git a/module-log.html b/module-log.html index b89fdb3b..e9d9076d 100644 --- a/module-log.html +++ b/module-log.html @@ -1,6 +1,6 @@ Module: log
On this page

System logging functions

The log module provides bindings to the POSIX syslog functions openlog(), syslog() and closelog() as well as - when available - the OpenWrt specific ulog library functions.

Functions can be individually imported and directly accessed using the named import syntax:

import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';
+    
On this page

System logging functions

The log module provides bindings to the POSIX syslog functions openlog(), syslog() and closelog() as well as - when available - the OpenWrt specific ulog library functions.

Functions can be individually imported and directly accessed using the named import syntax:

import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';
 
 openlog("my-log-ident", LOG_PID, LOG_USER);
 syslog(LOG_ERR, "An error occurred!");
@@ -58,4 +58,4 @@
 ulog(LOG_DEBUG, "Testing thresholds");
 
 // Using priority name
-ulog_threshold("debug");

Type Definitions

LogFacility

The following log facility strings are recognized:

FacilityDescription
"auth"Authentication/authorization messages.
"authpriv"Private authentication messages.
"cron"Clock daemon (cron and at commands).
"daemon"System daemons without separate facility values.
"ftp"FTP server daemon.
"kern"Kernel messages.
"lpr"Line printer subsystem.
"mail"Mail system.
"news"Network news subsystem.
"syslog"Messages generated internally by syslogd.
"user"Generic user-level messages.
"uucp"UUCP subsystem.
"local0"Local use 0 (custom facility).
"local1"Local use 1 (custom facility).
"local2"Local use 2 (custom facility).
"local3"Local use 3 (custom facility).
"local4"Local use 4 (custom facility).
"local5"Local use 5 (custom facility).
"local6"Local use 6 (custom facility).
"local7"Local use 7 (custom facility).
Type:
  • string

LogOption

The following log option strings are recognized:

Log OptionDescription
"pid"Include PID with each message.
"cons"Log to console if an error occurs while sending to syslog.
"ndelay"Open the connection to the logger immediately.
"odelay"Delay open until the first message is logged.
"nowait"Do not wait for child processes created during logging.
Type:
  • string

LogPriority

The following log priority strings are recognized:

PriorityDescription
"emerg"System is unusable.
"alert"Action must be taken immediately.
"crit"Critical conditions.
"err"Error conditions.
"warning"Warning conditions.
"notice"Normal, but significant, condition.
"info"Informational message.
"debug"Debug-level message.
Type:
  • string

UlogChannel

The following ulog channel strings are recognized:

ChannelDescription
"kmsg"Log to /dev/kmsg, log messages appear in dmesg.
"syslog"Use standard syslog() mechanism.
"stdio"Use stderr for log output.
Type:
  • string
\ No newline at end of file +ulog_threshold("debug");

Type Definitions

LogFacility

The following log facility strings are recognized:

FacilityDescription
"auth"Authentication/authorization messages.
"authpriv"Private authentication messages.
"cron"Clock daemon (cron and at commands).
"daemon"System daemons without separate facility values.
"ftp"FTP server daemon.
"kern"Kernel messages.
"lpr"Line printer subsystem.
"mail"Mail system.
"news"Network news subsystem.
"syslog"Messages generated internally by syslogd.
"user"Generic user-level messages.
"uucp"UUCP subsystem.
"local0"Local use 0 (custom facility).
"local1"Local use 1 (custom facility).
"local2"Local use 2 (custom facility).
"local3"Local use 3 (custom facility).
"local4"Local use 4 (custom facility).
"local5"Local use 5 (custom facility).
"local6"Local use 6 (custom facility).
"local7"Local use 7 (custom facility).
Type:
  • string

LogOption

The following log option strings are recognized:

Log OptionDescription
"pid"Include PID with each message.
"cons"Log to console if an error occurs while sending to syslog.
"ndelay"Open the connection to the logger immediately.
"odelay"Delay open until the first message is logged.
"nowait"Do not wait for child processes created during logging.
Type:
  • string

LogPriority

The following log priority strings are recognized:

PriorityDescription
"emerg"System is unusable.
"alert"Action must be taken immediately.
"crit"Critical conditions.
"err"Error conditions.
"warning"Warning conditions.
"notice"Normal, but significant, condition.
"info"Informational message.
"debug"Debug-level message.
Type:
  • string

UlogChannel

The following ulog channel strings are recognized:

ChannelDescription
"kmsg"Log to /dev/kmsg, log messages appear in dmesg.
"syslog"Use standard syslog() mechanism.
"stdio"Use stderr for log output.
Type:
  • string
\ No newline at end of file diff --git a/module-math.html b/module-math.html index 650583ce..676b49d7 100644 --- a/module-math.html +++ b/module-math.html @@ -1,6 +1,6 @@ Module: math
On this page

Mathematical Functions

The math module bundles various mathematical and trigonometrical functions.

Functions can be individually imported and directly accessed using the named import syntax:

import { pow, rand } from 'math';
+    
On this page

Mathematical Functions

The math module bundles various mathematical and trigonometrical functions.

Functions can be individually imported and directly accessed using the named import syntax:

import { pow, rand } from 'math';
 
 let x = pow(2, 5);
 let y = rand();
@@ -8,4 +8,4 @@
 
 let x = math.pow(2, 5);
 let y = math.rand();
-

Additionally, the math module namespace may also be imported by invoking the ucode interpreter with the -lmath switch.

Methods

abs(number) → {number}

Returns the absolute value of the given numeric value.

Parameters:
NameTypeDescription
number*

The number to return the absolute value for.

Returns:

Returns the absolute value or NaN if the given argument could not be converted to a number.

Type: 
number

atan2(y, x) → {number}

Calculates the principal value of the arc tangent of y/x, using the signs of the two arguments to determine the quadrant of the result.

On success, this function returns the principal value of the arc tangent of y/x in radians; the return value is in the range [-pi, pi].

  • If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.
  • If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.
  • If y is less than 0 and x is +0 or -0, -pi/2 is returned.
  • If y is greater than 0 and x is +0 or -0, pi/2 is returned.
  • If either x or y is NaN, a NaN is returned.
  • If y is +0 (-0) and x is -0, +pi (-pi) is returned.
  • If y is +0 (-0) and x is +0, +0 (-0) is returned.
  • If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.
  • If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.
  • If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.
  • If y is positive infinity (negative infinity) and x is negative infinity, +3pi/4 (-3pi/4) is returned.
  • If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned.

When either x or y can't be converted to a numeric value, NaN is returned.

Parameters:
NameTypeDescription
y*

The y value.

x*

The x value.

Returns:
Type: 
number

cos(x) → {number}

Calculates the cosine of x, where x is given in radians.

Returns the resulting consine value.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Radians value to calculate cosine for.

Returns:
Type: 
number

exp(x) → {number}

Calculates the value of e (the base of natural logarithms) raised to the power of x.

On success, returns the exponential value of x.

  • If x is positive infinity, positive infinity is returned.
  • If x is negative infinity, +0 is returned.
  • If the result underflows, a range error occurs, and zero is returned.
  • If the result overflows, a range error occurs, and Infinity is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Power to raise e to.

Returns:
Type: 
number

isnan(x) → {boolean}

Tests whether x is a NaN double.

This functions checks whether the given argument is of type double with a NaN (not a number) value.

Returns true if the value is NaN, otherwise false.

Note that a value can also be checked for NaN with the expression x !== x which only evaluates to true if x is NaN.

Parameters:
NameTypeDescription
xnumber

The value to test.

Returns:
Type: 
boolean

log(x) → {number}

Calculates the natural logarithm of x.

On success, returns the natural logarithm of x.

  • If x is 1, the result is +0.
  • If x is positive nfinity, positive infinity is returned.
  • If x is zero, then a pole error occurs, and the function returns negative infinity.
  • If x is negative (including negative infinity), then a domain error occurs, and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Value to calulate natural logarithm of.

Returns:
Type: 
number

pow(x, y) → {number}

Calculates the value of x raised to the power of y.

On success, returns the value of x raised to the power of y.

  • If the result overflows, a range error occurs, and the function returns Infinity.
  • If result underflows, and is not representable, a range error occurs, and 0.0 with the appropriate sign is returned.
  • If x is +0 or -0, and y is an odd integer less than 0, a pole error occurs Infinity is returned, with the same sign as x.
  • If x is +0 or -0, and y is less than 0 and not an odd integer, a pole error occurs and Infinity is returned.
  • If x is +0 (-0), and y is an odd integer greater than 0, the result is +0 (-0).
  • If x is 0, and y greater than 0 and not an odd integer, the result is +0.
  • If x is -1, and y is positive infinity or negative infinity, the result is 1.0.
  • If x is +1, the result is 1.0 (even if y is NaN).
  • If y is 0, the result is 1.0 (even if x is NaN).
  • If x is a finite value less than 0, and y is a finite noninteger, a domain error occurs, and NaN is returned.
  • If the absolute value of x is less than 1, and y is negative infinity, the result is positive infinity.
  • If the absolute value of x is greater than 1, and y is negative infinity, the result is +0.
  • If the absolute value of x is less than 1, and y is positive infinity, the result is +0.
  • If the absolute value of x is greater than 1, and y is positive infinity, the result is positive infinity.
  • If x is negative infinity, and y is an odd integer less than 0, the result is -0.
  • If x is negative infinity, and y less than 0 and not an odd integer, the result is +0.
  • If x is negative infinity, and y is an odd integer greater than 0, the result is negative infinity.
  • If x is negative infinity, and y greater than 0 and not an odd integer, the result is positive infinity.
  • If x is positive infinity, and y less than 0, the result is +0.
  • If x is positive infinity, and y greater than 0, the result is positive infinity.

Returns NaN if either the x or y value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

The base value.

ynumber

The power value.

Returns:
Type: 
number

rand() → {number}

Produces a pseudo-random positive integer.

Returns the calculated pseuo-random value. The value is within the range 0 to RAND_MAX inclusive where RAND_MAX is a platform specific value guaranteed to be at least 32767.

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is explicitly set by calling srand() prior to the first call to rand(), the math module will automatically seed the PRNG once, using the current time of day in milliseconds as seed value.

Returns:
Type: 
number

sin(x) → {number}

Calculates the sine of x, where x is given in radians.

Returns the resulting sine value.

  • When x is positive or negative infinity, a domain error occurs and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Radians value to calculate sine for.

Returns:
Type: 
number

sqrt(x) → {number}

Calculates the nonnegative square root of x.

Returns the resulting square root value.

  • If x is +0 (-0) then +0 (-0) is returned.
  • If x is positive infinity, positive infinity is returned.
  • If x is less than -0, a domain error occurs, and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Value to calculate square root for.

Returns:
Type: 
number

srand(seed)

Seeds the pseudo-random number generator.

This functions seeds the PRNG with the given value and thus affects the pseudo-random integer sequence produced by subsequent calls to rand().

Setting the same seed value will result in the same pseudo-random numbers produced by rand().

Parameters:
NameTypeDescription
seednumber

The seed value.

\ No newline at end of file +

Additionally, the math module namespace may also be imported by invoking the ucode interpreter with the -lmath switch.

Methods

abs(number) → {number}

Returns the absolute value of the given numeric value.

Parameters:
NameTypeDescription
number*

The number to return the absolute value for.

Returns:

Returns the absolute value or NaN if the given argument could not be converted to a number.

Type: 
number

atan2(y, x) → {number}

Calculates the principal value of the arc tangent of y/x, using the signs of the two arguments to determine the quadrant of the result.

On success, this function returns the principal value of the arc tangent of y/x in radians; the return value is in the range [-pi, pi].

  • If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.
  • If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.
  • If y is less than 0 and x is +0 or -0, -pi/2 is returned.
  • If y is greater than 0 and x is +0 or -0, pi/2 is returned.
  • If either x or y is NaN, a NaN is returned.
  • If y is +0 (-0) and x is -0, +pi (-pi) is returned.
  • If y is +0 (-0) and x is +0, +0 (-0) is returned.
  • If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.
  • If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.
  • If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.
  • If y is positive infinity (negative infinity) and x is negative infinity, +3pi/4 (-3pi/4) is returned.
  • If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned.

When either x or y can't be converted to a numeric value, NaN is returned.

Parameters:
NameTypeDescription
y*

The y value.

x*

The x value.

Returns:
Type: 
number

cos(x) → {number}

Calculates the cosine of x, where x is given in radians.

Returns the resulting consine value.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Radians value to calculate cosine for.

Returns:
Type: 
number

exp(x) → {number}

Calculates the value of e (the base of natural logarithms) raised to the power of x.

On success, returns the exponential value of x.

  • If x is positive infinity, positive infinity is returned.
  • If x is negative infinity, +0 is returned.
  • If the result underflows, a range error occurs, and zero is returned.
  • If the result overflows, a range error occurs, and Infinity is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Power to raise e to.

Returns:
Type: 
number

isnan(x) → {boolean}

Tests whether x is a NaN double.

This functions checks whether the given argument is of type double with a NaN (not a number) value.

Returns true if the value is NaN, otherwise false.

Note that a value can also be checked for NaN with the expression x !== x which only evaluates to true if x is NaN.

Parameters:
NameTypeDescription
xnumber

The value to test.

Returns:
Type: 
boolean

log(x) → {number}

Calculates the natural logarithm of x.

On success, returns the natural logarithm of x.

  • If x is 1, the result is +0.
  • If x is positive nfinity, positive infinity is returned.
  • If x is zero, then a pole error occurs, and the function returns negative infinity.
  • If x is negative (including negative infinity), then a domain error occurs, and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Value to calulate natural logarithm of.

Returns:
Type: 
number

pow(x, y) → {number}

Calculates the value of x raised to the power of y.

On success, returns the value of x raised to the power of y.

  • If the result overflows, a range error occurs, and the function returns Infinity.
  • If result underflows, and is not representable, a range error occurs, and 0.0 with the appropriate sign is returned.
  • If x is +0 or -0, and y is an odd integer less than 0, a pole error occurs Infinity is returned, with the same sign as x.
  • If x is +0 or -0, and y is less than 0 and not an odd integer, a pole error occurs and Infinity is returned.
  • If x is +0 (-0), and y is an odd integer greater than 0, the result is +0 (-0).
  • If x is 0, and y greater than 0 and not an odd integer, the result is +0.
  • If x is -1, and y is positive infinity or negative infinity, the result is 1.0.
  • If x is +1, the result is 1.0 (even if y is NaN).
  • If y is 0, the result is 1.0 (even if x is NaN).
  • If x is a finite value less than 0, and y is a finite noninteger, a domain error occurs, and NaN is returned.
  • If the absolute value of x is less than 1, and y is negative infinity, the result is positive infinity.
  • If the absolute value of x is greater than 1, and y is negative infinity, the result is +0.
  • If the absolute value of x is less than 1, and y is positive infinity, the result is +0.
  • If the absolute value of x is greater than 1, and y is positive infinity, the result is positive infinity.
  • If x is negative infinity, and y is an odd integer less than 0, the result is -0.
  • If x is negative infinity, and y less than 0 and not an odd integer, the result is +0.
  • If x is negative infinity, and y is an odd integer greater than 0, the result is negative infinity.
  • If x is negative infinity, and y greater than 0 and not an odd integer, the result is positive infinity.
  • If x is positive infinity, and y less than 0, the result is +0.
  • If x is positive infinity, and y greater than 0, the result is positive infinity.

Returns NaN if either the x or y value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

The base value.

ynumber

The power value.

Returns:
Type: 
number

rand() → {number}

Produces a pseudo-random positive integer.

Returns the calculated pseuo-random value. The value is within the range 0 to RAND_MAX inclusive where RAND_MAX is a platform specific value guaranteed to be at least 32767.

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is explicitly set by calling srand() prior to the first call to rand(), the math module will automatically seed the PRNG once, using the current time of day in milliseconds as seed value.

Returns:
Type: 
number

sin(x) → {number}

Calculates the sine of x, where x is given in radians.

Returns the resulting sine value.

  • When x is positive or negative infinity, a domain error occurs and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Radians value to calculate sine for.

Returns:
Type: 
number

sqrt(x) → {number}

Calculates the nonnegative square root of x.

Returns the resulting square root value.

  • If x is +0 (-0) then +0 (-0) is returned.
  • If x is positive infinity, positive infinity is returned.
  • If x is less than -0, a domain error occurs, and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Value to calculate square root for.

Returns:
Type: 
number

srand(seed)

Seeds the pseudo-random number generator.

This functions seeds the PRNG with the given value and thus affects the pseudo-random integer sequence produced by subsequent calls to rand().

Setting the same seed value will result in the same pseudo-random numbers produced by rand().

Parameters:
NameTypeDescription
seednumber

The seed value.

\ No newline at end of file diff --git a/module-struct.html b/module-struct.html index cacc0dee..dad7deab 100644 --- a/module-struct.html +++ b/module-struct.html @@ -1,6 +1,6 @@ Module: struct
On this page

Handle Packed Binary Data

The struct module provides routines for interpreting byte strings as packed binary data.

Functions can be individually imported and directly accessed using the named import syntax:

import { pack, unpack } from 'struct';
+    
On this page

Handle Packed Binary Data

The struct module provides routines for interpreting byte strings as packed binary data.

Functions can be individually imported and directly accessed using the named import syntax:

import { pack, unpack } from 'struct';
 
 let buffer = pack('bhl', -13, 1234, 444555666);
 let values = unpack('bhl', buffer);
@@ -45,4 +45,4 @@
 const data = pack('!III', 1, 2, 3);

unpack(format, input, offsetopt) → {array}

Unpack given byte string according to specified format.

The unpack() function interpretes a byte string according to the given format string and returns the resulting values. If the optional offset argument is given, unpacking starts from this byte position within the input. If not specified, the start offset defaults to 0, the start of the given input string.

Returns an array of unpacked values.

Raises a runtime exception if the format string is invalid or if an invalid input string or offset value is given.

Parameters:
NameTypeAttributesDefaultDescription
formatstring

The format string.

inputstring

The input string to unpack.

offsetnumber<optional>
0

The offset within the input string to start unpacking from.

Returns:
Type: 
array
Example
// Unpack three consecutive unsigned int values in network byte order.
 const numbers =
   unpack('!III', '\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03');
-print(numbers, "\n"); // [ 1, 2, 3 ]
\ No newline at end of file +print(numbers, "\n"); // [ 1, 2, 3 ]
\ No newline at end of file diff --git a/module-struct.instance.html b/module-struct.instance.html index 87417c7e..d08e2850 100644 --- a/module-struct.instance.html +++ b/module-struct.instance.html @@ -1,9 +1,9 @@ Class: instance
On this page

struct. instance

Represents a struct instance created by new().

Example
const fmt = struct.new(…);
+    
On this page

struct. instance

Represents a struct instance created by new().

Example
const fmt = struct.new(…);
 
 fmt.pack(…);
 
 const values = fmt.unpack(…);

Methods

pack(…values) → {string}

Pack given values.

The pack() function creates a byte string containing the argument values packed according to the given format instance.

Returns the packed string.

Raises a runtime exception if a given argument value does not match the required type of the corresponding format string directive.

Parameters:
NameTypeAttributesDescription
values*<repeatable>

Variable number of values to pack.

Returns:
Type: 
string
Example
const fmt = struct.new(…);
 const data = fmt.pack(…);

unpack(input, offsetopt) → {array}

Unpack given byte string.

The unpack() function interpretes a byte string according to the given format instance and returns the resulting values. If the optional offset argument is given, unpacking starts from this byte position within the input. If not specified, the start offset defaults to 0, the start of the given input string.

Returns an array of unpacked values.

Raises a runtime exception if an invalid input string or offset value is given.

Parameters:
NameTypeAttributesDefaultDescription
inputstring

The input string to unpack.

offsetnumber<optional>
0

The offset within the input string to start unpacking from.

Returns:
Type: 
array
Example
const fmt = struct.new(…);
-const values = fmt.unpack(…);
\ No newline at end of file +const values = fmt.unpack(…);
\ No newline at end of file diff --git a/module-uci.cursor.html b/module-uci.cursor.html new file mode 100644 index 00000000..39df4dfd --- /dev/null +++ b/module-uci.cursor.html @@ -0,0 +1,149 @@ +Class: cursor
On this page

uci. cursor

Represents a context for interacting with uci configuration files.

Operations on uci configurations are performed through a uci cursor object which operates on in-memory representations of loaded configuration files.

Any changes made to configuration values are local to the cursor object and held in memory only until they're written out to the filesystem using the save() and commit() methods.

Changes performed in one cursor instance are not reflected in another, unless the first instance writes those changes to the filesystem and the other instance explicitly (re)loads the affected configuration files.

Example
const ctx = cursor(…);
+
+// Enumerate configuration files
+ctx.configs();
+
+// Load configuration files
+ctx.load(…);
+ctx.unload(…);
+
+// Query values
+ctx.get(…);
+ctx.get_all(…);
+ctx.get_first(…);
+ctx.foreach(…);
+
+// Modify values
+ctx.add(…);
+ctx.set(…);
+ctx.rename(…);
+ctx.reorder(…);
+ctx.delete(…);
+
+// Stage, revert, save changes
+ctx.changes(…);
+ctx.save(…);
+ctx.revert(…);
+ctx.commit(…);

Methods

add(config, type) → (nullable) {string}

Add anonymous section to given configuration.

Adds a new anonymous (unnamed) section of the specified type to the given configuration. In order to add a named section, the three argument form of set() should be used instead.

In contrast to other query functions, add() will not implicitly load the configuration into the cursor. The configuration either needs to be loaded explicitly through load() beforehand, or implicitly by querying it through one of the get(), get_all(), get_first() or foreach() functions.

Returns the autogenerated, ephemeral name of the added unnamed section on success.

Returns null on error, e.g. if the targeted configuration was not loaded or if an invalid section type value was passed.

Parameters:
NameTypeDescription
configstring

The name of the configuration file to add the section to, e.g. "system" to modify /etc/config/system.

typestring

The type value to use for the added section.

Returns:
Type: 
string
Example
const ctx = cursor(…);
+
+// Load firewall configuration
+ctx.load('firewall');
+
+// Add unnamed `config rule` section
+const sid = ctx.add('firewall', 'rule');
+
+// Set values on the newly added section
+ctx.set('firewall', sid, 'name', 'A test');
+ctx.set('firewall', sid, 'target', 'ACCEPT');
+…

changes(configopt) → (nullable) {Object.<string, Array.<module:uci.cursor.ChangeRecord>>}

Enumerate pending changes.

The changes() function returns a list of change records for currently loaded configuration files, originating both from the cursors associated delta directory and yet unsaved cursor changes.

When the optional "config" parameter is specified, the requested configuration is implicitly loaded if it not already loaded into the cursor.

Returns a dictionary of change record arrays, keyed by configuration name.

Returns null on error, e.g. if the requested configuration could not be loaded.

Parameters:
NameTypeAttributesDescription
configstring<optional>

The name of the configuration file to enumerate changes for, e.g. "system" to query pending changes for the /etc/config/system file.

Returns:
Type: 
Object.<string, Array.<module:uci.cursor.ChangeRecord>>
Example
const ctx = cursor(…);
+
+// Enumerate changes for all currently loaded configurations
+const deltas = ctx.changes();
+
+// Explicitly load and enumerate changes for the "system" configuration
+const deltas = ctx.changes('system');

commit(configopt) → (nullable) {boolean}

Update configuration files with accumulated cursor changes.

The commit() function merges changes made to in-memory copies of loaded configuration files as well as existing delta records in the cursors configured delta directory and writes them back into the underlying configuration files, persistently committing changes to the file system.

When the optional "config" parameter is omitted, all currently loaded configuration files with either present delta records or yet unsaved cursor changes are updated.

Returns the true if operation completed successfully.

Returns null on error, e.g. if the requested configuration was not loaded or when a file system error occurred.

Parameters:
NameTypeAttributesDescription
configstring<optional>

The name of the configuration file to commit, e.g. "system" to update the /etc/config/system file.

Returns:
Type: 
boolean
Example
const ctx = cursor(…);
+
+ctx.set('system', '@system[0]', 'hostname', 'example.org');
+ctx.commit('system');

configs() → (nullable) {Array.<string>}

Enumerate existing configurations.

The configs() function yields an array of configuration files present in the cursors associated configuration directory, /etc/config/ by default.

Returns an array of configuration names on success.

Returns null on error, e.g. due to filesystem errors.

Returns:
Type: 
Array.<string>
Example
const ctx = cursor(…);
+
+// Enumerate all present configuration file names
+const configurations = ctx.configs();

delete(config, section, optionopt) → (nullable) {boolean}

Delete an option or section from given configuration.

When invoked with three arguments, the function deletes the given option within the specified section of the given configuration.

When invoked with two arguments, the function deletes the entire specified section within the given configuration.

In either case, the given configuration is implicitly loaded into the cursor if not already present.

Returns the true if specified option or section has been deleted.

Returns null on error, e.g. if the targeted configuration was not found or if an invalid value was passed.

Parameters:
NameTypeAttributesDescription
configstring

The name of the configuration file to delete values in, e.g. "system" to modify /etc/config/system.

sectionstring

The section name to remove the specified option in or, when the subsequent argument is omitted, the section to remove entirely.

optionstring<optional>

The option name to remove within the section.

Returns:
Type: 
boolean
Example
const ctx = cursor(…);
+
+// Delete 'disabled' option in first wifi-iface section
+ctx.delete('wireless', '@wifi-iface[0]', 'disabled');
+
+// Delete 'wan' interface
+ctx.delete('network', 'lan');
+
+// Delete last firewall rule
+ctx.delete('firewall', '@rule[-1]');

error() → (nullable) {string}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string
Example
// Trigger error
+const ctx = cursor();
+ctx.set("not_existing_config", "test", "1");
+
+// Print error (should yield "Entry not found")
+print(ctx.error(), "\n");

foreach(config, typenullable, callback) → (nullable) {boolean}

Iterate configuration sections.

The foreach() function iterates all sections of the given configuration, optionally filtered by type, and invokes the given callback function for each encountered section.

When the optional "type" parameter is specified, the callback is only invoked for sections of the given type, otherwise it is invoked for all sections.

The requested configuration is implicitly loaded into the cursor.

Returns true if the callback was executed successfully at least once.

Returns false if the callback was never invoked, e.g. when the configuration is empty or contains no sections of the given type.

Returns null on error, e.g. when an invalid callback was passed or the requested configuration not found.

Parameters:
NameTypeAttributesDescription
configstring

The configuration to iterate sections for, e.g. "system" to read the /etc/config/system file.

typestring<nullable>

Invoke the callback only for sections of the specified type.

callbackmodule:uci.cursor.SectionCallback

The callback to invoke for each section, will receive a section dictionary as sole argument.

Returns:
Type: 
boolean
Example
const ctx = cursor(…);
+
+// Iterate all network interfaces
+ctx.foreach('network', 'interface',
+	   section => print(`Have interface ${section[".name"]}\n`));

get(config, section, optionopt) → (nullable) {string|Array.<string>}

Query a single option value or section type.

When invoked with three arguments, the function returns the value of the given option, within the specified section of the given configuration.

When invoked with just a config and section argument, the function returns the type of the specified section.

In either case, the given configuration is implicitly loaded into the cursor if not already present.

Returns the configuration value or section type on success.

Returns null on error, e.g. if the requested configuration does not exist or if an invalid argument was passed.

Parameters:
NameTypeAttributesDescription
configstring

The name of the configuration file to query, e.g. "system" to query values in /etc/config/system.

sectionstring

The name of the section to query within the configuration.

optionstring<optional>

The name of the option to query within the section. If omitted, the type of the section is returned instead.

Returns:
Type: 
string | Array.<string>
Example
const ctx = cursor(…);
+
+// Query an option, extended section notation is supported
+ctx.get('system', '@system[0]', 'hostname');
+
+// Query a section type (should yield 'interface')
+ctx.get('network', 'lan');

get_all(config, sectionopt) → (nullable) {Object.<string, module:uci.cursor.SectionObject>|module:uci.cursor.SectionObject}

Query a complete section or configuration.

When invoked with two arguments, the function returns all values of the specified section within the given configuration as dictionary.

When invoked with just a config argument, the function returns a nested dictionary of all sections present within the given configuration.

In either case, the given configuration is implicitly loaded into the cursor if not already present.

Returns the section or configuration dictionary on success.

Returns null on error, e.g. if the requested configuration does not exist or if an invalid argument was passed.

Parameters:
NameTypeAttributesDescription
configstring

The name of the configuration file to query, e.g. "system" to query values in /etc/config/system.

sectionstring<optional>

The name of the section to query within the configuration. If omitted a nested dictionary containing all section values is returned.

Example
const ctx = cursor(…);
+
+// Query all lan interface details
+ctx.get_all('network', 'lan');
+
+// Dump the entire dhcp configuration
+ctx.get_all('dhcp');

get_first(config, type, optionopt) → (nullable) {string|Array.<string>}

Query option value or name of first section of given type.

When invoked with three arguments, the function returns the value of the given option within the first found section of the specified type in the given configuration.

When invoked with just a config and section type argument, the function returns the name of the first found section of the given type.

In either case, the given configuration is implicitly loaded into the cursor if not already present.

Returns the configuration value or section name on success.

Returns null on error, e.g. if the requested configuration does not exist or if an invalid argument was passed.

Parameters:
NameTypeAttributesDescription
configstring

The name of the configuration file to query, e.g. "system" to query values in /etc/config/system.

typestring

The section type to find the first section for within the configuration.

optionstring<optional>

The name of the option to query within the section. If omitted, the name of the section is returned instead.

Returns:
Type: 
string | Array.<string>
Example
const ctx = cursor(…);
+
+// Query hostname in first anonymous "system" section of /etc/config/system
+ctx.get_first('system', 'system', 'hostname');
+
+// Figure out name of first network interface section (usually "loopback")
+ctx.get_first('network', 'interface');

load(config) → (nullable) {boolean}

Explicitly reload configuration file.

Usually, any attempt to query or modify a value within a given configuration will implicitly load the underlying file into memory. By invoking load() explicitly, a potentially loaded stale configuration is discarded and reloaded from the file system, ensuring that the latest state is reflected in the cursor.

Returns true if the configuration was successfully loaded.

Returns null on error, e.g. if the requested configuration does not exist.

Parameters:
NameTypeDescription
configstring

The name of the configuration file to load, e.g. "system" to load /etc/config/system into the cursor.

Returns:
Type: 
boolean

rename(config, section, option_or_name, nameopt) → (nullable) {boolean}

Rename an option or section in given configuration.

When invoked with four arguments, the function renames the given option within the specified section of the given configuration to the provided value.

When invoked with three arguments, the function renames the entire specified section to the provided value.

In either case, the given configuration is implicitly loaded into the cursor if not already present.

Returns the true if specified option or section has been renamed.

Returns null on error, e.g. if the targeted configuration was not found or if an invalid value was passed.

Parameters:
NameTypeAttributesDescription
configstring

The name of the configuration file to rename values in, e.g. "system" to modify /etc/config/system.

sectionstring

The section name to rename or to rename an option in.

option_or_namestring

The option name to rename within the section or, when the subsequent name argument is omitted, the new name of the renamed section within the configuration.

namestring<optional>

The new name of the option to rename.

Returns:
Type: 
boolean
Example
const ctx = cursor(…);
+
+// Assign explicit name to last anonymous firewall rule section
+ctx.rename('firewall', '@rule[-1]', 'my_block_rule');
+
+// Rename 'server' to 'orig_server_list' in ntp section of system config
+ctx.rename('system', 'ntp', 'server', 'orig_server_list');
+
+// Rename 'wan' interface to 'external'
+ctx.rename('network', 'wan', 'external');

reorder(config, section, index, nameopt) → (nullable) {boolean}

Reorder sections in given configuration.

The reorder() function moves a single section by repositioning it to the given index within the configurations section list.

The given configuration is implicitly loaded into the cursor if not already present.

Returns the true if specified section has been moved.

Returns null on error, e.g. if the targeted configuration was not found or if an invalid value was passed.

Parameters:
NameTypeAttributesDescription
configstring

The name of the configuration file to move the section in, e.g. "system" to modify /etc/config/system.

sectionstring

The section name to move.

indexnumber

The target index to move the section to, starting from 0.

namestring<optional>

The new name of the option to rename.

Returns:
Type: 
boolean
Example
const ctx = cursor(…);
+
+// Query whole firewall config and reorder resulting dict by type and name
+const type_order = ['defaults', 'zone', 'forwarding', 'redirect', 'rule'];
+const values = ctx.get_all('firewall');
+
+sort(values, (k1, k2, s1, s2) => {
+    // Get weight from type_order array
+    let w1 = index(type_order, s1['.type']);
+    let w2 = index(type_order, s2['.type']);
+
+    // For unknown type orders, use type value itself as weight
+    if (w1 == -1) w1 = s1['.type'];
+    if (w2 == -1) w2 = s2['.type'];
+
+    // Get name from name option, fallback to section name
+    let n1 = s1.name ?? k1;
+    let n2 = s2.name ?? k2;
+
+    // Order by weight
+    if (w1 < w2) return -1;
+    if (w1 > w2) return 1;
+
+    // For same weight order by name
+    if (n1 < n2) return -1;
+    if (n1 > n2) return 1;
+
+    return 0;
+});
+
+// Sequentially reorder sorted sections in firewall configuration
+let position = 0;
+
+for (let sid in values)
+  ctx.reorder('firewall', sid, position++);

revert(configopt) → (nullable) {boolean}

Revert accumulated cursor changes and associated delta records.

The revert() function discards any changes made to in-memory copies of loaded configuration files and discards any related existing delta records in the cursors configured delta directory.

When the optional "config" parameter is omitted, all currently loaded configuration files with either present delta records or yet unsaved cursor changes are reverted.

Returns the true if operation completed successfully.

Returns null on error, e.g. if the requested configuration was not loaded or when a file system error occurred.

Parameters:
NameTypeAttributesDescription
configstring<optional>

The name of the configuration file to revert, e.g. "system" to discard any changes for the /etc/config/system file.

Returns:
Type: 
boolean
Example
const ctx = cursor(…);
+
+ctx.set('system', '@system[0]', 'hostname', 'example.org');
+ctx.revert('system');

save(configopt) → (nullable) {boolean}

Save accumulated cursor changes to delta directory.

The save() function writes consolidated changes made to in-memory copies of loaded configuration files to the uci delta directory which effectively makes them available to other processes using the same delta directory path as well as the uci changes cli command when using the default delta directory.

Note that uci deltas are overlayed over the actual configuration file values so they're reflected by get(), foreach() etc. even if the underlying configuration files are not actually changed (yet). The delta records may be either permanently merged into the configuration by invoking commit() or reverted through revert() in order to restore the current state of the underlying configuration file.

When the optional "config" parameter is omitted, delta records for all currently loaded configuration files are written.

In case that neither sharing changes with other processes nor any revert functionality is required, changes may be committed directly using commit() instead, bypassing any delta record creation.

Returns the true if operation completed successfully.

Returns null on error, e.g. if the requested configuration was not loaded or when a file system error occurred.

Parameters:
NameTypeAttributesDescription
configstring<optional>

The name of the configuration file to save delta records for, e.g. "system" to store changes for /etc/config/system.

Returns:
Type: 
boolean
Example
const ctx = cursor(…);
+
+ctx.set('wireless', '@wifi-iface[0]', 'disabled', '1');
+ctx.save('wireless');

set(config, section, option_or_type, valueopt) → (nullable) {boolean}

Set option value or add named section in given configuration.

When invoked with four arguments, the function sets the value of the given option within the specified section of the given configuration to the provided value. A value of "" (empty string) can be used to delete an existing option.

When invoked with three arguments, the function adds a new named section to the given configuration, using the specified type.

In either case, the given configuration is implicitly loaded into the cursor if not already present.

Returns the true if the named section was added or the specified option was set.

Returns null on error, e.g. if the targeted configuration was not found or if an invalid value was passed.

Parameters:
NameTypeAttributesDescription
configstring

The name of the configuration file to set values in, e.g. "system" to modify /etc/config/system.

sectionstring

The section name to create or set a value in.

option_or_typestring

The option name to set within the section or, when the subsequent value argument is omitted, the type of the section to create within the configuration.

valueArray.<(string|boolean|number)> | string | boolean | number<optional>

The option value to set.

Returns:
Type: 
boolean
Example
const ctx = cursor(…);
+
+// Add named `config interface guest` section
+ctx.set('network', 'guest', 'interface');
+
+// Set values on the newly added section
+ctx.set('network', 'guest', 'proto', 'static');
+ctx.set('network', 'guest', 'ipaddr', '10.0.0.1/24');
+ctx.set('network', 'guest', 'dns', ['8.8.4.4', '8.8.8.8']);
+…
+
+// Delete 'disabled' option in first wifi-iface section
+ctx.set('wireless', '@wifi-iface[0]', 'disabled', '');

unload(config) → (nullable) {boolean}

Explicitly unload configuration file.

The unload() function forcibly discards a loaded configuration state from the cursor so that the next attempt to read or modify that configuration will load it anew from the file system.

Returns true if the configuration was successfully unloaded.

Returns false if the configuration was not loaded to begin with.

Returns null on error, e.g. if the requested configuration does not exist.

Parameters:
NameTypeDescription
configstring

The name of the configuration file to unload.

Returns:
Type: 
boolean

Type Definitions

ChangeRecord

A uci change record is a plain array containing the change operation name as first element, the affected section ID as second argument and an optional third and fourth argument whose meanings depend on the operation.

Type:
  • Array.<string>
Properties
NameTypeDescription
0string

The operation name - may be one of add, set, remove, order, list-add, list-del or rename.

1string

The section ID targeted by the operation.

2string

The meaning of the third element depends on the operation.

  • For add it is type of the section that has been added
  • For set it either is the option name if a fourth element exists, or the type of a named section which has been added when the change entry only contains three elements.
  • For remove it contains the name of the option that has been removed.
  • For order it specifies the new sort index of the section.
  • For list-add it contains the name of the list option a new value has been added to.
  • For list-del it contains the name of the list option a value has been removed from.
  • For rename it contains the name of the option that has been renamed if a fourth element exists, else it contains the new name a section has been renamed to if the change entry only contains three elements.
4string

The meaning of the fourth element depends on the operation.

  • For set it is the value an option has been set to.
  • For list-add it is the new value that has been added to a list option.
  • For rename it is the new name of an option that has been renamed.

SectionCallback(section)

The sections callback is invoked for each section found within the given configuration and receives the section object and its associated name as arguments.

Parameters:
NameTypeDescription
sectionmodule:uci.cursor.SectionObject

The section object.

SectionObject

A section object represents the options and their corresponding values enclosed within a configuration section, as well as some additional meta data such as sort indexes and internal ID.

Any internal metadata fields are prefixed with a dot which isn't an allowed character for normal option names.

Type:
  • Object.<string, (boolean|number|string|Array.<string>)>
Properties
NameTypeDescription
.anonymousboolean

The .anonymous property specifies whether the configuration is anonymous (true) or named (false).

.indexnumber

The .index property specifies the sort order of the section.

.namestring

The .name property holds the name of the section object. It may be either an anonymous ID in the form cfgXXXXXX with X being a hexadecimal digit or a string holding the name of the section.

.typestring

The .type property contains the type of the corresponding uci section.

*string | Array.<string>

A section object may contain an arbitrary number of further properties representing the uci option enclosed in the section.

All option property names will be in the form [A-Za-z0-9_]+ and either contain a string value or an array of strings, in case the underlying option is an UCI list.

\ No newline at end of file diff --git a/module-uci.html b/module-uci.html new file mode 100644 index 00000000..43a19649 --- /dev/null +++ b/module-uci.html @@ -0,0 +1,16 @@ +Module: uci
On this page

OpenWrt UCI configuration

The uci module provides access to the native OpenWrt libuci API for reading and manipulating UCI configuration files.

Functions can be individually imported and directly accessed using the named import syntax:

import { cursor } from 'uci';
+
+let ctx = cursor();
+let hostname = ctx.get_first('system', 'system', 'hostname');
+

Alternatively, the module namespace can be imported using a wildcard import statement:

import * as uci from 'uci';
+
+let ctx = uci.cursor();
+let hostname = ctx.get_first('system', 'system', 'hostname');
+

Additionally, the uci module namespace may also be imported by invoking the ucode interpreter with the -luci switch.

Classes

cursor

Methods

cursor(config_diropt, delta_diropt) → (nullable) {module:uci.cursor}

Instantiate uci cursor.

A uci cursor is a context for interacting with uci configuration files. It's purpose is to cache and hold changes made to loaded configuration states until those changes are written out to disk or discared.

Unsaved and uncommitted changes in a cursor instance are private and not visible to other cursor instances instantiated by the same program or other processes on the system.

Returns the instantiated cursor on success.

Returns null on error, e.g. if an invalid path argument was provided.

Parameters:
NameTypeAttributesDefaultDescription
config_dirstring<optional>
/etc/config

The directory to search for configuration files. It defaults to the well known uci configuration directory /etc/config but may be set to a different path for special purpose applications.

delta_dirstring<optional>
/tmp/.uci

The directory to save delta records in. It defaults to the well known /tmp/.uci path which is used as default by the uci command line tool.

By changing this path to a different location, it is possible to isolate uncommitted application changes from the uci cli or other processes on the system.

Returns:
Type: 
module:uci.cursor

error() → (nullable) {string}

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns:
Type: 
string
Example
// Trigger error
+const ctx = cursor();
+ctx.set("not_existing_config", "test", "1");
+
+// Print error (should yield "Entry not found")
+print(ctx.error(), "\n");
\ No newline at end of file diff --git a/tutorial-01-usage.html b/tutorial-01-usage.html index 31ecf2d0..6605ab9e 100644 --- a/tutorial-01-usage.html +++ b/tutorial-01-usage.html @@ -1,8 +1,8 @@ Tutorial: Usage
On this page

Usage

The ucode command line utility provides a set of options and arguments for executing and compiling ucode programs. Here is a detailed explanation of each option and its usage:

  • -h: Display the help message, which provides an overview of the available options and their usage.

  • -e "expression": Execute the given expression as a ucode program. This option allows you to provide a single-line ucode expression for immediate execution.

  • -p "expression": Execute the given expression as a ucode program and print the result after execution.

  • -c [-s] [-o output.uc] input.uc [input2.uc ...]: Compile the specified source file(s) to bytecode instead of executing them. By default, the compiled bytecode is written to ./uc.out. The -s option omits debug information, reducing the size of the compiled bytecode. The -o option allows specifying the output file path for the compiled bytecode.

  • -t: Enable VM (Virtual Machine) execution tracing. This option enables tracing of the ucode program's execution, providing detailed information for debugging purposes.

  • -g interval: Perform periodic garbage collection at regular intervals defined by the interval parameter. Garbage collection is a memory management process that frees up memory occupied by objects that are no longer in use.

  • -S: Enable strict mode, which enforces strict adherence to ucode language rules and prevents the use of certain potentially error-prone or unsafe language features.

  • -R: Process source file(s) as raw script code. This is the default mode of operation, where the ucode interpreter treats the source files as direct ucode script code.

  • -T[flag,flag,...]: Process the source file(s) as templates instead of raw script code. This option enables the usage of Jinja-like templates with embedded ECMAScript 6 code. The flags provide additional control over template processing, such as preserving leading whitespace or trailing newlines.

  • -D [name=]value: Define a global variable in the ucode program. If the name parameter is omitted, a JSON dictionary is expected as the value, where each property becomes a global variable with its corresponding value. If name is specified, it defines a global variable with the provided value, parsed as JSON or as a literal string if JSON parsing fails.

  • -F [name=]path: Similar to the -D option, but reads the value from a file specified by the path parameter. The file must contain a single, well-formed JSON dictionary.

  • -U name: Undefine the given global variable name. This option removes the specified global variable from the ucode program's scope.

  • -l [name=]library: Preload the specified library for use in the ucode program. Optionally, the library can be aliased to a different name within the program.

  • -L pattern: Prepend the provided pattern to the default library search paths. This option allows specifying custom paths for loading libraries. If the pattern does not contain an asterisk (*), it is added twice, once with /*.so and once with /*.uc appended to it.

Examples

Here are some examples showcasing the invocation of the ucode program with different options:

  1. Execute a ucode expression:

    ucode -e "print('Hello, World!\n');"
    +    
    On this page

    Usage

    The ucode command line utility provides a set of options and arguments for executing and compiling ucode programs. Here is a detailed explanation of each option and its usage:

    • -h: Display the help message, which provides an overview of the available options and their usage.

    • -e "expression": Execute the given expression as a ucode program. This option allows you to provide a single-line ucode expression for immediate execution.

    • -p "expression": Execute the given expression as a ucode program and print the result after execution.

    • -c [-s] [-o output.uc] input.uc [input2.uc ...]: Compile the specified source file(s) to bytecode instead of executing them. By default, the compiled bytecode is written to ./uc.out. The -s option omits debug information, reducing the size of the compiled bytecode. The -o option allows specifying the output file path for the compiled bytecode.

    • -t: Enable VM (Virtual Machine) execution tracing. This option enables tracing of the ucode program's execution, providing detailed information for debugging purposes.

    • -g interval: Perform periodic garbage collection at regular intervals defined by the interval parameter. Garbage collection is a memory management process that frees up memory occupied by objects that are no longer in use.

    • -S: Enable strict mode, which enforces strict adherence to ucode language rules and prevents the use of certain potentially error-prone or unsafe language features.

    • -R: Process source file(s) as raw script code. This is the default mode of operation, where the ucode interpreter treats the source files as direct ucode script code.

    • -T[flag,flag,...]: Process the source file(s) as templates instead of raw script code. This option enables the usage of Jinja-like templates with embedded ECMAScript 6 code. The flags provide additional control over template processing, such as preserving leading whitespace or trailing newlines.

    • -D [name=]value: Define a global variable in the ucode program. If the name parameter is omitted, a JSON dictionary is expected as the value, where each property becomes a global variable with its corresponding value. If name is specified, it defines a global variable with the provided value, parsed as JSON or as a literal string if JSON parsing fails.

    • -F [name=]path: Similar to the -D option, but reads the value from a file specified by the path parameter. The file must contain a single, well-formed JSON dictionary.

    • -U name: Undefine the given global variable name. This option removes the specified global variable from the ucode program's scope.

    • -l [name=]library: Preload the specified library for use in the ucode program. Optionally, the library can be aliased to a different name within the program.

    • -L pattern: Prepend the provided pattern to the default library search paths. This option allows specifying custom paths for loading libraries. If the pattern does not contain an asterisk (*), it is added twice, once with /*.so and once with /*.uc appended to it.

    Examples

    Here are some examples showcasing the invocation of the ucode program with different options:

    1. Execute a ucode expression:

      ucode -e "print('Hello, World!\n');"
       
    2. Execute a ucode expression and print the result:

      ucode -p "2 ** 3"
       
    3. Execute a ucode program from a source file:

      ucode program.uc
       
    4. Compile a ucode program to bytecode:

      ucode -c program.uc
       
    5. Compile a ucode program to bytecode with a specified output file:

      ucode -c -o compiled.uc program.uc
      -
    \ No newline at end of file +
\ No newline at end of file diff --git a/tutorial-02-syntax.html b/tutorial-02-syntax.html index 9a4d783c..1d630d7b 100644 --- a/tutorial-02-syntax.html +++ b/tutorial-02-syntax.html @@ -1,6 +1,6 @@ Tutorial: Syntax
On this page

Syntax

The ucode programming language features a syntax that closely resembles ECMAScript 6. However, the ucode interpreter supports two distinct syntax modes: template mode and raw mode.

In template mode, ucode consumes Jinja-like templates that allow for the embedding of script code within the template structure. This mode enables the combination of expressive template constructs with JavaScript like functionality.

On the other hand, raw mode in ucode directly consumes ECMAScript 6-like syntax without any template-specific markup. This mode is mainly useful to develop standalone applications or libraries.

Template mode

By default, ucode is executed in raw mode, means it expects a given source file to only contain script code. By invoking the ucode interpreter with the -T flag or by using the utpl alias, the ucode interpreter is switched into template mode where the source file is expected to be a plaintext file containing template blocks containing ucode script expressions or comments.

Block types

There are three kinds of blocks; expression blocks, statement blocks and comment blocks. The former two embed code logic using ucode's JavaScript-like syntax while the latter comment block type is simply discarded during processing.

1. Statement block

Statement blocks are enclosed in an opening {% and a closing %} tag and may contain any number of script code statements, even entire programs.

It is allowed to omit the closing %} of a statement block to parse the entire remaining source text after the opening tag as ucode script.

By default, statement blocks produce no output and the entire block is reduced to an empty string during template evaluation but contained script code might invoke functions such as print() to explicitly output contents.

For example the following template would result in The epoch is odd or The epoch is even, depending on the current epoch value:

The epoch is {% if (time() % 2): %}odd{% else %}even{% endif %}!

2. Expression block

Expression blocks are enclosed in an opening {{ and a closing }} tag and may only contain a single expression statement (multiple expressions may be chained with comma). The implicit result of the rightmost evaluated expression is used as output when processing the block.

For example the template Hello world, {{ getenv("USER") }}! would result in the output "Hello world, user!" where user would correspond to the name of the current user executing the ucode interpreter.

3. Comment block

Comment blocks, which are denoted with an opening {# and a closing #} tag may contain arbitrary text except the closing #} tag itself. Comments blocks are completely stripped during processing and are replaced with an empty string.

The following example template would result in the output "Hello world":

Hello {# mad #}word

Whitespace handling

Each block start tag may be suffixed with a dash to strip any whitespace before the block and likewise any block end tag may be prefixed with a dash to strip any whitespace following the block.

Without using whitespace stripping, the following example:

This is a first line
+    
On this page

Syntax

The ucode programming language features a syntax that closely resembles ECMAScript 6. However, the ucode interpreter supports two distinct syntax modes: template mode and raw mode.

In template mode, ucode consumes Jinja-like templates that allow for the embedding of script code within the template structure. This mode enables the combination of expressive template constructs with JavaScript like functionality.

On the other hand, raw mode in ucode directly consumes ECMAScript 6-like syntax without any template-specific markup. This mode is mainly useful to develop standalone applications or libraries.

Template mode

By default, ucode is executed in raw mode, means it expects a given source file to only contain script code. By invoking the ucode interpreter with the -T flag or by using the utpl alias, the ucode interpreter is switched into template mode where the source file is expected to be a plaintext file containing template blocks containing ucode script expressions or comments.

Block types

There are three kinds of blocks; expression blocks, statement blocks and comment blocks. The former two embed code logic using ucode's JavaScript-like syntax while the latter comment block type is simply discarded during processing.

1. Statement block

Statement blocks are enclosed in an opening {% and a closing %} tag and may contain any number of script code statements, even entire programs.

It is allowed to omit the closing %} of a statement block to parse the entire remaining source text after the opening tag as ucode script.

By default, statement blocks produce no output and the entire block is reduced to an empty string during template evaluation but contained script code might invoke functions such as print() to explicitly output contents.

For example the following template would result in The epoch is odd or The epoch is even, depending on the current epoch value:

The epoch is {% if (time() % 2): %}odd{% else %}even{% endif %}!

2. Expression block

Expression blocks are enclosed in an opening {{ and a closing }} tag and may only contain a single expression statement (multiple expressions may be chained with comma). The implicit result of the rightmost evaluated expression is used as output when processing the block.

For example the template Hello world, {{ getenv("USER") }}! would result in the output "Hello world, user!" where user would correspond to the name of the current user executing the ucode interpreter.

3. Comment block

Comment blocks, which are denoted with an opening {# and a closing #} tag may contain arbitrary text except the closing #} tag itself. Comments blocks are completely stripped during processing and are replaced with an empty string.

The following example template would result in the output "Hello world":

Hello {# mad #}word

Whitespace handling

Each block start tag may be suffixed with a dash to strip any whitespace before the block and likewise any block end tag may be prefixed with a dash to strip any whitespace following the block.

Without using whitespace stripping, the following example:

This is a first line
 {% for (x in [1, 2, 3]): %}
 This is item {{ x }}.
 {% endfor %}
@@ -224,4 +224,4 @@
 
   print(a);              // { }
 %}
-

5.7. Precedence

Operator precedence determines the order in which operators are evaluated in an expression. In ucode, operators have different precedence levels, as outline in the table below.

PrecedenceOperator typeAssociativity
19Grouping ( … )n/a
18Property access … . …left-to-right
18Optional chaining … ?. …left-to-right
18Computed propery access … [ … ]n/a
18Function call … (…)n/a
17Postfix increment … ++n/a
17Postfix decrement … --n/a
16Logical not ! …n/a
16Bitwise not ~ …n/a
16Unary plus + …n/a
16Unary negation - …n/a
16Prefix increment ++ …n/a
16Prefix decrement -- …n/a
16Property deletion delete …n/a
15Exponentiation … ** …right-to-left
14Multiplication … * …left-to-right
14Division … / …left-to-right
14Remainder … % …left-to-right
13Addition … + …left-to-right
13Substraction … - …left-to-right
12Bitwise left shift … << …left-to-right
12Bitwise right shift … >> …left-to-right
11Less than … < …left-to-right
11Less than or equal … <= …left-to-right
11Greater than … > …left-to-right
11Greater than or equal … >= …left-to-right
11In … in …left-to-right
10Equality … == …left-to-right
10Inequality … != …left-to-right
10Strict equality … === …left-to-right
10Strict inequality … !== …left-to-right
9Bitwise AND … & …left-to-right
8Bitwise XOR … ^ …left-to-right
7Bitwise OR … | …left-to-right
6Logical AND … && …left-to-right
5Logical OR … || …left-to-right
5Nullish coalescing … ?? …left-to-right
4Assignment … = …right-to-left
4Assignment … += …right-to-left
4Assignment … -= …right-to-left
4Assignment … **= …right-to-left
4Assignment … *= …right-to-left
4Assignment … /= …right-to-left
4Assignment … %= …right-to-left
4Assignment … <<= …right-to-left
4Assignment … >>= …right-to-left
4Assignment … &= …right-to-left
4Assignment … ^= …right-to-left
4Assignment … |= …right-to-left
4Assignment … &&= …right-to-left
4Assignment … ||= …right-to-left
4Assignment … ??= …right-to-left
3Ternary … ? … : …right-to-left
2Arrow … => …right-to-left
2Spread ... …n/a
1Sequence … , …left-to-right

Operators with a higher precedence value are evaluated before operators with a lower precedence value. When operators have the same precedence, their associativity determines the order of evaluation (e.g., left-to-right or right-to-left).

\ No newline at end of file +

5.7. Precedence

Operator precedence determines the order in which operators are evaluated in an expression. In ucode, operators have different precedence levels, as outline in the table below.

PrecedenceOperator typeAssociativity
19Grouping ( … )n/a
18Property access … . …left-to-right
18Optional chaining … ?. …left-to-right
18Computed propery access … [ … ]n/a
18Function call … (…)n/a
17Postfix increment … ++n/a
17Postfix decrement … --n/a
16Logical not ! …n/a
16Bitwise not ~ …n/a
16Unary plus + …n/a
16Unary negation - …n/a
16Prefix increment ++ …n/a
16Prefix decrement -- …n/a
16Property deletion delete …n/a
15Exponentiation … ** …right-to-left
14Multiplication … * …left-to-right
14Division … / …left-to-right
14Remainder … % …left-to-right
13Addition … + …left-to-right
13Substraction … - …left-to-right
12Bitwise left shift … << …left-to-right
12Bitwise right shift … >> …left-to-right
11Less than … < …left-to-right
11Less than or equal … <= …left-to-right
11Greater than … > …left-to-right
11Greater than or equal … >= …left-to-right
11In … in …left-to-right
10Equality … == …left-to-right
10Inequality … != …left-to-right
10Strict equality … === …left-to-right
10Strict inequality … !== …left-to-right
9Bitwise AND … & …left-to-right
8Bitwise XOR … ^ …left-to-right
7Bitwise OR … | …left-to-right
6Logical AND … && …left-to-right
5Logical OR … || …left-to-right
5Nullish coalescing … ?? …left-to-right
4Assignment … = …right-to-left
4Assignment … += …right-to-left
4Assignment … -= …right-to-left
4Assignment … **= …right-to-left
4Assignment … *= …right-to-left
4Assignment … /= …right-to-left
4Assignment … %= …right-to-left
4Assignment … <<= …right-to-left
4Assignment … >>= …right-to-left
4Assignment … &= …right-to-left
4Assignment … ^= …right-to-left
4Assignment … |= …right-to-left
4Assignment … &&= …right-to-left
4Assignment … ||= …right-to-left
4Assignment … ??= …right-to-left
3Ternary … ? … : …right-to-left
2Arrow … => …right-to-left
2Spread ... …n/a
1Sequence … , …left-to-right

Operators with a higher precedence value are evaluated before operators with a lower precedence value. When operators have the same precedence, their associativity determines the order of evaluation (e.g., left-to-right or right-to-left).

\ No newline at end of file diff --git a/tutorial-03-memory.html b/tutorial-03-memory.html index 6fb93278..4688533c 100644 --- a/tutorial-03-memory.html +++ b/tutorial-03-memory.html @@ -1,6 +1,6 @@ Tutorial: Memory Management
On this page

Memory Management

The ucode scripting language utilizes a reference count-based garbage collector as its primary method of memory management. When assigning an array or object value, the reference count is incremented. When a local variable holding a reference goes out of scope, the reference count is decremented. If the reference count reaches zero, a recursive traversal is performed to decrease the reference count of any nested references. Once the traversal is complete, the top-level array or object structure is freed.

Example 1:

x = [ { a: 1 }, { b: 2 }, { c: 3 } ];
+    
On this page

Memory Management

The ucode scripting language utilizes a reference count-based garbage collector as its primary method of memory management. When assigning an array or object value, the reference count is incremented. When a local variable holding a reference goes out of scope, the reference count is decremented. If the reference count reaches zero, a recursive traversal is performed to decrease the reference count of any nested references. Once the traversal is complete, the top-level array or object structure is freed.

Example 1:

x = [ { a: 1 }, { b: 2 }, { c: 3 } ];
 // `x` holds a reference to `[...]` (refcount 1)
 // `x[0]` holds a reference to `{ a: 1 }` (refcount 1)
 // `x[1]` holds a reference to `{ b: 2 }` (refcount 1)
@@ -31,4 +31,4 @@
 // `a` holds a reference to itself (refcount 1)
 

Example 3:

x = { y: { z: [ ] } }; x.y.z = x;
 // `x` holds a reference to itself through `x.y.z` (refcount 1)
-

In these examples, cyclic references are created where objects or arrays point back to themselves or create a circular chain. Since each element within the cycle maintains a reference, the reference count for each object or array never reaches zero, resulting in a memory leak. The reference count-based garbage collector cannot automatically reclaim memory in such cases.

To address cyclic structures and avoid memory leaks, ucode provides a secondary mark-and-sweep garbage collector. This collector can be enabled by passing the -g flag to the ucode interpreter or manually triggered using the gc() function during runtime. The mark-and-sweep collector identifies and frees unreachable objects, including those involved in cyclic references.

\ No newline at end of file +

In these examples, cyclic references are created where objects or arrays point back to themselves or create a circular chain. Since each element within the cycle maintains a reference, the reference count for each object or array never reaches zero, resulting in a memory leak. The reference count-based garbage collector cannot automatically reclaim memory in such cases.

To address cyclic structures and avoid memory leaks, ucode provides a secondary mark-and-sweep garbage collector. This collector can be enabled by passing the -g flag to the ucode interpreter or manually triggered using the gc() function during runtime. The mark-and-sweep collector identifies and frees unreachable objects, including those involved in cyclic references.

\ No newline at end of file diff --git a/ucode.css b/ucode.css index a40f4787..966228a6 100644 --- a/ucode.css +++ b/ucode.css @@ -6,6 +6,24 @@ h1 { display: flex; } +h3[id].name:not(h2 + h3) { + margin-top: 2.5rem; + border-top: 1px solid #292929; + padding-top: 1.5rem; +} + +h3[id].name:not(h2 + h3) .link-anchor { + top: 1.5rem; +} + +.light h3[id].name { + border-color: #ccc; +} + +html body { + line-height: 1.5; +} + article .description > ul, article .description > ol { list-style: initial; @@ -18,3 +36,66 @@ article .description > ol { background-position: 1rem center; padding-left: 3rem; } + +section table td:first-child, +section .params td:first-child, +section table thead th:first-child, +section .params thead th:first-child, +section .props thead th:first-child { + border-top-left-radius: .5rem; + border-bottom-left-radius: .5rem; +} + +section table td:last-child, +section .params td:last-child, +section table thead th:last-child, +section .params thead th:last-child, +section .props thead th:last-child { + border-top-right-radius: .5rem; + border-bottom-right-radius: .5rem; +} + +section .params td, +section .params th, +section .props td, +section .props th, +section th, +section td, +section .details .details-item-container { + padding: .5rem 1rem; +} + +section ul, +section ol { + padding-left: 1.5rem; +} + +section ul li, +section ol li { + padding: .25rem 0; +} + +section p { + margin: .75rem 0; +} + +section .details { + border-radius: .5rem; +} + +section .pre-div { + margin: 1rem 0; + border-radius: .5rem; +} + +.param-type { + font-family: "code"; +} + +.signature-attributes { + font-variant: sub; +} + +.method-member-container > strong + dl.param-type > dt { + display: none; +} diff --git a/ucode.js b/ucode.js index 6728cdbd..2377c7ed 100644 --- a/ucode.js +++ b/ucode.js @@ -4,4 +4,36 @@ document.addEventListener('DOMContentLoaded', (ev) => { if (accordionState == null || accordionState == '{}') document.querySelectorAll('[data-isopen="false"]') .forEach(item => item.setAttribute('data-isopen', 'true')); + + const moduleName = location.pathname.match(/\/module-(.+)\.html$/)?.[1]; + + if (moduleName) { + const modulePrefix = `module:${moduleName}.`; + + document.querySelectorAll(`a[href^="module-${CSS.escape(moduleName)}."]`).forEach(a => { + if (a.text?.indexOf(modulePrefix) == 0) + a.text = a.text.substring(modulePrefix.length); + }); + } + + document.querySelectorAll('.param-type, .type-signature').forEach(span => { + let replaced; + do { + replaced = false; + span.innerHTML = span.innerHTML.replace(/\b(Object|Array)\.<((?:(?!&[lg]t;).)+)>/, + (m, t, st) => { + replaced = true; + + if (t == 'Object') + return `Object<${st.replace(/,\s*/, ': ')}>`; + else + return `${st}[]`; + }); + } while (replaced); + }); + + document.querySelectorAll('.type-signature').forEach(span => { + span.innerHTML = span.innerHTML.replace(/\(nullable\) (.+)$/, + '$1nullable'); + }); });