nish 0.35.0 → 0.37.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.
Files changed (129) hide show
  1. package/docs/AI.md +50 -4
  2. package/docs/INSTALL.md +73 -59
  3. package/package.json +19 -5
  4. package/runtime/async.d.mts +2 -0
  5. package/runtime/async.mjs +7 -0
  6. package/runtime/nish.d.ts +4849 -430
  7. package/runtime/nish.h +25 -0
  8. package/runtime/page.d.ts +53 -0
  9. package/runtime/page.mjs +146 -0
  10. package/runtime/runtime-async.c +557 -0
  11. package/runtime/runtime-wasm.c +63 -7
  12. package/runtime/vite.d.ts +30 -0
  13. package/runtime/vite.mjs +150 -0
  14. package/scripts/build.sh +252 -15
  15. package/scripts/fuzz.sh +1 -0
  16. package/scripts/undocumented.txt +14 -0
  17. package/std/README.md +107 -82
  18. package/std/base64.ts +34 -5
  19. package/std/bytes.ts +279 -59
  20. package/std/cli-args.ts +296 -70
  21. package/std/cli-flags.ts +184 -19
  22. package/std/cli.ts +475 -54
  23. package/std/collections.ts +121 -23
  24. package/std/compress/checksum.ts +44 -14
  25. package/std/compress/deflate.ts +224 -111
  26. package/std/compress/gzip.ts +217 -53
  27. package/std/compress/zlib.ts +63 -7
  28. package/std/crypto/aes.ts +128 -52
  29. package/std/crypto/base64url.ts +29 -5
  30. package/std/crypto/bcrypt-batch.ts +101 -34
  31. package/std/crypto/bcrypt.ts +93 -27
  32. package/std/crypto/chacha20poly1305.ts +69 -14
  33. package/std/crypto/ct.ts +32 -13
  34. package/std/crypto/ed25519.ts +66 -16
  35. package/std/crypto/hkdf.ts +198 -13
  36. package/std/crypto/hmac.ts +242 -37
  37. package/std/crypto/jwt.ts +204 -72
  38. package/std/crypto/p256.ts +222 -72
  39. package/std/crypto/p384.ts +51 -23
  40. package/std/crypto/pki-roots.ts +32 -2
  41. package/std/crypto/pki.ts +99 -30
  42. package/std/crypto/rsa.ts +56 -22
  43. package/std/crypto/sha1.ts +3 -0
  44. package/std/crypto/sha256.ts +24 -1
  45. package/std/crypto/sha512.ts +99 -14
  46. package/std/crypto/x25519.ts +163 -24
  47. package/std/crypto/x509-random.ts +10 -0
  48. package/std/crypto/x509.ts +133 -66
  49. package/std/host/ring.ts +124 -0
  50. package/std/json-equal.ts +31 -11
  51. package/std/json-format.ts +112 -13
  52. package/std/json-number.ts +76 -26
  53. package/std/json-pointer.ts +23 -1
  54. package/std/json-tokenizer.ts +126 -51
  55. package/std/json-typed.ts +757 -96
  56. package/std/json-value.ts +438 -157
  57. package/std/json.ts +170 -38
  58. package/std/map.ts +25 -7
  59. package/std/math.ts +36 -4
  60. package/std/net/buffer-pool.ts +42 -11
  61. package/std/net/dns-config.ts +109 -23
  62. package/std/net/dns-message.ts +62 -7
  63. package/std/net/dns-resolver.ts +247 -53
  64. package/std/net/dns.ts +203 -35
  65. package/std/net/fetch.ts +1267 -290
  66. package/std/net/handler.ts +296 -80
  67. package/std/net/hpack.ts +290 -77
  68. package/std/net/http-compress.ts +152 -36
  69. package/std/net/http-fields.ts +85 -9
  70. package/std/net/http1-client-codec.ts +129 -44
  71. package/std/net/http1-codec.ts +279 -114
  72. package/std/net/http1-server.ts +409 -139
  73. package/std/net/http2-frame.ts +289 -51
  74. package/std/net/http2-tls.ts +152 -49
  75. package/std/net/http2.ts +314 -160
  76. package/std/net/http3-frame.ts +165 -27
  77. package/std/net/http3-server.ts +282 -131
  78. package/std/net/http3.ts +377 -173
  79. package/std/net/outbound.ts +37 -3
  80. package/std/net/postgres-carrier.ts +144 -8
  81. package/std/net/postgres.ts +898 -260
  82. package/std/net/prefork.ts +202 -65
  83. package/std/net/qpack.ts +120 -32
  84. package/std/net/quic-conn-ack.ts +60 -12
  85. package/std/net/quic-conn-cid.ts +135 -27
  86. package/std/net/quic-conn-params.ts +109 -22
  87. package/std/net/quic-datagram.ts +50 -3
  88. package/std/net/quic-frame.ts +333 -23
  89. package/std/net/quic-listener.ts +161 -75
  90. package/std/net/quic-packet.ts +373 -73
  91. package/std/net/quic-recovery.ts +287 -65
  92. package/std/net/quic-stream.ts +436 -146
  93. package/std/net/quic.ts +693 -323
  94. package/std/net/router.ts +87 -40
  95. package/std/net/tls/client.ts +167 -51
  96. package/std/net/tls/codec.ts +494 -68
  97. package/std/net/tls/record-client.ts +140 -73
  98. package/std/net/tls/record-server.ts +233 -105
  99. package/std/net/tls/record.ts +142 -36
  100. package/std/net/tls/schedule.ts +235 -26
  101. package/std/net/tls/ticket.ts +161 -40
  102. package/std/net/tls/verify.ts +57 -10
  103. package/std/net/tls-tcp.ts +308 -95
  104. package/std/net/tls.ts +276 -102
  105. package/std/net/upstream.ts +81 -45
  106. package/std/net/url.ts +109 -22
  107. package/std/net/websocket.ts +140 -26
  108. package/std/net/webtransport.ts +243 -106
  109. package/std/pair.ts +10 -2
  110. package/std/random.ts +42 -15
  111. package/std/regex.ts +422 -257
  112. package/std/region.ts +70 -15
  113. package/std/secret.ts +52 -11
  114. package/std/sort.ts +17 -2
  115. package/std/sqlite.ts +256 -35
  116. package/std/sync/ring.ts +229 -56
  117. package/std/sync/shm.ts +203 -23
  118. package/std/term-io.ts +154 -78
  119. package/std/term-pixels.ts +144 -19
  120. package/std/term-probe.ts +77 -35
  121. package/std/term-rate.ts +199 -118
  122. package/std/term.ts +400 -175
  123. package/std/testing.ts +130 -32
  124. package/std/text.ts +84 -17
  125. package/std/threads.ts +248 -56
  126. package/std/yaml-json.ts +111 -97
  127. package/std/yaml-lines.ts +47 -15
  128. package/std/yaml-write.ts +45 -30
  129. package/std/yaml.ts +764 -384
package/std/README.md CHANGED
@@ -50,18 +50,21 @@ whatever program imports it, and subject to the same rules as `examples/` or
50
50
 
51
51
  ## `nish/crypto` — the primitives under TLS 1.3
52
52
 
53
- The first lanes of [WP34](https://github.com/amritk/nish/blob/main/docs/wp34-hosting-cs.md) §5: K1's hashes, MACs and
54
- key derivation, K2's and K3's AEADs, K4's key exchange, K5's signatures and
55
- K6's certificates, in
56
- pure Nish (decision S1), each module imported by its own specifier. Every one
57
- is written from its specification, with three exceptions that keep their
58
- upstream notice: `crypto/aes.ts`'s `ghashMul32` is adapted from BearSSL,
59
- `crypto/p256.ts`'s field and scalar arithmetic is ported from fiat-crypto and
60
- its nonce's safegcd inversion from libsecp256k1, and `crypto/p384.ts`'s field
61
- and scalar arithmetic is ported from fiat-crypto
62
- ([`THIRD_PARTY_NOTICES.md`](https://github.com/amritk/nish/blob/main/THIRD_PARTY_NOTICES.md)). Each reproduces its
63
- specification's published vectors in its `tests/link/crypto_*` programs. The
64
- performance gate compiles every module with no diagnostics under both
53
+ The first lanes of
54
+ [WP34](https://github.com/amritk/nish/blob/main/docs/wp34-hosting-cs.md) §5:
55
+ K1's hashes, MACs and key derivation, K2's and K3's AEADs, K4's key exchange,
56
+ K5's signatures and K6's certificates, in pure Nish (decision S1), each module
57
+ imported by its own specifier. Every one is written from its specification,
58
+ with three exceptions that keep their upstream notice: `crypto/aes.ts`'s
59
+ `ghashMul32` is adapted from BearSSL, `crypto/p256.ts`'s field and scalar
60
+ arithmetic is ported from fiat-crypto and its nonce's safegcd inversion from
61
+ libsecp256k1, and `crypto/p384.ts`'s field and scalar arithmetic is ported from
62
+ fiat-crypto
63
+ ([`THIRD_PARTY_NOTICES.md`](https://github.com/amritk/nish/blob/main/THIRD_PARTY_NOTICES.md)).
64
+ Each reproduces its specification's published vectors in its
65
+ `tests/link/crypto_*` programs.
66
+
67
+ The performance gate compiles every module with no diagnostics under both
65
68
  `--number-mode i32` and `f64`, and the hashes, HMAC, HKDF, X25519,
66
69
  ChaCha20-Poly1305, AES-GCM, P-256 and X.509 also run their vectors in `f64`
67
70
  (`crypto_*_f64`). SHA-1 is here too, for one non-security use (its row says
@@ -70,13 +73,17 @@ which), and does both.
70
73
  Every module here was security-audited (#363); the records are in
71
74
  [`docs/security/`](../docs/security/README.md), and how to report a
72
75
  vulnerability is in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.md). Two limits hold across the
73
- modules. **Lengths stop at 2^31 − 1.** No array built by `push` or `new Array`,
74
- no array or string the runtime makes (a file read, a concatenation, a
75
- template) and no string built by `join` can pass 2^31 − 1 elements or bytes
76
- (K1-6, CG-3, closed), so `length` is right in both number modes, and the
77
- one-shot functions below refuse a longer input as each row says. **Private
78
- keys are `Secret`s.** `crypto/p256.ts`, `crypto/x25519.ts`, `crypto/ed25519.ts`,
79
- `crypto/x509.ts` and `crypto/x509-random.ts` take and give a private key as a `Secret<u8[]>` from
76
+ modules.
77
+
78
+ **Lengths stop at 2^31 − 1.** No array built by `push` or `new Array`, no array
79
+ or string the runtime makes (a file read, a concatenation, a template) and no
80
+ string built by `join` can pass 2^31 − 1 elements or bytes (K1-6, CG-3,
81
+ closed), so `length` is right in both number modes, and the one-shot functions
82
+ below refuse a longer input as each row says.
83
+
84
+ **Private keys are `Secret`s.** `crypto/p256.ts`, `crypto/x25519.ts`,
85
+ `crypto/ed25519.ts`, `crypto/x509.ts` and `crypto/x509-random.ts` take and give
86
+ a private key as a `Secret<u8[]>` from
80
87
  `nish:secret`, compute on it only inside `expose`, and wipe every intermediate
81
88
  the key reaches before they return, with a store the optimiser may not remove
82
89
  (ECC-2, X509-7, closed); `crypto/hmac.ts` (`hmacSha256Secret` and its two
@@ -130,7 +137,9 @@ Three rules hold across the modules:
130
137
  255 steps, AES reads no table, P-256's comb and window read every entry of
131
138
  a table and keep one by mask, and base64url maps characters by arithmetic on range masks
132
139
  rather than a table. Every branch is on a length, a loop counter or a bit
133
- position. WP34 N6 checks that the machine code kept that shape:
140
+ position.
141
+
142
+ WP34 N6 checks that the machine code kept that shape:
134
143
  `tests/ct-asm.js` disassembles golden fixtures on x86-64 and aarch64 and
135
144
  refuses a branch, a call, a secret-addressed load, or a divide or square
136
145
  root of a secret (whose latency follows its operands) in them. It reads what
@@ -159,18 +168,19 @@ Three rules hold across the modules:
159
168
  - `tests/cases/ct_asm_aes`: one full bitsliced round, one GHASH multiply and
160
169
  the tag compare. Packing, the key schedule and the loops over blocks
161
170
  remain discipline.
162
- - `tests/cases/ct_asm_p256`: fiat's field multiply, square, add and
163
- subtract, its scalar multiply and its conditional move; the sixteen-entry
164
- table read by a secret digit; the complete doubling and addition; and one
165
- window step of the scalar multiplication (four doublings, the table read
166
- and an addition); and the fixed-base comb that multiplies G for a public
167
- key or a signature: its digit, the fifteen-entry read of the precomputed
168
- table, the mixed addition, the masked keep, and one whole comb step; and
169
- the nonce's safegcd inversion: thirty divsteps, held to the module's loop
170
- body, and both matrix updates. The check follows each call into the field
171
- functions. The 64-window and 4-row loops, the window's table build, the
172
- field inversion, safegcd's limb conversions, the encodings and
173
- RFC 6979's nonce derivation remain discipline.
171
+ - `tests/cases/ct_asm_p256`: fiat's field multiply, square, add and subtract,
172
+ its scalar multiply and its conditional move; the sixteen-entry table read
173
+ by a secret digit; the complete doubling and addition; and one window step
174
+ of the scalar multiplication (four doublings, the table read and an
175
+ addition); and the fixed-base comb that multiplies G for a public key or a
176
+ signature: its digit, the fifteen-entry read of the precomputed table, the
177
+ mixed addition, the masked keep, and one whole comb step; and the nonce's
178
+ safegcd inversion: thirty divsteps, held to the module's loop body, and
179
+ both matrix updates. The check follows each call into the field functions.
180
+
181
+ The 64-window and 4-row loops, the window's table build, the field
182
+ inversion, safegcd's limb conversions, the encodings and RFC 6979's nonce
183
+ derivation remain discipline.
174
184
 
175
185
  The SHA-2 hashes and HKDF are additions, rotations and xors that branch
176
186
  only on lengths, and are not in a fixture either; nor is `crypto/x509.ts`,
@@ -265,6 +275,7 @@ through both Finished messages) and `TLS_LEVEL_APPLICATION`. A carrier hands
265
275
  `receive` the bytes it got at a level, in any split, and sends what
266
276
  `takeOutput(level)` answers under that level's keys: TLS over TCP (T2) in
267
277
  records, QUIC (Q2) in CRYPTO frames of the matching packet number space.
278
+
268
279
  `writeKnown(level)` and `readKnown(level)` say when the server's and the
269
280
  client's traffic secret for the Handshake and Application levels is known
270
281
  (the Initial level has none); the secrets themselves are `Secret` fields of
@@ -272,7 +283,9 @@ client's traffic secret for the Handshake and Application levels is known
272
283
  `clientHandshake`, `serverApplication`, `clientApplication` and `exporter` —
273
284
  which a carrier reads only through `expose` (`installHeld` turns one into a
274
285
  record key), and `wipeSecret(TLS_SECRET_*)` zeroes one once the carrier has
275
- what it needs. The state says what is due: `TLS_STATE_WAIT_SIGNATURE` after the
286
+ what it needs.
287
+
288
+ The state says what is due: `TLS_STATE_WAIT_SIGNATURE` after the
276
289
  first flight is written, `TLS_STATE_WAIT_FINISHED` once it is signed,
277
290
  `TLS_STATE_CONNECTED` when the client's Finished verified, and
278
291
  `TLS_STATE_FAILED` with `alert` set after a refusal. Over QUIC, set `quic` in
@@ -283,7 +296,9 @@ ways (`clientTransportParameters` holds the client's).
283
296
  computed with, are `Secret`s wiped on every path, and `tlsSignEcdsaP256` takes
284
297
  its key as a `Secret`. The one-shot key-schedule functions of
285
298
  `nish/net/tls/schedule` and `tlsNextTrafficSecret` take and answer their
286
- secrets as `Secret<u8[]>`s, so a plain array there is a compile error. What `TlsServer` keeps for an open connection —
299
+ secrets as `Secret<u8[]>`s, so a plain array there is a compile error.
300
+
301
+ What `TlsServer` keeps for an open connection —
287
302
  the caller's ephemeral key, copied in by `restart`, and the handshake,
288
303
  traffic, exporter and resumption secrets — and the four traffic secrets
289
304
  `TlsRecordServer` keeps for KeyUpdate are `Secret` fields, readonly and read
@@ -293,6 +308,7 @@ zeroed once the carrier has what it needs from it and at every end of the
293
308
  connection (TLS-1 in
294
309
  [`docs/security/tls.md`](../docs/security/tls.md), the record that also lists
295
310
  what each refusal is and the test that pins it).
311
+
296
312
  `tests/link/net_tls_*` are the module's programs, each also run under
297
313
  `--number-mode f64`.
298
314
 
@@ -302,18 +318,20 @@ test or another transport. The program is the loop: there are no callbacks,
302
318
  so each call answers the slot's interest and the program re-arms the
303
319
  descriptor with `pollModify(loop, tls.fd(slot), wants & 3, slot)`, signs on
304
320
  `TLS_RECORD_SIGN`, reads on `TLS_RECORD_DATA` and calls `close(slot)` on
305
- `TLS_RECORD_DONE`. A slot's buffers — about 136 KB of resident memory, measured over a 400-slot pool, with the handshake's own state in them — are
306
- allocated once, on the first accept into the slot, and after its handshake a connection allocates nothing that
307
- outlives a record. The handshake keeps its state in the slot, which `accept`
308
- restarts, and a KeyUpdate installs its keys in place, so neither leaves
309
- anything in the arena (TLS-3); a connection still takes at most
310
- `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The carrier
311
- has no clock, so
312
- closing quiet slots is the program's (TLS-4). On this path the record layer
313
- wipes `TlsServer`'s traffic and handshake secrets and the ephemeral key once
314
- it has what it needs from them, which narrows TLS-1.
315
- `tests/link/net_tls_record_*` are its programs, and the `net_tls_tcp` block
316
- of `tests/run.js` drives the carrier with openssl and Node's `https`.
321
+ `TLS_RECORD_DONE`.
322
+
323
+ A slot's buffers — about 136 KB of resident memory, measured over a 400-slot
324
+ pool, with the handshake's own state in them — are allocated once, on the first
325
+ accept into the slot, and after its handshake a connection allocates nothing
326
+ that outlives a record. The handshake keeps its state in the slot, which
327
+ `accept` restarts, and a KeyUpdate installs its keys in place, so neither
328
+ leaves anything in the arena (TLS-3); a connection still takes at most
329
+ `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The carrier has
330
+ no clock, so closing quiet slots is the program's (TLS-4). On this path the
331
+ record layer wipes `TlsServer`'s traffic and handshake secrets and the
332
+ ephemeral key once it has what it needs from them, which narrows TLS-1.
333
+ `tests/link/net_tls_record_*` are its programs, and the `net_tls_tcp` block of
334
+ `tests/run.js` drives the carrier with openssl and Node's `https`.
317
335
 
318
336
  **How a server drives `QuicConnection`.** Keep one `QuicListener` for the
319
337
  server, with the same `QuicServerConfig` its connections use: two static keys
@@ -321,34 +339,37 @@ of `QUIC_CONN_STATIC_KEY_SIZE` bytes (the stateless reset key, which has to
321
339
  survive a restart to be any use, and the Retry token key) and whether to
322
340
  ask for Retry. `listener.release()` wipes the listener's seed and scratch
323
341
  when the server stops; the two keys are the caller's to wipe then, unless
324
- `Http3Server.stop` does it (QUIC-5). Route each datagram by
325
- its first packet's DCID: to the connection whose `ownsConnectionId` says it
326
- is its, and anything else to `listener.handle(datagram, address, now)`, which
327
- answers what to send back or says to make a connection — and must see nothing
328
- a live connection owns, or a stateless reset would end that connection.
329
- Make the connection when it says so, with `QUIC_CONN_ENTROPY_SIZE` bytes from
330
- `crypto.getRandomValues`: the TLS server random and x25519 key, the server's
331
- first connection ID and the seed its later IDs are derived from all come out
332
- of them, so a test injects fixed bytes and a recorded exchange replays byte
333
- for byte. Neither has a clock: `now` is the caller's monotonic time in
334
- milliseconds, and `deadline()` says when to call `handleTimer(now)` next.
335
- Hand the connection every datagram the client sends;
342
+ `Http3Server.stop` does it (QUIC-5).
343
+
344
+ Route each datagram by its first packet's DCID: to the connection whose
345
+ `ownsConnectionId` says it is its, and anything else to
346
+ `listener.handle(datagram, address, now)`, which answers what to send back or
347
+ says to make a connection — and must see nothing a live connection owns, or a
348
+ stateless reset would end that connection. Make the connection when it says so,
349
+ with `QUIC_CONN_ENTROPY_SIZE` bytes from `crypto.getRandomValues`: the TLS
350
+ server random and x25519 key, the server's first connection ID and the seed its
351
+ later IDs are derived from all come out of them, so a test injects fixed bytes
352
+ and a recorded exchange replays byte for byte. Neither has a clock: `now` is
353
+ the caller's monotonic time in milliseconds, and `deadline()` says when to call
354
+ `handleTimer(now)` next. Hand the connection every datagram the client sends;
336
355
  when `signatureInput()` answers bytes, sign them (`tlsSignEcdsaP256`) and hand
337
- the signature to `sign`; then send whatever `takeDatagram(now)` answers until it
338
- answers `null`, to the address the datagram came from. `ownsConnectionId`
339
- says whether a datagram's DCID is the connection's, which is how a server
340
- with many routes them. Stream data comes out of `readStream()` in order per
341
- stream, and `writeStream` queues a reply within the credit the client gave.
342
- `state` says where it is, and `error` why it closed. The keys of each level
343
- are wiped when the level is discarded, each key generation when an update
344
- replaces it, and the rest by `release()` or the idle timeout; what no wipe
345
- reaches is QUIC-2 in [`docs/security/quic.md`](../docs/security/quic.md).
356
+ the signature to `sign`; then send whatever `takeDatagram(now)` answers until
357
+ it answers `null`, to the address the datagram came from. `ownsConnectionId`
358
+ says whether a datagram's DCID is the connection's, which is how a server with
359
+ many routes them. Stream data comes out of `readStream()` in order per stream,
360
+ and `writeStream` queues a reply within the credit the client gave. `state`
361
+ says where it is, and `error` why it closed.
362
+
363
+ The keys of each level are wiped when the level is discarded, each key
364
+ generation when an update replaces it, and the rest by `release()` or the idle
365
+ timeout; what no wipe reaches is QUIC-2 in
366
+ [`docs/security/quic.md`](../docs/security/quic.md).
346
367
  `tests/link/net_quic_frame`, `net_quic_conn_parts`, `net_quic_conn`,
347
368
  `net_quic_conn_replay`, `net_quic_lifecycle` and `net_quic_lifecycle_replay`
348
369
  are its programs, each also run under `--number-mode f64`; the two replays
349
- send, over loopback from a Nish UDP client, exchanges recorded against
350
- aioquic by their `record.sh`: a handshake and echo, and Version Negotiation,
351
- Retry, key update both ways, the idle timeout and a stateless reset.
370
+ send, over loopback from a Nish UDP client, exchanges recorded against aioquic
371
+ by their `record.sh`: a handshake and echo, and Version Negotiation, Retry, key
372
+ update both ways, the idle timeout and a stateless reset.
352
373
 
353
374
  `net/http1-codec.ts`, `net/http1-server.ts` and `net/websocket.ts` run their checks
354
375
  again under `--number-mode f64` (`net_http1_f64`, `net_http1_server_f64`,
@@ -374,7 +395,9 @@ specifier works at any depth and from outside this repository.
374
395
  §2), so an import of a `std/` module is not a link against a built library: the
375
396
  module is compiled with the program that imports it, and the whole-program
376
397
  attribute pass sees through it exactly as it sees through the program's own
377
- functions. A `std/` function is inlined, specialised or dropped on the same
398
+ functions.
399
+
400
+ A `std/` function is inlined, specialised or dropped on the same
378
401
  terms as a local one — and a module you import but never call is dropped
379
402
  whole. Measured at the `speed` and `size` profiles, both of which link with
380
403
  `-flto -Wl,--gc-sections`: a program importing three `std/text` functions and
@@ -426,17 +449,18 @@ that are *not* this package.
426
449
 
427
450
  - **Spell the widths — and then convert what the builtins hand you.** `i32`,
428
451
  `i64`, `f64`, never `number`, so the module means the same thing under
429
- `--number-mode f64` as it does by default (`examples/arrays.ts` says that half
430
- for the same reason). It is necessary and **not sufficient**: `s.length`,
431
- `a.length` and `s.charCodeAt(i)` answer `number`, which *is* `f64` in that
432
- mode, so a module that declares every width of its own and still writes
433
- `let end: i32 = text.length` or `while (i < text.length)` does not compile
434
- there at all. Read each of those through `toI32` —
435
- `const length: i32 = toI32(text.length)`, once per function rather than once
436
- per iteration — and the module means one program in both modes. The default
437
- mode pays nothing for it, because `toI32` on an `i32` is identity.
438
- `tests/link/std_text_f64` is what keeps this from being prose;
439
- [`docs/wp26-stdlib.md`](https://github.com/amritk/nish/blob/main/docs/wp26-stdlib.md) §4 is the reasoning.
452
+ `--number-mode f64` as it does by default (`examples/arrays.ts` says that
453
+ half for the same reason). It is necessary and **not sufficient**:
454
+ `s.length`, `a.length` and `s.charCodeAt(i)` answer `number`, which *is*
455
+ `f64` in that mode, so a module that declares every width of its own and
456
+ still writes `let end: i32 = text.length` or `while (i < text.length)` does
457
+ not compile there at all. Read each of those through `toI32` — `const length:
458
+ i32 = toI32(text.length)`, once per function rather than once per iteration —
459
+ and the module means one program in both modes. The default mode pays nothing
460
+ for it, because `toI32` on an `i32` is identity. `tests/link/std_text_f64` is
461
+ what keeps this from being prose;
462
+ [`docs/wp26-stdlib.md`](https://github.com/amritk/nish/blob/main/docs/wp26-stdlib.md)
463
+ §4 is the reasoning.
440
464
  - **Name the private helpers as though they were exported.** A `std/` module
441
465
  belongs to package `nish`, so its symbols no longer collide with the
442
466
  importing program's (`tests/link/std_package_scope`), but every `std/` module
@@ -463,6 +487,7 @@ that are *not* this package.
463
487
  module into the corpus the stage1 oracles read
464
488
  ([`.claude/selfhost.md`](https://github.com/amritk/nish/blob/main/.claude/selfhost.md)): a `std/` module with no
465
489
  importer in `tests/link/` is compiled on no run.
490
+
466
491
  `testing.ts` has two, one per outcome — `tests/link/std_testing` (exit 0) and
467
492
  `tests/link/std_testing_fail` (exit 1, and the wording of every failure
468
493
  message) — and `text.ts` and `json.ts` have `tests/link/std_text` and
package/std/base64.ts CHANGED
@@ -2,7 +2,17 @@
2
2
  * `nish/base64` — standard base64 (RFC 4648 §4) with `=` padding, the encoding
3
3
  * kitty graphics frames are sent in.
4
4
  *
5
- * The alphabet is `A-Z a-z 0-9 + /`. Every three bytes become four characters,
5
+ * import { base64Encode, base64EncodeInto, base64EncodedLength } from "nish/base64";
6
+ *
7
+ * export const main = (): i32 => {
8
+ * const hi: u8[] = [72, 105]; // "Hi"
9
+ * const text: string = base64Encode(hi); // "SGk="
10
+ * const out: u8[] = new Array<u8>(base64EncodedLength(2) + 1);
11
+ * const end: i32 = base64EncodeInto(hi, 0, 2, out, 1); // out[1..5) is "SGk=", end is 5
12
+ * return end;
13
+ * };
14
+ *
15
+ * **The alphabet is `A-Z a-z 0-9 + /`.** Every three bytes become four characters,
6
16
  * and a final group of one or two bytes becomes two or three characters filled
7
17
  * out to four with `=` (RFC 4648 §4, the padding rules of §3.2), so the text is
8
18
  * always a multiple of four long.
@@ -13,15 +23,15 @@
13
23
  * can be encoded chunk by chunk straight into its output buffer.
14
24
  * - `base64Encode(bytes)` is the whole array as a string.
15
25
  *
16
- * This module only encodes: what it is for writes base64 and never reads it
26
+ * **This module only encodes**: what it is for writes base64 and never reads it
17
27
  * back. It is not the strict decoder of `nish/crypto/base64url`, which is a
18
28
  * different alphabet without padding and is written not to branch on the data;
19
29
  * what goes through here is pixels, not secrets, so a sextet becomes its
20
30
  * character by indexing the alphabet. The output is ASCII, so the string is
21
31
  * the same bytes natively and under Node.
22
32
  *
23
- * Private helpers share the importing program's flat symbol namespace
24
- * (`docs/wp26-stdlib.md` §3e), which is why each one carries the module's name.
33
+ * **Private helpers carry the module's name** because they share the
34
+ * importing program's flat symbol namespace (`docs/wp26-stdlib.md` §3e).
25
35
  */
26
36
 
27
37
  /** The 64 characters of RFC 4648 §4's Table 1, in value order. */
@@ -34,6 +44,10 @@ const BASE64_PAD: i32 = 61
34
44
  * The characters `n` bytes encode to: four for every three, a short final
35
45
  * group counted as a whole one. Panics when `n` is negative or the length
36
46
  * would pass 2^31 - 1, which `n` above 1,610,612,733 does.
47
+ *
48
+ * @param n How many bytes are to be encoded; zero answers zero.
49
+ * @returns The number of base64 characters, padding included, that `n` bytes
50
+ * encode to: always a multiple of four.
37
51
  */
38
52
  export const base64EncodedLength = (n: i32): i32 => {
39
53
  if (n < 0) {
@@ -55,6 +69,15 @@ const base64CharOf = (v: i32): u8 => toU8(BASE64_ALPHABET.charCodeAt(v))
55
69
  * `at + base64EncodedLength(len)`. Nothing is allocated. Panics when the source
56
70
  * range is not inside `src` or the encoding does not fit in `dst` from `at`;
57
71
  * both are checked before anything is written.
72
+ *
73
+ * @param src The bytes to encode from; only `src[off..off+len)` is read.
74
+ * @param off Where in `src` the bytes to encode start.
75
+ * @param len How many bytes of `src` to encode; zero writes nothing and
76
+ * answers `at`.
77
+ * @param dst The buffer the characters are written into, one ASCII byte per
78
+ * character; bytes outside the written range are left as they were.
79
+ * @param at Where in `dst` the first character goes.
80
+ * @returns The index in `dst` just past the last character written.
58
81
  */
59
82
  export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i32): i32 => {
60
83
  // Refused before `toI32`, which saturates a longer length under
@@ -104,7 +127,13 @@ export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i
104
127
  return o
105
128
  }
106
129
 
107
- /** `bytes` as padded base64. Panics past 1,610,612,733 bytes, whose encoding would not fit a string. */
130
+ /**
131
+ * `bytes` as padded base64. Panics past 1,610,612,733 bytes, whose encoding
132
+ * would not fit a string.
133
+ *
134
+ * @param bytes The bytes to encode, all of them; an empty array answers `""`.
135
+ * @returns A fresh string holding the padded encoding.
136
+ */
108
137
  export const base64Encode = (bytes: u8[]): string => {
109
138
  if (bytes.length > 2147483647) {
110
139
  panic("base64Encode: more than 2^31 - 1 bytes")