@yaks/api 0.0.0-stage → 0.2.36

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 (152) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +956 -2
  3. package/_dist/actor.d.ts +59 -0
  4. package/_dist/actor.d.ts.map +1 -0
  5. package/_dist/address.d.ts +33 -0
  6. package/_dist/address.d.ts.map +1 -0
  7. package/_dist/asset.d.ts +15 -0
  8. package/_dist/asset.d.ts.map +1 -0
  9. package/_dist/batches.d.ts +4 -0
  10. package/_dist/batches.d.ts.map +1 -0
  11. package/_dist/body.d.ts +7 -0
  12. package/_dist/body.d.ts.map +1 -0
  13. package/_dist/deno.d.ts +38 -0
  14. package/_dist/deno.d.ts.map +1 -0
  15. package/_dist/doors.d.ts +134 -0
  16. package/_dist/doors.d.ts.map +1 -0
  17. package/_dist/graph.d.ts +17 -0
  18. package/_dist/graph.d.ts.map +1 -0
  19. package/_dist/headers.d.ts +5 -0
  20. package/_dist/headers.d.ts.map +1 -0
  21. package/_dist/log.d.ts +253 -0
  22. package/_dist/log.d.ts.map +1 -0
  23. package/_dist/mod.d.ts +71 -0
  24. package/_dist/mod.d.ts.map +1 -0
  25. package/_dist/publish.d.ts +7 -0
  26. package/_dist/publish.d.ts.map +1 -0
  27. package/_dist/reached.d.ts +145 -0
  28. package/_dist/reached.d.ts.map +1 -0
  29. package/_dist/receipts.d.ts +153 -0
  30. package/_dist/receipts.d.ts.map +1 -0
  31. package/_dist/refuse.d.ts +51 -0
  32. package/_dist/refuse.d.ts.map +1 -0
  33. package/_dist/relay.d.ts +3 -0
  34. package/_dist/relay.d.ts.map +1 -0
  35. package/_dist/request.d.ts +79 -0
  36. package/_dist/request.d.ts.map +1 -0
  37. package/_dist/requests.d.ts +7 -0
  38. package/_dist/requests.d.ts.map +1 -0
  39. package/_dist/route.d.ts +71 -0
  40. package/_dist/route.d.ts.map +1 -0
  41. package/_dist/routed.d.ts +33 -0
  42. package/_dist/routed.d.ts.map +1 -0
  43. package/_dist/routes.d.ts +46 -0
  44. package/_dist/routes.d.ts.map +1 -0
  45. package/_dist/save.d.ts +6 -0
  46. package/_dist/save.d.ts.map +1 -0
  47. package/_dist/socket.d.ts +73 -0
  48. package/_dist/socket.d.ts.map +1 -0
  49. package/_dist/subs.d.ts +134 -0
  50. package/_dist/subs.d.ts.map +1 -0
  51. package/_dist/timing.d.ts +8 -0
  52. package/_dist/timing.d.ts.map +1 -0
  53. package/_dist/tools.d.ts +80 -0
  54. package/_dist/tools.d.ts.map +1 -0
  55. package/_dist/vocab.d.ts +6 -0
  56. package/_dist/vocab.d.ts.map +1 -0
  57. package/access.js +32 -0
  58. package/access.js.map +1 -0
  59. package/access.ts +42 -0
  60. package/actor.js +75 -0
  61. package/actor.js.map +1 -0
  62. package/actor.ts +106 -0
  63. package/address.js +42 -0
  64. package/address.js.map +1 -0
  65. package/address.ts +49 -0
  66. package/admission.js +71 -0
  67. package/admission.js.map +1 -0
  68. package/admission.ts +64 -0
  69. package/asset.js +37 -0
  70. package/asset.js.map +1 -0
  71. package/asset.ts +47 -0
  72. package/batches.js +92 -0
  73. package/batches.js.map +1 -0
  74. package/batches.ts +96 -0
  75. package/body.js +51 -0
  76. package/body.js.map +1 -0
  77. package/body.ts +82 -0
  78. package/deno.js +88 -0
  79. package/deno.js.map +1 -0
  80. package/deno.json +1 -0
  81. package/deno.ts +150 -0
  82. package/doors.js +435 -0
  83. package/doors.js.map +1 -0
  84. package/doors.ts +570 -0
  85. package/graph.js +12 -0
  86. package/graph.js.map +1 -0
  87. package/graph.ts +23 -0
  88. package/headers.js +5 -0
  89. package/headers.js.map +1 -0
  90. package/headers.ts +9 -0
  91. package/interest.js +224 -0
  92. package/interest.js.map +1 -0
  93. package/interest.ts +264 -0
  94. package/log.js +1011 -0
  95. package/log.js.map +1 -0
  96. package/log.ts +1035 -0
  97. package/mod.js +69 -0
  98. package/mod.js.map +1 -0
  99. package/mod.ts +142 -0
  100. package/package.json +75 -4
  101. package/peer_query.js +164 -0
  102. package/peer_query.js.map +1 -0
  103. package/peer_query.ts +158 -0
  104. package/publish.js +7 -0
  105. package/publish.js.map +1 -0
  106. package/publish.ts +16 -0
  107. package/reached.js +456 -0
  108. package/reached.js.map +1 -0
  109. package/reached.ts +549 -0
  110. package/receipts.js +543 -0
  111. package/receipts.js.map +1 -0
  112. package/receipts.ts +749 -0
  113. package/refuse.js +120 -0
  114. package/refuse.js.map +1 -0
  115. package/refuse.ts +179 -0
  116. package/relay.js +249 -0
  117. package/relay.js.map +1 -0
  118. package/relay.ts +284 -0
  119. package/request.js +218 -0
  120. package/request.js.map +1 -0
  121. package/request.ts +235 -0
  122. package/requests.js +250 -0
  123. package/requests.js.map +1 -0
  124. package/requests.ts +257 -0
  125. package/route.js +139 -0
  126. package/route.js.map +1 -0
  127. package/route.ts +228 -0
  128. package/routed.js +25 -0
  129. package/routed.js.map +1 -0
  130. package/routed.ts +53 -0
  131. package/routes.js +154 -0
  132. package/routes.js.map +1 -0
  133. package/routes.ts +201 -0
  134. package/save.js +341 -0
  135. package/save.js.map +1 -0
  136. package/save.ts +393 -0
  137. package/socket.js +398 -0
  138. package/socket.js.map +1 -0
  139. package/socket.ts +496 -0
  140. package/subs.js +2295 -0
  141. package/subs.js.map +1 -0
  142. package/subs.ts +2979 -0
  143. package/timing.js +17 -0
  144. package/timing.js.map +1 -0
  145. package/timing.ts +26 -0
  146. package/tools.js +251 -0
  147. package/tools.js.map +1 -0
  148. package/tools.ts +315 -0
  149. package/vocab.js +18 -0
  150. package/vocab.js.map +1 -0
  151. package/vocab.json +93 -0
  152. package/vocab.ts +18 -0
package/body.js ADDED
@@ -0,0 +1,51 @@
1
+ // Read a whole request before acting on it. A cancelled upload is the
2
+ // caller's refusal; failures elsewhere keep their original error identity.
3
+ import { Refused } from "@yaks/graph/errors";
4
+ /** Receive body bytes, distinguishing cancellation from a server failure. */ export let receiveBody = async (request, read)=>{
5
+ try {
6
+ return await read();
7
+ } catch (error) {
8
+ if (request.signal.aborted || error instanceof Error && error.name == 'AbortError' || error instanceof TypeError && error.message == "Can't read from request stream because client disconnected.") throw new Refused('request body was interrupted');
9
+ throw error;
10
+ }
11
+ };
12
+ /** Receive the complete body, refusing an upload its client interrupted. */ export let readBody = (request)=>receiveBody(request, ()=>request.text());
13
+ /** An atomic write is read whole. Larger imports use the streaming wire. */ export let WRITE_BYTES = 4 * 1024 * 1024;
14
+ /** Whether a request carries a newline-delimited bulk import. */ export let poured = (request)=>(request.headers.get('content-type') ?? '').toLowerCase().includes('ndjson');
15
+ /** A write whose input needs the streaming wire or a smaller batch. */ export let writeSize = ()=>new Refused('Write exceeds the Store batch size. Send smaller batches or use NDJSON for a bulk import.');
16
+ /** Read request chunks with their upload cancellation semantics. */ export let bodyChunks = async function*(request) {
17
+ if (!request.body) return;
18
+ let reader = request.body.getReader();
19
+ let finished = false;
20
+ try {
21
+ while(true){
22
+ let { done, value } = await receiveBody(request, ()=>reader.read());
23
+ if (done || !value) {
24
+ finished = true;
25
+ return;
26
+ }
27
+ yield value;
28
+ }
29
+ } finally{
30
+ if (!finished) void reader.cancel().catch(()=>{});
31
+ reader.releaseLock();
32
+ }
33
+ };
34
+ /** Read one atomic JSON or binary batch, rejecting before buffering it whole
35
+ * if it exceeds the limit. */ export let writeBytes = async (request)=>{
36
+ let parts = [];
37
+ let length = 0;
38
+ for await (let bytes of bodyChunks(request)){
39
+ length += bytes.byteLength;
40
+ if (length > WRITE_BYTES) throw writeSize();
41
+ parts.push(bytes);
42
+ }
43
+ let out = new Uint8Array(length);
44
+ let at = 0;
45
+ for (let bytes of parts){
46
+ out.set(bytes, at);
47
+ at += bytes.byteLength;
48
+ }
49
+ return out;
50
+ };
51
+ //# sourceMappingURL=body.js.map
package/body.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"body.js","sources":["./body.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,2EAA2E;AAC3E,SAAS,OAAO,kCAAuC;AAEvD,2EAA2E,GAC3E,OAAO,IAAI,cAAc,OACvB,SACA;EAEA,IAAI;IACF,OAAO,MAAM;EACf,EAAE,OAAO,OAAO;IACd,IACE,QAAQ,MAAM,CAAC,OAAO,IACtB,iBAAiB,SAAS,MAAM,IAAI,IAAI,gBACxC,iBAAiB,aACf,MAAM,OAAO,IACX,+DACJ,MAAM,IAAI,QAAQ;IACpB,MAAM;EACR;AACF,EAAC;AAED,0EAA0E,GAC1E,OAAO,IAAI,WAAW,CAAC,UACrB,YAAY,SAAS,IAAM,QAAQ,IAAI,IAAG;AAE5C,0EAA0E,GAC1E,OAAO,IAAI,cAAc,IAAI,OAAO,KAAI;AAExC,+DAA+D,GAC/D,OAAO,IAAI,SAAS,CAAC,UACnB,CAAC,QAAQ,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,EAAE,WAAW,GAAG,QAAQ,CAAC,UAAS;AAE9E,qEAAqE,GACrE,OAAO,IAAI,YAAY,IACrB,IAAI,QACF,6FACD;AAEH,kEAAkE,GAClE,OAAO,IAAI,aAAa,gBACtB,OAAgB;EAEhB,IAAI,CAAC,QAAQ,IAAI,EAAE;EACnB,IAAI,SAAS,QAAQ,IAAI,CAAC,SAAS;EACnC,IAAI,WAAW;EACf,IAAI;IACF,MAAO,KAAM;MACX,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,YAAY,SAAS,IAAM,OAAO,IAAI;MAClE,IAAI,QAAQ,CAAC,OAAO;QAClB,WAAW;QACX;MACF;MACA,MAAM;IACR;EACF,SAAU;IACR,IAAI,CAAC,UAAU,KAAK,OAAO,MAAM,GAAG,KAAK,CAAC,KAAO;IACjD,OAAO,WAAW;EACpB;AACF,EAAC;AAED;4BAC4B,GAC5B,OAAO,IAAI,aAAa,OACtB;EAEA,IAAI,QAAsB,EAAE;EAC5B,IAAI,SAAS;EACb,WAAW,IAAI,SAAS,WAAW,SAAU;IAC3C,UAAU,MAAM,UAAU;IAC1B,IAAI,SAAS,aAAa,MAAM;IAChC,MAAM,IAAI,CAAC;EACb;EACA,IAAI,MAAM,IAAI,WAAW;EACzB,IAAI,KAAK;EACT,KAAK,IAAI,SAAS,MAAO;IACvB,IAAI,GAAG,CAAC,OAAO;IACf,MAAM,MAAM,UAAU;EACxB;EACA,OAAO;AACT,EAAC"}
package/body.ts ADDED
@@ -0,0 +1,82 @@
1
+ // Read a whole request before acting on it. A cancelled upload is the
2
+ // caller's refusal; failures elsewhere keep their original error identity.
3
+ import { Refused } from '@yaks/graph/errors'
4
+
5
+ /** Receive body bytes, distinguishing cancellation from a server failure. */
6
+ export let receiveBody = async <T>(
7
+ request: Request,
8
+ read: () => Promise<T>,
9
+ ): Promise<T> => {
10
+ try {
11
+ return await read()
12
+ } catch (error) {
13
+ if (
14
+ request.signal.aborted ||
15
+ error instanceof Error && error.name == 'AbortError' ||
16
+ error instanceof TypeError &&
17
+ error.message ==
18
+ "Can't read from request stream because client disconnected."
19
+ ) throw new Refused('request body was interrupted')
20
+ throw error
21
+ }
22
+ }
23
+
24
+ /** Receive the complete body, refusing an upload its client interrupted. */
25
+ export let readBody = (request: Request): Promise<string> =>
26
+ receiveBody(request, () => request.text())
27
+
28
+ /** An atomic write is read whole. Larger imports use the streaming wire. */
29
+ export let WRITE_BYTES = 4 * 1024 * 1024
30
+
31
+ /** Whether a request carries a newline-delimited bulk import. */
32
+ export let poured = (request: Request): boolean =>
33
+ (request.headers.get('content-type') ?? '').toLowerCase().includes('ndjson')
34
+
35
+ /** A write whose input needs the streaming wire or a smaller batch. */
36
+ export let writeSize = (): Refused =>
37
+ new Refused(
38
+ 'Write exceeds the Store batch size. Send smaller batches or use NDJSON for a bulk import.',
39
+ )
40
+
41
+ /** Read request chunks with their upload cancellation semantics. */
42
+ export let bodyChunks = async function* (
43
+ request: Request,
44
+ ): AsyncGenerator<Uint8Array> {
45
+ if (!request.body) return
46
+ let reader = request.body.getReader()
47
+ let finished = false
48
+ try {
49
+ while (true) {
50
+ let { done, value } = await receiveBody(request, () => reader.read())
51
+ if (done || !value) {
52
+ finished = true
53
+ return
54
+ }
55
+ yield value
56
+ }
57
+ } finally {
58
+ if (!finished) void reader.cancel().catch(() => {})
59
+ reader.releaseLock()
60
+ }
61
+ }
62
+
63
+ /** Read one atomic JSON or binary batch, rejecting before buffering it whole
64
+ * if it exceeds the limit. */
65
+ export let writeBytes = async (
66
+ request: Request,
67
+ ): Promise<Uint8Array<ArrayBuffer>> => {
68
+ let parts: Uint8Array[] = []
69
+ let length = 0
70
+ for await (let bytes of bodyChunks(request)) {
71
+ length += bytes.byteLength
72
+ if (length > WRITE_BYTES) throw writeSize()
73
+ parts.push(bytes)
74
+ }
75
+ let out = new Uint8Array(length)
76
+ let at = 0
77
+ for (let bytes of parts) {
78
+ out.set(bytes, at)
79
+ at += bytes.byteLength
80
+ }
81
+ return out
82
+ }
package/deno.js ADDED
@@ -0,0 +1,88 @@
1
+ // The runtime-specific steps, kept in the one file that knows about a runtime.
2
+ // Everything else in this package is standard `Request`, `Response` and
3
+ // `WebSocket`. Two things are not standard: upgrading a request to a WebSocket,
4
+ // which the application supplies, and binding a TCP port, which the `serve`
5
+ // tool does. Both default to the runtime most applications start on.
6
+ //
7
+ // The `Deno` global is looked up at call time rather than imported, so this
8
+ // module loads and type-checks anywhere, with no Deno types in the package's
9
+ // compile at all. On another runtime it throws when called, and the error
10
+ // names the fix: pass your own `upgrade`.
11
+ // This runtime's `Deno.upgradeWebSocket`, or null when there is none.
12
+ let found = ()=>{
13
+ let host = globalThis;
14
+ if (!host || typeof host != 'object' || !('Deno' in host)) return null;
15
+ let deno = host.Deno;
16
+ if (!deno || typeof deno != 'object' || !('upgradeWebSocket' in deno)) {
17
+ return null;
18
+ }
19
+ let up = deno.upgradeWebSocket;
20
+ return typeof up == 'function' ? (request)=>up(request) : null;
21
+ };
22
+ // Deno ties an upgrade to the Request it served. One rebuilt from it with
23
+ // `new Request(served, init)` upgrades too, but the socket it gives sends
24
+ // frames every client refuses ("Reserved bits are not zero"). So each request
25
+ // `rebuild` makes remembers the one Deno served, and the upgrade takes that.
26
+ let served = new WeakMap();
27
+ /** `new Request(request, init)`, which still upgrades to a WebSocket through
28
+ * {@link denoUpgrade} as the request Deno served. */ export let rebuild = (request, init)=>{
29
+ let copy = new Request(request, init);
30
+ served.set(copy, served.get(request) ?? request);
31
+ return copy;
32
+ };
33
+ /**
34
+ * Deno's WebSocket upgrade, as an {@link Upgrade}. The default for `/ws`; on
35
+ * any other runtime it throws, and the application passes its own.
36
+ *
37
+ * ```ts ignore
38
+ * Deno.serve(api({ graph, upgrade: denoUpgrade }))
39
+ * ```
40
+ */ export let denoUpgrade = (request)=>{
41
+ let up = found();
42
+ if (!up) {
43
+ throw new Error('@yaks/api: no Deno.upgradeWebSocket here — pass `upgrade`');
44
+ }
45
+ return up(served.get(request) ?? request);
46
+ };
47
+ // This runtime's `Deno.serve`, or null when there is none — found the same way
48
+ // as the upgrade above, and for the same reason.
49
+ let listener = ()=>{
50
+ let host = globalThis;
51
+ if (!host || typeof host != 'object' || !('Deno' in host)) return null;
52
+ let deno = host.Deno;
53
+ if (!deno || typeof deno != 'object' || !('serve' in deno)) return null;
54
+ let go = deno.serve;
55
+ return typeof go == 'function' ? (opts, handler)=>go(opts, handler) : null;
56
+ };
57
+ /**
58
+ * Deno's own server, as a {@link Listen} — what the `serve` tool binds a port
59
+ * with (./tools.ts). A runtime that binds its own port, such as a Cloudflare
60
+ * Worker, has no `Deno.serve` and nothing for that tool to do, so this throws
61
+ * there rather than pretending to listen.
62
+ */ export let denoListen = (opts, handler)=>{
63
+ let go = listener();
64
+ if (!go) {
65
+ throw new Error('@yaks/api: no Deno.serve here — this runtime binds its own');
66
+ }
67
+ return go(opts, handler);
68
+ };
69
+ let files = ()=>{
70
+ let host = globalThis;
71
+ let deno = host && typeof host == 'object' && 'Deno' in host ? host.Deno : null;
72
+ if (!deno || typeof deno != 'object' || !('writeTextFile' in deno)) {
73
+ throw new Error('@yaks/api: no Deno here to say a server is ready');
74
+ }
75
+ return deno;
76
+ };
77
+ /**
78
+ * Say this process is serving: its pid, written to `path` for whoever waits
79
+ * on a replacement before stopping the server it replaces (@yaks/cli
80
+ * `restart`). The function returned takes it back.
81
+ */ export let denoReady = async (path)=>{
82
+ let fs = files();
83
+ await fs.writeTextFile(path, `${fs.pid}\n`);
84
+ return ()=>fs.remove(path).catch((error)=>{
85
+ if (error.name != 'NotFound') throw error;
86
+ });
87
+ };
88
+ //# sourceMappingURL=deno.js.map
package/deno.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deno.js","sources":["./deno.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,wEAAwE;AACxE,gFAAgF;AAChF,4EAA4E;AAC5E,qEAAqE;AACrE,EAAE;AACF,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;AAC1E,0CAA0C;AAM1C,sEAAsE;AACtE,IAAI,QAAQ;EACV,IAAI,OAAgB;EACpB,IAAI,CAAC,QAAQ,OAAO,QAAQ,YAAY,CAAC,CAAC,UAAU,IAAI,GAAG,OAAO;EAClE,IAAI,OAAO,KAAK,IAAI;EACpB,IAAI,CAAC,QAAQ,OAAO,QAAQ,YAAY,CAAC,CAAC,sBAAsB,IAAI,GAAG;IACrE,OAAO;EACT;EACA,IAAI,KAAK,KAAK,gBAAgB;EAC9B,OAAO,OAAO,MAAM,aAAa,CAAC,UAAY,GAAG,WAAW;AAC9D;AAEA,0EAA0E;AAC1E,0EAA0E;AAC1E,8EAA8E;AAC9E,6EAA6E;AAC7E,IAAI,SAAS,IAAI;AAEjB;mDACmD,GACnD,OAAO,IAAI,UAAU,CAAC,SAAkB;EACtC,IAAI,OAAO,IAAI,QAAQ,SAAS;EAChC,OAAO,GAAG,CAAC,MAAM,OAAO,GAAG,CAAC,YAAY;EACxC,OAAO;AACT,EAAC;AAED;;;;;;;CAOC,GACD,OAAO,IAAI,cAAuB,CAAC;EACjC,IAAI,KAAK;EACT,IAAI,CAAC,IAAI;IACP,MAAM,IAAI,MAAM;EAClB;EACA,OAAO,GAAG,OAAO,GAAG,CAAC,YAAY;AACnC,EAAC;AAmCD,+EAA+E;AAC/E,iDAAiD;AACjD,IAAI,WAAW;EACb,IAAI,OAAgB;EACpB,IAAI,CAAC,QAAQ,OAAO,QAAQ,YAAY,CAAC,CAAC,UAAU,IAAI,GAAG,OAAO;EAClE,IAAI,OAAO,KAAK,IAAI;EACpB,IAAI,CAAC,QAAQ,OAAO,QAAQ,YAAY,CAAC,CAAC,WAAW,IAAI,GAAG,OAAO;EACnE,IAAI,KAAK,KAAK,KAAK;EACnB,OAAO,OAAO,MAAM,aAChB,CAAC,MAAM,UAAY,GAAG,MAAM,WAC5B;AACN;AAEA;;;;;CAKC,GACD,OAAO,IAAI,aAAqB,CAAC,MAAM;EACrC,IAAI,KAAK;EACT,IAAI,CAAC,IAAI;IACP,MAAM,IAAI,MACR;EAEJ;EACA,OAAO,GAAG,MAAM;AAClB,EAAC;AASD,IAAI,QAAQ;EACV,IAAI,OAAgB;EACpB,IAAI,OAAO,QAAQ,OAAO,QAAQ,YAAY,UAAU,OACpD,KAAK,IAAI,GACT;EACJ,IAAI,CAAC,QAAQ,OAAO,QAAQ,YAAY,CAAC,CAAC,mBAAmB,IAAI,GAAG;IAClE,MAAM,IAAI,MAAM;EAClB;EACA,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,IAAI,YAAY,OAAO;EAC5B,IAAI,KAAK;EACT,MAAM,GAAG,aAAa,CAAC,MAAM,GAAG,GAAG,GAAG,CAAC,EAAE,CAAC;EAC1C,OAAO,IACL,GAAG,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC;MACrB,IAAI,AAAC,MAAgB,IAAI,IAAI,YAAY,MAAM;IACjD;AACJ,EAAC"}
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"compilerOptions":{"lib":["dom","esnext"]},"publish":{"exclude":["**/*_test.ts","testing.ts"]},"name":"@yaks/api","version":"0.2.36","license":"Apache-2.0","description":"Serves graph writes, queries, and live query subscriptions through an HTTP and WebSocket request handler.","exports":{"./headers":"./headers.ts",".":"./mod.ts","./vocab":"./vocab.ts","./address":"./address.ts","./tools":"./tools.ts","./routes":"./routes.ts","./timing":"./timing.ts","./refuse":"./refuse.ts","./graph":"./graph.ts","./asset":"./asset.ts","./routed":"./routed.ts","./log":"./log.ts","./receipts":"./receipts.ts","./reached":"./reached.ts"},"imports":{"@yaks/api/headers":"./headers.ts","@yaks/api":"./mod.ts","@yaks/api/vocab":"./vocab.ts","@yaks/api/address":"./address.ts","@yaks/api/tools":"./tools.ts","@yaks/api/routes":"./routes.ts","@yaks/api/timing":"./timing.ts","@yaks/api/refuse":"./refuse.ts","@yaks/api/graph":"./graph.ts","@yaks/api/asset":"./asset.ts","@yaks/api/routed":"./routed.ts","@yaks/api/log":"./log.ts","@yaks/api/receipts":"./receipts.ts","@yaks/api/reached":"./reached.ts"}}
package/deno.ts ADDED
@@ -0,0 +1,150 @@
1
+ // The runtime-specific steps, kept in the one file that knows about a runtime.
2
+ // Everything else in this package is standard `Request`, `Response` and
3
+ // `WebSocket`. Two things are not standard: upgrading a request to a WebSocket,
4
+ // which the application supplies, and binding a TCP port, which the `serve`
5
+ // tool does. Both default to the runtime most applications start on.
6
+ //
7
+ // The `Deno` global is looked up at call time rather than imported, so this
8
+ // module loads and type-checks anywhere, with no Deno types in the package's
9
+ // compile at all. On another runtime it throws when called, and the error
10
+ // names the fix: pass your own `upgrade`.
11
+
12
+ import type { Socket, Upgrade } from './socket.ts'
13
+
14
+ type Upgrader = (request: Request) => { socket: Socket; response: Response }
15
+
16
+ // This runtime's `Deno.upgradeWebSocket`, or null when there is none.
17
+ let found = (): Upgrader | null => {
18
+ let host: unknown = globalThis
19
+ if (!host || typeof host != 'object' || !('Deno' in host)) return null
20
+ let deno = host.Deno
21
+ if (!deno || typeof deno != 'object' || !('upgradeWebSocket' in deno)) {
22
+ return null
23
+ }
24
+ let up = deno.upgradeWebSocket
25
+ return typeof up == 'function' ? (request) => up(request) : null
26
+ }
27
+
28
+ // Deno ties an upgrade to the Request it served. One rebuilt from it with
29
+ // `new Request(served, init)` upgrades too, but the socket it gives sends
30
+ // frames every client refuses ("Reserved bits are not zero"). So each request
31
+ // `rebuild` makes remembers the one Deno served, and the upgrade takes that.
32
+ let served = new WeakMap<Request, Request>()
33
+
34
+ /** `new Request(request, init)`, which still upgrades to a WebSocket through
35
+ * {@link denoUpgrade} as the request Deno served. */
36
+ export let rebuild = (request: Request, init: RequestInit): Request => {
37
+ let copy = new Request(request, init)
38
+ served.set(copy, served.get(request) ?? request)
39
+ return copy
40
+ }
41
+
42
+ /**
43
+ * Deno's WebSocket upgrade, as an {@link Upgrade}. The default for `/ws`; on
44
+ * any other runtime it throws, and the application passes its own.
45
+ *
46
+ * ```ts ignore
47
+ * Deno.serve(api({ graph, upgrade: denoUpgrade }))
48
+ * ```
49
+ */
50
+ export let denoUpgrade: Upgrade = (request) => {
51
+ let up = found()
52
+ if (!up) {
53
+ throw new Error('@yaks/api: no Deno.upgradeWebSocket here — pass `upgrade`')
54
+ }
55
+ return up(served.get(request) ?? request)
56
+ }
57
+
58
+ /** What a runtime gives back for a port it is now listening on: the promise
59
+ * that settles once it has stopped, and the way to ask it to stop. */
60
+ export type Listener = {
61
+ finished: Promise<void>
62
+ shutdown: () => Promise<void>
63
+ }
64
+
65
+ /** Where a server ended up listening. */
66
+ export type Addr = { hostname: string; port: number }
67
+
68
+ /** The transport's peer address, supplied by the listener rather than HTTP headers. */
69
+ export type Peer = { remoteAddr: Addr }
70
+
71
+ /** A request together with the connection it arrived on. */
72
+ export type Incoming = (
73
+ request: Request,
74
+ peer: Peer,
75
+ ) => Response | Promise<Response>
76
+
77
+ /** How this package asks a runtime to listen on a port. `reusePort` lets
78
+ * another server that asks the same way listen on it too (SO_REUSEPORT, Linux
79
+ * only; Deno needs `--unstable-net`), so a replacement can start answering
80
+ * before the server it replaces stops. */
81
+ export type Listen = (
82
+ opts: {
83
+ port: number
84
+ hostname?: string
85
+ reusePort?: boolean
86
+ onListen?: (addr: Addr) => void
87
+ },
88
+ handler: Incoming,
89
+ ) => Listener
90
+
91
+ // This runtime's `Deno.serve`, or null when there is none — found the same way
92
+ // as the upgrade above, and for the same reason.
93
+ let listener = (): Listen | null => {
94
+ let host: unknown = globalThis
95
+ if (!host || typeof host != 'object' || !('Deno' in host)) return null
96
+ let deno = host.Deno
97
+ if (!deno || typeof deno != 'object' || !('serve' in deno)) return null
98
+ let go = deno.serve
99
+ return typeof go == 'function'
100
+ ? (opts, handler) => go(opts, handler) as Listener
101
+ : null
102
+ }
103
+
104
+ /**
105
+ * Deno's own server, as a {@link Listen} — what the `serve` tool binds a port
106
+ * with (./tools.ts). A runtime that binds its own port, such as a Cloudflare
107
+ * Worker, has no `Deno.serve` and nothing for that tool to do, so this throws
108
+ * there rather than pretending to listen.
109
+ */
110
+ export let denoListen: Listen = (opts, handler) => {
111
+ let go = listener()
112
+ if (!go) {
113
+ throw new Error(
114
+ '@yaks/api: no Deno.serve here — this runtime binds its own',
115
+ )
116
+ }
117
+ return go(opts, handler)
118
+ }
119
+
120
+ // The file calls `denoReady` makes, on this runtime's `Deno`, found the same
121
+ // way as the two above.
122
+ type Files = {
123
+ pid: number
124
+ writeTextFile: (path: string, data: string) => Promise<void>
125
+ remove: (path: string) => Promise<void>
126
+ }
127
+ let files = (): Files => {
128
+ let host: unknown = globalThis
129
+ let deno = host && typeof host == 'object' && 'Deno' in host
130
+ ? host.Deno
131
+ : null
132
+ if (!deno || typeof deno != 'object' || !('writeTextFile' in deno)) {
133
+ throw new Error('@yaks/api: no Deno here to say a server is ready')
134
+ }
135
+ return deno as Files
136
+ }
137
+
138
+ /**
139
+ * Say this process is serving: its pid, written to `path` for whoever waits
140
+ * on a replacement before stopping the server it replaces (@yaks/cli
141
+ * `restart`). The function returned takes it back.
142
+ */
143
+ export let denoReady = async (path: string): Promise<() => Promise<void>> => {
144
+ let fs = files()
145
+ await fs.writeTextFile(path, `${fs.pid}\n`)
146
+ return () =>
147
+ fs.remove(path).catch((error) => {
148
+ if ((error as Error).name != 'NotFound') throw error
149
+ })
150
+ }