@amritk/nish-aarch64-linux 0.38.0 → 0.40.1

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 (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
@@ -37,8 +37,10 @@
37
37
  * the order of what follows the key (`[1]`, `[2]`, `[3]`), and decodes the
38
38
  * extensions a path validator needs: subjectAltName, basicConstraints,
39
39
  * keyUsage, extKeyUsage, nameConstraints and the two key identifiers. A
40
- * duplicate or malformed one refuses the certificate, and any other critical
41
- * one sets `unknownCritical`. It parses and does not validate: applying these
40
+ * duplicate or malformed one refuses the certificate, and each one's critical
41
+ * flag is kept. An authorityInfoAccess is held to its syntax but not kept, and
42
+ * any other critical extension sets `unknownCritical`. It parses and does not
43
+ * validate: applying these
42
44
  * to a chain is RFC 5280 §6 path validation, which `nish/crypto/pki`'s
43
45
  * `pkiVerifyServer` does. The mint writes two extensions of its own (below).
44
46
  *
@@ -246,6 +248,11 @@ export class X509Certificate {
246
248
  subject: u8[]
247
249
  /** The subjectPublicKey BIT STRING's octets: for a P-256 key, the 65-byte uncompressed point. */
248
250
  publicKey: u8[]
251
+ /**
252
+ * The subjectPublicKeyInfo's DER, whole: the key and its algorithm, as a
253
+ * key pin or `nish/crypto/pki`'s `pkiDistrustSpki` hashes it.
254
+ */
255
+ spki: u8[]
249
256
  /** The signatureValue BIT STRING's octets: for ECDSA, the DER `SEQUENCE { r, s }`. */
250
257
  signature: u8[]
251
258
  /** The first instant the certificate is valid, inclusive (RFC 5280 §4.1.2.5). */
@@ -307,6 +314,31 @@ export class X509Certificate {
307
314
  ncUnsupported: boolean = false
308
315
  /** Whether a critical extension is one this module does not decode: RFC 5280 §4.2 has a verifier refuse it. */
309
316
  unknownCritical: boolean = false
317
+ /** Whether an authorityKeyIdentifier extension is present (RFC 5280 §4.2.1.1), with or without its keyIdentifier. */
318
+ akiPresent: boolean = false
319
+ /** Whether the authorityKeyIdentifier carries authorityCertIssuer and authorityCertSerialNumber, which are read and not kept. */
320
+ akiIssuerSerial: boolean = false
321
+ /** Whether the authorityKeyIdentifier is marked critical, which RFC 5280 §4.2.1.1 forbids. */
322
+ akiCritical: boolean = false
323
+ /** Whether the subjectKeyIdentifier is marked critical, which RFC 5280 §4.2.1.2 forbids. */
324
+ skiCritical: boolean = false
325
+ /** Whether keyUsage is marked critical, as RFC 5280 §4.2.1.3 says it should be. */
326
+ kuCritical: boolean = false
327
+ /** Whether subjectAltName is marked critical: RFC 5280 §4.2.1.6 has it critical when the subject is empty, and not otherwise. */
328
+ sanCritical: boolean = false
329
+ /** Whether basicConstraints is marked critical, which RFC 5280 §4.2.1.9 requires of a CA. */
330
+ bcCritical: boolean = false
331
+ /** Whether extKeyUsage is marked critical, which RFC 5280 §4.2.1.12 allows and the Web PKI does not. */
332
+ ekuCritical: boolean = false
333
+ /** Whether nameConstraints is marked critical, which RFC 5280 §4.2.1.10 requires. */
334
+ ncCritical: boolean = false
335
+ /**
336
+ * Whether a policyConstraints extension (RFC 5280 §4.2.1.11) is present. It
337
+ * is not decoded, so a critical one also sets `unknownCritical`.
338
+ */
339
+ pcPresent: boolean = false
340
+ /** Whether policyConstraints is marked critical, which RFC 5280 §4.2.1.11 requires. */
341
+ pcCritical: boolean = false
310
342
 
311
343
  /**
312
344
  * A certificate with every field empty, zero, `false` or `null`, and
@@ -320,6 +352,7 @@ export class X509Certificate {
320
352
  this.issuer = []
321
353
  this.subject = []
322
354
  this.publicKey = []
355
+ this.spki = []
323
356
  this.signature = []
324
357
  this.sanDns = []
325
358
  this.sanIp = []
@@ -669,12 +702,16 @@ const X509_CE_BASIC_CONSTRAINTS: i32 = 19
669
702
  const X509_CE_NAME_CONSTRAINTS: i32 = 30
670
703
  const X509_CE_AUTHORITY_KEY_ID: i32 = 35
671
704
  const X509_CE_EXT_KEY_USAGE: i32 = 37
705
+ const X509_CE_POLICY_CONSTRAINTS: i32 = 36
672
706
 
673
707
  /** What `x509ReadExtension` answers: an extension it does not decode, one it decoded, one that is malformed. */
674
708
  const X509_EXT_UNKNOWN: i32 = 0
675
709
  const X509_EXT_SOUND: i32 = 1
676
710
  const X509_EXT_MALFORMED: i32 = 2
677
711
 
712
+ /** id-pe-authorityInfoAccess, 1.3.6.1.5.5.7.1.1 (RFC 5280 §4.2.2.1). */
713
+ const x509OidAuthorityInfoAccess = (): u8[] => x509DerOidContents([1, 3, 6, 1, 5, 5, 7, 1, 1])
714
+
678
715
  /** id-kp-serverAuth, 1.3.6.1.5.5.7.3.1 (RFC 5280 §4.2.1.12). */
679
716
  const x509OidServerAuth = (): u8[] => x509DerOidContents([1, 3, 6, 1, 5, 5, 7, 3, 1])
680
717
 
@@ -1883,13 +1920,15 @@ const x509GeneralNamesSound = (der: u8[], e: X509DerElement): boolean => {
1883
1920
  * OPTIONAL }`, its keyIdentifier, which may not be empty, into `out.akid`.
1884
1921
  * The other two are held to their order, to being both present or both
1885
1922
  * absent, as §4.2.1.1 has them, to a non-empty GeneralNames and a minimal
1886
- * INTEGER, and not kept. `false` when it is malformed.
1923
+ * INTEGER, and not kept: `out.akiIssuerSerial` says they are there. `false`
1924
+ * when it is malformed.
1887
1925
  */
1888
1926
  const x509ReadAuthorityKeyId = (der: u8[], start: i32, end: i32, out: X509Certificate): boolean => {
1889
1927
  const seq: X509DerElement | null = x509DerExpect(der, start, end, X509_TAG_SEQUENCE)
1890
1928
  if (seq === null || seq.end !== end) {
1891
1929
  return false
1892
1930
  }
1931
+ out.akiPresent = true
1893
1932
  let at: i32 = seq.start
1894
1933
  if (x509DerPeek(der, at, seq.end) === 0x80) {
1895
1934
  const id: X509DerElement | null = x509DerRead(der, at, seq.end)
@@ -1911,11 +1950,66 @@ const x509ReadAuthorityKeyId = (der: u8[], start: i32, end: i32, out: X509Certif
1911
1950
  ) {
1912
1951
  return false
1913
1952
  }
1953
+ out.akiIssuerSerial = true
1914
1954
  at = serial.end
1915
1955
  }
1916
1956
  return at === seq.end
1917
1957
  }
1918
1958
 
1959
+ /**
1960
+ * Whether authorityInfoAccess (RFC 5280 §4.2.2.1) is well formed: a non-empty
1961
+ * `SEQUENCE OF AccessDescription { accessMethod OID, accessLocation
1962
+ * GeneralName }`, each a sound OID and a sound GeneralName, and nothing after
1963
+ * it. Nothing is kept: no access method is followed.
1964
+ */
1965
+ const x509AuthorityInfoAccessSound = (der: u8[], start: i32, end: i32): boolean => {
1966
+ const seq: X509DerElement | null = x509DerExpect(der, start, end, X509_TAG_SEQUENCE)
1967
+ if (seq === null || seq.end !== end || seq.end === seq.start) {
1968
+ return false
1969
+ }
1970
+ let at: i32 = seq.start
1971
+ while (at < seq.end) {
1972
+ const desc: X509DerElement | null = x509DerExpect(der, at, seq.end, X509_TAG_SEQUENCE)
1973
+ const method: X509DerElement | null =
1974
+ desc === null ? null : x509DerExpect(der, desc.start, desc.end, X509_TAG_OID)
1975
+ const location: X509DerElement | null =
1976
+ desc === null || method === null ? null : x509DerRead(der, method.end, desc.end)
1977
+ if (
1978
+ desc === null ||
1979
+ method === null ||
1980
+ location === null ||
1981
+ location.end !== desc.end ||
1982
+ !x509DerOidSound(der, method) ||
1983
+ x509GeneralNameKind(der, location) === -1
1984
+ ) {
1985
+ return false
1986
+ }
1987
+ at = desc.end
1988
+ }
1989
+ return true
1990
+ }
1991
+
1992
+ /** Notes in `out` that the extension at arc `ce` under 2.5.29, one this module decodes or policyConstraints, is marked critical. */
1993
+ const x509NoteCritical = (ce: i32, out: X509Certificate): void => {
1994
+ if (ce === X509_CE_SUBJECT_ALT_NAME) {
1995
+ out.sanCritical = true
1996
+ } else if (ce === X509_CE_BASIC_CONSTRAINTS) {
1997
+ out.bcCritical = true
1998
+ } else if (ce === X509_CE_KEY_USAGE) {
1999
+ out.kuCritical = true
2000
+ } else if (ce === X509_CE_EXT_KEY_USAGE) {
2001
+ out.ekuCritical = true
2002
+ } else if (ce === X509_CE_NAME_CONSTRAINTS) {
2003
+ out.ncCritical = true
2004
+ } else if (ce === X509_CE_SUBJECT_KEY_ID) {
2005
+ out.skiCritical = true
2006
+ } else if (ce === X509_CE_AUTHORITY_KEY_ID) {
2007
+ out.akiCritical = true
2008
+ } else if (ce === X509_CE_POLICY_CONSTRAINTS) {
2009
+ out.pcCritical = true
2010
+ }
2011
+ }
2012
+
1919
2013
  /**
1920
2014
  * One extension's value, the contents of its extnValue OCTET STRING, decoded
1921
2015
  * into `out` by the arc `ce` it has under 2.5.29: `X509_EXT_SOUND`, or
@@ -1960,9 +2054,12 @@ const x509ExtensionArc = (der: u8[], id: X509DerElement): i32 => {
1960
2054
  * FALSE, extnValue OCTET STRING }` and nothing after it. `false` when any is
1961
2055
  * malformed, a critical flag is not DER's TRUE, an OID appears twice (§4.2:
1962
2056
  * "MUST NOT include more than one instance"), there are more than
1963
- * `X509_MAX_EXTENSIONS`, or a decoded extension is malformed. A critical
1964
- * extension this module does not decode sets `out.unknownCritical`; a
1965
- * non-critical one is skipped.
2057
+ * `X509_MAX_EXTENSIONS`, a decoded extension is malformed, or an
2058
+ * authorityInfoAccess is not `x509AuthorityInfoAccessSound`. A decoded
2059
+ * extension's critical flag is kept (`sanCritical` and the rest), and so is
2060
+ * policyConstraints' presence and flag. A critical extension this module does
2061
+ * not decode, authorityInfoAccess and policyConstraints among them, sets
2062
+ * `out.unknownCritical`; a non-critical one is skipped.
1966
2063
  */
1967
2064
  const x509ReadExtensions = (der: u8[], e: X509DerElement, out: X509Certificate): boolean => {
1968
2065
  const seq: X509DerElement | null = x509DerExpect(der, e.start, e.end, X509_TAG_SEQUENCE)
@@ -1977,6 +2074,7 @@ const x509ReadExtensions = (der: u8[], e: X509DerElement, out: X509Certificate):
1977
2074
  const id = new X509DerElement(0, 0, 0, 0)
1978
2075
  const flag = new X509DerElement(0, 0, 0, 0)
1979
2076
  const value = new X509DerElement(0, 0, 0, 0)
2077
+ const aia: u8[] = x509OidAuthorityInfoAccess()
1980
2078
  let at: i32 = seq.start
1981
2079
  while (at < seq.end) {
1982
2080
  if (
@@ -2007,10 +2105,20 @@ const x509ReadExtensions = (der: u8[], e: X509DerElement, out: X509Certificate):
2007
2105
  if (!x509DerExpectInto(der, next, ext.end, X509_TAG_OCTET_STRING, value) || value.end !== ext.end) {
2008
2106
  return false
2009
2107
  }
2010
- const read: i32 = x509ReadExtension(der, x509ExtensionArc(der, id), value.start, value.end, out)
2108
+ const ce: i32 = x509ExtensionArc(der, id)
2109
+ const read: i32 = x509ReadExtension(der, ce, value.start, value.end, out)
2011
2110
  if (read === X509_EXT_MALFORMED) {
2012
2111
  return false
2013
2112
  }
2113
+ if (x509DerContentsAre(der, id, aia) && !x509AuthorityInfoAccessSound(der, value.start, value.end)) {
2114
+ return false
2115
+ }
2116
+ if (ce === X509_CE_POLICY_CONSTRAINTS) {
2117
+ out.pcPresent = true
2118
+ }
2119
+ if (critical) {
2120
+ x509NoteCritical(ce, out)
2121
+ }
2014
2122
  if (read === X509_EXT_UNKNOWN) {
2015
2123
  out.unknownCritical = out.unknownCritical || critical
2016
2124
  }
@@ -2036,9 +2144,10 @@ const x509ReadExtensions = (der: u8[], e: X509DerElement, out: X509Certificate):
2036
2144
  *
2037
2145
  * Extensions are read: subjectAltName, basicConstraints, keyUsage,
2038
2146
  * extKeyUsage, nameConstraints and the two key identifiers are decoded into
2039
- * their fields, and `null` is the answer when any of them is malformed or any
2040
- * extension appears twice. A critical extension it does not decode sets
2041
- * `unknownCritical`, which RFC 5280 §4.2 obliges a validator to refuse.
2147
+ * their fields with their critical flags, and `null` is the answer when any of
2148
+ * them, or an authorityInfoAccess, is malformed or any extension appears
2149
+ * twice. A critical extension it does not decode sets `unknownCritical`, which
2150
+ * RFC 5280 §4.2 obliges a validator to refuse.
2042
2151
  *
2043
2152
  * **A parser, not a validator.** It checks that the bytes are one certificate
2044
2153
  * and what its extensions say. It does not check the signature
@@ -2172,6 +2281,7 @@ export const x509ParseCertificate = (der: u8[]): X509Certificate | null => {
2172
2281
  out.issuer = x509DerWhole(der, issuer)
2173
2282
  out.subject = x509DerWhole(der, subject)
2174
2283
  out.publicKey = publicKey
2284
+ out.spki = x509DerWhole(der, spki)
2175
2285
  out.p256 = out.keyType === X509_KEY_P256
2176
2286
  out.notBefore = before
2177
2287
  out.notAfter = after
@@ -0,0 +1,273 @@
1
+ /**
2
+ * `nish/host/game` — the memory a game built for `wasm32` shares with the page
3
+ * that runs it: the frame it draws, the input the page feeds it, the sounds it
4
+ * asks for and the samples the page plays them from. Every piece is module
5
+ * storage, so the page reaches it in place through the loader's
6
+ * `views().storage` (the keys below are the storage's names) and nothing is
7
+ * copied across the boundary in either direction.
8
+ *
9
+ * | Storage | Words | Written by | Holds |
10
+ * | --- | --- | --- | --- |
11
+ * | `GAME_FRAME` | `Int32Array(960 × 540)` | the game | the frame, `0xRRGGBB`, row-major, `width` words a row |
12
+ * | `GAME_INFO` | `Int32Array(4)` | the game | `[width, height, samples, sampleRate]` |
13
+ * | `GAME_INPUT` | `Int32Array(2 + 7 × 64)` | the page | a `nish/host/ring` of input events, 7 words each |
14
+ * | `GAME_SOUNDS` | `Int32Array(2 + 32)` | the game | a `nish/host/ring` of sound ids to start |
15
+ * | `GAME_SAMPLES` | `Float32Array(96000)` | the game | one sound's samples, `-1..1` |
16
+ *
17
+ * **The frame.** The game picks its size with `gameSetSize` (at most
18
+ * `GAME_MAX_WIDTH × GAME_MAX_HEIGHT`) and draws into `GAME_FRAME`, for
19
+ * instance by lending it to `nish/raster` with `gameWidth()` and
20
+ * `gameHeight()`. The page reads `GAME_INFO[0]` and `[1]` and copies the first
21
+ * `width × height` words into its canvas, setting each pixel's alpha to 255
22
+ * as it does. Storage cannot be returned or aliased, so a program names
23
+ * `GAME_FRAME` itself rather than asking a function for it.
24
+ *
25
+ * **Input.** The page pushes one record of `GAME_EVENT_WORDS` words per event
26
+ * onto `GAME_INPUT`, and pushes a record only when the ring has room for all
27
+ * of it. The words are:
28
+ *
29
+ * | Word | Key event | Pointer event | Focus event |
30
+ * | --- | --- | --- | --- |
31
+ * | 0 | `EVENT_KEY` | `EVENT_MOUSE` | `EVENT_FOCUS` |
32
+ * | 1 | the `KEY_` kind | the `MOUSE_` button, `MOUSE_NONE` for a move | 1 gained, 0 lost |
33
+ * | 2 | the code point, for `KEY_CHAR` | 0 | 0 |
34
+ * | 3 | the `MOD_` bits | the `MOD_` bits | 0 |
35
+ * | 4 | `ACTION_PRESS`, `ACTION_REPEAT` or `ACTION_RELEASE` | `ACTION_PRESS`, `ACTION_RELEASE` or `ACTION_MOVE` | 0 |
36
+ * | 5 | 0 | x, in frame pixels | 0 |
37
+ * | 6 | 0 | y, in frame pixels | 0 |
38
+ *
39
+ * The constants are `nish/term`'s, so a step reads the page's keys exactly as
40
+ * it reads a terminal's. Each step the game calls `gameReadInput`, which
41
+ * drains the ring into a `nish/input` `StepInput`: its `events` become this
42
+ * step's events and its `keys` (a `KeyState`) keep which keys are held, for
43
+ * `isDown`. A page sees every key go up, so it sends a release for every press
44
+ * (`keyup`) and a lost focus on `blur`, which releases every held key; the
45
+ * reader turns `KeyState`'s synthetic releases off. A page has no terminal to
46
+ * quit, so Ctrl-C arrives as an ordinary key press, never `EVENT_QUIT`. Nor
47
+ * does the reader make up auto-repeat: a page that wants it sends
48
+ * `ACTION_REPEAT` records itself (a `keydown` with `repeat` set, say). A
49
+ * pointer event's x and y are set as both the event's cell (`x`, `y`) and its
50
+ * pixel (`px`, `py`).
51
+ * A record with an unknown kind is dropped, and so is a trailing part-record
52
+ * a page pushed out of protocol.
53
+ *
54
+ * **Sound.** The game names its sounds by small ids and asks for one with
55
+ * `gamePlaySound`, which queues the id on `GAME_SOUNDS`; the page shifts the
56
+ * ring after each step and starts each id's buffer. To build those buffers,
57
+ * the page calls an export of the game's once per id at start, which
58
+ * synthesizes the sound (with `nish/synth`, say) and hands it to
59
+ * `gameWriteSamples`; the page then reads `GAME_INFO[2]` samples of
60
+ * `GAME_SAMPLES` at `GAME_INFO[3]` Hz into an `AudioBuffer`.
61
+ *
62
+ * import { GAME_FRAME, gameHeight, gamePlaySound, gameReadInput, gameSetSize, gameWidth, gameWriteSamples } from "nish/host/game";
63
+ * import { KeyState } from "nish/term";
64
+ * import { StepInput } from "nish/input";
65
+ * import { rasterRect } from "nish/raster";
66
+ * import { SYNTH_SQUARE, synthSilence, synthTone } from "nish/synth";
67
+ *
68
+ * const input = new StepInput(new KeyState());
69
+ *
70
+ * export const start = (): void => gameSetSize(320, 180);
71
+ *
72
+ * export const sound = (id: i32): i32 => {
73
+ * const out = synthSilence(0.1, 22050);
74
+ * synthTone(out, 22050, 0.0, 0.1, 440.0 + toF64(id) * 110.0, 220.0, SYNTH_SQUARE, 0.3, 20.0);
75
+ * return gameWriteSamples(out, 22050);
76
+ * };
77
+ *
78
+ * export const step = (nowMs: f64): void => {
79
+ * gameReadInput(input, nowMs);
80
+ * if (input.events.length > 0) gamePlaySound(0);
81
+ * rasterRect(GAME_FRAME, gameWidth(), gameHeight(), 0, 0, 320, 180, 0x101830, 256);
82
+ * };
83
+ *
84
+ * **Building it.** A page's game is compiled with `--target wasm32` and
85
+ * linked by `scripts/build.sh` with `--profile wasm-host`, which exports the
86
+ * storage above for the loader's `views()`, and `--memory <MiB>`, which pins
87
+ * the memory so those views never go stale. The
88
+ * storage alone is about 2.5 MB (`GAME_FRAME` 2 MB, `GAME_SAMPLES` 384 KB,
89
+ * the rings 2 KB), so pin at least 4 MiB, more for what the game itself
90
+ * allocates. The `GAME_*` names are the page's keys and are reserved: when
91
+ * two modules declare storage of one name, the later module's is keyed by its
92
+ * symbol instead, so a program's own `GAME_FRAME` could move this module's
93
+ * off the key the page reads.
94
+ *
95
+ * The module is ordinary Nish everywhere: a native build has the same
96
+ * storage, so a test can push records onto `GAME_INPUT` and read the frame
97
+ * back without a page. It needs no capability and does no I/O.
98
+ */
99
+ import { ringClear, ringPush, ringShift, ringSize } from "nish/host/ring"
100
+ import { StepInput } from "nish/input"
101
+ import { EVENT_FOCUS, EVENT_KEY, EVENT_MOUSE, TermEvent } from "nish/term"
102
+
103
+ /** The widest frame `GAME_FRAME` holds, in pixels. */
104
+ export const GAME_MAX_WIDTH: i32 = 960
105
+
106
+ /** The tallest frame `GAME_FRAME` holds, in pixels. */
107
+ export const GAME_MAX_HEIGHT: i32 = 540
108
+
109
+ /** The words of one input record on `GAME_INPUT`. */
110
+ export const GAME_EVENT_WORDS: i32 = 7
111
+
112
+ /** The input records `GAME_INPUT` holds at once. */
113
+ export const GAME_INPUT_EVENTS: i32 = 64
114
+
115
+ /** The sound ids `GAME_SOUNDS` holds at once. */
116
+ export const GAME_SOUND_SLOTS: i32 = 32
117
+
118
+ /** The samples `GAME_SAMPLES` holds: two seconds at 48000 Hz. */
119
+ export const GAME_SAMPLE_LIMIT: i32 = 96000
120
+
121
+ /** `GAME_INFO`'s word for the frame's width in pixels. */
122
+ export const GAME_INFO_WIDTH: i32 = 0
123
+
124
+ /** `GAME_INFO`'s word for the frame's height in pixels. */
125
+ export const GAME_INFO_HEIGHT: i32 = 1
126
+
127
+ /** `GAME_INFO`'s word for how many samples `gameWriteSamples` last wrote. */
128
+ export const GAME_INFO_SAMPLES: i32 = 2
129
+
130
+ /** `GAME_INFO`'s word for the sample rate of those samples, in Hz. */
131
+ export const GAME_INFO_RATE: i32 = 3
132
+
133
+ /** The frame: `0xRRGGBB` pixels, row-major, `GAME_INFO[GAME_INFO_WIDTH]` words a row. */
134
+ export const GAME_FRAME = new Int32Array(960 * 540)
135
+
136
+ /** The frame's size and the last sound's sample count and rate; see `GAME_INFO_WIDTH` and the rest. */
137
+ export const GAME_INFO = new Int32Array(4)
138
+
139
+ /** The page's input events: a `nish/host/ring` of `GAME_EVENT_WORDS`-word records. */
140
+ export const GAME_INPUT = new Int32Array(2 + 7 * 64)
141
+
142
+ /** The sound ids the game asked for since the page last looked: a `nish/host/ring`. */
143
+ export const GAME_SOUNDS = new Int32Array(2 + 32)
144
+
145
+ /** One sound's samples, written by `gameWriteSamples` for the page to copy. */
146
+ export const GAME_SAMPLES = new Float32Array(96000)
147
+
148
+ /** `v` held to `0..most`. */
149
+ const gameClamp = (v: i32, most: i32): i32 => Math.min(Math.max(v, 0), most)
150
+
151
+ /**
152
+ * Set the frame's size, which the page reads to know how much of `GAME_FRAME`
153
+ * to show. Each side is held to `0..GAME_MAX_WIDTH` and `0..GAME_MAX_HEIGHT`.
154
+ * The pixels are not touched: the next frame draws over them.
155
+ *
156
+ * @param width - the frame's width in pixels
157
+ * @param height - the frame's height in pixels
158
+ */
159
+ export const gameSetSize = (width: i32, height: i32): void => {
160
+ GAME_INFO[GAME_INFO_WIDTH] = gameClamp(width, GAME_MAX_WIDTH)
161
+ GAME_INFO[GAME_INFO_HEIGHT] = gameClamp(height, GAME_MAX_HEIGHT)
162
+ }
163
+
164
+ /**
165
+ * The frame's width, as `gameSetSize` set it.
166
+ *
167
+ * @returns the width in pixels, held to `0..GAME_MAX_WIDTH` even if the page wrote the word
168
+ */
169
+ export const gameWidth = (): i32 => gameClamp(GAME_INFO[GAME_INFO_WIDTH], GAME_MAX_WIDTH)
170
+
171
+ /**
172
+ * The frame's height, as `gameSetSize` set it.
173
+ *
174
+ * @returns the height in pixels, held to `0..GAME_MAX_HEIGHT` even if the page wrote the word
175
+ */
176
+ export const gameHeight = (): i32 => gameClamp(GAME_INFO[GAME_INFO_HEIGHT], GAME_MAX_HEIGHT)
177
+
178
+ /** The next record on `GAME_INPUT` as a `TermEvent`, or null for a kind the reader does not know. */
179
+ const gameEventOf = (): TermEvent | null => {
180
+ const type: i32 = ringShift(GAME_INPUT)
181
+ const what: i32 = ringShift(GAME_INPUT)
182
+ const code: i32 = ringShift(GAME_INPUT)
183
+ const modifiers: i32 = ringShift(GAME_INPUT)
184
+ const action: i32 = ringShift(GAME_INPUT)
185
+ const x: i32 = ringShift(GAME_INPUT)
186
+ const y: i32 = ringShift(GAME_INPUT)
187
+ if (type !== EVENT_KEY && type !== EVENT_MOUSE && type !== EVENT_FOCUS) {
188
+ return null
189
+ }
190
+ const e = new TermEvent(type)
191
+ if (type === EVENT_FOCUS) {
192
+ e.gained = what !== 0
193
+ return e
194
+ }
195
+ e.modifiers = modifiers
196
+ e.action = action
197
+ if (type === EVENT_KEY) {
198
+ e.key = what
199
+ e.code = code
200
+ return e
201
+ }
202
+ e.button = what
203
+ e.x = x
204
+ e.y = y
205
+ e.px = x
206
+ e.py = y
207
+ return e
208
+ }
209
+
210
+ /**
211
+ * Drain the page's input into `input`: every whole record on `GAME_INPUT`
212
+ * becomes a `TermEvent`, and `input.events` becomes what `input.keys.apply`
213
+ * makes of them at `nowMs`, so `input.isDown` answers for the keys still held.
214
+ * The page sends real key releases, so the key state's synthetic releases are
215
+ * turned off, and Ctrl-C is an ordinary key (a page's copy), not a quit. A
216
+ * trailing part-record is dropped.
217
+ *
218
+ * @param input - the step's input, kept by the game from step to step
219
+ * @param nowMs - the step's clock in milliseconds, for the key state
220
+ */
221
+ export const gameReadInput = (input: StepInput, nowMs: f64): void => {
222
+ input.keys.releasesAreSynthetic = false
223
+ input.keys.quitOnCtrlC = false
224
+ const read: TermEvent[] = []
225
+ while (ringSize(GAME_INPUT) >= GAME_EVENT_WORDS) {
226
+ const e = gameEventOf()
227
+ if (e !== null) {
228
+ read.push(e)
229
+ }
230
+ }
231
+ if (ringSize(GAME_INPUT) > 0) {
232
+ ringClear(GAME_INPUT)
233
+ }
234
+ input.events = input.keys.apply(read, nowMs)
235
+ }
236
+
237
+ /**
238
+ * Ask the page to start a sound: `id` goes on `GAME_SOUNDS`, which the page
239
+ * drains after the step. A full queue drops the id, since a sound late by a
240
+ * frame is worse than one missed.
241
+ *
242
+ * @param id - the sound's id, the one the page fetched its samples by
243
+ * @returns whether the id was queued
244
+ */
245
+ export const gamePlaySound = (id: i32): boolean => ringPush(GAME_SOUNDS, id)
246
+
247
+ /**
248
+ * Hand one sound's samples to the page: each is clipped to `-1..1` (NaN is
249
+ * 0) and written to `GAME_SAMPLES` as an `f32`, and `GAME_INFO` records how
250
+ * many and at what rate. Samples past `GAME_SAMPLE_LIMIT` are cut off.
251
+ *
252
+ * @param samples - the sound, at `sampleRate` samples a second
253
+ * @param sampleRate - the samples' rate in Hz
254
+ * @returns how many samples were written
255
+ */
256
+ export const gameWriteSamples = (samples: f64[], sampleRate: i32): i32 => {
257
+ const n: i32 = Math.min(toI32(samples.length), GAME_SAMPLE_LIMIT)
258
+ for (let i: i32 = 0; i < n && i < toI32(samples.length); i++) {
259
+ const s: f64 = samples[i]
260
+ let x: f64 = 0.0
261
+ if (s > 1.0) {
262
+ x = 1.0
263
+ } else if (s < -1.0) {
264
+ x = -1.0
265
+ } else if (s >= -1.0) {
266
+ x = s
267
+ }
268
+ GAME_SAMPLES[i] = toF32(x)
269
+ }
270
+ GAME_INFO[GAME_INFO_SAMPLES] = n
271
+ GAME_INFO[GAME_INFO_RATE] = sampleRate
272
+ return n
273
+ }
package/std/input.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `nish/input` — what one fixed step of a program reads from its player: the
3
+ * key and mouse events since the last step, and which keys are held down.
4
+ *
5
+ * The module is pure: no capability, no I/O and no clock. Code that steps a
6
+ * scene takes a `StepInput`, so it compiles for a terminal, for `wasm32`
7
+ * behind a page, or for a test that scripts the keys, and runs the same way
8
+ * under each. The host owns one `StepInput` and points it at what it read
9
+ * each step; nothing is copied.
10
+ *
11
+ * import { KEY_CHAR, KeyState } from "nish/term"
12
+ * import { StepInput } from "nish/input"
13
+ *
14
+ * const quits = (input: StepInput): boolean => input.isDown(KEY_CHAR, 113)
15
+ *
16
+ * const input = new StepInput(new KeyState())
17
+ * // each step, with the events the host read and its clock in ms:
18
+ * input.events = input.keys.apply(read, nowMs)
19
+ * if (quits(input)) { ... }
20
+ *
21
+ * A terminal program sets `events` and `keys` from the `TermInput` that
22
+ * `nish/term-io`'s `runTerminal` hands it. The events and key state themselves
23
+ * (`TermEvent`, `KeyState` and the `KEY_`, `EVENT_` and `ACTION_` constants)
24
+ * are `nish/term`'s, which is pure too.
25
+ */
26
+ import { KeyState, TermEvent } from "nish/term"
27
+
28
+ /** The input of one step: the events since the last step and which keys are down. */
29
+ export class StepInput {
30
+ /** The events since the last step, in the order they arrived; the step may filter them in place. */
31
+ events: TermEvent[]
32
+ /** Which keys are down, for `isDown`. */
33
+ keys: KeyState
34
+
35
+ /**
36
+ * An input with no events yet.
37
+ *
38
+ * @param keys The key state the host keeps current, which `isDown` reads.
39
+ */
40
+ constructor(keys: KeyState) {
41
+ this.events = []
42
+ this.keys = keys
43
+ }
44
+
45
+ /**
46
+ * Whether a key is down.
47
+ *
48
+ * @param key The key's `KEY_` kind.
49
+ * @param code The code point for `KEY_CHAR`; it tells `KEY_CONTROL` and `KEY_UNKNOWN` keys apart
50
+ * too, and is ignored for the other kinds.
51
+ * @returns True from the key's press until its release, real or synthetic, or a loss of focus.
52
+ */
53
+ isDown(key: i32, code: i32): boolean {
54
+ return this.keys.isDown(key, code)
55
+ }
56
+ }