nish 0.50.0 → 0.51.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/docs/AI.md +4 -1
- package/package.json +5 -5
- package/runtime/nish.d.ts +82 -2
- package/runtime/nish.h +5 -0
- package/runtime/runtime-host.c +21 -5
- package/std/README.md +7 -7
- package/std/base64.ts +61 -95
- package/std/bytes.ts +6 -4
- package/std/cli-args.ts +150 -107
- package/std/compress/checksum.ts +68 -10
- package/std/compress/deflate.ts +193 -100
- package/std/compress/gzip.ts +124 -49
- package/std/compress/zlib.ts +57 -15
- package/std/crypto/aes.ts +51 -9
- package/std/crypto/ed25519.ts +12 -10
- package/std/crypto/hkdf.ts +405 -283
- package/std/crypto/hmac.ts +483 -148
- package/std/crypto/jwt.ts +19 -21
- package/std/crypto/p256.ts +5 -7
- package/std/crypto/pki-roots.ts +28 -8
- package/std/crypto/rsa-sign.ts +5 -2
- package/std/crypto/sha256.ts +81 -26
- package/std/crypto/sha512.ts +135 -49
- package/std/json-value.ts +14 -15
- package/std/net/buffer-pool.ts +25 -14
- package/std/net/fetch.ts +108 -27
- package/std/net/handler.ts +11 -22
- package/std/net/hpack.ts +38 -19
- package/std/net/http-compress.ts +21 -12
- package/std/net/http-server.ts +9 -4
- package/std/net/http1-client-codec.ts +22 -15
- package/std/net/http1-codec.ts +37 -36
- package/std/net/http3-server.ts +127 -45
- package/std/net/http3.ts +99 -50
- package/std/net/postgres-async.ts +5 -10
- package/std/net/qpack.ts +83 -17
- package/std/net/quic-listener.ts +42 -27
- package/std/net/quic-packet.ts +91 -50
- package/std/net/quic-stream.ts +29 -22
- package/std/net/quic.ts +48 -23
- package/std/net/static.ts +5 -3
- package/std/net/tls/client.ts +81 -34
- package/std/net/tls/codec.ts +3 -4
- package/std/net/tls/record.ts +54 -22
- package/std/net/tls/schedule.ts +339 -149
- package/std/net/tls.ts +42 -12
- package/std/net/upstream.ts +18 -19
- package/std/net/url.ts +78 -21
- package/std/net/websocket.ts +3 -11
- package/std/net/webtransport.ts +95 -21
- package/std/raster.ts +12 -2
- package/std/term-pixels.ts +18 -2
- package/std/text.ts +5 -5
package/docs/AI.md
CHANGED
|
@@ -2842,7 +2842,10 @@ link answers for itself), `geteuid()` (`i64`) and `isExecutableSync(path)`
|
|
|
2842
2842
|
**The host.** `Date.now()` (an `f64` of whole milliseconds, the wall clock —
|
|
2843
2843
|
**the only `Date` there is**: `new Date()`, `Date.parse` and the rest are
|
|
2844
2844
|
refused), `crypto.getRandomValues(bytes)` (a statement over a `u8[]` only, at
|
|
2845
|
-
most 65,536 bytes a call, from the kernel's CSPRNG; more panics
|
|
2845
|
+
most 65,536 bytes a call, from the kernel's CSPRNG; more panics, and so does a
|
|
2846
|
+
failing source), its twin `crypto.tryGetRandomValues(bytes)` (a `boolean`:
|
|
2847
|
+
`false` for more than 65,536 bytes or a failing source, never an exit, so it
|
|
2848
|
+
is the one a program built without `--allow-panics` calls),
|
|
2846
2849
|
`statMtimeSync(path)` (an `f64` of milliseconds, **NaN** — not `null` — when the
|
|
2847
2850
|
path cannot be stat'd, so test `m !== m`), and `signalFd()` / `readSignal(fd)`:
|
|
2848
2851
|
call `signalFd()` once at the top of `main`, then `readSignal(fd)` blocks until
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nish",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.51.0",
|
|
4
4
|
"description": "Nish: an ahead-of-time compiler from a static subset of TypeScript to LLVM IR",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -114,9 +114,9 @@
|
|
|
114
114
|
"typescript": "^6.0.3"
|
|
115
115
|
},
|
|
116
116
|
"optionalDependencies": {
|
|
117
|
-
"@amritk/nish-aarch64-darwin": "0.
|
|
118
|
-
"@amritk/nish-aarch64-linux": "0.
|
|
119
|
-
"@amritk/nish-x86_64-darwin": "0.
|
|
120
|
-
"@amritk/nish-x86_64-linux": "0.
|
|
117
|
+
"@amritk/nish-aarch64-darwin": "0.51.0",
|
|
118
|
+
"@amritk/nish-aarch64-linux": "0.51.0",
|
|
119
|
+
"@amritk/nish-x86_64-darwin": "0.51.0",
|
|
120
|
+
"@amritk/nish-x86_64-linux": "0.51.0"
|
|
121
121
|
}
|
|
122
122
|
}
|
package/runtime/nish.d.ts
CHANGED
|
@@ -737,6 +737,26 @@ declare function geteuid(): i64;
|
|
|
737
737
|
*/
|
|
738
738
|
declare function isExecutableSync(path: string): boolean;
|
|
739
739
|
|
|
740
|
+
// ---- Misuse (`nish:panic`) ---------------------------------------------------
|
|
741
|
+
//
|
|
742
|
+
// Declared as a global, as the `nish:unsafe` functions below are, so `tsc`
|
|
743
|
+
// reads a program that names it, but `nish` refuses a call that is not
|
|
744
|
+
// imported from `nish:panic`: the import is the module's visible opt-in. The
|
|
745
|
+
// refusal reads `` `misuse` is a `nish:panic` name and is used only through an
|
|
746
|
+
// import of it ``. A user function of the same name, with no import, is the
|
|
747
|
+
// user's.
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* `message` and a newline to stderr, then exit 1, as `panic` does: called
|
|
751
|
+
* only through an import of `nish:panic`, where it is an allowed `misuse`
|
|
752
|
+
* site in the no-panic scope (`--deny-misuse` refuses it). Statement
|
|
753
|
+
* position, and it terminates control flow. Capability: none.
|
|
754
|
+
*
|
|
755
|
+
* @param message what the caller got wrong; a string the program fixes.
|
|
756
|
+
* @returns never: the program ends.
|
|
757
|
+
*/
|
|
758
|
+
declare function misuse(message: string): never;
|
|
759
|
+
|
|
740
760
|
// ---- Unsafe (`nish:unsafe`) --------------------------------------------------
|
|
741
761
|
//
|
|
742
762
|
// Declared as globals so `tsc` reads a program that imports them, as every
|
|
@@ -2491,7 +2511,7 @@ interface DateConstructor {
|
|
|
2491
2511
|
now(): number;
|
|
2492
2512
|
}
|
|
2493
2513
|
|
|
2494
|
-
/** The system's random source, with its one member. */
|
|
2514
|
+
/** The system's random source, with its one member and that member's answering twin. */
|
|
2495
2515
|
declare var crypto: {
|
|
2496
2516
|
/**
|
|
2497
2517
|
* Every byte of `bytes` from the kernel's CSPRNG (`getrandom(2)` on Linux,
|
|
@@ -2507,7 +2527,7 @@ declare var crypto: {
|
|
|
2507
2527
|
* panic, `crypto.getRandomValues: <n> bytes asked for, and one call fills at
|
|
2508
2528
|
* most 65536`, exit 1. A source that fails is a panic too; nothing weaker is
|
|
2509
2529
|
* ever substituted. It is the source for a key. `crypto` has no other member
|
|
2510
|
-
* (NL2403, for example `crypto.randomUUID`). Refused at compile time on
|
|
2530
|
+
* but its twin `tryGetRandomValues` (NL2403, for example `crypto.randomUUID`). Refused at compile time on
|
|
2511
2531
|
* wasm32 and the WASI profile (NL2404). Under Node the prelude fills a plain
|
|
2512
2532
|
* `u8[]` too and panics past 65,536 with the same words; without the prelude
|
|
2513
2533
|
* it takes only a typed array. Capability: entropy.
|
|
@@ -2515,6 +2535,21 @@ declare var crypto: {
|
|
|
2515
2535
|
* @param bytes the buffer filled.
|
|
2516
2536
|
*/
|
|
2517
2537
|
getRandomValues(bytes: u8[]): void;
|
|
2538
|
+
/**
|
|
2539
|
+
* `getRandomValues`'s twin for code built without `--allow-panics`: the same
|
|
2540
|
+
* fill from the same source under the same rules (a `u8[]` only, written,
|
|
2541
|
+
* refused on wasm32 and the WASI profile, capability entropy), but where
|
|
2542
|
+
* `getRandomValues` exits it answers `false`: more than 65,536 bytes, or a
|
|
2543
|
+
* source that fails, which may leave a prefix of `bytes` written. Nothing
|
|
2544
|
+
* weaker is ever substituted. An expression, so a caller can turn the
|
|
2545
|
+
* `false` into its own `Result`; it is no panic site. `--emit-ts` writes it
|
|
2546
|
+
* as a length test and the runtime's fill; the Node prelude that runs a
|
|
2547
|
+
* source file as TypeScript does not define it.
|
|
2548
|
+
*
|
|
2549
|
+
* @param bytes the buffer filled.
|
|
2550
|
+
* @returns `true` when every byte of `bytes` was filled, `false` otherwise.
|
|
2551
|
+
*/
|
|
2552
|
+
tryGetRandomValues(bytes: u8[]): boolean;
|
|
2518
2553
|
};
|
|
2519
2554
|
|
|
2520
2555
|
// ---- The builtin modules (`nish:`) ---------------------------------------------
|
|
@@ -3713,6 +3748,51 @@ declare module "nish:net" {
|
|
|
3713
3748
|
export function netRingState(): i32;
|
|
3714
3749
|
}
|
|
3715
3750
|
|
|
3751
|
+
/**
|
|
3752
|
+
* A panic the author states can never happen in a fixed program: one call to
|
|
3753
|
+
* `misuse(message)` from a module that imports it.
|
|
3754
|
+
*
|
|
3755
|
+
* import { misuse } from "nish:panic";
|
|
3756
|
+
*
|
|
3757
|
+
* export const pick = (mode: i32): i32 => {
|
|
3758
|
+
* if (mode === 0) return 10;
|
|
3759
|
+
* if (mode === 1) return 20;
|
|
3760
|
+
* misuse("pick: mode is 0 or 1");
|
|
3761
|
+
* };
|
|
3762
|
+
*
|
|
3763
|
+
* It lowers exactly like `panic`: the same message and newline to stderr, the
|
|
3764
|
+
* same exit 1. The difference is only in the no-panic scope. A `misuse` call is
|
|
3765
|
+
* a `misuse` site, which the default rule allows, as it allows `oom` and
|
|
3766
|
+
* `unchecked`: `--emit-panics` lists it with `allowed: true`, and a caller in
|
|
3767
|
+
* the scope raises neither NL2457 nor NL2458 for it. `--deny-misuse` refuses it
|
|
3768
|
+
* again, as an ordinary unproven site.
|
|
3769
|
+
*
|
|
3770
|
+
* It is for a panic only a wrong program reaches: a caller that passes a value
|
|
3771
|
+
* its documentation rules out, with the value fixed in the caller's own code.
|
|
3772
|
+
* A panic that input can reach, from a file, the network, the terminal or an
|
|
3773
|
+
* argument, stays proven away or becomes a `Result`. The global spelling is
|
|
3774
|
+
* refused: `misuse` is called only through an import of `nish:panic`, so each
|
|
3775
|
+
* module that uses it says so at its top.
|
|
3776
|
+
*
|
|
3777
|
+
* **Under Node.** `--emit-ts` writes the import as the runtime's `panic`, so the
|
|
3778
|
+
* emitted program ends the same way. `runtime/nish.mjs` does not answer
|
|
3779
|
+
* `nish:panic` yet, so a `.ts` file run directly under Node cannot import it.
|
|
3780
|
+
*
|
|
3781
|
+
* Rules: https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#nishpanic-a-panic-for-misuse
|
|
3782
|
+
*/
|
|
3783
|
+
declare module "nish:panic" {
|
|
3784
|
+
/**
|
|
3785
|
+
* `message` and a newline to stderr, then exit 1, as `panic` does, recorded
|
|
3786
|
+
* as an allowed `misuse` site rather than an unproven one. Statement
|
|
3787
|
+
* position, and it terminates control flow, so it is `never`. Capability:
|
|
3788
|
+
* none.
|
|
3789
|
+
*
|
|
3790
|
+
* @param message what the caller got wrong; a string the program fixes.
|
|
3791
|
+
* @returns never: the program ends.
|
|
3792
|
+
*/
|
|
3793
|
+
export function misuse(message: string): never;
|
|
3794
|
+
}
|
|
3795
|
+
|
|
3716
3796
|
/**
|
|
3717
3797
|
* Element access with no bounds check, signed arithmetic that wraps, a C
|
|
3718
3798
|
* string or struct read through a pointer nothing proves, and the errno a C
|
package/runtime/nish.h
CHANGED
|
@@ -781,6 +781,11 @@ double nish_date_now(void);
|
|
|
781
781
|
* bytes, the Web API's limit for one call, and a failing entropy source both
|
|
782
782
|
* print a message and exit 1; nothing weaker is ever substituted. */
|
|
783
783
|
void nish_random_fill(nish_array *bytes);
|
|
784
|
+
/* `crypto.tryGetRandomValues(bytes)`: the same fill from the same source, but
|
|
785
|
+
* where `nish_random_fill` exits it answers false (more than 65,536 bytes, or
|
|
786
|
+
* a failing source, which may leave a prefix written); true when every byte
|
|
787
|
+
* was filled. It never exits. */
|
|
788
|
+
bool nish_random_try_fill(nish_array *bytes);
|
|
784
789
|
/* `statMtimeSync(path)`: the modification time in milliseconds with its
|
|
785
790
|
* sub-millisecond fraction, computed as Node's `mtimeMs` is, or NaN when
|
|
786
791
|
* `stat` fails. Follows a symbolic link. */
|
package/runtime/runtime-host.c
CHANGED
|
@@ -73,25 +73,41 @@ static NISH_COLD void nish_entropy_fail(uint64_t asked) {
|
|
|
73
73
|
API's limit of 65,536 bytes a call is kept, so a program behaves the same
|
|
74
74
|
under Node. `getrandom` without flags blocks only until the pool is first
|
|
75
75
|
initialised at boot and can return short or be interrupted, so it loops;
|
|
76
|
-
`getentropy` fills at most 256 bytes a call and retries nothing itself.
|
|
77
|
-
|
|
76
|
+
`getentropy` fills at most 256 bytes a call and retries nothing itself.
|
|
77
|
+
The fill both builtins share: true when every byte of `bytes` came from the
|
|
78
|
+
source, false past the limit or when the source fails, which may leave a
|
|
79
|
+
prefix written. */
|
|
80
|
+
static bool nish_random_draw(nish_array *bytes) {
|
|
78
81
|
uint64_t n = bytes->len;
|
|
79
82
|
char *p = bytes->data;
|
|
80
|
-
if (n > 65536)
|
|
83
|
+
if (n > 65536) return false;
|
|
81
84
|
while (n > 0) {
|
|
82
85
|
#if defined(__linux__)
|
|
83
86
|
ssize_t got = getrandom(p, n, 0);
|
|
84
87
|
if (got < 0) {
|
|
85
88
|
if (errno == EINTR) continue;
|
|
86
|
-
|
|
89
|
+
return false;
|
|
87
90
|
}
|
|
88
91
|
#else
|
|
89
92
|
size_t got = n < 256 ? n : 256;
|
|
90
|
-
if (getentropy(p, got) != 0)
|
|
93
|
+
if (getentropy(p, got) != 0) return false;
|
|
91
94
|
#endif
|
|
92
95
|
p += got;
|
|
93
96
|
n -= (uint64_t)got;
|
|
94
97
|
}
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
void nish_random_fill(nish_array *bytes) {
|
|
102
|
+
if (!nish_random_draw(bytes)) nish_entropy_fail(bytes->len);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/* `crypto.tryGetRandomValues(bytes)`: the same fill, answering whether it
|
|
106
|
+
happened instead of exiting, so a program built without `--allow-panics`
|
|
107
|
+
can turn a failing source into its own error. Nothing weaker is tried
|
|
108
|
+
either: on false the bytes are not a key and the caller is told so. */
|
|
109
|
+
bool nish_random_try_fill(nish_array *bytes) {
|
|
110
|
+
return nish_random_draw(bytes);
|
|
95
111
|
}
|
|
96
112
|
|
|
97
113
|
/* `statMtimeSync(path)`: the modification time in milliseconds, with the
|
package/std/README.md
CHANGED
|
@@ -34,11 +34,11 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
34
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
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
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
|
-
| [`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
|
|
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 (`null` past 1,610,612,733 bytes), `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array, or an encoding that does not fit, answers -1 before a byte is written, as does `base64EncodeIfFits(src, off, len, dst, at)`. 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_if_fits`, `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
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
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
|
-
| [`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
|
|
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. A declaration mistake panics nowhere: a call that answers a handle answers `NO_HANDLE`, the first mistake is kept for `declarationError()`, and `parse` then answers `PARSE_ERROR` with exit code 2 and the mistake as its message. `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
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)) |
|
|
@@ -243,7 +243,7 @@ reads one, and it still takes its randomness as an argument.
|
|
|
243
243
|
| [`net/quic-conn-ack.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-conn-ack.ts) | `QuicAckRanges`: the packet numbers one space received, as at most 32 disjoint ranges, for duplicate detection (`record`, `contains`) and for the ACK frame written from them (`pushAck`, or `putAck` in place). Past 32 ranges the lowest is dropped and a floor raised over it, below which every packet number reads as already received | RFC 9000 §12.3, §13.2, §19.3 |
|
|
244
244
|
| [`net/quic-conn-cid.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-conn-cid.ts) | `QuicCidTable`: the connection IDs a connection issued (routed by `ownsLocal`, retired by the peer with `retireLocal`) and the ones its peer issued (`addPeer`, with Retire Prior To retiring older ones into `retirePending`, and `currentPeer` the one sent to). A reused sequence number, an ID under two sequence numbers and retiring the ID a packet was sent to are PROTOCOL_VIOLATION; more active IDs than advertised, or more owed retirements than twice that, CONNECTION_ID_LIMIT_ERROR. Its slots are fixed when it is made: an ID is copied into one, `addPeerAt` / `ownsLocalAt` / `retireLocal` read it from the packet in place, and `reset` empties the table for the next connection | RFC 9000 §5.1, §19.15, §19.16 |
|
|
245
245
|
| [`net/quic.ts`](https://github.com/amritk/nish/blob/main/std/net/quic.ts) | The server side of a QUIC connection: `new QuicConnection(config, entropy)`, `receive(datagram, now)`, `signatureInput()` / `sign(signature)`, `takeDatagram(now)` until `null`, `deadline()` / `handleTimer(now)` for its timers, and `readStream()` / `writeStream(id, data, fin)` once connected; `updateKeys()`, `close(code)` and `release()`; `acceptRetry(originalDcid, retryScid)` for a connection a Retry token opened; `quicStatelessResetToken(key, cid)`. TLS 1.3 runs over CRYPTO frames at the Initial, Handshake and 1-RTT levels (`TlsServer` with `quic` set), the keys of each level come from `nish/net/quic-packet` as the secrets appear and are discarded and wiped as RFC 9001 §4.9 says, transport parameters go both ways and the client's are checked, every ack-eliciting packet is acknowledged in its space, the client gets new connection IDs once the handshake is confirmed, PATH_CHALLENGE is answered, and an ack-eliciting Initial is padded to 1200 bytes and held to three times what the unvalidated client sent. A protocol violation closes the connection with the RFC's transport error, a TLS alert with CRYPTO_ERROR; a packet that cannot be used is dropped and counted. The idle timeout is the smaller of both sides' `max_idle_timeout`, at least three probe timeouts, and closes silently; key update runs both ways, the client's followed (at most `QUIC_CONN_MAX_KEY_UPDATES`, QUIC-4) and the server's started by `updateKeys()`, with the next read keys derived in advance and the previous kept a probe timeout for reordered packets; every connection ID carries the stateless reset token the configuration's static key gives it. Loss recovery is `nish/net/quic-recovery`'s: what a lost packet carried (CRYPTO, STREAM, HANDSHAKE_DONE and the connection-ID frames) is sent again, a probe timeout sends a probe (two datagrams in the Initial and Handshake spaces, `QUIC_CONN_HANDSHAKE_PROBES`, each with the oldest CRYPTO data not acknowledged), a client that shows it lacks the handshake flight (an Initial repeating CRYPTO data, an ack-eliciting Handshake packet) gets it again at once, up to `QUIC_CONN_EARLY_RESENDS` times a connection (QUIC-8), and NewReno's window holds back everything but ACKs and probes. Streams are `nish/net/quic-stream`'s, both ways and both kinds, through `nextStreamEvent()`, `openStream(bidirectional)`, `streamRead(id, buf, at, length)`, `streamWrite(id, buf, from, length, fin)`, `streamReset(id, code)` and `streamStopSending(id, code)`; RFC 9221's datagrams through `sendDatagram(buf, from, length)`, `readDatagram(buf, at, cap)` and `maxDatagramPayload()` when `config.maxDatagramFrameSize` offers them. Nothing is allocated per packet (QUIC-3): `receiveWindow(buf, off, len, now)` and `takeDatagramInto(out, at, now)` open and build packets in place inside an arena block, and `reset(entropy)` makes the connection a reusable slot for the next client. The AEAD limits of RFC 9001 §6.6 are kept: a 1-RTT write key under AES-GCM seals at most 2^23 packets, the server starting a key update at three quarters of that and closing with AEAD_LIMIT_REACHED at it if none can be made, and packets that fail to authenticate past the integrity limit (2^52 for AES-GCM, 2^36 for ChaCha20-Poly1305) close the connection the same way (QUIC-6). One Application Data packet number in every 128 to 1024 is skipped, and an ACK of a skipped one is PROTOCOL_VIOLATION, an optimistic ACK (RFC 9000 §21.4, QUIC-7) | RFC 9000 §10.1, §10.3.2, §21.4; RFC 9001 §4, §5.7, §6, §8; RFC 9221; a handshake and stream echo, and an update each way, against aioquic, recorded and replayed byte for byte |
|
|
246
|
-
| [`net/quic-listener.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-listener.ts) | What a QUIC server answers to a datagram no connection owns: `new QuicListener(config, entropy)` and `handleWindow(buf, at, len, address, now, answer)`, which reads the datagram `buf[at .. at + len)` in place and fills `answer`, a `QuicListenerAnswer` made once with `QUIC_LISTENER_ANSWER_SIZE` of room and refilled in it, so a datagram costs no arena memory whatever it is answered with (H3-3); `handle(datagram, address, now)` does the same over a whole array into an answer of its own. An answer's `kind` is `QUIC_LISTEN_DROP`, `_ACCEPT` (make a `QuicConnection`; after a Retry, `acceptRetry` it with the answer's IDs), or a `reply` to send: `_VERSION_NEGOTIATION` for another version in a full-sized datagram, `_RETRY` with an address-validation token when `config.retry` is set, `_INVALID_TOKEN` for a Retry token that is forged, moved, expired or for another ID, and `_STATELESS_RESET` for a short header to an ID the server has no connection for. A token is 128 bits of HMAC-SHA256 under `config.retryTokenKey` over its issue time, the original DCID, the new ID and the client's address and port, good for `config.retryTokenLifetime`. A reset ends in `quicStatelessResetToken` of the packet's ID, is always shorter than the datagram it answers and never under 21 bytes, and is rate limited. Its own unpredictable bytes come from an HMAC generator seeded once by the caller. `release()` wipes the seed, the generator, the scratch, the INVALID_TOKEN keys and the spare answer `handle` keeps, and `handle` and `handleWindow` answer nothing after it; its other methods still run, under the zeroed seed, and are the caller's not to call (QUIC-5). For the carrier's send loop, `quicListenerTakePaced(conn, now)` takes a connection's next datagram only when its pacer has the credit, and `quicListenerPaceTime(conn, now)` says when it will; `quicListenerTakeFlight(conn, now, buf, at, cap, flight)` writes a paced flight back to back for one GSO send, with the `UDP_SEGMENT` size in its `QuicFlight`, and `quicListenerReceiveSegments` hands a connection a GRO receive segment by segment, in place | RFC 9002 §7.7; RFC 9000 §5.2.2, §6, §8.1, §10.3, §17.2.1, §17.2.5; Version Negotiation, Retry, a stateless reset and the idle timeout against aioquic, recorded and replayed byte for byte |
|
|
246
|
+
| [`net/quic-listener.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-listener.ts) | What a QUIC server answers to a datagram no connection owns: `new QuicListener(config, entropy)` and `handleWindow(buf, at, len, address, now, answer)`, which reads the datagram `buf[at .. at + len)` in place (a window outside `buf` is dropped unread) and fills `answer`, a `QuicListenerAnswer` made once with `QUIC_LISTENER_ANSWER_SIZE` of room and refilled in it, so a datagram costs no arena memory whatever it is answered with (H3-3); `handle(datagram, address, now)` does the same over a whole array into an answer of its own. An answer's `kind` is `QUIC_LISTEN_DROP`, `_ACCEPT` (make a `QuicConnection`; after a Retry, `acceptRetry` it with the answer's IDs), or a `reply` to send: `_VERSION_NEGOTIATION` for another version in a full-sized datagram, `_RETRY` with an address-validation token when `config.retry` is set, `_INVALID_TOKEN` for a Retry token that is forged, moved, expired or for another ID, and `_STATELESS_RESET` for a short header to an ID the server has no connection for. A token is 128 bits of HMAC-SHA256 under `config.retryTokenKey` over its issue time, the original DCID, the new ID and the client's address and port, good for `config.retryTokenLifetime`. A reset ends in `quicStatelessResetToken` of the packet's ID, is always shorter than the datagram it answers and never under 21 bytes, and is rate limited. Its own unpredictable bytes come from an HMAC generator seeded once by the caller. `release()` wipes the seed, the generator, the scratch, the INVALID_TOKEN keys and the spare answer `handle` keeps, and `handle` and `handleWindow` answer nothing after it; its other methods still run, under the zeroed seed, and are the caller's not to call (QUIC-5). For the carrier's send loop, `quicListenerTakePaced(conn, now)` takes a connection's next datagram only when its pacer has the credit, and `quicListenerPaceTime(conn, now)` says when it will; `quicListenerTakeFlight(conn, now, buf, at, cap, flight)` writes a paced flight back to back for one GSO send, with the `UDP_SEGMENT` size in its `QuicFlight`, and `quicListenerReceiveSegments` hands a connection a GRO receive segment by segment, in place | RFC 9002 §7.7; RFC 9000 §5.2.2, §6, §8.1, §10.3, §17.2.1, §17.2.5; Version Negotiation, Retry, a stateless reset and the idle timeout against aioquic, recorded and replayed byte for byte |
|
|
247
247
|
| [`net/quic-recovery.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-recovery.ts) | QUIC loss detection and congestion control, sans-IO, for the server side: `QuicRecovery` holds one `QuicSentPackets` ring per packet number space (16 packets for Initial and Handshake, 128 for Application Data, fixed when it is made); `onPacketSent(space, pn, size, now)` records an ack-eliciting packet and answers its slot, `onAck(space, ranges, count, ackDelay, now)` reads an ACK frame's ranges and lists the slots it acknowledged and showed lost (`acked`, `lost`), `deadline(amplificationBlocked)` and `onTimeout(now, amplificationBlocked)` run the time-threshold loss timer and the probe timeout with its backoff, `discardSpace` drops a space whose keys are gone, `evictOldest` frees a slot for a probe. The RTT estimate (`latestRtt`, `smoothedRtt`, `rttVar`, `minRtt`, `probeTimeout()`), loss by packet threshold 3 and time threshold 9/8, NewReno (slow start, one halving per recovery period, congestion avoidance, the 2400-byte floor, persistent congestion) and a pacer at 5/4 of the window per smoothed RTT (`pacerDelay`, `onPaced`), all in integer milliseconds and bytes | RFC 9002 §5–7, Appendices A and B, worked by hand in `net_quic_recovery` |
|
|
248
248
|
| [`net/quic-stream.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-stream.ts) | QUIC streams, sans-IO, which `nish/net/quic` drives: `QuicStreams` holds one `QuicStream` slot per stream that may be open at once (the client's bidirectional and unidirectional limits and the server's own), each with a fixed receive and send buffer, found by ID through a hash index. The send and receive state machines of §3 (`QUIC_SEND_*`, `QUIC_RECV_*`), reassembly into the receive buffer, flow control per stream and for the connection both ways (MAX_STREAM_DATA and MAX_DATA raised as the application reads, STREAM_DATA_BLOCKED and DATA_BLOCKED once per limit), the stream limits (MAX_STREAMS raised as the client's streams finish, STREAMS_BLOCKED at the client's), STOP_SENDING answered with RESET_STREAM, and the refusals STREAM_STATE_ERROR, STREAM_LIMIT_ERROR, FLOW_CONTROL_ERROR and FINAL_SIZE_ERROR. The application's answers are `QUIC_STREAM_OK`, `QUIC_STREAM_END` and `QUIC_STREAM_ERR_*` | RFC 9000 §2–§4, §19.4–§19.14 |
|
|
249
249
|
| [`net/quic-datagram.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-datagram.ts) | `QuicDatagramQueue`: a fixed ring of DATAGRAM payloads, one each way per connection, copied in (`push`) and out (`pop`, or `putFrame` as a DATAGRAM frame), refusing past a full ring and counting what it drops | RFC 9221 §5 |
|
|
@@ -253,7 +253,7 @@ reads one, and it still takes its randomness as an argument.
|
|
|
253
253
|
| [`net/dns-resolver.ts`](https://github.com/amritk/nish/blob/main/std/net/dns-resolver.ts) | The DNS stub resolver with no I/O of its own: `DnsResolver(config, hosts, maxLookups)` takes `start(name, port, now)` and answers a lookup's index, or `DNS_RESOLVE_BUSY` past `maxLookups` (at most 64). Each lookup asks A and AAAA at once; the caller sends what `nextOutgoing(out, to, meta, id)` gives (a datagram, a TCP connection or a close, with the caller's random ID), feeds what comes back to `receive` or `receiveStream`, calls `tick(now)` once `nextDeadlineNanos()` passes, and reads `result(lookup, out, ttls)`: the count of 18-byte addresses, A first, each with its TTL, or `DNS_RESOLVE_PENDING`, `NOT_FOUND`, `NO_ANSWER` or `CNAME`. Servers are tried in turn for `attempts` rounds of `timeout`; TC asks again over TCP (a reply over `DNS_TCP_MAX_REPLY`, 16 KiB, fails the server); a CNAME left unanswered is followed by a query of its own, at most 8 hops and never back to the start; the search list and `ndots` run as resolv.conf(5) says. `localhost`, an address literal and a hosts entry answer with no packet. A reply from another address or port, or with another ID or question, is dropped, counted (`droppedSource`, `droppedId`, `droppedQuestion`, `droppedMalformed`) and the query keeps waiting. It never imports `nish:net`, reads a clock or a file, and builds for `wasm32`; every buffer is made in the constructor | RFC 1035 §4.2 and §7.3; RFC 5452 (forgery resilience); RFC 7766 (DNS over TCP); resolv.conf(5); scripted packets for every drop, bound and error path (`tests/link/std_dns_resolver`) |
|
|
254
254
|
| [`net/dns.ts`](https://github.com/amritk/nish/blob/main/std/net/dns.ts) | `nish/net/dns-resolver` on `nish:net` sockets, on the caller's loop: `DnsClient(resolver, loop, tokenBase)` opens a new UDP socket on a kernel-chosen port for each try, or a TCP connection for a TCP one, under a token of its range (`owns`), draws each query ID from `crypto.getRandomValues`, and never waits: the program's `pollWait` hands it `ready(token, events, now)`, calls `tick(now)` and waits no longer than `timeoutMs(now, own)`. `resolveHost(name, timeoutMs, port, out, ttls)` reads `/etc/resolv.conf` and `/etc/hosts` and blocks on a loop of its own, for a CLI or start-up; `dnsLookupWith` does the same with a configuration given. | A Nish DNS server on loopback: UDP, TCP, TC, CNAME, the search list, a dead server, `attempts`, the hosts file and spoofed replies (`tests/link/std_dns`); the capability report (`std_dns_caps`); a flat arena over 2,000 lookups (`std_dns_soak`) |
|
|
255
255
|
| [`net/hpack.ts`](https://github.com/amritk/nish/blob/main/std/net/hpack.ts) | HPACK, HTTP/2's header compression: `HpackEncoder` and `HpackDecoder`, one per direction of a connection, each with its `HpackTable`; and beneath them the §5.1 integer (`hpackEncodeInteger` / `hpackDecodeInteger`), the §5.2 string (`hpackEncodeString` / `hpackDecodeString`) and Appendix B's Huffman code (`HpackHuffman`, `hpackHuffmanEncode`, `hpackHuffmanDecode`, `hpackHuffmanLength`). Names and values are `u8[]`. The encoder takes the representation and the Huffman choice per field, and sends a never-indexed field as a literal even when a table holds it. The decoder answers a negative `HPACK_ERR_*` code, and stays spent, for a truncated block, an integer past 2^31 - 1, an index of zero or out of range, bad Huffman padding, EOS, a size update above the SETTINGS limit, after a field or missing when a lowered limit requires one, and for a block that would copy more than `HPACK_COPY_FACTOR` times the larger of the table's size and the block's length into and out of the table (`HPACK_ERR_COPY_BUDGET`; `tableCopied` counts those octets); a header list past the caller's limit is decoded to the end, its excess dropped, and answered with `HPACK_LIST_TOO_LARGE`, which is not fatal. A window outside its buffer, a negative size or limit, and an integer prefix outside 1 to 8 bits are the program's mistakes and panic | RFC 7541 Appendix C (C.1–C.6, with the dynamic table after every step) and every code of Appendix B |
|
|
256
|
-
| [`net/qpack.ts`](https://github.com/amritk/nish/blob/main/std/net/qpack.ts) | QPACK, HTTP/3's field compression, with a dynamic table of capacity 0: `QpackEncoder` and `QpackDecoder`, one per connection. The encoder writes a field section that starts `00 00` (Required Insert Count 0, Base 0) with `beginSection`, then one field line per `encodeField(out, name, off, len, value, off, len, neverIndexed, huffman)`: an Indexed Field Line when the 99-entry static table holds the field, else a literal with the name by static index when it can, each string Huffman-coded when that is shorter and `huffman` is set, and a never-indexed field always a literal with the N bit. The decoder answers a section's fields as windows into its own `bytes` (`nameStart`, `nameLength`, `valueStart`, `valueLength`, `neverIndexed`, `count`), its arrays reused from section to section. It answers QPACK_DECOMPRESSION_FAILED, and stays spent, for a truncated section, an integer past 2^62 − 1, a non-zero Required Insert Count, a negative Base, any dynamic-table reference, a static index past 98 and bad Huffman; a section past `maxFieldSectionSize` answers `QPACK_SECTION_TOO_LARGE`, which is not fatal. `receiveEncoderStream` accepts Set Dynamic Table Capacity 0 and answers QPACK_ENCODER_STREAM_ERROR for any other capacity, Insert or Duplicate; the encoder's `receiveDecoderStream` accepts Stream Cancellations, split anywhere, and answers QPACK_DECODER_STREAM_ERROR for a Section Acknowledgment or Insert Count Increment; `reason` names the rule. `qpackPushStreamCancellation` is the one instruction it may send. The Huffman code is `nish/net/hpack`'s. A window outside its buffer
|
|
256
|
+
| [`net/qpack.ts`](https://github.com/amritk/nish/blob/main/std/net/qpack.ts) | QPACK, HTTP/3's field compression, with a dynamic table of capacity 0: `QpackEncoder` and `QpackDecoder`, one per connection. The encoder writes a field section that starts `00 00` (Required Insert Count 0, Base 0) with `beginSection`, then one field line per `encodeField(out, name, off, len, value, off, len, neverIndexed, huffman)`: an Indexed Field Line when the 99-entry static table holds the field, else a literal with the name by static index when it can, each string Huffman-coded when that is shorter and `huffman` is set, and a never-indexed field always a literal with the N bit. The decoder answers a section's fields as windows into its own `bytes` (`nameStart`, `nameLength`, `valueStart`, `valueLength`, `neverIndexed`, `count`), its arrays reused from section to section. It answers QPACK_DECOMPRESSION_FAILED, and stays spent, for a truncated section, an integer past 2^62 − 1, a non-zero Required Insert Count, a negative Base, any dynamic-table reference, a static index past 98 and bad Huffman; a section past `maxFieldSectionSize` answers `QPACK_SECTION_TOO_LARGE`, which is not fatal. `receiveEncoderStream` accepts Set Dynamic Table Capacity 0 and answers QPACK_ENCODER_STREAM_ERROR for any other capacity, Insert or Duplicate; the encoder's `receiveDecoderStream` accepts Stream Cancellations, split anywhere, and answers QPACK_DECODER_STREAM_ERROR for a Section Acknowledgment or Insert Count Increment; `reason` names the rule. `qpackPushStreamCancellation` is the one instruction it may send. The Huffman code is `nish/net/hpack`'s. A window outside its buffer and a stream ID outside 0 to 2^62 − 1 panic; a decoder made with a negative field-section limit refuses every section with `QPACK_REASON_LIMIT` | RFC 9204 Appendix B.1, every Appendix A entry by its index, B.2 to B.5's instructions refused, and a request matched byte for byte with pylsqpack's encoding |
|
|
257
257
|
| [`net/http1-codec.ts`](https://github.com/amritk/nish/blob/main/std/net/http1-codec.ts) | `Http1Parser`, an incremental HTTP/1.1 request parser: `feed(buf, off, len)` any slice, then `next()` answers `HTTP1_NEED_MORE`, `HTTP1_HEAD` (`method`, `target`, `minor`, lowercased `names` beside `values`, `header(name)`, `contentLength` or `chunked`, `keepAlive`, `upgrade`), `HTTP1_BODY` (a window onto its buffer, de-chunked), `HTTP1_END`, or one of three final events: `HTTP1_UPGRADE` (`upgradeBytes()` and `declineUpgrade()`), `HTTP1_CLOSED` and `HTTP1_ERROR` with the `status` to answer. It refuses with 400 every request-smuggling shape — `Content-Length` with `Transfer-Encoding`, a repeated or non-digit `Content-Length`, an obs-fold, a bare LF, whitespace before a colon, a malformed chunk size or terminator — and with 413, 414, 431, 501 and 505 what those mean. The head is also kept as spans in a buffer reused from request to request (`head`, `spans`, `methodIs`, `targetIs`, `headerIndex`, `headerIs`, `upgradeIs`), so a parser with `keepText` off allocates nothing per request; `maxChunk` caps each `HTTP1_BODY`, and `restart()` readies it for the next connection. The writer is `http1ResponseHead(status, reason, names, values, bodyLength)`, which adds the framing field itself and refuses (`null`) a CR, LF or other control character anywhere a caller's string lands, and `http1Chunk` and `http1LastChunk` for a chunked body; `http1WriteResponseHead` and `http1WriteChunk` write the same bytes into a caller's buffer at an offset, answering `HTTP1_NO_ROOM` or `HTTP1_REFUSED`, and the first takes a date's bytes to send as a `Date` field on a final response, unless the caller's fields hold one | RFC 9112 §2–§7 and §9.3, RFC 9110 §5, §6.2, §7.2 and §7.8; a corpus fed at every split point (`tests/link/net_http1`) |
|
|
258
258
|
| [`net/http1-client-codec.ts`](https://github.com/amritk/nish/blob/main/std/net/http1-client-codec.ts) | The client side of HTTP/1.1, sans-IO. The writer is `http1RequestHead(method, target, names, values, bodyLength)`, `Host` first and the framing field added for `bodyLength` (`Content-Length`, `HTTP1_CHUNKED` or `HTTP1_NO_BODY`), and `http1WriteRequestHead` into a caller's buffer, answering `HTTP1_NO_ROOM` or `HTTP1_REFUSED` with nothing written; it refuses a method that is not a token, a target that is not a form the method may send, a CR, LF or control byte in a value, not exactly one `Host`, the caller's own framing fields and a `Connection: upgrade`; `http1UpgradeRequestHead(method, target, names, values, upgrade)` writes `Upgrade` and `Connection: Upgrade` itself, with no body. `Http1ResponseParser(maxStatusLine, maxHeaderBytes, maxHeaders, maxBody, maxTrailerBytes)` is told what was asked (`expect(head, connect)`, then `expectUpgrade()` for a request that asked to switch protocols), fed any slice, and `next()` answers `HTTP1_INFORMATIONAL`, `HTTP1_HEAD` (`status`, `reason`, `minor`, lowercased `names` beside `values`, `header(name)`, `contentLength`), `HTTP1_BODY` (a window, de-chunked), `HTTP1_END` with `keepAlive()`, or the final `HTTP1_UPGRADE` (a 2xx to CONNECT or a 101 asked for, `tunnelBytes()`), `HTTP1_CLOSED` and `HTTP1_ERROR`; `finish()` reports the close that ends a body read until close, and anywhere else is `HTTP1_E_TRUNCATED`. Every smuggling shape is refused with its own `HTTP1_E_*` code, as is a 101 not asked for, more than `HTTP1_MAX_INFORMATIONAL` interim responses and a chunk-size line over `HTTP1_MAX_CHUNK_LINE`. Record: [`docs/security/http1-client-codec.md`](../docs/security/http1-client-codec.md) | RFC 9112 §4–§7 and §9.3, RFC 9110 §9.3.6 and §15.2; a corpus fed whole, cut at every byte and a byte at a time, every refusal and limit at its edge, and the server parser reading what the writer writes (`tests/link/net_http1_client`, `_f64`, `_feed_window`) |
|
|
259
259
|
| [`net/fetch.ts`](https://github.com/amritk/nish/blob/main/std/net/fetch.ts) | A blocking HTTP/1.1 client for command-line programs: `fetchSync(request, options)` looks the host up, connects, sends an `HttpRequest` (`method`, `url`, `header(name, value)`, `body`) and answers an `HttpResponse` (`status`, `reason`, `url`, `header(name)`) once its head is in, its body read through `body.read` or `body.readAll(limit)`; null on a failure. `FetchSyncClient(options)` does the same and keeps one connection alive between fetches, sending an idempotent request once more when a kept connection turns out to be gone, and says why a fetch failed in `error` (an `HTTP_E_*` code, `httpErrorName`) and `errorText`. `HttpOptions` bounds every wait (`connectTimeoutMs`, `readTimeoutMs`, `totalTimeoutMs`) and every body (`maxBodyBytes`), follows redirects only when asked (`followRedirects`, `maxRedirects`, `crossOriginRedirects`, never https to http, credentials dropped across origins), and reads `http_proxy`, `https_proxy` and `no_proxy` when `useEnvProxy` is set (`HTTP_PROXY` ignored under CGI; https through `CONNECT`). Every byte goes through `nish/net/http1-client-codec`. Native only. Record: [`docs/security/fetch.md`](../docs/security/fetch.md) | RFC 9110 §9.2.2 and §15.4, RFC 9112; a loopback server and proxy in the test itself: keep-alive, retries, redirects, proxies, timeouts and body caps (`tests/link/net_http_fetch`) |
|
|
@@ -269,9 +269,9 @@ reads one, and it still takes its randomness as an argument.
|
|
|
269
269
|
| [`net/http2-tls.ts`](https://github.com/amritk/nish/blob/main/std/net/http2-tls.ts) | `Http2TlsServer`: HTTP/2 over `nish/net/tls-tcp` for a program that owns its loop — a pool of `Http2Connection`s beside the TLS slots, slot 0's built by the constructor and every other on the first accept into its slot, each reused with `restart`; `accept`, `readable` / `writable`, `signP256`, `next(slot)` for the slot's next event, `flush(slot)`, `close`. A slot whose ALPN did not choose `h2` is shut down with `close_notify` (RFC 9113 §3.2). Every slot's final responses carry the pool's one `HttpDate` (`date`, from `nish/net/http1-server`), refreshed at `connection(slot)` and `next(slot)` and formatted at most once a second; `date.pin(unixMs)` fixes it for a test. Native only, as `nish:net` is | A Nish TLS client over loopback (`tests/link/net_http2_tls`): ALPN, a GET, an echoed POST, a hundred DATA frames with the arena flat, the date with the arena flat while the pinned clock crosses seconds and shared by two slots, GOAWAY, and the pool; `curl --http2` against its `serve` mode |
|
|
270
270
|
| [`net/http2-cleartext.ts`](https://github.com/amritk/nish/blob/main/std/net/http2-cleartext.ts) | `Http2CleartextServer`: HTTP/2 over plain TCP with prior knowledge (h2c), a pool of `Http2Connection`s, one per accepted socket, for a program that owns its readiness loop — `nish/net/http2-tls`'s loop with a TCP socket in place of TLS, the same method names and interest bits (`H2C_WANT_READ`, `H2C_WANT_WRITE`, `H2C_DONE`), plus `expire(now)` for the preface deadline. Each slot checks the 24-byte preface byte by byte as it arrives and closes the socket, sending nothing, at the first byte that differs; until the preface is whole a slot holds no connection buffer. No `Upgrade: h2c` and no HTTP/1.1 fallback on the same port. No confidentiality and no integrity: serve it only behind a TLS-terminating proxy, on loopback or on a private network ([`docs/security/http2-cleartext.md`](../docs/security/http2-cleartext.md)) | RFC 9113 §3.3 (`tests/link/net_http2_cleartext`, and a refused configuration in `net_http2_cleartext_bad_slots` and `net_http2_cleartext_bad_timeout`) |
|
|
271
271
|
| [`net/http3-frame.ts`](https://github.com/amritk/nish/blob/main/std/net/http3-frame.ts) | HTTP/3's frames and stream types, sans-IO and allocation-free: `h3ReadFrameHeader` reads a type and a length (0 until both are in the window), `h3ReadSettings` a SETTINGS payload into a reused `Http3Settings` (the three identifiers it understands, and the first eight it does not, kept for an extension), `h3ReadIdPayload` a GOAWAY, MAX_PUSH_ID or CANCEL_PUSH; `h3PutFrameHeader`, `h3PutSettings`, `h3PutIdFrame` and `h3PutVarint` write in place. `h3ReservedHttp2Frame` names HTTP/2's reserved types, `h3Greased` the `0x1f * N + 0x21` ones, and the `H3_*` constants are RFC 9114's types, settings and error codes | RFC 9114 §6.2, §7, §8.1, against frames built by hand from §7's layouts (`tests/link/net_http3_frame`) |
|
|
272
|
-
| [`net/http3.ts`](https://github.com/amritk/nish/blob/main/std/net/http3.ts) | `Http3Connection`, the server side of HTTP/3 over a `QuicConnection`'s streams: `next()` answers `H3_REQUEST` (`stream`, `fields`), `H3_DATA` (a window onto `data`, at most `bodyChunk`), `H3_TRAILERS`, `H3_END`, `H3_RESET`, `H3_WRITABLE`, `H3_GOAWAY` or the final `H3_ERROR`; `respond`, `writeData` (takes what the send buffer has room for), `writeTrailers`, `reset` and `goaway` write. It opens its control stream with SETTINGS and its QPACK streams (capacity 0, through `nish/net/qpack`), checks every field section with `nish/net/http-fields`, answers a section past `maxFieldSectionSize` with a 431, sends one `date` field from the connection's `date` bytes on every final head (straight after `:status`, counted against the client's field-section limit, never on trailers) unless the program's fields hold one, and closes the connection with RFC 9114's code for each connection error. No server push. A warm connection allocates nothing per request (`docs/security/http3.md`) | RFC 9114 §4–§8 and RFC 9204 §4.2: a Nish client over QUIC, requests with bodies both ways, trailers, the date and its limit, GOAWAY, cancellation, every error code (`tests/link/net_http3`, `net_http3_errors`) |
|
|
273
|
-
| [`net/http3-server.ts`](https://github.com/amritk/nish/blob/main/std/net/http3-server.ts) | `Http3Server`: HTTP/3 over QUIC on one UDP socket for a program that owns its loop — a pool of `QuicConnection` slots with an `Http3Connection` each, a slot's built on the first Initial accepted into it, slots 0 up, and reused, while the connection-ID index, the timer wheel and the rings are sized from the cap at start-up; a `QuicListener` in front; datagrams routed by a hashed index of every slot's connection IDs; `receive(now, key)`, `tick(now)`, `ready()` for the next slot with news, `flush(now)` sending paced GSO flights, `timeout(now)` from a timer wheel. A handshake that did not choose ALPN `h3` is closed with no_application_protocol (RFC 9114 §3.1); a slot done after GOAWAY is closed and freed. Every slot's final responses carry the server's one `HttpDate` (`date`), refreshed at `connection(slot)` and `ready()` and formatted at most once a second. `stop()` releases every connection and the listener and wipes the configuration's stateless reset and Retry token keys, which are the server's once handed in, and its last answer; the keys are zeroed in place, so a `QuicServerConfig` serves one server (QUIC-5). Native only, as `nish:net` is | A Nish client across loopback (`tests/link/net_http3_server`): requests, a paced 300 KB response, GOAWAY and the slot freed, ALPN, a full pool, the arena over connections through one slot while the pinned date moves a second on for each, one date formatted for two slots; every key read back as zero after `stop()` (`tests/link/net_quic_server_wipes`); aioquic and `curl --http3` against its `serve` mode |
|
|
274
|
-
| [`net/webtransport.ts`](https://github.com/amritk/nish/blob/main/std/net/webtransport.ts) | `WebTransport`, the server side of WebTransport over HTTP/3 as draft-ietf-webtrans-http3-02 has it and Chrome and `wtransport` 0.7 negotiate it, a layer over one `Http3Connection` whose `Http3Config.webtransportSessions` turns it on (extended CONNECT, SETTINGS_H3_DATAGRAM and the draft's two WebTransport settings): `next()` answers `WT_SESSION` (the program `accept`s or `refuse`s it), `WT_DATAGRAM`, `WT_STREAM`, `WT_STREAM_DATA`, `WT_STREAM_END`, `WT_STREAM_RESET`, `WT_STREAM_STOPPED`, `WT_WRITABLE`, `WT_DRAIN` and `WT_CLOSED`, and passes a plain request's `H3_*` events through; `sendDatagram` (the quarter stream ID, then the payload), `openStream`, `write`, `resetStream`, `stopSending`, `close` (CLOSE_WEBTRANSPORT_SESSION) and `drain`. Streams that arrive before their session wait, bounded; every cap is fixed at start-up, and a warm session allocates nothing per datagram or stream (`docs/security/webtransport.md`) | RFC 9220, RFC 9297 and draft-02: a Nish client over QUIC — sessions, datagrams at the size limits, streams both ways, close and drain from either side, every refusal — and one exchange recorded from a `wtransport` 0.7 client replayed byte for byte (`tests/link/net_webtransport`) |
|
|
272
|
+
| [`net/http3.ts`](https://github.com/amritk/nish/blob/main/std/net/http3.ts) | `Http3Connection`, the server side of HTTP/3 over a `QuicConnection`'s streams: `next()` answers `H3_REQUEST` (`stream`, `fields`), `H3_DATA` (a window onto `data`, at most `bodyChunk`), `H3_TRAILERS`, `H3_END`, `H3_RESET`, `H3_WRITABLE`, `H3_GOAWAY` or the final `H3_ERROR`; `respond`, `writeData` (takes what the send buffer has room for), `writeTrailers`, `reset` and `goaway` write. It opens its control stream with SETTINGS and its QPACK streams (capacity 0, through `nish/net/qpack`), checks every field section with `nish/net/http-fields`, answers a section past `maxFieldSectionSize` with a 431, sends one `date` field from the connection's `date` bytes on every final head (straight after `:status`, counted against the client's field-section limit, never on trailers) unless the program's fields hold one, and closes the connection with RFC 9114's code for each connection error. A configuration that breaks one of its caps fails the connection from the start with H3_INTERNAL_ERROR, `fault` naming the rule. No server push. A warm connection allocates nothing per request (`docs/security/http3.md`) | RFC 9114 §4–§8 and RFC 9204 §4.2: a Nish client over QUIC, requests with bodies both ways, trailers, the date and its limit, GOAWAY, cancellation, every error code (`tests/link/net_http3`, `net_http3_errors`) |
|
|
273
|
+
| [`net/http3-server.ts`](https://github.com/amritk/nish/blob/main/std/net/http3-server.ts) | `Http3Server`: HTTP/3 over QUIC on one UDP socket for a program that owns its loop — a pool of `QuicConnection` slots with an `Http3Connection` each, a slot's built on the first Initial accepted into it, slots 0 up, and reused, while the connection-ID index, the timer wheel and the rings are sized from the cap at start-up; a `QuicListener` in front; datagrams routed by a hashed index of every slot's connection IDs; `receive(now, key)`, `tick(now)`, `ready()` for the next slot with news, `flush(now)` sending paced GSO flights, `timeout(now)` from a timer wheel. A handshake that did not choose ALPN `h3` is closed with no_application_protocol (RFC 9114 §3.1); a slot done after GOAWAY is closed and freed; an Initial that arrives while the entropy source fails (`crypto.tryGetRandomValues`) is dropped and counted in `starved`, its slot left free. Every slot's final responses carry the server's one `HttpDate` (`date`), refreshed at `connection(slot)` and `ready()` and formatted at most once a second. `stop()` releases every connection and the listener and wipes the configuration's stateless reset and Retry token keys, which are the server's once handed in, and its last answer; the keys are zeroed in place, so a `QuicServerConfig` serves one server (QUIC-5). `openHttp3Server` answers a slot count or timeout out of range as an `Err` where the constructor panics on either, at start-up. Native only, as `nish:net` is | A Nish client across loopback (`tests/link/net_http3_server`): requests, a paced 300 KB response, GOAWAY and the slot freed, ALPN, a full pool, the arena over connections through one slot while the pinned date moves a second on for each, one date formatted for two slots; every key read back as zero after `stop()` (`tests/link/net_quic_server_wipes`); aioquic and `curl --http3` against its `serve` mode |
|
|
274
|
+
| [`net/webtransport.ts`](https://github.com/amritk/nish/blob/main/std/net/webtransport.ts) | `WebTransport`, the server side of WebTransport over HTTP/3 as draft-ietf-webtrans-http3-02 has it and Chrome and `wtransport` 0.7 negotiate it, a layer over one `Http3Connection` whose `Http3Config.webtransportSessions` turns it on (extended CONNECT, SETTINGS_H3_DATAGRAM and the draft's two WebTransport settings): `next()` answers `WT_SESSION` (the program `accept`s or `refuse`s it), `WT_DATAGRAM`, `WT_STREAM`, `WT_STREAM_DATA`, `WT_STREAM_END`, `WT_STREAM_RESET`, `WT_STREAM_STOPPED`, `WT_WRITABLE`, `WT_DRAIN` and `WT_CLOSED`, and passes a plain request's `H3_*` events through; `sendDatagram` (the quarter stream ID, then the payload), `openStream`, `write`, `resetStream`, `stopSending`, `close` (CLOSE_WEBTRANSPORT_SESSION) and `drain`. Streams that arrive before their session wait, bounded; every cap is fixed at start-up and `openWebTransport` answers one out of range, or a connection with WebTransport off, as an `Err`, and a warm session allocates nothing per datagram or stream (`docs/security/webtransport.md`) | RFC 9220, RFC 9297 and draft-02: a Nish client over QUIC — sessions, datagrams at the size limits, streams both ways, close and drain from either side, every refusal — and one exchange recorded from a `wtransport` 0.7 client replayed byte for byte (`tests/link/net_webtransport`) |
|
|
275
275
|
| [`net/http-compress.ts`](https://github.com/amritk/nish/blob/main/std/net/http-compress.ts) | Content coding for HTTP responses: `httpAcceptEncoding(buf, start, end, offered)` reads an `Accept-Encoding` value (q-values, `*`, `identity`, `x-gzip`) into `HTTP_CODING_GZIP`, `HTTP_CODING_DEFLATE`, `HTTP_CODING_IDENTITY` or `HTTP_CODING_NONE`, allocating nothing; `HttpCompressor(level, minLength, maxLength)` gzips a body into its own buffer when it is worth it (-1 to send it as it is) and builds the response fields (`addFields`: `Content-Encoding: gzip` and, while `vary`, `Vary: Accept-Encoding`). It sends gzip only when it pays: `minLength`, `minSaving` bytes or `minSavingPercent`, and `segmentMode` (fewer TCP segments of `mss`, head included, than as it is); `decision` says why (`HTTP_COMPRESS_SENT`, `_NOT_ACCEPTED`, `_TOO_SMALL`, `_TOO_LARGE`, `_TOO_LITTLE_SAVED`, `_NO_FEWER_SEGMENTS`). Bodies up to `fixedLimit` use the fixed-Huffman encoder (`encoder`: `HTTP_ENCODER_AUTO`, `_FIXED`, `_LEVEL`). On HTTP/1.1, `Http1Connection.acceptEncoding()` and `respondEncoded(status, names, values, body, off, len, enc, coding)` answer a request in one call with the compressed `Content-Length`, or nothing at all (`H1_AGAIN`, `H1_INVALID`); `identity;q=0` is honoured. Opt-in; BREACH is the program's to avoid (`docs/security/compress.md`) | RFC 9110 §8.4 and §12.5.3: the negotiation table, and sans-IO responses gunzipped back (`tests/link/std_http_compress`) |
|
|
276
276
|
| [`net/router.ts`](https://github.com/amritk/nish/blob/main/std/net/router.ts) | `Router`, a method and path router that knows no carrier and allocates nothing per match: `add(method, pattern)` answers the route's index (0, 1, 2 in the order added) or a refusal — `ROUTER_BAD_PATTERN`, `ROUTER_BAD_METHOD`, `ROUTER_TOO_LONG`, `ROUTER_AMBIGUOUS` (`*` not last), `ROUTER_DUPLICATE` (the same shape and method, whatever the parameter names) or `ROUTER_FULL`, against `RouterLimits`; `match(method, mStart, mEnd, target, tStart, tEnd, params)` answers the index, `ROUTER_NOT_FOUND` or `ROUTER_METHOD_NOT_ALLOWED`, writing each `:name` and a final `*` as a `[start, end)` pair into the caller's `params` (`ROUTER_TOO_MANY_PARAMS` when it is short). Literal before parameter before `*`, segment by segment, backtracking; a lookup enters each node at most once. The query is left unparsed and nothing is decoded: `routerDecode` decodes one parameter (`ROUTER_BAD_ESCAPE`, `ROUTER_NO_ROOM`) (`docs/security/router.md`) | Every refusal code, precedence and backtracking, 405 against 404, `%2F` kept in one segment, the query, `*` and authority-form targets, a target deeper than any route, the lookup bound, params past storage, and the arena flat over matches (`tests/link/net_router`, `net_router_f64`, five `net_router_negative_*`) |
|
|
277
277
|
| [`net/handler.ts`](https://github.com/amritk/nish/blob/main/std/net/handler.ts) | `HttpHandler`, complete requests and their answers over the HTTP/1.1 carrier: it owns the readiness loop, routes each request through a `Router` at its head, gathers its body up to `HandlerLimits.http.maxBody` (1 MiB; past it the carrier answers 413), and hands it over whole. The program pulls — `wait(ms)`, `ready()`, `take()` — and switches on `req.route`; `HttpRequest` reads parameters, form-decoded query values and fields as ranges into its own buffers. Each request is answered once, now or in a later turn, by `send`, `sendFields`, `empty`, `json()` + `sendJson`, `problem` (RFC 9457), `refuse` (404, or 405 with `Allow`) or `start`/`write`/`end`; an answer whose connection closed first is `HANDLER_DROPPED` and reaches no later peer. `HEAD` takes a `GET` route. `watch`/`fired` add the program's own descriptors (`signalFd()`), and `drain` stops gracefully. Nothing is allocated per request once warm (`docs/security/handler.md`) | Routing, parameters and form-decoded queries, `HEAD`, 404 and 405 problems, chunked bodies in and out, the body cap at and one past it, pipelining order, late answers dropped across a reused slot, the arena and pool flat over two thousand requests, and the drain (`tests/link/net_handler`, and `net_http_app` over `examples/http-app`) |
|
package/std/base64.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* export const main = (): i32 => {
|
|
8
8
|
* const hi: u8[] = [72, 105]; // "Hi"
|
|
9
|
-
* const text: string = base64Encode(hi);
|
|
9
|
+
* const text: string | null = base64Encode(hi); // "SGk="
|
|
10
10
|
* const out: u8[] = new Array<u8>(base64EncodedLength(2) + 1);
|
|
11
11
|
* const end: i32 = base64EncodeInto(hi, 0, 2, out, 1); // out[1..5) is "SGk=", end is 5
|
|
12
12
|
* return end;
|
|
@@ -21,9 +21,10 @@
|
|
|
21
21
|
* - `base64EncodeInto(src, off, len, dst, at)` writes the encoding of
|
|
22
22
|
* `src[off..off+len)` into `dst` from `at` and allocates nothing, so a frame
|
|
23
23
|
* can be encoded chunk by chunk straight into its output buffer.
|
|
24
|
-
* - `base64EncodeIfFits(src, off, len, dst, at)` is the same write
|
|
25
|
-
*
|
|
26
|
-
* - `base64Encode(bytes)` is the whole array as a string
|
|
24
|
+
* - `base64EncodeIfFits(src, off, len, dst, at)` is the same write and the
|
|
25
|
+
* same answer, kept for callers written against it.
|
|
26
|
+
* - `base64Encode(bytes)` is the whole array as a string, or `null` for an
|
|
27
|
+
* array past 1,610,612,733 bytes, whose encoding no string can hold.
|
|
27
28
|
*
|
|
28
29
|
* **This module only encodes**: what it is for writes base64 and never reads it
|
|
29
30
|
* back. It is not the strict decoder of `nish/crypto/base64url`, which is a
|
|
@@ -44,20 +45,18 @@ const BASE64_PAD: i32 = 61
|
|
|
44
45
|
|
|
45
46
|
/**
|
|
46
47
|
* The characters `n` bytes encode to: four for every three, a short final
|
|
47
|
-
* group counted as a whole one.
|
|
48
|
-
* would pass 2^31 - 1,
|
|
48
|
+
* group counted as a whole one. A negative `n`, or one above 1,610,612,733
|
|
49
|
+
* whose length would pass 2^31 - 1, answers -1.
|
|
49
50
|
*
|
|
50
51
|
* @param n How many bytes are to be encoded; zero answers zero.
|
|
51
52
|
* @returns The number of base64 characters, padding included, that `n` bytes
|
|
52
|
-
* encode to: always a multiple of four.
|
|
53
|
+
* encode to: always a multiple of four. -1 for a negative `n` or one whose
|
|
54
|
+
* encoding would be longer than 2^31 - 1 characters.
|
|
53
55
|
*/
|
|
54
56
|
export const base64EncodedLength = (n: i32): i32 => {
|
|
55
|
-
if (n < 0) {
|
|
56
|
-
panic("base64EncodedLength: a negative byte count")
|
|
57
|
-
}
|
|
58
57
|
// (2^31 - 1) / 4 * 3 groups' worth of bytes is the most whose encoding fits.
|
|
59
|
-
if (n > 1610612733) {
|
|
60
|
-
|
|
58
|
+
if (n < 0 || n > 1610612733) {
|
|
59
|
+
return -1
|
|
61
60
|
}
|
|
62
61
|
const groups: i32 = toI32((n + 2) / 3)
|
|
63
62
|
return groups * 4
|
|
@@ -66,10 +65,10 @@ export const base64EncodedLength = (n: i32): i32 => {
|
|
|
66
65
|
/**
|
|
67
66
|
* Write the base64 of `src[off..off+len)` into `dst` from index `at`, and
|
|
68
67
|
* answer the index just past the last character written, which is
|
|
69
|
-
* `at + base64EncodedLength(len)`. Nothing is allocated.
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
68
|
+
* `at + base64EncodedLength(len)`. Nothing is allocated. A source range not
|
|
69
|
+
* inside `src`, an encoding that does not fit in `dst` from `at`, or either
|
|
70
|
+
* array longer than 2^31 - 1 bytes answers -1 with nothing written: all three
|
|
71
|
+
* are checked before anything is written.
|
|
73
72
|
*
|
|
74
73
|
* @param src The bytes to encode from; only `src[off..off+len)` is read.
|
|
75
74
|
* @param off Where in `src` the bytes to encode start.
|
|
@@ -78,32 +77,40 @@ export const base64EncodedLength = (n: i32): i32 => {
|
|
|
78
77
|
* @param dst The buffer the characters are written into, one ASCII byte per
|
|
79
78
|
* character; bytes outside the written range are left as they were.
|
|
80
79
|
* @param at Where in `dst` the first character goes.
|
|
81
|
-
* @returns The index in `dst` just past the last character written
|
|
80
|
+
* @returns The index in `dst` just past the last character written, or -1
|
|
81
|
+
* when the range does not fit.
|
|
82
82
|
*/
|
|
83
83
|
export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i32): i32 => {
|
|
84
84
|
// Refused before `toI32`, which saturates a longer length under
|
|
85
85
|
// `--number-mode f64` and would let a range past the true end through.
|
|
86
86
|
if (src.length > 2147483647 || dst.length > 2147483647) {
|
|
87
|
-
|
|
87
|
+
return -1
|
|
88
88
|
}
|
|
89
89
|
const srcLength: i32 = toI32(src.length)
|
|
90
90
|
const dstLength: i32 = toI32(dst.length)
|
|
91
|
-
if (off < 0 || len < 0 ||
|
|
92
|
-
|
|
91
|
+
if (off < 0 || len < 0 || len > srcLength - off) {
|
|
92
|
+
return -1
|
|
93
93
|
}
|
|
94
|
-
|
|
94
|
+
// Past this many bytes the encoding is longer than 2^31 - 1 characters, as
|
|
95
|
+
// in `base64EncodedLength`.
|
|
96
|
+
if (len > 1610612733) {
|
|
97
|
+
return -1
|
|
98
|
+
}
|
|
99
|
+
const need: i32 = toI32((len + 2) / 3) * 4
|
|
95
100
|
if (at < 0 || need > dstLength - at) {
|
|
96
|
-
|
|
101
|
+
return -1
|
|
97
102
|
}
|
|
98
103
|
// A local, so that `abc.length >= 64` below is a fact about the string each
|
|
99
104
|
// character is read from.
|
|
100
105
|
const abc: string = BASE64_ALPHABET
|
|
101
106
|
let i: i32 = off
|
|
102
107
|
let o: i32 = at
|
|
103
|
-
|
|
108
|
+
// At most `srcLength`, by the range check above; summed as `i64` because
|
|
109
|
+
// the overflow proof reads each operand's range alone.
|
|
110
|
+
const end: i32 = toI32(toI64(off) + toI64(len))
|
|
104
111
|
// The checks above make every term after the first true; they are written out
|
|
105
112
|
// because they are what proves the loop's accesses in range.
|
|
106
|
-
while (
|
|
113
|
+
while (i >= 0 && i < srcLength - 2 && i + 2 < end && o >= 0 && o < dstLength - 3 && abc.length >= 64) {
|
|
107
114
|
const group: i32 = (toI32(src[i]) << 16) | (toI32(src[i + 1]) << 8) | toI32(src[i + 2])
|
|
108
115
|
dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
|
|
109
116
|
dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
|
|
@@ -111,30 +118,29 @@ export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i
|
|
|
111
118
|
dst[o + 3] = toU8(abc.charCodeAt(group & 63))
|
|
112
119
|
i = i + 3
|
|
113
120
|
o = o + 4
|
|
114
|
-
rest = rest - 3
|
|
115
121
|
}
|
|
116
|
-
|
|
117
|
-
//
|
|
118
|
-
|
|
122
|
+
const rest: i64 = toI64(end) - toI64(i)
|
|
123
|
+
// A short final group of one or two bytes, padded; `rest` is 0, 1 or 2, tested
|
|
124
|
+
// by order (`===` 2 on an i64 misreads under runtime/nish.mjs). Every later term is false.
|
|
125
|
+
if (rest < 1 || i < 0 || i >= srcLength || o < 0 || o >= dstLength - 3 || abc.length < 64) {
|
|
119
126
|
return o
|
|
120
127
|
}
|
|
121
128
|
let group: i32 = toI32(src[i]) << 16
|
|
122
|
-
if (rest
|
|
129
|
+
if (rest > 1 && i < srcLength - 1) {
|
|
123
130
|
group = group | (toI32(src[i + 1]) << 8)
|
|
124
131
|
}
|
|
125
132
|
dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
|
|
126
133
|
dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
|
|
127
|
-
dst[o + 2] = rest
|
|
134
|
+
dst[o + 2] = rest > 1 ? toU8(abc.charCodeAt((group >> 6) & 63)) : toU8(BASE64_PAD)
|
|
128
135
|
dst[o + 3] = toU8(BASE64_PAD)
|
|
129
136
|
return o + 4
|
|
130
137
|
}
|
|
131
138
|
|
|
132
139
|
/**
|
|
133
|
-
* `base64EncodeInto`
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
* panics.
|
|
140
|
+
* `base64EncodeInto` under its earlier name: the same bytes written to the same
|
|
141
|
+
* place, or -1, with nothing written, when `src[off..off+len)` is not inside
|
|
142
|
+
* `src`, the encoding does not fit in `dst` from `at`, or either array is
|
|
143
|
+
* longer than 2^31 - 1 bytes.
|
|
138
144
|
*
|
|
139
145
|
* @param src The bytes to encode from; only `src[off..off+len)` is read.
|
|
140
146
|
* @param off Where in `src` the bytes to encode start.
|
|
@@ -146,71 +152,31 @@ export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i
|
|
|
146
152
|
* @returns The index in `dst` just past the last character written, or -1
|
|
147
153
|
* when the range does not fit.
|
|
148
154
|
*/
|
|
149
|
-
export const base64EncodeIfFits = (src: u8[], off: i32, len: i32, dst: u8[], at: i32): i32 =>
|
|
150
|
-
|
|
151
|
-
if (src.length > 2147483647 || dst.length > 2147483647) {
|
|
152
|
-
return -1
|
|
153
|
-
}
|
|
154
|
-
const srcLength: i32 = toI32(src.length)
|
|
155
|
-
const dstLength: i32 = toI32(dst.length)
|
|
156
|
-
if (off < 0 || len < 0 || off > srcLength - len) {
|
|
157
|
-
return -1
|
|
158
|
-
}
|
|
159
|
-
// Past this many bytes the encoding is longer than 2^31 - 1 characters, as
|
|
160
|
-
// in `base64EncodedLength`, which this restates without its panics.
|
|
161
|
-
if (len > 1610612733) {
|
|
162
|
-
return -1
|
|
163
|
-
}
|
|
164
|
-
const need: i32 = toI32((len + 2) / 3) * 4
|
|
165
|
-
if (at < 0 || need > dstLength - at) {
|
|
166
|
-
return -1
|
|
167
|
-
}
|
|
168
|
-
// A local, so that `abc.length >= 64` below is a fact about the string each
|
|
169
|
-
// character is read from.
|
|
170
|
-
const abc: string = BASE64_ALPHABET
|
|
171
|
-
let i: i32 = off
|
|
172
|
-
let o: i32 = at
|
|
173
|
-
let rest: i32 = len
|
|
174
|
-
// The checks above make every term after the first true; they are written out
|
|
175
|
-
// because they are what proves the loop's accesses in range.
|
|
176
|
-
while (rest >= 3 && i >= 0 && i < srcLength - 2 && o >= 0 && o < dstLength - 3 && abc.length >= 64) {
|
|
177
|
-
const group: i32 = (toI32(src[i]) << 16) | (toI32(src[i + 1]) << 8) | toI32(src[i + 2])
|
|
178
|
-
dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
|
|
179
|
-
dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
|
|
180
|
-
dst[o + 2] = toU8(abc.charCodeAt((group >> 6) & 63))
|
|
181
|
-
dst[o + 3] = toU8(abc.charCodeAt(group & 63))
|
|
182
|
-
i = i + 3
|
|
183
|
-
o = o + 4
|
|
184
|
-
rest = rest - 3
|
|
185
|
-
}
|
|
186
|
-
// A short final group of one or two bytes, padded. As in the loop, the
|
|
187
|
-
// checks above make every term after the first false.
|
|
188
|
-
if (rest === 0 || i < 0 || i >= srcLength || o < 0 || o >= dstLength - 3 || abc.length < 64) {
|
|
189
|
-
return o
|
|
190
|
-
}
|
|
191
|
-
let group: i32 = toI32(src[i]) << 16
|
|
192
|
-
if (rest === 2 && i < srcLength - 1) {
|
|
193
|
-
group = group | (toI32(src[i + 1]) << 8)
|
|
194
|
-
}
|
|
195
|
-
dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
|
|
196
|
-
dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
|
|
197
|
-
dst[o + 2] = rest === 2 ? toU8(abc.charCodeAt((group >> 6) & 63)) : toU8(BASE64_PAD)
|
|
198
|
-
dst[o + 3] = toU8(BASE64_PAD)
|
|
199
|
-
return o + 4
|
|
200
|
-
}
|
|
155
|
+
export const base64EncodeIfFits = (src: u8[], off: i32, len: i32, dst: u8[], at: i32): i32 =>
|
|
156
|
+
base64EncodeInto(src, off, len, dst, at)
|
|
201
157
|
|
|
202
158
|
/**
|
|
203
|
-
* `bytes` as padded base64
|
|
204
|
-
* would not fit a string.
|
|
159
|
+
* `bytes` as padded base64, or `null` past 1,610,612,733 bytes, whose encoding
|
|
160
|
+
* would be longer than 2^31 - 1 characters and so would not fit a string.
|
|
205
161
|
*
|
|
206
162
|
* @param bytes The bytes to encode, all of them; an empty array answers `""`.
|
|
207
|
-
* @returns A fresh string holding the padded encoding
|
|
163
|
+
* @returns A fresh string holding the padded encoding, or `null` for an array
|
|
164
|
+
* too long to encode.
|
|
208
165
|
*/
|
|
209
|
-
export const base64Encode = (bytes: u8[]): string => {
|
|
166
|
+
export const base64Encode = (bytes: u8[]): string | null => {
|
|
210
167
|
// A longer length saturates to the largest `i32` under `--number-mode f64`,
|
|
211
|
-
// which
|
|
168
|
+
// which this refuses, as it does any count past 1,610,612,733 (the most
|
|
169
|
+
// bytes whose encoding fits, as in `base64EncodedLength`).
|
|
212
170
|
const n: i32 = toI32(bytes.length)
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
171
|
+
if (n > 1610612733) {
|
|
172
|
+
return null
|
|
173
|
+
}
|
|
174
|
+
// `n` is at most 1,610,612,733 here, so the length is never -1.
|
|
175
|
+
const length: i32 = base64EncodedLength(n)
|
|
176
|
+
const out: u8[] = length > 0 ? new Array<u8>(length) : []
|
|
177
|
+
// `out` is exactly the encoding's length and the range is all of `bytes`,
|
|
178
|
+
// so this writes all of it and never answers -1.
|
|
179
|
+
base64EncodeInto(bytes, 0, n, out, 0)
|
|
180
|
+
// The encoding fills `out` exactly, so its length is where the string ends.
|
|
181
|
+
return String.fromBytes(out, 0, toI32(out.length))
|
|
216
182
|
}
|