New documentation website

This commit is contained in:
Saúl Ibarra Corretgé 2024-09-25 22:21:45 +02:00 committed by GitHub
parent 946d653c58
commit 7cfedb0952
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 15984 additions and 1033 deletions

View file

@ -7,7 +7,7 @@ on:
- '!.gitignore'
- '!LICENSE'
- '!TODO'
- '!doc/**'
- '!docs/**'
- '!examples/**'
- '.github/workflows/ci.yml'
push:

49
.github/workflows/docs.yml vendored Normal file
View file

@ -0,0 +1,49 @@
name: Docs
on:
push:
branches:
- master
paths:
- 'docs/**'
- '.github/workflows/*docs.yml'
jobs:
build:
name: Build Docusaurus
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: 'docs/.nvmrc'
- name: Install dependencies
working-directory: ./docs
run: npm install
- name: Build
working-directory: ./docs
run: npm run build
- name: Upload Build Artifact
uses: actions/upload-pages-artifact@v3
with:
path: docs/build
deploy:
name: Deploy to GitHub Pages
needs: build
# Grant GITHUB_TOKEN the permissions required to make a Pages deployment
permissions:
pages: write # to deploy to Pages
id-token: write # to verify the deployment originates from an appropriate source
# Deploy to the github-pages environment
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

23
.github/workflows/test-docs.yml vendored Normal file
View file

@ -0,0 +1,23 @@
name: Test Docs
on:
pull_request:
paths:
- 'docs/**'
- '.github/workflows/*docs.yml'
jobs:
test-docs:
name: Test Docusaurus build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: 'docs/.nvmrc'
- name: Install dependencies
working-directory: ./docs
run: npm install
- name: Build
working-directory: ./docs
run: npm run build

File diff suppressed because it is too large Load diff

20
docs/.gitignore vendored Normal file
View file

@ -0,0 +1,20 @@
# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

1
docs/.nvmrc Normal file
View file

@ -0,0 +1 @@
18

3
docs/babel.config.js Normal file
View file

@ -0,0 +1,3 @@
module.exports = {
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
};

46
docs/docs/building.md Normal file
View file

@ -0,0 +1,46 @@
---
sidebar_position: 2
---
# Building
QuickJS uses [CMake] as its main build system, with an additional helper [Makefile].
:::note
Windows users will need to run the CMake commands manually.
:::
## Compiling everything
```bash
make
```
This will build the `qjs` and `qjsc` executables and other test tools. Head over [here](./cli) for
instructions on how to use them.
## Debug builds
```bash
make debug
```
This will produce a debug build without optimizations, suitable for developers.
## Running test262
```bash
make test262
```
This will run the test262 suite.
```bash
make test262-update
```
This will run the test262 suite and update the error / pass report, useful after
implementing a new feature that would alter the result of the test suite.
[CMake]: https://cmake.org
[Makefile]: https://www.gnu.org/software/make/

77
docs/docs/cli.md Normal file
View file

@ -0,0 +1,77 @@
---
sidebar_position: 4
---
# The qjs and qjsc CLI tools
## `qjs` - The QuickJS JavaScript interpreter
The `qjs` executable runs the JavaScript interpreter. It includes a simple standard
library and REPL.
```
$ qjs
usage: qjs [options] [file [args]]
-h --help list options
-e --eval EXPR evaluate EXPR
-i --interactive go to interactive mode
-m --module load as ES6 module (default=autodetect)
--script load as ES6 script (default=autodetect)
-I --include file include an additional file
--std make 'std' and 'os' available to the loaded script
-T --trace trace memory allocation
-d --dump dump the memory usage stats
-D --dump-flags flags for dumping debug data (see DUMP_* defines)
--memory-limit n limit the memory usage to 'n' Kbytes
--stack-size n limit the stack size to 'n' Kbytes
--unhandled-rejection dump unhandled promise rejections
-q --quit just instantiate the interpreter and quit
```
The following dump flags are supported:
```
DUMP_BYTECODE_FINAL 0x01 /* dump pass 3 final byte code */
DUMP_BYTECODE_PASS2 0x02 /* dump pass 2 code */
DUMP_BYTECODE_PASS1 0x04 /* dump pass 1 code */
DUMP_BYTECODE_HEX 0x10 /* dump bytecode in hex */
DUMP_BYTECODE_PC2LINE 0x20 /* dump line number table */
DUMP_BYTECODE_STACK 0x40 /* dump compute_stack_size */
DUMP_BYTECODE_STEP 0x80 /* dump executed bytecode */
DUMP_READ_OBJECT 0x100 /* dump the marshalled objects at load time */
DUMP_FREE 0x200 /* dump every object free */
DUMP_GC 0x400 /* dump the occurrence of the automatic GC */
DUMP_GC_FREE 0x800 /* dump objects freed by the GC */
DUMP_MODULE_RESOLVE 0x1000 /* dump module resolution steps */
DUMP_PROMISE 0x2000 /* dump promise steps */
DUMP_LEAKS 0x4000 /* dump leaked objects and strings in JS_FreeRuntime */
DUMP_ATOM_LEAKS 0x8000 /* dump leaked atoms in JS_FreeRuntime */
DUMP_MEM 0x10000 /* dump memory usage in JS_FreeRuntime */
DUMP_OBJECTS 0x20000 /* dump objects in JS_FreeRuntime */
DUMP_ATOMS 0x40000 /* dump atoms in JS_FreeRuntime */
DUMP_SHAPES 0x80000 /* dump shapes in JS_FreeRuntime */
```
## `qjsc` - The QuickJS JavaScript compiler
The `qjsc` executable runs the JavaScript compiler, it can generate bytecode from
source files which can then be embedded in an executable, or it can generate the necessary
scaffolding to build a C application which embeds QuickJS.
```
$ qjsc
usage: qjsc [options] [files]
options are:
-b output raw bytecode instead of C code
-e output main() and bytecode in a C file
-o output set the output filename
-n script_name set the script name (as used in stack traces)
-N cname set the C name of the generated data
-m compile as JavaScript module (default=autodetect)
-D module_name compile a dynamically loaded module or worker
-M module_name[,cname] add initialization code for an external C module
-p prefix set the prefix of the generated C names
-s strip the source code, specify twice to also strip debug info
-S n set the maximum stack size to 'n' bytes (default=262144)
```

View file

@ -0,0 +1,7 @@
{
"label": "Developer Guide",
"position": 6,
"link": {
"type": "generated-index"
}
}

View file

@ -0,0 +1,3 @@
# API Reference
WIP.

View file

@ -0,0 +1,117 @@
# Internals
## Bytecode
The compiler generates bytecode directly with no intermediate
representation such as a parse tree, hence it is very fast. Several
optimizations passes are done over the generated bytecode.
A stack-based bytecode was chosen because it is simple and generates
compact code.
For each function, the maximum stack size is computed at compile time so that
no runtime stack overflow tests are needed.
A separate compressed line number table is maintained for the debug
information.
Access to closure variables is optimized and is almost as fast as local
variables.
Direct `eval` in strict mode is optimized.
## Runtime
### Strings
Strings are stored either as an 8 bit or a 16 bit array of
characters. Hence random access to characters is always fast.
The C API provides functions to convert JavaScript Strings to C UTF-8 encoded
strings. The most common case where the JavaScript string contains
only ASCII characters involves no copying.
### Objects
The object shapes (object prototype, property names and flags) are shared
between objects to save memory.
Arrays with no holes (except at the end of the array) are optimized.
TypedArray accesses are optimized.
### Atoms
Object property names and some strings are stored as Atoms (unique
strings) to save memory and allow fast comparison. Atoms are
represented as a 32 bit integer. Half of the atom range is reserved for
immediate integer literals from 0 to 2^31-1.
### Numbers
Numbers are represented either as 32-bit signed integers or 64-bit IEEE-754
floating point values. Most operations have fast paths for the 32-bit
integer case.
### Garbage collection
Reference counting is used to free objects automatically and
deterministically. A separate cycle removal pass is done when the allocated
memory becomes too large. The cycle removal algorithm only uses the
reference counts and the object content, so no explicit garbage
collection roots need to be manipulated in the C code.
### JSValue
It is a JavaScript value which can be a primitive type (such as
Number, String, ...) or an Object. NaN boxing is used in the 32-bit version
to store 64-bit floating point numbers. The representation is
optimized so that 32-bit integers and reference counted values can be
efficiently tested.
In 64-bit code, JSValue are 128-bit large and no NaN boxing is used. The
rationale is that in 64-bit code memory usage is less critical.
In both cases (32 or 64 bits), JSValue exactly fits two CPU registers,
so it can be efficiently returned by C functions.
### Function call
The engine is optimized so that function calls are fast. The system
stack holds the JavaScript parameters and local variables.
### RegExp
A specific regular expression engine was developed. It is both small
and efficient and supports all the ES2020+ features including the
Unicode properties. As the JavaScript compiler, it directly generates
bytecode without a parse tree.
Backtracking with an explicit stack is used so that there is no
recursion on the system stack. Simple quantifiers are specifically
optimized to avoid recursions.
Infinite recursions coming from quantifiers with empty terms are
avoided.
The full regexp library weighs about 15 KiB (x86 code), excluding the
Unicode library.
### Unicode
A specific Unicode library was developed so that there is no
dependency on an external large Unicode library such as ICU. All the
Unicode tables are compressed while keeping a reasonable access
speed.
The library supports case conversion, Unicode normalization, Unicode
script queries, Unicode general category queries and all Unicode
binary properties.
The full Unicode library weighs about 45 KiB (x86 code).
### BigInt
BigInt is implemented with the [libbf](https://bellard.org/libbf) library.
It weights about 90 KiB (x86 code) and provides arbitrary precision IEEE 754 floating
point operations and transcendental functions with exact rounding.

View file

@ -0,0 +1,113 @@
---
sidebar_position: 1
---
# The QuickJS C API
The C API was designed to be simple and efficient. The C API is
defined in the header `quickjs.h`.
## Runtime and contexts
`JSRuntime` represents a JavaScript runtime corresponding to an
object heap. Several runtimes can exist at the same time but they
cannot exchange objects. Inside a given runtime, no multi-threading is
supported.
`JSContext` represents a JavaScript context (or Realm). Each
JSContext has its own global objects and system objects. There can be
several JSContexts per JSRuntime and they can share objects, similar
to frames of the same origin sharing JavaScript objects in a
web browser.
## JSValue
`JSValue` represents a JavaScript value which can be a primitive
type or an object. Reference counting is used, so it is important to
explicitly duplicate (`JS_DupValue()`, increment the reference
count) or free (`JS_FreeValue()`, decrement the reference count)
JSValues.
## C functions
C functions can be created with
`JS_NewCFunction()`. `JS_SetPropertyFunctionList()` is a
shortcut to easily add functions, setters and getters properties to a
given object.
Unlike other embedded JavaScript engines, there is no implicit stack,
so C functions get their parameters as normal C parameters. As a
general rule, C functions take constant `JSValue`s as parameters
(so they don't need to free them) and return a newly allocated (=live)
`JSValue`.
## Exceptions
Most C functions can return a JavaScript exception. It
must be explicitly tested and handled by the C code. The specific
`JSValue` `JS_EXCEPTION` indicates that an exception
occurred. The actual exception object is stored in the
`JSContext` and can be retrieved with `JS_GetException()`.
## Script evaluation
Use `JS_Eval()` to evaluate a script or module source.
If the script or module was compiled to bytecode with `qjsc`, it
can be evaluated by calling `js_std_eval_binary()`. The advantage
is that no compilation is needed so it is faster and smaller because
the compiler can be removed from the executable if no `eval` is
required.
Note: the bytecode format is linked to a given QuickJS
version. Moreover, no security check is done before its
execution. Hence the bytecode should not be loaded from untrusted
sources.
## JS Classes
C opaque data can be attached to a JavaScript object. The type of the
C opaque data is determined with the class ID (`JSClassID`) of
the object. Hence the first step is to register a new class ID and JS
class (`JS_NewClassID()`, `JS_NewClass()`). Then you can
create objects of this class with `JS_NewObjectClass()` and get or
set the C opaque point with `JS_GetOpaque()` / `JS_SetOpaque()`.
When defining a new JS class, it is possible to declare a finalizer
which is called when the object is destroyed. The finalizer should be
used to release C resources. It is invalid to execute JS code from
it. A `gc_mark` method can be provided so that the cycle removal
algorithm can find the other objects referenced by this object. Other
methods are available to define exotic object behaviors.
The Class ID are allocated per-runtime. The
`JSClass` are allocated per `JSRuntime`. `JS_SetClassProto()`
is used to define a prototype for a given class in a given
`JSContext`. `JS_NewObjectClass()` sets this prototype in the
created object.
Examples are available in `quickjs-libc.c`.
## C Modules
Native ES6 modules are supported and can be dynamically or statically
linked. The standard library `quickjs-libc.c` is a good example
of a native module.
## Memory handling
Use `JS_SetMemoryLimit()` to set a global memory allocation limit
to a given `JSRuntime`.
Custom memory allocation functions can be provided with `JS_NewRuntime2()`.
The maximum system stack size can be set with `JS_SetMaxStackSize()`.
## Execution timeout and interrupts
Use `JS_SetInterruptHandler()` to set a callback which is
regularly called by the engine when it is executing code. This
callback can be used to implement an execution timeout.
It is used by the command line interpreter to implement a
`Ctrl-C` handler.

11
docs/docs/es_features.md Normal file
View file

@ -0,0 +1,11 @@
---
sidebar_position: 7
---
# ECMAScript Features
QuickJS aims to support the latest available ECMAScript features once they hit the spec.
Progress on _test262_ compliance can be checked [here](https://test262.fyi/#|qjs_ng).
Due to size constraints it is unlikely QuickJS will ever support the [Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) APIs.

34
docs/docs/installation.md Normal file
View file

@ -0,0 +1,34 @@
---
sidebar_position: 3
---
# Installation
Installing QuickJS is simple, and we provide several ways to do so.
## Build from source
If you built it from source as outlined in [building](./building) you can just run:
```bash
make install
```
and it will be installed in your system. The default installation path is `/usr/local`.
## Using a prebuilt binary
Each [release on GitHub] includes binaries for several systems and architectures.
## Using jsvu
As of version 2.2.0 of `jsvu`, QuickJS-ng will be installed when the `quickjs` engine is requested.
```bash
npm install jsvu -g
```
[release on GitHub]: https://github.com/quickjs-ng/quickjs/releases

48
docs/docs/intro.md Normal file
View file

@ -0,0 +1,48 @@
---
slug: /
sidebar_position: 1
sidebar_label: Welcome
---
# Welcome to QuickJS-NG
QuickJS is a small and embeddable JavaScript engine. It aims to support the latest
[ECMAScript] specification.
This project is a _fork_ of the [original QuickJS project] by Fabrice Bellard, after it went
dormant for several years, with the intent of reigniting its development.
In October 2023 [@bnoordhuis] and [@saghul] decided to fork the original project with
the aim of reigniting it. They reached out to the original authors ([@bellard] and [@chqrlie])
about their intentions.
As of December 2023 the initial goal was somewhat accomplished. [@bellard] resumed working on
the project and both parties have been pulling patches from each other since.
As of early 2024 both projects agree the proper path forward involves merging both projects
and combining the efforts. While that may take a while, since both projects diverged in certain
areas, there is willingness to go in this direction from both sides.
This fork is focused on (but not limited to):
- Community development
- Testing
- Cross-platform support
- ES features
:::note
This site is under construction, the entire API is not yet documented.
:::
## Getting Started
Head over to [building](./building) if you want to build QuickJS from source or [installation](./installation)
for installing it from prebuilt binaries.
[ECMAScript]: https://tc39.es/ecma262/
[original QuickJS project]: https://bellard.org/quickjs
[@bellard]: https://github.com/bellard
[@bnoordhuis]: https://github.com/bnoordhuis
[@chqrlie]: https://github.com/chqrlie
[@saghul]: https://github.com/saghul

551
docs/docs/stdlib.md Normal file
View file

@ -0,0 +1,551 @@
---
sidebar_position: 5
---
# Standard library
The standard libary is provided as part of the `qjs` executable and the `quickjs-libc.c` source file
and it's not part of the core engine.
## Globals
### `argv0`
Provides the executable path.
### `scriptArgs`
Provides the command line arguments. The first argument is the script name.
### `print(...args)`
Print the arguments separated by spaces and a trailing newline.
### `console.log(...args)`
Same as `print()`.
### `navigator.userAgent`
Returns `quickjs-ng/<version>`.
### `gc()`
Shorthand for `std.gc()`.
## `bjson` module
### `bjson.write(obj, [flags])`
Serializes the given object into the QuickJS internal serialization format.
Returns an ArrayBuffer with the serialized data.
Supported flags:
- `WRITE_OBJ_BYTECODE`: allow serializing functions and modules
- `WRITE_OBJ_REFERENCE`: allow serializing object references
- `WRITE_OBJ_SAB`: allow serializing SharedArrayBuffer instances
- `WRITE_OBJ_STRIP_DEBUG`: strip debugging information when serializing
- `WRITE_OBJ_STRIP_SOURCE`: strip the source information when serializing
### `bjson.read(buf, [pos], [len], [flags])`
De-serialize the given ArrayBuffer (in QuickJS internal serialization format) back into a JavaScript value.
Supported flags:
- `READ_OBJ_BYTECODE`: allow de-serializing functions and modules
- `READ_OBJ_REFERENCE`: allow de-serializing object references
- `READ_OBJ_SAB`: allow de-serializing SharedArrayBuffer instances
## `os` module
The `os` module provides Operating System specific functions:
- low level file access
- signals
- timers
- basic asynchronous I/O
- workers (threads)
The OS functions usually return 0 if OK or an OS specific negative
error code.
### `open(filename, flags, mode = 0o666)`
Open a file. Return a handle or < 0 if error.
Supported flags:
- `O_RDONLY`
- `O_WRONLY`
- `O_RDWR`
- `O_APPEND`
- `O_CREAT`
- `O_EXCL`
- `O_TRUNC`
POSIX open flags.
- `O_TEXT`
(Windows specific). Open the file in text mode. The default is binary mode.
### `close(fd)`
Close the file handle `fd`.
### `seek(fd, offset, whence)`
Seek in the file. Use `std.SEEK_*` for
`whence`. `offset` is either a number or a BigInt. If
`offset` is a BigInt, a BigInt is returned too.
### `read(fd, buffer, offset, length)`
Read `length` bytes from the file handle `fd` to the
ArrayBuffer `buffer` at byte position `offset`.
Return the number of read bytes or < 0 if error.
### `write(fd, buffer, offset, length)`
Write `length` bytes to the file handle `fd` from the
ArrayBuffer `buffer` at byte position `offset`.
Return the number of written bytes or < 0 if error.
### `isatty(fd)`
Return `true` is `fd` is a TTY (terminal) handle.
### `ttyGetWinSize(fd)`
Return the TTY size as `[width, height]` or `null` if not available.
### `ttySetRaw(fd)`
Set the TTY in raw mode.
### `remove(filename)`
Remove a file. Return 0 if OK or `-errno`.
### `rename(oldname, newname)`
Rename a file. Return 0 if OK or `-errno`.
### `realpath(path)`
Return `[str, err]` where `str` is the canonicalized absolute
pathname of `path` and `err` the error code.
### `getcwd()`
Return `[str, err]` where `str` is the current working directory
and `err` the error code.
### `chdir(path)`
Change the current directory. Return 0 if OK or `-errno`.
### `mkdir(path, mode = 0o777)`
Create a directory at `path`. Return 0 if OK or `-errno`.
### `stat(path)` / `lstat(path)`
Return `[obj, err]` where `obj` is an object containing the
file status of `path`. `err` is the error code. The
following fields are defined in `obj`: `dev`, `ino`, `mode`, `nlink`,
`uid`, `gid`, `rdev`, `size`, `blocks`, `atime`, `mtime`, `ctime`. The times are
specified in milliseconds since 1970. `lstat()` is the same as
`stat()` excepts that it returns information about the link
itself.
- `S_IFMT`
- `S_IFIFO`
- `S_IFCHR`
- `S_IFDIR`
- `S_IFBLK`
- `S_IFREG`
- `S_IFSOCK`
- `S_IFLNK`
- `S_ISGID`
- `S_ISUID`
Constants to interpret the `mode` property returned by
`stat()`. They have the same value as in the C system header
`sys/stat.h`.
### `utimes(path, atime, mtime)`
Change the access and modification times of the file `path`. The
times are specified in milliseconds since 1970. Return 0 if OK or `-errno`.
### `symlink(target, linkpath)`
Create a link at `linkpath` containing the string `target`. Return 0 if OK or `-errno`.
### `readlink(path)`
Return `[str, err]` where `str` is the link target and `err`
the error code.
### `readdir(path)`
Return `[array, err]` where `array` is an array of strings
containing the filenames of the directory `path`. `err` is
the error code.
### `setReadHandler(fd, func)`
Add a read handler to the file handle `fd`. `func` is called
each time there is data pending for `fd`. A single read handler
per file handle is supported. Use `func = null` to remove the
handler.
### `setWriteHandler(fd, func)`
Add a write handler to the file handle `fd`. `func` is
called each time data can be written to `fd`. A single write
handler per file handle is supported. Use `func = null` to remove
the handler.
### `signal(signal, func)`
Call the function `func` when the signal `signal`
happens. Only a single handler per signal number is supported. Use
`null` to set the default handler or `undefined` to ignore
the signal. Signal handlers can only be defined in the main thread.
- `SIGINT`
- `SIGABRT`
- `SIGFPE`
- `SIGILL`
- `SIGSEGV`
- `SIGTERM`
POSIX signal numbers.
### `kill(pid, sig)`
Send the signal `sig` to the process `pid`.
### `exec(args[, options])`
Execute a process with the arguments `args`. `options` is an
object containing optional parameters:
- `block` - Boolean (default = true). If true, wait until the process is
terminated. In this case, `exec` return the exit code if positive
or the negated signal number if the process was interrupted by a
signal. If false, do not block and return the process id of the child.
- `usePath` - Boolean (default = true). If true, the file is searched in the
`PATH` environment variable.
- `file` - String (default = `args[0]`). Set the file to be executed.
- `cwd` - String. If present, set the working directory of the new process.
- `stdin`, `stdout`, `stderr` - If present, set the handle in the child for stdin, stdout or stderr.
- `env` - Object. If present, set the process environment from the object
key-value pairs. Otherwise use the same environment as the current
process.
- `uid` - Integer. If present, the process uid with `setuid`.
- `gid` - Integer. If present, the process gid with `setgid`.
### `waitpid(pid, options)`
`waitpid` Unix system call. Return the array `[ret, status]`.
`ret` contains `-errno` in case of error.
- `WNOHANG`
Constant for the `options` argument of `waitpid`.
### `dup(fd)`
`dup` Unix system call.
### `dup2(oldfd, newfd)`
`dup2` Unix system call.
### `pipe()`
`pipe` Unix system call. Return two handles as `[read_fd, write_fd]` or null in case of error.
### `sleep(delay_ms)`
Sleep during `delay_ms` milliseconds.
### `sleepAsync(delay_ms)`
Asynchronouse sleep during `delay_ms` milliseconds. Returns a promise. Example:
```js
await os.sleepAsync(500);
```
### `setTimeout(func, delay)`
Call the function `func` after `delay` ms. Return a timer ID.
### `clearTimeout(id)`
Cancel a timer.
### `platform`
Return a string representing the platform: `"linux"`, `"darwin"`, `"win32"` or `"js"`.
### `Worker(module_filename)`
Constructor to create a new thread (worker) with an API close to that of
`WebWorkers`. `module_filename` is a string specifying the
module filename which is executed in the newly created thread. As for
dynamically imported module, it is relative to the current script or
module path. Threads normally don't share any data and communicate
between each other with messages. Nested workers are not supported. An
example is available in `tests/test_worker.js`.
The worker class has the following static properties:
- `parent` - In the created worker, `Worker.parent` represents the parent
worker and is used to send or receive messages.
The worker instances have the following properties:
- `postMessage(msg)` - Send a message to the corresponding worker. `msg` is cloned in
the destination worker using an algorithm similar to the `HTML`
structured clone algorithm. `SharedArrayBuffer` are shared
between workers.
- `onmessage` - Getter and setter. Set a function which is called each time a
message is received. The function is called with a single
argument. It is an object with a `data` property containing the
received message. The thread is not terminated if there is at least
one non `null` `onmessage` handler.
## `std` module
The `std` module provides wrappers to libc (`stdlib.h` and `stdio.h`) and a few other utilities.
### `exit(n)`
Exit the process.
### `evalScript(str, options = undefined)`
Evaluate the string `str` as a script (global
eval). `options` is an optional object containing the following
optional properties:
- `backtrace_barrier` - Boolean (default = false). If true, error backtraces do not list the
stack frames below the evalScript.
- `async` - Boolean (default = false). If true, `await` is accepted in the
script and a promise is returned. The promise is resolved with an
object whose `value` property holds the value returned by the
script.
### `loadScript(filename)`
Evaluate the file `filename` as a script (global eval).
### `loadFile(filename)`
Load the file `filename` and return it as a string assuming UTF-8
encoding. Return `null` in case of I/O error.
### `open(filename, flags, errorObj = undefined)`
Open a file (wrapper to the libc `fopen()`). Return the FILE
object or `null` in case of I/O error. If `errorObj` is not
undefined, set its `errno` property to the error code or to 0 if
no error occurred.
### `popen(command, flags, errorObj = undefined)`
Open a process by creating a pipe (wrapper to the libc
`popen()`). Return the FILE
object or `null` in case of I/O error. If `errorObj` is not
undefined, set its `errno` property to the error code or to 0 if
no error occurred.
### `fdopen(fd, flags, errorObj = undefined)`
Open a file from a file handle (wrapper to the libc
`fdopen()`). Return the FILE
object or null` in case of I/O error. If `errorObj` is not
undefined, set its `errno` property to the error code or to 0 if
no error occurred.
### `tmpfile(errorObj = undefined)`
Open a temporary file. Return the FILE
object or `null` in case of I/O error. If `errorObj` is not
undefined, set its `errno` property to the error code or to 0 if
no error occurred.
### `puts(str)`
Equivalent to `std.out.puts(str)`.
### `printf(fmt, ...args)`
Equivalent to `std.out.printf(fmt, ...args)`.
### `sprintf(fmt, ...args)`
Equivalent to the libc sprintf().
### `in`, `out`, `err`
Wrappers to the libc file `stdin`, `stdout`, `stderr`.
### `Error`
Enumeration object containing the integer value of common errors
(additional error codes may be defined):
- `EINVAL`
- `EIO`
- `EACCES`
- `EEXIST`
- `ENOSPC`
- `ENOSYS`
- `EBUSY`
- `ENOENT`
- `EPERM`
- `EPIPE`
### `strerror(errno)`
Return a string that describes the error `errno`.
### `gc()`
Manually invoke the cycle removal algorithm. The cycle removal
algorithm is automatically started when needed, so this function is
useful in case of specific memory constraints or for testing.
### `getenv(name)`
Return the value of the environment variable `name` or
`undefined` if it is not defined.
### `setenv(name, value)`
Set the value of the environment variable `name` to the string
`value`.
### `unsetenv(name)`
Delete the environment variable `name`.
### `getenviron()`
Return an object containing the environment variables as key-value pairs.
### `urlGet(url, options = undefined)`
Download `url` using the `curl` command line
utility. `options` is an optional object containing the following
optional properties:
- `binary` - Boolean (default = false). If true, the response is an ArrayBuffer
instead of a string. When a string is returned, the data is assumed
to be UTF-8 encoded.
- `full` - Boolean (default = false). If true, return the an object contains
the properties `response` (response content),
`responseHeaders` (headers separated by CRLF), `status`
(status code). `response` is `null` is case of protocol or
network error. If `full` is false, only the response is
returned if the status is between 200 and 299. Otherwise `null`
is returned.
### `FILE`
File object.
#### `close()`
Close the file. Return 0 if OK or `-errno` in case of I/O error.
#### `puts(str)`
Outputs the string with the UTF-8 encoding.
#### `printf(fmt, ...args)`
Formatted printf.
The same formats as the standard C library `printf` are
supported. Integer format types (e.g. `%d`) truncate the Numbers
or BigInts to 32 bits. Use the `l` modifier (e.g. `%ld`) to
truncate to 64 bits.
#### `flush()`
Flush the buffered file.
#### `seek(offset, whence)`
Seek to a give file position (whence is
`std.SEEK_*`). `offset` can be a number or a BigInt. Return
0 if OK or `-errno` in case of I/O error.
- `SEEK_SET`
- `SEEK_CUR`
- `SEEK_END`
Constants for seek().
#### `tell()`
Return the current file position.
#### `tello()`
Return the current file position as a BigInt.
#### `eof()`
Return true if end of file.
#### `fileno()`
Return the associated OS handle.
#### `error()`
Return true if there was an error.
#### `clearerr()`
Clear the error indication.
#### `read(buffer, position, length)`
Read `length` bytes from the file to the ArrayBuffer `buffer` at byte
position `position` (wrapper to the libc `fread`).
#### `write(buffer, position, length)`
Write `length` bytes to the file from the ArrayBuffer `buffer` at byte
position `position` (wrapper to the libc `fwrite`).
#### `getline()`
Return the next line from the file, assuming UTF-8 encoding, excluding
the trailing line feed.
#### `readAsString(max_size = undefined)`
Read `max_size` bytes from the file and return them as a string
assuming UTF-8 encoding. If `max_size` is not present, the file
is read up its end.
#### `getByte()`
Return the next byte from the file. Return -1 if the end of file is reached.
#### `putByte(c)`
Write one byte to the file.

View file

@ -0,0 +1,18 @@
---
sidebar_position: 8
---
# Supported Platforms
| System | Supported versions | Notes |
|---|---|---|
| GNU/Linux | * | glibc and musl are supported |
| macOS | macOS >= 11 | Currently supported macOS releases |
| Windows | >= Windows 8 | VS >= 2022 and Clang are supported |
| FreeBSD | * | Limited testing |
| OpenBSD | * | Limited testing |
| NetBSD | * | Limited testing |
| Android | NDK >= 26.0.10792818 | Limited testing |
| iOS | * | Limited testing |
| MinGW | MinGW-w64 | |
| Other | N/A | Missing? Open a PR! |

114
docs/docusaurus.config.js Normal file
View file

@ -0,0 +1,114 @@
// @ts-check
// `@type` JSDoc annotations allow editor autocompletion and type checking
// (when paired with `@ts-check`).
// There are various equivalent ways to declare your Docusaurus config.
// See: https://docusaurus.io/docs/api/docusaurus-config
/** @type {import('@docusaurus/types').Config} */
const config = {
title: 'QuickJS-NG',
tagline: 'QuickJS, the Next Generation: a mighty JavaScript engine',
favicon: 'img/favicon.ico',
// Set the production url of your site here
url: 'https://quickjs-ng.github.io',
// Set the /<baseUrl>/ pathname under which your site is served
// For GitHub pages deployment, it is often '/<projectName>/'
baseUrl: '/quickjs/',
// GitHub pages deployment config.
// If you aren't using GitHub pages, you don't need these.
organizationName: 'quickjs-ng', // Usually your GitHub org/user name.
projectName: 'quickjs', // Usually your repo name.
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'throw',
// Even if you don't use internationalization, you can use this field to set
// useful metadata like html lang. For example, if your site is Chinese, you
// may want to replace "en" with "zh-Hans".
i18n: {
defaultLocale: 'en',
locales: ['en'],
},
presets: [
[
'classic',
/** @type {import('@docusaurus/preset-classic').Options} */
({
docs: {
routeBasePath: '/',
sidebarPath: './sidebars.js',
// Please change this to your repo.
// Remove this to remove the "edit this page" links.
editUrl: 'https://github.com/quickjs-ng/quickjs/tree/master/docs/',
},
blog: false,
theme: {
customCss: './src/css/custom.css',
},
}),
],
],
themeConfig:
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
({
// Replace with your project's social card
image: 'img/docusaurus-social-card.jpg',
navbar: {
title: 'QuickJS-NG',
items: [
{
type: 'docSidebar',
sidebarId: 'docsSidebar',
position: 'left',
label: 'Documentation',
},
{
href: 'https://github.com/quickjs-ng/quickjs',
label: 'GitHub',
position: 'right',
},
],
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
],
},
{
title: 'Community',
items: [
{
label: 'GitHub Discussions',
href: 'https://github.com/quickjs-ng/quickjs/discussions',
},
{
label: 'Matrix',
href: 'https://matrix.to/#/%23quickjs-ng%3Amatrix.org?via=matrix.org',
},
],
},
{
title: 'More',
items: [
{
label: 'GitHub',
href: 'https://github.com/quickjs-ng/quickjs',
},
],
},
],
copyright: `Copyright © ${new Date().getFullYear()} QuickJS-NG project contributors.`,
},
prism: {
},
}),
};
export default config;

14656
docs/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

42
docs/package.json Normal file
View file

@ -0,0 +1,42 @@
{
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
"serve": "docusaurus serve",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "3.5.2",
"@docusaurus/preset-classic": "3.5.2",
"@mdx-js/react": "3.0.1",
"clsx": "2.1.1",
"prism-react-renderer": "2.4.0",
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.5.2",
"@docusaurus/types": "3.5.2"
},
"browserslist": {
"production": [
">0.5%",
"not dead",
"not op_mini all"
],
"development": [
"last 3 chrome version",
"last 3 firefox version",
"last 5 safari version"
]
},
"engines": {
"node": ">=18.0"
}
}

20
docs/sidebars.js Normal file
View file

@ -0,0 +1,20 @@
/**
* Creating a sidebar enables you to:
- create an ordered group of docs
- render a sidebar for each doc of that group
- provide next/previous navigation
The sidebars can be generated from the filesystem, or explicitly defined here.
Create as many sidebars as you want.
*/
// @ts-check
/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
const sidebars = {
// By default, Docusaurus generates a sidebar from the docs folder structure
docsSidebar: [{type: 'autogenerated', dirName: '.'}],
};
export default sidebars;

30
docs/src/css/custom.css Normal file
View file

@ -0,0 +1,30 @@
/**
* Any CSS included here will be global. The classic template
* bundles Infima by default. Infima is a CSS framework designed to
* work well for content-centric websites.
*/
/* You can override the default Infima variables here. */
:root {
--ifm-color-primary: #2e8555;
--ifm-color-primary-dark: #29784c;
--ifm-color-primary-darker: #277148;
--ifm-color-primary-darkest: #205d3b;
--ifm-color-primary-light: #33925d;
--ifm-color-primary-lighter: #359962;
--ifm-color-primary-lightest: #3cad6e;
--ifm-code-font-size: 95%;
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1);
}
/* For readability concerns, you should choose a lighter palette in dark mode. */
[data-theme='dark'] {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: #21af90;
--ifm-color-primary-darker: #1fa588;
--ifm-color-primary-darkest: #1a8870;
--ifm-color-primary-light: #29d5b0;
--ifm-color-primary-lighter: #32d8b4;
--ifm-color-primary-lightest: #4fddbf;
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3);
}

0
docs/static/.nojekyll vendored Normal file
View file

BIN
docs/static/img/favicon.ico vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB