@amritk/nish-x86_64-linux 0.45.1 → 0.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/INSTALL.md +3 -1
- package/bin/nish +0 -0
- package/docs/AI.md +29 -18
- package/package.json +1 -1
- package/runtime/nish.d.ts +41 -0
- package/runtime/nish.h +11 -0
- package/runtime/nish.mjs +1 -0
- package/runtime/runtime-bytes.c +167 -7
- package/runtime/runtime-host.c +15 -0
- package/runtime/runtime-net.c +272 -9
- package/runtime/runtime-os.c +15 -1
- package/runtime/runtime-uring.c +394 -85
- package/runtime/sqlite/nish-sqlite.c +448 -148
- package/std/README.md +14 -14
- package/std/base64.ts +28 -30
- package/std/crypto/aes.ts +81 -45
- package/std/crypto/bcrypt-batch.ts +23 -4
- package/std/crypto/bcrypt.ts +36 -11
- package/std/crypto/chacha20poly1305.ts +93 -52
- package/std/crypto/x25519.ts +7 -4
- package/std/host/game.ts +52 -20
- package/std/host/ring.ts +115 -31
- package/std/host/text.ts +9 -3
- package/std/json.ts +83 -0
- package/std/math.ts +161 -131
- package/std/net/handler.ts +42 -7
- package/std/net/http1-server.ts +36 -11
- package/std/net/prefork.ts +1 -2
- package/std/net/static.ts +7 -2
- package/std/random.ts +34 -51
- package/std/raster.ts +360 -110
- package/std/regex.ts +46 -15
- package/std/release.ts +19 -13
- package/std/sqlite.ts +551 -16
- package/std/synth.ts +11 -2
- package/std/temporal.ts +740 -363
- package/std/term-io.ts +81 -33
- package/std/term-pixels.ts +287 -112
- package/std/term-probe.ts +7 -3
- package/std/term-rate.ts +142 -66
- package/std/term.ts +782 -406
- package/std/testing.ts +14 -7
package/std/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Nish modules written in Nish, for Nish programs to import. A module in this
|
|
4
4
|
directory is an ordinary Nish source file, compiled as part of whatever program
|
|
5
5
|
imports it and subject to the same rules as any other
|
|
6
|
-
([`docs/LANGUAGE.md`](
|
|
6
|
+
([`docs/LANGUAGE.md`](../docs/reference/language.md) is the style guide).
|
|
7
7
|
The compiler knows about a few of them, and each such row says how: the modules
|
|
8
8
|
a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
9
9
|
`math.ts`), the functions it lowers in place (`map.ts`, `threads.ts`,
|
|
@@ -13,14 +13,14 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
13
13
|
| Module | What it is |
|
|
14
14
|
| --- | --- |
|
|
15
15
|
| [`testing.ts`](https://github.com/amritk/nish/blob/main/std/testing.ts) | a test runner: a `Suite` a program drives with straight-line assertions, printing the `PASS` / `FAIL` / `SKIP` lines the repository's own harness prints, and answering the exit code |
|
|
16
|
-
| [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `split` and `splitLimit` (JavaScript's `split(sep, limit)`), `toFixed` (JavaScript's `x.toFixed(digits)`, rounded on the exact binary value), `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](
|
|
16
|
+
| [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `split` and `splitLimit` (JavaScript's `split(sep, limit)`), `toFixed` (JavaScript's `x.toFixed(digits)`, rounded on the exact binary value), `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
|
|
17
17
|
| [`math.ts`](https://github.com/amritk/nish/blob/main/std/math.ts) | `Math.tan`, `Math.atan2` and `Math.hypot` on `f64`, ported from fdlibm (`LICENSE-fdlibm`) so that every target, wasm included, answers alike without libm. A program never imports it: a call to one of the three loads it, and the compiler copies the functions the call reaches into the calling module as `internal` ones. JavaScript's answer for every NaN, signed zero and infinity, and within one ulp elsewhere (0.83, 0.84 and 0.93 ulp measured against mpmath). `tests/cases/math_std_edges` pins the special values |
|
|
18
18
|
| [`sort.ts`](https://github.com/amritk/nish/blob/main/std/sort.ts) | `xs.sort(cmp)` on any array: `sortWith`, a stable merge sort over runs of 32 sorted by insertion — one scratch array released before it returns, a pair of runs already in order copied without merging, no bounds check left in it — so its order is element for element Node's `Array.prototype.sort`. Like `math.ts` it is one the compiler knows about: a program never imports it, a `.sort(cmp)` call loads it, the checker rewrites the call to `sortWith`, and each comparator's instantiation — the comparator called directly, no function pointer — is copied into the module that sorts. Under Node the call stays the platform's own. `tests/cases/arr_sort_cmp*` are its programs, a 10,000-element sort with ties among them |
|
|
19
19
|
| [`array.ts`](https://github.com/amritk/nish/blob/main/std/array.ts) | the array methods that take a callback, and `slice`: `xs.map(f)`, `filter`, `some`, `every`, `findIndex` and `slice`, each a plain loop compiled once per callback, with no function pointer. A program never imports it: a call to one of those methods on an array loads it, and the compiler routes `xs.map(f)` to `map` or `mapIndexed` by how many parameters `f` takes. Each walks the array in order up to the length it had when the call began, as `Array.prototype` does, and `some`, `every` and `findIndex` stop at the element that decides the answer; a callback that shrinks the array ends the walk at the new length, where JavaScript goes on. Under Node the methods are the platform's own (`tests/cases/arr_map`, `arr_filter` and their kin) |
|
|
20
20
|
| [`regex.ts`](https://github.com/amritk/nish/blob/main/std/regex.ts) | Regular expressions in JavaScript's syntax with the `u` flag's strictness, matched by a Pike VM in time linear in the input whatever the pattern; finding every match is one search per match, so `findAll` and its kin can be quadratic when a long branch is preferred to a short one that wins ([`docs/security/regex.md`](../docs/security/regex.md)). `regexCompile(pattern, flags)` answers a `Regex` or the error text; `test`, `exec` into a reused `RegexMatch`, `find`, `findAll`, `count`, `replace` and `replaceAll` with `$&`, `$1` and `$<name>`, and `split`. Flags `i`, `m`, `s` and `u`; `i` folds by Unicode's simple case folding, ASCII letters only to ASCII. `\p{…}` and `\P{…}` take Unicode 16.0's General_Category, Script, Script_Extensions and binary properties by JavaScript's names, from tables `scripts/gen-regex-unicode.mjs` generates into the module and checks against Node's `RegExp`; backreferences and lookaround are refused at compile time. Offsets are UTF-8 bytes. A search allocates nothing beyond its answer: the thread lists and capture tables are the `Regex`'s, so one `Regex` serves one thread at a time. A leading literal is found with `indexOf`, a small leading set with `indexOfAny`. `tests/link/std_regex` and `tests/link/std_regex_unicode` check it against JavaScript's own answers |
|
|
21
21
|
| [`json.ts`](https://github.com/amritk/nish/blob/main/std/json.ts) | `jsonField(object, name)`: the value of one field of one flat JSON object, which is the shape the compiler's own `--json` diagnostics have. A reader and not a parser — it answers text, answers `null` for a field that is not there, and does not validate. `JsonWriter` is the other direction: any JSON value written into a caller-owned `u8[]`, commas and colons included, byte for byte what `JSON.stringify` writes, and allocating nothing per call except an `f64`'s digits, a temporary string the call gives back before it returns (`text()` and `jsonStringifyString` build strings by design); misuse and a full buffer set a sticky negative `JSON_WRITE_*` code in `failed` rather than panicking. `setIndent(n)` and `setIndentTab()` write what `JSON.stringify(v, null, n)` or `(v, null, "\t")` writes, with no allocation for the indent, and `setStrict(true)` makes NaN and the infinities the sticky `JSON_WRITE_NON_FINITE` instead of `null`; both modes are off by default and kept by `reset`. `jsonStringifyString(s)` is the string rule answered as a string. `stringBytes(bytes, off, len)` and `keyBytes(bytes, off, len)` write a window of a byte array as `string` and `key` write a string of those bytes, allocating nothing, and refuse a window outside the array with `JSON_WRITE_BAD_WINDOW` |
|
|
22
22
|
| [`json-tokenizer.ts`](https://github.com/amritk/nish/blob/main/std/json-tokenizer.ts) | `JsonTokenizer`: a validating, streaming tokenizer for RFC 8259 JSON held in a window of a `u8[]`. `next()` answers one `JSON_TOK_*` token at a time — object and array openers and closers, keys, strings, numbers and the three literals — then `JSON_TOK_END`, or a negative `JSON_TOK_ERR_*` code that sticks in `failed`, with the byte in `errorAt`. Strings are checked as UTF-8 and a lone surrogate escape is refused; `stringInto` decodes the current string into the caller's array and `keyEquals` compares it with a name, neither allocating. `numberF64` is correctly rounded; `isInteger` and `numberI64` read an integer that fits an `i64`, and `isU64` and `numberU64` one that fits a `u64`. `isIntegral` asks whether a number's value is whole however it is written (`1.0`, `1e2`, `1e400`), JSON Schema's "integer", from the text and at any exponent. `skipValue` steps over a value. `JsonLimits` caps nesting depth, string, number and total bytes, each with its own code; `reset` reuses the tokenizer, so a reused body keeps the arena flat. Duplicate keys are reported as tokens. No input panics and no byte outside the window is read; [`docs/security/json.md`](../docs/security/json.md) is its record, and `tests/link/std_json_tokenizer` runs JSONTestSuite and a seeded fuzz |
|
|
23
|
-
| [`json-typed.ts`](https://github.com/amritk/nish/blob/main/std/json-typed.ts) | `jsonDecode(d, out)` and `jsonEncode(w, value)`: one JSON object read into a class and written back, with code the compiler writes at each call from the class's fields — scalars (`u64` exact to 2^64 - 1), strings, enums (a numeric one as its number, a string one as its member's string), nested classes, arrays of those, `Map<string, V>` of those and `\| null` — through `JsonDecoder` (a `JsonTokenizer` and a sticky error) and `JsonWriter`. A class's one `static readonly json` literal renames a field's key and makes a key optional, a missing one setting its field to the initializer; otherwise every field is required, each key once, an unknown key refused unless `ignoreUnknown`, and every outcome a sticky `JSON_DECODE_*` or `JSON_TOK_ERR_*` code with its byte in `errorAt`; decoding into a reused object reuses its objects, arrays and equal strings, so the arena stays flat (a map's entries are made anew, at most `maxMapKeys` over all the maps of one decode, 4,096 by default); a key is sent to its field by its length, then one byte. A `JsonNumber` field keeps a number's text byte for byte. Under Node the types are erased and both calls panic ([`docs/LANGUAGE.md`](
|
|
23
|
+
| [`json-typed.ts`](https://github.com/amritk/nish/blob/main/std/json-typed.ts) | `jsonDecode(d, out)` and `jsonEncode(w, value)`: one JSON object read into a class and written back, with code the compiler writes at each call from the class's fields — scalars (`u64` exact to 2^64 - 1), strings, enums (a numeric one as its number, a string one as its member's string), nested classes, arrays of those, `Map<string, V>` of those and `\| null` — through `JsonDecoder` (a `JsonTokenizer` and a sticky error) and `JsonWriter`. A class's one `static readonly json` literal renames a field's key and makes a key optional, a missing one setting its field to the initializer; otherwise every field is required, each key once, an unknown key refused unless `ignoreUnknown`, and every outcome a sticky `JSON_DECODE_*` or `JSON_TOK_ERR_*` code with its byte in `errorAt`; decoding into a reused object reuses its objects, arrays and equal strings, so the arena stays flat (a map's entries are made anew, at most `maxMapKeys` over all the maps of one decode, 4,096 by default); a key is sent to its field by its length, then one byte. A `JsonNumber` field keeps a number's text byte for byte. Under Node the types are erased and both calls panic ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#typed-json-nishjson-typed), [`docs/security/json.md`](../docs/security/json.md)) |
|
|
24
24
|
| [`json-value.ts`](https://github.com/amritk/nish/blob/main/std/json-value.ts) | `JsonDocument`: any JSON document parsed into a tree of `JsonValue` handles (`i32`s into the document), read with `kind`, `boolean`, `string`, `stringEquals`, `length`, `at`, `keyAt` and `get`, built with the `new*` methods, `push` and `set`, and written back through `JsonWriter` with `write`, or as text with `stringify`. A number keeps its source text and is read on request as an `i64` or `u64` that fits (`isI64`, `isU64`), the nearest `f64`, or the text, and `isIntegral` asks whether its value is whole however it is written (`1.0`, `1e2`), so integers and decimals wider than any type round-trip byte for byte. Objects keep insertion order; a repeated key is `JSON_VALUE_ERR_DUPLICATE` unless `duplicates` is `JSON_VALUE_DUPLICATE_LAST`, `JSON.parse`'s rule. Every parse error and limit is the tokenizer's, with the depth held to the writer's 64 so that whatever parses writes back, nothing panics, and a value is in at most one container, so a tree built through `push` and `set` cannot hold itself. A handle carries the generation of the document it came from, so one kept across a `parse` or `clear` reads as nothing; `maxValues` (262,144 by default, `JSON_VALUE_ERR_VALUES` past it) bounds the memory a document keeps. `parseRanged` and `parseTextRanged` also record each value's byte range (`start`, `end`) and each key's (`keyStart`, `keyEnd`), 20 bytes more per value, and `setRange` and `setKeyRange` give built values theirs; after `parse` or `parseText` every range reads `-1`. Each `parse` reuses the document's arrays, so a reused document keeps the arena flat. `tests/link/std_json_value` runs JSONTestSuite through it ([`docs/security/json.md`](../docs/security/json.md)) |
|
|
25
25
|
| [`json-pointer.ts`](https://github.com/amritk/nish/blob/main/std/json-pointer.ts) | RFC 6901 JSON Pointers over a `JsonDocument`: `jsonPointerParse` (the decoded tokens, or `null`), `jsonPointerEscape` (one token, `~0` and `~1`), and `jsonPointerResolve` (the value, `JSON_POINTER_NONE` when the pointer names nothing, `JSON_POINTER_ERR_SYNTAX` when it is not one); `isJsonPointer` and `isRelativeJsonPointer` check JSON Schema's `json-pointer` and `relative-json-pointer` forms, reading the text once and allocating nothing. A resolve costs the pointer's length plus each object step's size. `tests/link/std_json_pointer` runs the suite's two format files through it |
|
|
26
26
|
| [`json-equal.ts`](https://github.com/amritk/nish/blob/main/std/json-equal.ts) | JSON Schema's value equality for `const`, `enum` and `uniqueItems`: `jsonEqual` across two documents (numbers by value, `1` is `1.0`; member order ignored; `true` is not `1`), `jsonEqualCanonical` (a text equal for exactly the equal values), `jsonEqualHash` (64-bit FNV-1a of it, unkeyed) and `jsonEqualFirstDuplicate` (`-1` when the items are unique). Nothing recurses, so any depth a document holds compares; a call costs the values' sizes plus sorting object keys. `tests/link/std_json_equal` runs the suite's `const`, `enum` and `uniqueItems` |
|
|
@@ -31,16 +31,16 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
31
31
|
| [`yaml-lines.ts`](https://github.com/amritk/nish/blob/main/std/yaml-lines.ts) | `YamlLineIndex`: byte offsets turned into 1-based `line` and `column` (characters) or `byteColumn`, by binary search over line starts found once with `indexOf`. LF, CR LF and a lone CR each break a line; an offset is clamped to the text first. |
|
|
32
32
|
| [`yaml-write.ts`](https://github.com/amritk/nish/blob/main/std/yaml-write.ts) | `stringifyYaml(doc, v)`: a `json-value` value written as block-style YAML that `parseYaml` reads back as the same tree. A string YAML would read as something else (a null, bool or number word, an indicator, a `: ` or ` #`, an edge space, a control character) is double-quoted and escaped; a key over 1024 bytes is an explicit `? key`. `""` for a no-value handle or a tree deeper than `JSON_WRITER_MAX_DEPTH`. |
|
|
33
33
|
| [`pair.ts`](https://github.com/amritk/nish/blob/main/std/pair.ts) | `Pair<A, B>`: an interface with `first` and `second`, for a function that answers two values from one call. A type and nothing else — the caller writes an object literal at the return — and for returning two values rather than storing them side by side |
|
|
34
|
-
| [`collections.ts`](https://github.com/amritk/nish/blob/main/std/collections.ts) | the global `Map<K, V>` and `Set<T>`: insertion-ordered tables whose buckets carry a hash fingerprint beside the entry index and whose entries keep their full hash, so every `get`, `set`, `add`, `has` and `delete` is one probe. `get` is not a method here: its `V | undefined` never crosses a call, so the compiler lowers it to `probe` and, where the key was found, `valueAt`. Nor are `keys()` and `values()`: an iterator is not a value, so a `for...of` over one is lowered to `walkOpen`, `walkNext`, `keyAt` or `valueAt`, and `walkClose`, and a count of live walks defers compaction until no loop is walking the table. A program never imports it: naming `Map` or `Set` loads it, and the compiler emits what a module uses of it into that module ([`docs/LANGUAGE.md`](
|
|
35
|
-
| [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](
|
|
36
|
-
| [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](
|
|
34
|
+
| [`collections.ts`](https://github.com/amritk/nish/blob/main/std/collections.ts) | the global `Map<K, V>` and `Set<T>`: insertion-ordered tables whose buckets carry a hash fingerprint beside the entry index and whose entries keep their full hash, so every `get`, `set`, `add`, `has` and `delete` is one probe. `get` is not a method here: its `V | undefined` never crosses a call, so the compiler lowers it to `probe` and, where the key was found, `valueAt`. Nor are `keys()` and `values()`: an iterator is not a value, so a `for...of` over one is lowered to `walkOpen`, `walkNext`, `keyAt` or `valueAt`, and `walkClose`, and a count of live walks defers compaction until no loop is walking the table. A program never imports it: naming `Map` or `Set` loads it, and the compiler emits what a module uses of it into that module ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)). Its `hashKey`, `sameKey` and `storedKey` are lowered by the compiler per key type |
|
|
35
|
+
| [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)) |
|
|
36
|
+
| [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#byte-runs-skipblank-skipdigits-skipjsontext-skipjsonplain-and-copybytes-in-nishbytes)). The runs are variable-time. `tests/link/std_bytes*` are its programs |
|
|
37
37
|
| [`base64.ts`](https://github.com/amritk/nish/blob/main/std/base64.ts) | `nish/base64`: padded standard base64 (RFC 4648 §4), encode only, for kitty graphics frames. `base64Encode(bytes)` answers a string, `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array panics before a byte is written. It indexes its alphabet by the sextet, so it is not constant-time: it is for pixels, not secrets. A strict decoder, and an encoder for key material, are `crypto/base64url.ts`'s `base64StdPadDecode` and `base64StdPadEncode` (`tests/link/std_base64`, `std_base64_f64`, `std_base64_negative_*`; the two modules in one program: `tests/link/std_base64_two_modules`; [guide](../docs/guide/using-nish/standard-library.md#nishbase64)) |
|
|
38
|
-
| [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin. There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
|
|
39
|
-
| [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each,
|
|
38
|
+
| [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin; `tryPlainDate`, `tryPlainDateFrom` and `PlainDate.tryAdd` answer the `RangeError`'s text as a `Result` `Err` (`tests/link/std_temporal_result`). There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
|
|
39
|
+
| [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, its wrapping add taken in `f64` on the state read as an unsigned count and its multiplies through `Math.imul`, so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#random-numbers-rng-in-nishrandom)). A parallel body or a task that makes its own steps it without a shared write. Not for cryptography |
|
|
40
40
|
| [`cli.ts`](https://github.com/amritk/nish/blob/main/std/cli.ts) | a command-line tool's `--help`. `HelpMenu` builds it a line at a time — `header`, `usage`, `section`, `row(flag, placeholder, description)`, `note`, `value` — with descriptions lined up at the caller's columns, counted on the plain text, and answers it with `text()`. `Style` paints it in the basic ANSI colours, bold and faint, which the terminal's theme defines, or in bold and underline alone when `TERM` declares no colours; each role it paints (`heading`, `name`, `flag`, `meta`, `dim`) is a pair of SGR lists, `<role>Themed` and `<role>Mono`, a program may set. `Style` also paints any text: the sixteen colours (`red`, `brightBlack`, ...), their backgrounds (`bgRed`, `bgBrightRed`, ...), the attributes (`bold`, `faint`, `italic`, `underline`, `inverse`, `strikethrough`, which the failsafe keeps) and `sgr(text, codes)` for any parameter list, with the `SGR_` constants spelling the codes. `styleFor(fd, agent)` is the policy `nish --help` follows: plain unless the descriptor is a terminal, `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR_FORCE`, `CLICOLOR` and `TERM=dumb` honoured, plain for an agent (`agentDriven`), forced colour always the theme's; it reads the environment and, for the terminal check, forks `/bin/sh` once, which runs `tput` by absolute path. `HelpMenu` and `Style` reach no capability. The compiler's own help is built with it through a relative import, so the module may use only what the last release compiles (`tests/link/std_cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli)) |
|
|
41
41
|
| [`cli-args.ts`](https://github.com/amritk/nish/blob/main/std/cli-args.ts) | a command tree for a large command-line tool. `Cli` declares it with a builder — `group`, `command(parent, name, id, description)`, `alias`, `flag`, `globalFlag`, `argument`, then `defaultValue`, `required`, `repeatable`, `negatable` and `epilog` on what they answer — every declaration an `i32` handle and every mistake a panic at its call. `parse(argv, start)` walks the arguments once and answers a `ParseResult`: the reached command's id and path, each flag's value with its `source` (the command line, its default or unset), the positionals and what follows `--`, or the first error with a did-you-mean. `finish` prints help (laid out by `HelpMenu`), the version or the error and exits 0 or 2. `parse` reaches no capability (`tests/link/std_cli_args`, `examples/api-cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli-args)) |
|
|
42
42
|
| [`cli-flags.ts`](https://github.com/amritk/nish/blob/main/std/cli-flags.ts) | `nish/cli-flags`: a command line read against a declared table. `FlagTable` declares `string`, `number` (an `f64`), `boolean` (`--name` / `--no-name`) and `repeatable` flags and `command` paths of one or more words; `parse(args)` (or `parseFrom(process.argv, 1)`) answers a `ParsedFlags` with the longest matched `command`, the `positionals` and each flag by name (`str`, `num`, `bool`, `all`, `has`). `--name value`, `--name=value`, `--` and a lone `-` follow the GNU long-option grammar; there are no short options. A usage error (unknown flag, missing value, not a number, given twice, value on a boolean, unknown command) is carried as `code`, `message` and `argument`, and `exitUsage()` writes it to stderr and exits 2. `writeHelp(menu)` adds the table's rows to a `nish/cli` `HelpMenu`. Reaches `exit` only through `exitUsage` (`tests/link/std_cli_flags`, `std_cli_flags_bad_*`; [guide](../docs/guide/using-nish/standard-library.md#parsing-flags)) |
|
|
43
|
-
| [`sqlite.ts`](https://github.com/amritk/nish/blob/main/std/sqlite.ts) | SQLite, vendored in `runtime/sqlite/` and linked into a program that imports the module, through the C adapter `runtime/sqlite/nish-sqlite.c`. `openDatabase(path, flags)` answers a `Database`: `exec`, `begin` / `commit` / `rollback`, `prepare` into a `Statement`, `lastInsertRowid`, `changes` and `close`, which finalizes the connection's statements. A `Statement` binds (`bindI64`, `bindF64`, `bindNull`, `bindText`, `bindTextBytes`, `bindBlob`), steps, resets and reads columns (`columnType`, `columnI64`, `columnF64`, `columnBytes`, `columnText`, and `columnInto`, a copy into the caller's `u8[]`), so a row allocates nothing. Every failure is a `Result` of SQLite's extended code, and `error(code)` builds the `SqliteError` with its message. A handle is an `i32` into the adapter's thread-local tables, and one used after `close` or `finalize` answers `SQLITE_MISUSE`. Reaches `ffi`; links natively and under `--profile wasi` (`tests/link/std_sqlite*`; [`docs/LANGUAGE.md`](
|
|
43
|
+
| [`sqlite.ts`](https://github.com/amritk/nish/blob/main/std/sqlite.ts) | SQLite, vendored in `runtime/sqlite/` and linked into a program that imports the module, through the C adapter `runtime/sqlite/nish-sqlite.c`. `openDatabase(path, flags)` answers a `Database`: `exec`, `begin` / `commit` / `rollback`, `prepare` into a `Statement`, `lastInsertRowid`, `changes` and `close`, which finalizes the connection's statements. A `Statement` binds (`bindI64`, `bindF64`, `bindNull`, `bindText`, `bindTextBytes`, `bindBlob`), steps, resets and reads columns (`columnType`, `columnI64`, `columnF64`, `columnBytes`, `columnText`, and `columnInto`, a copy into the caller's `u8[]`), so a row allocates nothing. Every failure is a `Result` of SQLite's extended code, and `error(code)` builds the `SqliteError` with its message. A handle is an `i32` into the adapter's thread-local tables, and one used after `close` or `finalize` answers `SQLITE_MISUSE`. Reaches `ffi`; links natively and under `--profile wasi` (`tests/link/std_sqlite*`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#sqlite-nishsqlite)) |
|
|
44
44
|
| [`release.ts`](https://github.com/amritk/nish/blob/main/std/release.ts) | `nish/release`: whether a newer release of a project on GitHub is out, and its `install.sh`. `releaseLatest(base, timeoutMs)` asks `<base>/releases/latest` once without following the redirect and answers the version only when it goes to exactly `<base>/releases/tag/v<version>`, else null; `releaseIsNewer`, `releaseCompare` and `releaseParseVersion` order semantic versions (a prerelease below its release, build metadata ignored, nothing that does not parse ever newer); `releaseValidVersion` is `install.sh`'s rule for a version that may go in a URL. `releaseCheckCached(base, current, path, maxAgeMs, timeoutMs)` keeps the answer in a file believed only when it is a regular file this user owns that nobody else can write, and refreshed when stale or dated in the future; `releaseFetchInstaller` writes a tag's `install.sh` to a file, never to a shell. https only, or http to loopback. The compiler's update notice and `nish upgrade` run on it ([`docs/security/release.md`](../docs/security/release.md); `tests/run.js` "nish/release"; [guide](../docs/guide/using-nish/standard-library.md#nishrelease)) |
|
|
45
45
|
| [`term.ts`](https://github.com/amritk/nish/blob/main/std/term.ts) | a terminal UI with no I/O of its own. `Screen` holds `width × height` cells (code point, 24-bit foreground and background, bold and inverse) for the frame being drawn and the frame last sent; `flush()` answers the string that turns one into the other — cursor moves and only the cells that changed, a style sent only where it differs — for the caller to `write`. A `Screen` made with `palette256` sends the nearest 256-colour index instead. `Canvas` draws pixels on a screen, two to a cell with the half block "▀" (`setPixel`, `fillRect`, `line`, `text`). The escapes (`enterAltScreen`, `hideCursor`, `clearScreen`, `beginSync`, …) are functions answering strings, and a `Screen` with `sync` set wraps each flush that changes anything in synchronized output (mode 2026). `FixedStep` is a fixed-step clock: `advance(nowMs)` answers the whole steps of `1000 / stepsPerSecond` ms since the last call, at most `maxSteps`, and `alpha()` the remainder, for logic at 240 Hz and drawing at 120. `KeyDecoder` turns raw-mode bytes into `KeyEvent`s (arrows as `ESC [` or `ESC O`, Enter, Space, Escape, Ctrl-C, characters), carries a sequence a read cut short into the next `feed`, and decides a lone ESC on a timeout the caller's clock measures. `feedEvents` and `pollEvents` read the same bytes as `TermEvent`s, whose `type` is an `EVENT_` constant: keys with `MOD_` bits and an `ACTION_` (legacy, modifyOtherKeys and the kitty keyboard protocol), SGR mouse reports in cells or pixels, bracketed paste, focus, and the terminal's replies to queries, which never come out as keys. `KeyState` tracks which keys are held, making up the releases a terminal without the kitty protocol never sends and turning Ctrl-C into `EVENT_QUIT`. The size, raw mode and the clock are the caller's, so the module reaches no capability and prints the same bytes under Node (`tests/link/std_term`, `std_term_f64`; [guide](../docs/guide/using-nish/standard-library.md#nishterm)) |
|
|
46
46
|
| [`term-probe.ts`](https://github.com/amritk/nish/blob/main/std/term-probe.ts) | what the terminal can do, asked once at start. `probeQueries(env)` is every query as one string — XTVERSION, DECRQM for synchronized output and pixel mouse, kitty's keyboard flags and a kitty graphics query, XTSMGRAPHICS, the cell and text-area sizes, a true-colour read-back, and DA1 last, wrapped for tmux's or screen's passthrough where only the outer terminal can answer. `TermProbe` takes the replies a read at a time (`feed`), holds back any key typed meanwhile (`heldEvents`), is `done()` once DA1 is answered or `timedOut(now)` after 250 ms, and `result()` reads the replies and a `TermEnv` (the `TERM`, `COLORTERM`, `TMUX`, `SSH_*`, `NO_COLOR` and `NISH_TERM_*` variables) into a `TermCaps`: colours, graphics backend, sync, kitty keyboard, cell size, pixel mouse, multiplexer. Pure: the environment, the bytes and the clock are the caller's (`tests/link/std_term_probe`; [guide](../docs/guide/using-nish/terminal.md#what-it-detects-and-what-it-falls-back-to)) |
|
|
@@ -50,10 +50,10 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
50
50
|
| [`input.ts`](https://github.com/amritk/nish/blob/main/std/input.ts) | `nish/input`: what one fixed step reads from its player, for a program whose steps run the same behind a terminal, a page or a test. `StepInput` holds the step's `events` and the `KeyState` of which keys are down, which a host owns and points at what it read each step; `isDown(key, code)` reads a key. The events and the key state are `nish/term`'s. Pure: no capability, no I/O and no clock |
|
|
51
51
|
| [`raster.ts`](https://github.com/amritk/nish/blob/main/std/raster.ts) | `nish/raster`: drawing into a frame of `0xRRGGBB` pixels held as an `Int32Array` with its width and height, so the same draw fills a terminal's `Framebuffer` (`rasterFrame(fb.pixels)` lends its `i32[]`) and a wasm page's module storage with no copy. Colours (`rasterRgb`, `rasterMix`, `rasterAdd`, `rasterDim`, `rasterHue`, `rasterWeight`), a gradient, rectangles, anti-aliased discs, additive glows, 5×7 pixel text (`rasterText`, `rasterTextWidth`), a fading `RasterTrail` and a `RasterParticles` pool made once and stepped in place. Every shape clips to the frame and to the rows the array has. Pure: no capability, no I/O and no clock. `tests/link/std_raster` |
|
|
52
52
|
| [`synth.ts`](https://github.com/amritk/nish/blob/main/std/synth.ts) | `nish/synth`: short sounds as `f64` samples at the caller's rate. `synthSilence(seconds, rate)` makes the array; `synthTone(out, rate, start, length, f0, f1, wave, volume, decay)` adds a square, triangle or noise voice into it with a log pitch slide, an exponential decay and click-free ends; `synthSemitone` steps a pitch. Samples are not clipped. Pure, and noise is a fixed xorshift sequence, so a call gives the same samples every time. `tests/link/std_synth` |
|
|
53
|
-
| [`region.ts`](https://github.com/amritk/nish/blob/main/std/region.ts) | The source behind the builtin module `nish:region`, and imported only by that name: `Region<T>`, `region`, `regionWith`, `enter`, `enterWith` and `free`. A `Region<T>` is a handle, a 64-bit integer, to memory the program frees when it says so; `region(f)` allocates what `f` builds into a new region and keeps its answer as the root, `enter(r, f)` runs `f(root)` there again and answers its scalar, the `*With` forms pass one argument through, and `free(r)` gives all of it back. A handle used after `free`, entered twice or freed while entered stops the program. The bodies are the meaning; the allocator swap is the emitter's (`src/emit-region.ts`) and what may cross a region's edge is the checker's (`src/region-check.ts`), keyed on this file ([`docs/LANGUAGE.md`](
|
|
54
|
-
| [`secret.ts`](https://github.com/amritk/nish/blob/main/std/secret.ts) | The source behind the builtin module `nish:secret`, and imported only by that name: `Secret<T>`, `secret`, `expose`, `exposeWith` and `wipe`. The bodies are the meaning; what makes a `Secret` one is the checker's, keyed on this file ([`docs/LANGUAGE.md`](
|
|
55
|
-
| [`threads.ts`](https://github.com/amritk/nish/blob/main/std/threads.ts) | `parallelMapInto(src, dst, f)` and `parallelReduce(src, f, identity)`: a function over every element of an array, on as many threads as the length is worth. Its bodies are the sequential meaning, which is what runs under Node; the compiler recognises the two templates by module and name, lowers the one loop in each onto `nish_parallel_range`, holds the function to the rules that make that safe, and compiles an importing program with `--threads` ([`docs/LANGUAGE.md`](
|
|
56
|
-
| [`sync/shm.ts`](https://github.com/amritk/nish/blob/main/std/sync/shm.ts) | `createRegion(name, bytes)`, `openRegion(name)` and `unlinkRegion(name)`: a named region of memory that several processes of one user map at once, through `runtime/runtime-shm.c`. A `SharedRegion` is read and written through checked slots, `loadI32` to `compareExchangeI64` at an ordering the call names (`RELAXED` to `SEQ_CST`), and byte windows (`read`, `write`); an offset outside the region or not a multiple of the slot's width stops the program. `waitI32` and `wake` sleep and wake on a slot across processes (Linux futex; `SHM_UNSUPPORTED` elsewhere). Native only, and it reaches `ffi` ([`docs/LANGUAGE.md`](
|
|
53
|
+
| [`region.ts`](https://github.com/amritk/nish/blob/main/std/region.ts) | The source behind the builtin module `nish:region`, and imported only by that name: `Region<T>`, `region`, `regionWith`, `enter`, `enterWith` and `free`. A `Region<T>` is a handle, a 64-bit integer, to memory the program frees when it says so; `region(f)` allocates what `f` builds into a new region and keeps its answer as the root, `enter(r, f)` runs `f(root)` there again and answers its scalar, the `*With` forms pass one argument through, and `free(r)` gives all of it back. A handle used after `free`, entered twice or freed while entered stops the program. The bodies are the meaning; the allocator swap is the emitter's (`src/emit-region.ts`) and what may cross a region's edge is the checker's (`src/region-check.ts`), keyed on this file ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#regions-nishregion); [guide](../docs/guide/language/regions.md)) |
|
|
54
|
+
| [`secret.ts`](https://github.com/amritk/nish/blob/main/std/secret.ts) | The source behind the builtin module `nish:secret`, and imported only by that name: `Secret<T>`, `secret`, `expose`, `exposeWith` and `wipe`. The bodies are the meaning; what makes a `Secret` one is the checker's, keyed on this file ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#secrets-nishsecret)). `wipe`'s body is written by the emitter, one volatile `llvm.memset`, and like `collections.ts` the module writes no `.ll` of its own |
|
|
55
|
+
| [`threads.ts`](https://github.com/amritk/nish/blob/main/std/threads.ts) | `parallelMapInto(src, dst, f)` and `parallelReduce(src, f, identity)`: a function over every element of an array, on as many threads as the length is worth. Its bodies are the sequential meaning, which is what runs under Node; the compiler recognises the two templates by module and name, lowers the one loop in each onto `nish_parallel_range`, holds the function to the rules that make that safe, and compiles an importing program with `--threads` ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#data-parallelism-nishthreads)). `tests/link/par_*` are its programs. `scope()`, bound by `using s = scope()`, runs unlike tasks, each on a thread of its own, and joins them at every exit of the block; `s.spawn(entry, arg, dst, at)` stores a task's answer, and `s.spawn(entry, arg)` and `s.spawn(() => ...)`, whose arrow reads the function's `const` locals, run one that answers `void` (`spawnWith` and `spawnThunk` are the methods the compiler reads them as, and under Node `spawn` itself tells them apart) ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#scoped-tasks-using-s--scope)). `scopeWithStack(bytes)` is a scope whose tasks each run on a new thread with at least `bytes` of stack, for a task that recurses deeper than a thread's default allows; under Node and without threads the size is checked and otherwise ignored (`tests/link/thread_stack_deep`). `Mutex<T>` is a lock that owns its data: the value is reachable only through the guard `using g = m.lock()` binds, which releases it at every exit of the block, so a scope's tasks can share and update one value without a data race or a deadlock ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#a-lock-that-owns-its-data-mutext); `tests/link/thread_mutex_*`, and `examples/histogram.ts` measured). `Channel<T>` carries scalars to one receiver, a task of the scope or the parent after the join, from the scope's sender tasks and from the parent before the block that spawns them, and closes when every sending task has returned ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#channels-channelt)). Every body in the module is its meaning under Node, where a task runs at its `spawn` |
|
|
56
|
+
| [`sync/shm.ts`](https://github.com/amritk/nish/blob/main/std/sync/shm.ts) | `createRegion(name, bytes)`, `openRegion(name)` and `unlinkRegion(name)`: a named region of memory that several processes of one user map at once, through `runtime/runtime-shm.c`. A `SharedRegion` is read and written through checked slots, `loadI32` to `compareExchangeI64` at an ordering the call names (`RELAXED` to `SEQ_CST`), and byte windows (`read`, `write`); an offset outside the region or not a multiple of the slot's width stops the program. `waitI32` and `wake` sleep and wake on a slot across processes (Linux futex; `SHM_UNSUPPORTED` elsewhere). Native only, and it reaches `ffi` ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#shared-memory-between-processes-nishsyncshm-and-nishsyncring); [`docs/security/shm.md`](../docs/security/shm.md)) |
|
|
57
57
|
| [`sync/ring.ts`](https://github.com/amritk/nish/blob/main/std/sync/ring.ts) | Lock-free rings of byte records in a `SharedRegion`: `SpscRing` (one producer, one consumer, records of any length) and `MpscRing` (many producers, one consumer, fixed slots), made with `initSpscRing` / `initMpscRing` and found from another process with `attachSpscRing` / `attachMpscRing`. `tryPush`, `tryPop` and `popBatch` never block; a ring made with a doorbell adds `popWait`, which sleeps on a futex that a push rings only when the consumer is asleep. A length a peer wrote that the ring cannot hold stops the program as corrupt. `tests/link/sync_ring`, `examples/prefork-jobs.ts` and `bench/ring-latency/` are its programs |
|
|
58
58
|
| [`host/text.ts`](https://github.com/amritk/nish/blob/main/std/host/text.ts) | Text in wasm module storage, for a module and its page. `textWrite(buf, at, s)` writes a string's UTF-8 bytes into a `u8[]` at `at` and answers the offset after them, `textWriteInt` and `textWriteF64` a number as a template literal formats it; text that does not fit writes nothing and answers -1, which every writer passes through, so a chain fails as a whole and never traps. `textRead(buf, n)` is the first `n` bytes as a string, what the page's `encodeInto` wrote, or `null` for an `n` past the buffer. `tests/host-import/text` is its round trip |
|
|
59
59
|
| [`host/ring.ts`](https://github.com/amritk/nish/blob/main/std/host/ring.ts) | `nish/host/ring`: a single-producer, single-consumer ring of `i32` words in an `Int32Array` of module storage, shared by a wasm module and the page that drives it — word 0 the head, word 1 the tail, the slots after. `ringPush`, `ringShift`, `ringSize`, `ringFree`, `ringCapacity` and `ringClear`; the page's half is `nish/page`'s `ringOver`, over the same layout. It needs no atomics because the page and the module run on one thread and never at once. A zero-filled ring is empty, and a ring whose counts a buggy page wrote out of protocol is still never read out of bounds (`tests/link/std_host_ring`) |
|
|
@@ -473,7 +473,7 @@ checklist in
|
|
|
473
473
|
three are what shape an API here more than any style preference — see the
|
|
474
474
|
header of `testing.ts` for what they did to that one, which has one
|
|
475
475
|
assertion per type. A new module can use
|
|
476
|
-
[generic functions and classes](
|
|
476
|
+
[generic functions and classes](../docs/reference/language/declarations.md#generic-functions);
|
|
477
477
|
`pair.ts` exports a generic type.
|
|
478
478
|
- **Ship it with a `tests/link/` case.** `tests/link/<name>/` is the only place a
|
|
479
479
|
multi-module program is exercised end to end, and it is also what puts the
|
package/std/base64.ts
CHANGED
|
@@ -57,12 +57,10 @@ export const base64EncodedLength = (n: i32): i32 => {
|
|
|
57
57
|
if (n > 1610612733) {
|
|
58
58
|
panic("base64EncodedLength: the encoding is longer than 2^31 - 1 characters")
|
|
59
59
|
}
|
|
60
|
-
|
|
60
|
+
const groups: i32 = toI32((n + 2) / 3)
|
|
61
|
+
return groups * 4
|
|
61
62
|
}
|
|
62
63
|
|
|
63
|
-
/** The byte of the character for the sextet `v` (`0 <= v <= 63`). */
|
|
64
|
-
const base64CharOf = (v: i32): u8 => toU8(BASE64_ALPHABET.charCodeAt(v))
|
|
65
|
-
|
|
66
64
|
/**
|
|
67
65
|
* Write the base64 of `src[off..off+len)` into `dst` from index `at`, and
|
|
68
66
|
* answer the index just past the last character written, which is
|
|
@@ -91,40 +89,41 @@ export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i
|
|
|
91
89
|
panic("base64EncodeInto: the source range is outside the array")
|
|
92
90
|
}
|
|
93
91
|
const need: i32 = base64EncodedLength(len)
|
|
94
|
-
if (at < 0 ||
|
|
92
|
+
if (at < 0 || need > dstLength - at) {
|
|
95
93
|
panic("base64EncodeInto: the encoding does not fit in the destination")
|
|
96
94
|
}
|
|
95
|
+
// A local, so that `abc.length >= 64` below is a fact about the string each
|
|
96
|
+
// character is read from.
|
|
97
|
+
const abc: string = BASE64_ALPHABET
|
|
97
98
|
let i: i32 = off
|
|
98
99
|
let o: i32 = at
|
|
99
|
-
|
|
100
|
+
let rest: i32 = len
|
|
100
101
|
// The checks above make every term after the first true; they are written out
|
|
101
102
|
// because they are what proves the loop's accesses in range.
|
|
102
|
-
while (
|
|
103
|
+
while (rest >= 3 && i >= 0 && i < srcLength - 2 && o >= 0 && o < dstLength - 3 && abc.length >= 64) {
|
|
103
104
|
const group: i32 = (toI32(src[i]) << 16) | (toI32(src[i + 1]) << 8) | toI32(src[i + 2])
|
|
104
|
-
dst[o] =
|
|
105
|
-
dst[o + 1] =
|
|
106
|
-
dst[o + 2] =
|
|
107
|
-
dst[o + 3] =
|
|
105
|
+
dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
|
|
106
|
+
dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
|
|
107
|
+
dst[o + 2] = toU8(abc.charCodeAt((group >> 6) & 63))
|
|
108
|
+
dst[o + 3] = toU8(abc.charCodeAt(group & 63))
|
|
108
109
|
i = i + 3
|
|
109
110
|
o = o + 4
|
|
111
|
+
rest = rest - 3
|
|
110
112
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
dst[o + 1] = base64CharOf((group >> 12) & 63)
|
|
116
|
-
dst[o + 2] = toU8(BASE64_PAD)
|
|
117
|
-
dst[o + 3] = toU8(BASE64_PAD)
|
|
118
|
-
o = o + 4
|
|
119
|
-
} else if (tail === 2) {
|
|
120
|
-
const group: i32 = (toI32(src[i]) << 16) | (toI32(src[i + 1]) << 8)
|
|
121
|
-
dst[o] = base64CharOf(group >> 18)
|
|
122
|
-
dst[o + 1] = base64CharOf((group >> 12) & 63)
|
|
123
|
-
dst[o + 2] = base64CharOf((group >> 6) & 63)
|
|
124
|
-
dst[o + 3] = toU8(BASE64_PAD)
|
|
125
|
-
o = o + 4
|
|
113
|
+
// A short final group of one or two bytes, padded. As in the loop, the
|
|
114
|
+
// checks above make every term after the first false.
|
|
115
|
+
if (rest === 0 || i < 0 || i >= srcLength || o < 0 || o >= dstLength - 3 || abc.length < 64) {
|
|
116
|
+
return o
|
|
126
117
|
}
|
|
127
|
-
|
|
118
|
+
let group: i32 = toI32(src[i]) << 16
|
|
119
|
+
if (rest === 2 && i < srcLength - 1) {
|
|
120
|
+
group = group | (toI32(src[i + 1]) << 8)
|
|
121
|
+
}
|
|
122
|
+
dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
|
|
123
|
+
dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
|
|
124
|
+
dst[o + 2] = rest === 2 ? toU8(abc.charCodeAt((group >> 6) & 63)) : toU8(BASE64_PAD)
|
|
125
|
+
dst[o + 3] = toU8(BASE64_PAD)
|
|
126
|
+
return o + 4
|
|
128
127
|
}
|
|
129
128
|
|
|
130
129
|
/**
|
|
@@ -135,9 +134,8 @@ export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i
|
|
|
135
134
|
* @returns A fresh string holding the padded encoding.
|
|
136
135
|
*/
|
|
137
136
|
export const base64Encode = (bytes: u8[]): string => {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
}
|
|
137
|
+
// A longer length saturates to the largest `i32` under `--number-mode f64`,
|
|
138
|
+
// which `base64EncodedLength` refuses, as it does any count past 1,610,612,733.
|
|
141
139
|
const n: i32 = toI32(bytes.length)
|
|
142
140
|
const out: u8[] = new Array<u8>(base64EncodedLength(n))
|
|
143
141
|
const end: i32 = base64EncodeInto(bytes, 0, n, out, 0)
|
package/std/crypto/aes.ts
CHANGED
|
@@ -491,20 +491,26 @@ const aesMixColumns = (q: u64[]): void => {
|
|
|
491
491
|
q[7] = t6 ^ n7 ^ aesRowAfterNext(t7)
|
|
492
492
|
}
|
|
493
493
|
|
|
494
|
-
/**
|
|
494
|
+
/**
|
|
495
|
+
* AddRoundKey (FIPS 197 §5.1.4): the eight words of `rk` from `at` into the
|
|
496
|
+
* state. Its callers pass `8 * round` for a round of at most 14, so `at` is at
|
|
497
|
+
* most 112 and the mask `at & 127` changes nothing; it bounds `base + 7`, so
|
|
498
|
+
* the sum cannot overflow, with no branch.
|
|
499
|
+
*/
|
|
495
500
|
const aesAddRoundKey = (q: u64[], rk: u64[], at: i32): void => {
|
|
501
|
+
const base: i32 = at & 127
|
|
496
502
|
// The first and last key words and the last plane first: their checked
|
|
497
503
|
// reads prove every other index below.
|
|
498
|
-
const k0: u64 = rk[
|
|
499
|
-
const k7: u64 = rk[
|
|
504
|
+
const k0: u64 = rk[base]
|
|
505
|
+
const k7: u64 = rk[base + 7]
|
|
500
506
|
const q7: u64 = q[7]
|
|
501
507
|
q[0] = q[0] ^ k0
|
|
502
|
-
q[1] = q[1] ^ rk[
|
|
503
|
-
q[2] = q[2] ^ rk[
|
|
504
|
-
q[3] = q[3] ^ rk[
|
|
505
|
-
q[4] = q[4] ^ rk[
|
|
506
|
-
q[5] = q[5] ^ rk[
|
|
507
|
-
q[6] = q[6] ^ rk[
|
|
508
|
+
q[1] = q[1] ^ rk[base + 1]
|
|
509
|
+
q[2] = q[2] ^ rk[base + 2]
|
|
510
|
+
q[3] = q[3] ^ rk[base + 3]
|
|
511
|
+
q[4] = q[4] ^ rk[base + 4]
|
|
512
|
+
q[5] = q[5] ^ rk[base + 5]
|
|
513
|
+
q[6] = q[6] ^ rk[base + 6]
|
|
508
514
|
q[7] = q7 ^ k7
|
|
509
515
|
}
|
|
510
516
|
|
|
@@ -529,17 +535,20 @@ export const aesBitslicedRound = (q: u64[], rk: u64[], at: i32): void => {
|
|
|
529
535
|
|
|
530
536
|
/**
|
|
531
537
|
* The cipher (FIPS 197 §5.1) on the four blocks of `buf[0 .. 64)`, in place,
|
|
532
|
-
* under the bitsliced round keys `rk`. `q` is scratch.
|
|
538
|
+
* under the bitsliced round keys `rk`. `q` is scratch. `rounds` is 10 or 14,
|
|
539
|
+
* so `rounds & 15` is `rounds`: the mask lets the bounds prover see that
|
|
540
|
+
* neither `8 * round` nor `8 * last` can overflow.
|
|
533
541
|
*/
|
|
534
542
|
const aesEncryptBatch = (rk: u64[], rounds: i32, buf: u8[], q: u64[]): void => {
|
|
535
543
|
aesPack(q, buf)
|
|
536
544
|
aesAddRoundKey(q, rk, 0)
|
|
537
|
-
|
|
545
|
+
const last: i32 = rounds & 15
|
|
546
|
+
for (let round: i32 = 1; round < last; round++) {
|
|
538
547
|
aesBitslicedRound(q, rk, 8 * round)
|
|
539
548
|
}
|
|
540
549
|
aesSbox(q)
|
|
541
550
|
aesShiftRows(q)
|
|
542
|
-
aesAddRoundKey(q, rk, 8 *
|
|
551
|
+
aesAddRoundKey(q, rk, 8 * last)
|
|
543
552
|
aesUnpack(buf, q)
|
|
544
553
|
}
|
|
545
554
|
|
|
@@ -570,26 +579,34 @@ const aesSubWord = (w: u32, q: u64[]): u32 => {
|
|
|
570
579
|
return out
|
|
571
580
|
}
|
|
572
581
|
|
|
573
|
-
/**
|
|
582
|
+
/**
|
|
583
|
+
* Four bytes of `data` from `at` as a big-endian word, or 0 for a window
|
|
584
|
+
* outside `data`, which no caller passes: each has checked it.
|
|
585
|
+
*/
|
|
574
586
|
const aesLoad32 = (data: u8[], at: i32): u32 => {
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
587
|
+
if (at < 0 || at > toI32(data.length) - 4) {
|
|
588
|
+
return 0
|
|
589
|
+
}
|
|
578
590
|
return (
|
|
579
591
|
(toU32(data[at]) << toU32(24)) |
|
|
580
592
|
(toU32(data[at + 1]) << toU32(16)) |
|
|
581
593
|
(toU32(data[at + 2]) << toU32(8)) |
|
|
582
|
-
|
|
594
|
+
toU32(data[at + 3])
|
|
583
595
|
)
|
|
584
596
|
}
|
|
585
597
|
|
|
586
|
-
/**
|
|
598
|
+
/**
|
|
599
|
+
* `w` big-endian into `out[at .. at + 4)`, or nothing for a window outside
|
|
600
|
+
* `out`, which no caller passes: each has checked it.
|
|
601
|
+
*/
|
|
587
602
|
const aesStore32 = (out: u8[], at: i32, w: u32): void => {
|
|
588
|
-
|
|
603
|
+
if (at < 0 || at > toI32(out.length) - 4) {
|
|
604
|
+
return
|
|
605
|
+
}
|
|
589
606
|
out[at] = toU8(w >> toU32(24))
|
|
590
|
-
out[at + 3] = toU8(w)
|
|
591
607
|
out[at + 1] = toU8(w >> toU32(16))
|
|
592
608
|
out[at + 2] = toU8(w >> toU32(8))
|
|
609
|
+
out[at + 3] = toU8(w)
|
|
593
610
|
}
|
|
594
611
|
|
|
595
612
|
/**
|
|
@@ -612,8 +629,9 @@ const aesScheduleInto = (key: u8[], rounds: i32, rk: u64[]): void => {
|
|
|
612
629
|
const nk: integer<4, 8> = aes128 ? 4 : 8
|
|
613
630
|
const total: integer<44, 60> = aes128 ? 44 : 60
|
|
614
631
|
const lastRound: integer<10, 14> = aes128 ? 10 : 14
|
|
615
|
-
// Sized for AES-256
|
|
616
|
-
|
|
632
|
+
// Sized for AES-256 and rounded up to 64 so a mask bounds its index;
|
|
633
|
+
// AES-128 uses the first 44 words.
|
|
634
|
+
const w: u32[] = new Array<u32>(64)
|
|
617
635
|
const q: u64[] = new Array<u64>(8)
|
|
618
636
|
const keyLength: i32 = toI32(key.length)
|
|
619
637
|
// The key's own Nk words.
|
|
@@ -638,7 +656,9 @@ const aesScheduleInto = (key: u8[], rounds: i32, rk: u64[]): void => {
|
|
|
638
656
|
} else if (nk > 6 && pos === 4) {
|
|
639
657
|
temp = aesSubWord(temp, q)
|
|
640
658
|
}
|
|
641
|
-
|
|
659
|
+
// `i - nk` is in [0, 56): the mask is a no-op the bounds prover can read.
|
|
660
|
+
const back: i32 = (i - nk) & 63
|
|
661
|
+
const word: u32 = w[back] ^ temp
|
|
642
662
|
w[i] = word
|
|
643
663
|
prev = word
|
|
644
664
|
}
|
|
@@ -683,13 +703,20 @@ const aesLoad64 = (data: u8[], at: i32, end: i32): u64 => {
|
|
|
683
703
|
return v
|
|
684
704
|
}
|
|
685
705
|
|
|
686
|
-
/**
|
|
706
|
+
/**
|
|
707
|
+
* `v` big-endian into `out[at .. at + 8)`, or nothing for a window outside
|
|
708
|
+
* `out`, which no caller passes: each writes inside an array it sized.
|
|
709
|
+
*/
|
|
687
710
|
const aesStore64 = (out: u8[], at: i32, v: u64): void => {
|
|
711
|
+
if (at < 0 || at > toI32(out.length) - 8) {
|
|
712
|
+
return
|
|
713
|
+
}
|
|
688
714
|
const length: i32 = toI32(out.length)
|
|
715
|
+
let to: i32 = at
|
|
689
716
|
for (let i: i32 = 0; i < 8; i++) {
|
|
690
|
-
|
|
691
|
-
if (to >= 0 && to < length) {
|
|
717
|
+
if (to < length) {
|
|
692
718
|
out[to] = toU8(v >> toU64((7 - i) * 8))
|
|
719
|
+
to = to + 1
|
|
693
720
|
}
|
|
694
721
|
}
|
|
695
722
|
}
|
|
@@ -823,9 +850,11 @@ export const aesKeyInto = (key: u8[], out: AesKey): boolean => {
|
|
|
823
850
|
out.rounds = rounds
|
|
824
851
|
const h: u8[] = new Array<u8>(AES_BLOCK)
|
|
825
852
|
aesEncryptOne(out, new Array<u8>(AES_BLOCK), h)
|
|
826
|
-
//
|
|
827
|
-
|
|
828
|
-
|
|
853
|
+
// Checked above; tested again here, where the bounds prover can see it.
|
|
854
|
+
if (toI32(hash.length) > 1) {
|
|
855
|
+
hash[0] = aesLoad64(h, 0, 8)
|
|
856
|
+
hash[1] = aesLoad64(h, 8, 16)
|
|
857
|
+
}
|
|
829
858
|
wipe(h)
|
|
830
859
|
return true
|
|
831
860
|
}
|
|
@@ -1173,9 +1202,12 @@ const aesGcmTag = (
|
|
|
1173
1202
|
ghashLengths(y, hHi, hLo, aadLength, textLength)
|
|
1174
1203
|
const mask: u8[] = new Array<u8>(AES_BLOCK)
|
|
1175
1204
|
aesEncryptOne(key, j0, mask)
|
|
1176
|
-
//
|
|
1177
|
-
|
|
1178
|
-
|
|
1205
|
+
// Every caller passes two words; tested here, where the bounds prover can
|
|
1206
|
+
// see it past the calls above.
|
|
1207
|
+
if (toI32(y.length) > 1) {
|
|
1208
|
+
y[0] = y[0] ^ aesLoad64(mask, 0, 16)
|
|
1209
|
+
y[1] = y[1] ^ aesLoad64(mask, 8, 16)
|
|
1210
|
+
}
|
|
1179
1211
|
wipe(mask)
|
|
1180
1212
|
}
|
|
1181
1213
|
|
|
@@ -1215,7 +1247,7 @@ export const aesGcmSeal = (key: AesKey, iv: u8[], aad: u8[], plaintext: u8[]): u
|
|
|
1215
1247
|
// is still an array length.
|
|
1216
1248
|
const h: u64[] = key.h
|
|
1217
1249
|
if (
|
|
1218
|
-
length >
|
|
1250
|
+
length > 2147483631 ||
|
|
1219
1251
|
toI32(h.length) !== 2 ||
|
|
1220
1252
|
!aesKeyUsable(key) ||
|
|
1221
1253
|
toI32(iv.length) === 0 ||
|
|
@@ -1231,10 +1263,11 @@ export const aesGcmSeal = (key: AesKey, iv: u8[], aad: u8[], plaintext: u8[]): u
|
|
|
1231
1263
|
aesGcmCtr(key, j0, plaintext, out, length)
|
|
1232
1264
|
const tag: u64[] = new Array<u64>(2)
|
|
1233
1265
|
aesGcmTag(tag, key, hHi, hLo, j0, aad, out, length)
|
|
1234
|
-
//
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1266
|
+
// Two words, as made above; tested where the bounds prover can see it.
|
|
1267
|
+
if (toI32(tag.length) > 1) {
|
|
1268
|
+
aesStore64(out, length, tag[0])
|
|
1269
|
+
aesStore64(out, length + 8, tag[1])
|
|
1270
|
+
}
|
|
1238
1271
|
wipe(j0)
|
|
1239
1272
|
return out
|
|
1240
1273
|
}
|
|
@@ -1277,14 +1310,17 @@ export const aesGcmOpen = (key: AesKey, iv: u8[], aad: u8[], sealed: u8[]): u8[]
|
|
|
1277
1310
|
const j0: u8[] = aesGcmJ0(key, hHi, hLo, iv)
|
|
1278
1311
|
const tag: u64[] = new Array<u64>(2)
|
|
1279
1312
|
aesGcmTag(tag, key, hHi, hLo, j0, aad, sealed, length)
|
|
1280
|
-
//
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1313
|
+
// Two words, as made above; tested where the bounds prover can see it, and
|
|
1314
|
+
// a tag it could not read matches nothing.
|
|
1315
|
+
let same: u64 = 0
|
|
1316
|
+
if (toI32(tag.length) > 1) {
|
|
1317
|
+
same = aesGcmTagMask(
|
|
1318
|
+
tag[0],
|
|
1319
|
+
tag[1],
|
|
1320
|
+
aesLoad64(sealed, length, total),
|
|
1321
|
+
aesLoad64(sealed, length + 8, total)
|
|
1322
|
+
)
|
|
1323
|
+
}
|
|
1288
1324
|
wipe(tag)
|
|
1289
1325
|
let out: u8[] | null = null
|
|
1290
1326
|
if ((same & hashKeySet) !== toU64(0)) {
|
|
@@ -222,6 +222,9 @@ const bcryptBatchLane = (share: BcryptBatchShare, list: i32[], n: i32, i: i32):
|
|
|
222
222
|
return null
|
|
223
223
|
}
|
|
224
224
|
const at: i32 = list[i]
|
|
225
|
+
if (at < 0 || at >= toI32(share.passwords.length)) {
|
|
226
|
+
return null
|
|
227
|
+
}
|
|
225
228
|
return share.passwords[at]
|
|
226
229
|
}
|
|
227
230
|
|
|
@@ -535,7 +538,9 @@ export class BcryptBatcher {
|
|
|
535
538
|
* @returns The count; 0 once `run` has handed out every answer.
|
|
536
539
|
*/
|
|
537
540
|
pending(): i32 {
|
|
538
|
-
|
|
541
|
+
// Summed as an `i64`, where three array lengths cannot overflow; the
|
|
542
|
+
// count itself is at most the two queues' lengths.
|
|
543
|
+
return toI32(toI64(this.kinds.length) - toI64(this.head) + toI64(this.early.length))
|
|
539
544
|
}
|
|
540
545
|
|
|
541
546
|
/**
|
|
@@ -625,8 +630,18 @@ export class BcryptBatcher {
|
|
|
625
630
|
if (queued >= this.width || head >= toI32(this.arrived.length)) {
|
|
626
631
|
return 0
|
|
627
632
|
}
|
|
628
|
-
|
|
629
|
-
|
|
633
|
+
// Both clocks are `monotonicNanos()` readings, never negative; a request
|
|
634
|
+
// that reads as arriving after `now` has waited no time.
|
|
635
|
+
const arrived: i64 = this.arrived[head]
|
|
636
|
+
const hold: i64 = this.holdNanos
|
|
637
|
+
if (now < 0 || arrived < 0 || hold <= 0) {
|
|
638
|
+
return 0
|
|
639
|
+
}
|
|
640
|
+
const waited: i64 = now - arrived
|
|
641
|
+
if (waited < 0) {
|
|
642
|
+
return hold
|
|
643
|
+
}
|
|
644
|
+
return waited >= hold ? 0 : hold - waited
|
|
630
645
|
}
|
|
631
646
|
|
|
632
647
|
/**
|
|
@@ -722,7 +737,11 @@ export class BcryptBatcher {
|
|
|
722
737
|
held.wipe()
|
|
723
738
|
}
|
|
724
739
|
}
|
|
725
|
-
|
|
740
|
+
// `taken` is at most what was queued past `head`, so this is at most the
|
|
741
|
+
// queue's length; summed as an `i64` and capped there for the prover.
|
|
742
|
+
const kinds: i32 = toI32(this.kinds.length)
|
|
743
|
+
const after: i64 = toI64(head) + toI64(taken)
|
|
744
|
+
this.head = after < toI64(kinds) ? toI32(after) : kinds
|
|
726
745
|
this.compact()
|
|
727
746
|
return answers
|
|
728
747
|
}
|