@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/requests.ts ADDED
@@ -0,0 +1,257 @@
1
+ // Read requests can be cancelled; admitted writes finish before their graph
2
+ // closes. These lifetimes belong to the HTTP server, not its storage adapter.
3
+ import { resolvers } from '@yaks/fp'
4
+ import { Refused } from '@yaks/graph/errors'
5
+ import type { Handler } from './route.ts'
6
+
7
+ class Cancelled extends Refused {}
8
+
9
+ let owners = new WeakMap<Request, (work: Promise<unknown>) => void>()
10
+
11
+ /** A response producer can outlive its headers and its connection. Keep its
12
+ * admitted work owned by the listener until it finishes. */
13
+ export let admit = <T>(request: Request, work: Promise<T>): Promise<T> => {
14
+ owners.get(request)?.(work)
15
+ return work
16
+ }
17
+
18
+ export let reading = (request: Request) =>
19
+ ['GET', 'HEAD', 'OPTIONS'].includes(request.method)
20
+
21
+ let readers = new WeakMap<Request, () => void>()
22
+
23
+ /** A request whose method is a write's but whose work only reads, such as an
24
+ * MCP call to a read-only tool: the cut at the end of a grace answers it 503,
25
+ * as it does a GET, and the drain no longer waits for it. */
26
+ export let reads = (request: Request): void => readers.get(request)?.()
27
+
28
+ let cuts = new WeakMap<Request, AbortSignal>()
29
+
30
+ // A caller that hung up hears nothing: 499 only names it in logs. A read the
31
+ // server cut while shutting down still has its caller, who is told to ask
32
+ // again, as it would a server not yet up.
33
+ let hungUp = () => new Response(null, { status: 499 })
34
+ let closing = () =>
35
+ new Response(null, { status: 503, headers: { 'retry-after': '1' } })
36
+
37
+ /** The cut at the end of a grace, for a write's request: what its admitted
38
+ * work stops waiting on, such as the extras an MCP call reads beside a kept
39
+ * answer, or a tool still running (@yaks/tools `Invocation.call`). */
40
+ export let cutOf = (request: Request): AbortSignal | undefined =>
41
+ cuts.get(request)
42
+
43
+ /** A cancelled read has no caller waiting for its answer. A write remains
44
+ * admitted even if its connection goes away after the body was received. */
45
+ export let receive = async <T>(
46
+ request: Request,
47
+ read: () => T | Promise<T>,
48
+ ) => {
49
+ if (
50
+ !reading(request) ||
51
+ (request.headers.get('upgrade') ?? '').toLowerCase() == 'websocket'
52
+ ) return await read()
53
+ let signal = request.signal
54
+ // Made only when the read is cut short: an error captures its stack, and
55
+ // nearly every read finishes.
56
+ let cancelled = () => new Cancelled('request was interrupted')
57
+ if (signal.aborted) throw cancelled()
58
+ let abort!: () => void
59
+ let stopped = new Promise<never>((_resolve, reject) => {
60
+ abort = () => reject(cancelled())
61
+ signal.addEventListener('abort', abort, { once: true })
62
+ })
63
+ try {
64
+ return await Promise.race([read(), stopped])
65
+ } finally {
66
+ signal.removeEventListener('abort', abort)
67
+ }
68
+ }
69
+
70
+ // The response belongs to its request until its body ends, not just until
71
+ // headers arrive. Keep our own reader so shutdown can cancel a locked body.
72
+ let streamed = (
73
+ response: Response,
74
+ signal: AbortSignal | undefined,
75
+ ended: () => void,
76
+ keep: (done: Promise<unknown>) => void,
77
+ ) => {
78
+ // A 101 is the runtime's opaque upgrade response. Reconstructing it as a
79
+ // streamed Response loses its socket ownership and corrupts the handshake.
80
+ if (response.status == 101 || !response.body) {
81
+ ended()
82
+ return response
83
+ }
84
+ let reader = response.body.getReader()
85
+ let closed = false
86
+ let end = () => {
87
+ closed = true
88
+ signal?.removeEventListener('abort', abort)
89
+ ended()
90
+ }
91
+ let abort = () => {
92
+ if (closed) return
93
+ end()
94
+ output.close()
95
+ keep(reader.cancel())
96
+ }
97
+ let output!: ReadableStreamDefaultController<Uint8Array>
98
+ let body = new ReadableStream<Uint8Array>({
99
+ start: (controller) => {
100
+ output = controller
101
+ signal?.addEventListener('abort', abort, { once: true })
102
+ if (signal?.aborted) abort()
103
+ },
104
+ pull: async () => {
105
+ try {
106
+ let next = await reader.read()
107
+ if (closed) return
108
+ if (next.done) {
109
+ end()
110
+ output.close()
111
+ } else output.enqueue(next.value)
112
+ } catch (error) {
113
+ if (closed) return
114
+ end()
115
+ output.error(error)
116
+ }
117
+ },
118
+ cancel: (reason) => {
119
+ end()
120
+ return reader.cancel(reason)
121
+ },
122
+ })
123
+ return new Response(body, response)
124
+ }
125
+
126
+ /** The work a listener admits: the cut at the end of a grace stops reads and
127
+ * every answer still streaming that no admitted work is producing, never an
128
+ * admitted write. */
129
+ export let requests = (handler: Handler) => {
130
+ let cut = new AbortController()
131
+ let pending = new Set<Promise<unknown>>()
132
+ let open = new Map<Request, string>()
133
+ let producers = new Map<Promise<unknown>, Request>()
134
+ let outputs = new Map<Request, AbortController>()
135
+ let producing = (request: Request) =>
136
+ [...producers.values()].includes(request)
137
+ let failures: unknown[] = []
138
+ let keep = (done: Promise<unknown>) => {
139
+ pending.add(done)
140
+ void done.then(() => pending.delete(done), (error) => {
141
+ pending.delete(done)
142
+ failures.push(error)
143
+ })
144
+ }
145
+ return {
146
+ open: () =>
147
+ [
148
+ ...open,
149
+ ...[...producers.values()].map((request): [Request, string] => [
150
+ request,
151
+ 'producer',
152
+ ]),
153
+ ].map(([request, phase]) => ({
154
+ method: request.method,
155
+ path: new URL(request.url).pathname,
156
+ phase,
157
+ })),
158
+ handle: (request: Request) => {
159
+ owners.set(request, (work) => {
160
+ producers.set(work, request)
161
+ keep(work)
162
+ void work.then(
163
+ () => producers.delete(work),
164
+ () => producers.delete(work),
165
+ )
166
+ })
167
+ open.set(request, 'handler')
168
+ let ended = () => {
169
+ open.delete(request)
170
+ outputs.delete(request)
171
+ }
172
+ let response = (answer: Response, signal?: AbortSignal) => {
173
+ open.set(request, 'response body')
174
+ return streamed(answer, signal, ended, keep)
175
+ }
176
+ // Runtime upgrades are tied to the incoming Request's internal socket.
177
+ // A standards-level clone does not carry that ownership in Deno.
178
+ if ((request.headers.get('upgrade') ?? '').toLowerCase() == 'websocket') {
179
+ return Promise.resolve(handler(request)).then((answer) => {
180
+ ended()
181
+ return answer
182
+ }, (error) => {
183
+ ended()
184
+ throw error
185
+ })
186
+ }
187
+ if (reading(request)) {
188
+ let scoped = new Request(request, {
189
+ signal: AbortSignal.any([request.signal, cut.signal]),
190
+ })
191
+ return receive(scoped, () => handler(scoped)).then(
192
+ (answer) => response(answer, scoped.signal),
193
+ (error) => {
194
+ ended()
195
+ if (error instanceof Cancelled) {
196
+ return request.signal.aborted ? hungUp() : closing()
197
+ }
198
+ throw error
199
+ },
200
+ )
201
+ }
202
+ let done = Promise.resolve().then(() => handler(request))
203
+ // A write's request said to only read is let go at the cut, once
204
+ // both have happened, whichever comes first; an answer it gives after
205
+ // is nobody's.
206
+ let read = false, left = false
207
+ let gone = resolvers<Response>()
208
+ let leave = () => {
209
+ if (left || !read || !cut.signal.aborted) return
210
+ left = true
211
+ ended()
212
+ gone.resolve(closing())
213
+ }
214
+ cuts.set(request, cut.signal)
215
+ readers.set(request, () => {
216
+ read = true
217
+ leave()
218
+ })
219
+ cut.signal.addEventListener('abort', leave, { once: true })
220
+ let held = done.finally(() =>
221
+ cut.signal.removeEventListener('abort', leave)
222
+ )
223
+ keep(Promise.race([held, gone.promise]))
224
+ let answered = held.then((answer) => {
225
+ if (left) {
226
+ void answer.body?.cancel().catch(() => {})
227
+ return gone.promise
228
+ }
229
+ // An answer its admitted work is still producing ends with that work.
230
+ // Any other still streaming at the cut is only output, like an MCP
231
+ // call's event stream, and would hold the listener open past any
232
+ // grace. An answer given after the cut is a finished write's, whole.
233
+ if (cut.signal.aborted) return response(answer)
234
+ let quiet = new AbortController()
235
+ outputs.set(request, quiet)
236
+ return response(answer, quiet.signal)
237
+ }, (error) => {
238
+ if (left) return gone.promise
239
+ ended()
240
+ throw error
241
+ })
242
+ return Promise.race([answered, gone.promise])
243
+ },
244
+ cancel: () => {
245
+ cut.abort()
246
+ for (let [request, quiet] of outputs) {
247
+ if (!producing(request)) quiet.abort()
248
+ }
249
+ },
250
+ drain: async () => {
251
+ while (pending.size) await Promise.allSettled(pending)
252
+ if (failures.length) {
253
+ throw new AggregateError(failures, 'request drain failed')
254
+ }
255
+ },
256
+ }
257
+ }
package/route.js ADDED
@@ -0,0 +1,139 @@
1
+ // The route table. Five paths, and the callbacks the application supplies;
2
+ // every answer is watched for breaking by ./request.ts `served`.
3
+ //
4
+ // Attribution is decided here. `authenticate` runs on every request — a read,
5
+ // a write and a WebSocket upgrade alike — and what it returns is what signs
6
+ // the write; whatever `$actor` a client sent is discarded before the graph
7
+ // sees it. `upgrade` is the only step no web standard covers, so a runtime
8
+ // other than Deno supplies its own.
9
+ import { Refused } from "@yaks/graph/errors";
10
+ import { whole } from "@yaks/query";
11
+ import { applier, ask } from "./doors.js";
12
+ import { denoUpgrade } from "./deno.js";
13
+ import { json } from "./refuse.js";
14
+ import { served } from "./request.js";
15
+ import { attach } from "./socket.js";
16
+ import { subscriptions } from "./subs.js";
17
+ import { pathOf } from "./routed.js";
18
+ export { pathOf, routed } from "./routed.js";
19
+ let nobody = ()=>null;
20
+ let no = (message, code)=>json({
21
+ error: code == 404 ? 'NotFound' : 'NotAllowed',
22
+ message
23
+ }, code);
24
+ // Who this door says is calling: the actor, for a graph that names its
25
+ // callers by asking this one (./actor.ts `asking`), and beside it what the
26
+ // host says of them, which never renames the actor.
27
+ let introduced = async (request, actor, standing)=>request.method != 'GET' ? no('/who takes GET', 405) : json(standing ? {
28
+ ...await standing(request, actor),
29
+ ...actor
30
+ } : actor);
31
+ /**
32
+ * `GET /who` alone, as {@link api} answers it: the actor `authenticate` names
33
+ * and what `standing` says beside it, for a host whose other doors are its
34
+ * own.
35
+ *
36
+ * ```ts
37
+ * import { whoDoor } from '@yaks/api'
38
+ * import { assertEquals } from '@std/assert'
39
+ *
40
+ * let door = whoDoor({
41
+ * authenticate: () => ({ by: 'ada' }),
42
+ * standing: () => ({ writes: true }),
43
+ * })
44
+ * let answer = await door(new Request('http://notes.test/who'))
45
+ * assertEquals(await answer.json(), { by: 'ada', writes: true })
46
+ * ```
47
+ */ export let whoDoor = (opts)=>async (request)=>await introduced(request, await (opts.authenticate ?? nobody)(request), opts.standing);
48
+ /** The paths {@link api} answers itself. */ export let DOORS = [
49
+ '/apply',
50
+ '/query',
51
+ '/ws',
52
+ '/vocab',
53
+ '/who'
54
+ ];
55
+ /**
56
+ * Build the request handler for a graph: `POST /apply`, `GET|POST /query`,
57
+ * `/ws` for live subscriptions, `GET /vocab`, the vocabulary, and `GET /who`,
58
+ * the actor `authenticate` names for the request with what `standing` says
59
+ * beside it ({@link whoDoor}). Everything else is a 404, every thrown error
60
+ * becomes the refusal body it describes (see the README's Refusals), and an
61
+ * answer at 500 or over goes to `report` as a `request` bundle (./request.ts
62
+ * `served`).
63
+ *
64
+ * ```ts ignore
65
+ * Deno.serve(api({ graph, authenticate }))
66
+ * ```
67
+ */ export let api = (opts)=>{
68
+ let { graph } = opts;
69
+ let subs = opts.subs ?? subscriptions(graph, {
70
+ activity: opts.activity ?? graph
71
+ });
72
+ let authenticate = opts.authenticate ?? nobody;
73
+ let upgrade = opts.upgrade ?? denoUpgrade;
74
+ let apply = applier(opts);
75
+ let door = async (request)=>{
76
+ let path = pathOf(request, opts.under);
77
+ // The apply door names its own writer: a request its host trusts names
78
+ // none here.
79
+ if (path == '/apply' && request.method == 'POST') {
80
+ return await apply.apply(request);
81
+ }
82
+ let who = await authenticate(request);
83
+ if (path == '/apply') return no('/apply takes POST', 405);
84
+ let context = opts.read && (path == '/query' || path == '/ws') ? await opts.read(request) : undefined;
85
+ let readOpts = {
86
+ person: who?.by ?? null,
87
+ ...context
88
+ };
89
+ if (path == '/query') {
90
+ if (request.method != 'GET' && request.method != 'POST') {
91
+ return no('/query takes GET or POST', 405);
92
+ }
93
+ let url = new URL(request.url);
94
+ if (request.method == 'GET' && url.searchParams.get('live') == '1') {
95
+ let q = url.searchParams.get('q');
96
+ if (q == null) throw new Refused('/query needs a query: ?q=…');
97
+ let rows = await subs.snapshot(whole(q), {
98
+ ...readOpts,
99
+ signal: request.signal
100
+ });
101
+ return json(opts.list && Array.isArray(rows) ? await opts.list(rows, request) : rows);
102
+ }
103
+ return await ask(graph, request, opts.activity ?? graph, readOpts, opts.list);
104
+ }
105
+ // What a client must load to read and write this graph as it does:
106
+ // the documents and the keyword sets they are written with, for
107
+ // @yaks/vocab `loadVocab(docs, keywords)`.
108
+ if (path == '/vocab') {
109
+ let { docs, keywords } = graph.vocab;
110
+ return request.method == 'GET' ? json({
111
+ docs,
112
+ keywords
113
+ }) : no('/vocab takes GET', 405);
114
+ }
115
+ if (path == '/who') return await introduced(request, who, opts.standing);
116
+ if (path == '/ws') {
117
+ if ((request.headers.get('upgrade') ?? '').toLowerCase() != 'websocket') {
118
+ return no('/ws is a WebSocket endpoint', 405);
119
+ }
120
+ let { socket, response } = upgrade(request);
121
+ attach(subs, socket, opts.socketTimer, opts.socketNow, readOpts, {
122
+ actor: who,
123
+ speaks: readOpts?.speaks
124
+ });
125
+ return response;
126
+ }
127
+ return no(`no route for ${path}`, 404);
128
+ };
129
+ return served(door, {
130
+ graph: opts.activity ?? graph,
131
+ report: opts.report,
132
+ tags: opts.tags,
133
+ route: (request)=>{
134
+ let path = pathOf(request, opts.under);
135
+ return DOORS.includes(path) ? path : undefined;
136
+ }
137
+ });
138
+ };
139
+ //# sourceMappingURL=route.js.map
package/route.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.js","sources":["./route.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,iEAAiE;AACjE,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,2EAA2E;AAC3E,2EAA2E;AAC3E,oCAAoC;AAGpC,SAAS,OAAO,kCAAuC;AACvD,SAAS,KAAK,2BAAgC;AAE9C,SAAS,OAAO,EAAiB,GAAG,qBAAoC;AACxE,SAAS,WAAW,oBAAmB;AACvC,SAAS,IAAI,sBAAqB;AAClC,SAAsB,MAAM,uBAAsB;AAClD,SAAS,MAAM,sBAAmC;AAClD,SAAoB,aAAa,oBAAmB;AAEpD,SAAuB,MAAM,sBAAqB;AAElD,SAAuB,MAAM,EAAc,MAAM,sBAAqB;AAgEtE,IAAI,SAAuB,IAAM;AAEjC,IAAI,KAAK,CAAC,SAAiB,OACzB,KAAK;IAAE,OAAO,QAAQ,MAAM,aAAa;IAAc;EAAQ,GAAG;AAEpE,uEAAuE;AACvE,2EAA2E;AAC3E,oDAAoD;AACpD,IAAI,aAAa,OACf,SACA,OACA,WAEA,QAAQ,MAAM,IAAI,QACd,GAAG,kBAAkB,OACrB,KAAK,WAAW;IAAE,GAAG,MAAM,SAAS,SAAS,MAAM;IAAE,GAAG,KAAK;EAAC,IAAI;AAExE;;;;;;;;;;;;;;;;CAgBC,GAC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@@
1
+ // The route table. Five paths, and the callbacks the application supplies;
2
+ // every answer is watched for breaking by ./request.ts `served`.
3
+ //
4
+ // Attribution is decided here. `authenticate` runs on every request — a read,
5
+ // a write and a WebSocket upgrade alike — and what it returns is what signs
6
+ // the write; whatever `$actor` a client sent is discarded before the graph
7
+ // sees it. `upgrade` is the only step no web standard covers, so a runtime
8
+ // other than Deno supplies its own.
9
+
10
+ import type { Actor, ReadOpts } from 'jsr:@yaks/graph@0.2.36'
11
+ import { Refused } from '@yaks/graph/errors'
12
+ import { whole } from '@yaks/query'
13
+ import { type Authenticate } from './actor.js'
14
+ import { applier, type Applying, ask, type ListQuery } from './doors.js'
15
+ import { denoUpgrade } from './deno.js'
16
+ import { json } from './refuse.js'
17
+ import { type Report, served } from './request.js'
18
+ import { attach, type Upgrade } from './socket.js'
19
+ import { type Subs, subscriptions } from './subs.js'
20
+
21
+ import { type Handler, pathOf } from './routed.js'
22
+
23
+ export { type Handler, pathOf, type Route, routed } from './routed.js'
24
+
25
+ /** A check every request passes before any route or door answers it: a
26
+ * plugin's own word on which requests it lets in. It refuses one by throwing
27
+ * (a `Denied`, say, which answers 403), and anything it does not throw at goes
28
+ * on. */
29
+ export type Filter = (request: Request) => void | Promise<void>
30
+
31
+ /** Who a request that reached the host through a plugin's link (a tunnel) is
32
+ * from: its actor, `null` for nobody, or `undefined` for a request that came
33
+ * another way. How a request arrived outranks what it says about itself, so a
34
+ * host asks this before its `authenticate`: a request through a link never
35
+ * names one of the host's own runs. */
36
+ export type Arrived = (
37
+ request: Request,
38
+ ) => Actor | null | undefined | Promise<Actor | null | undefined>
39
+
40
+ /** The tools a request that reached the host through a plugin's link is
41
+ * offered, by name, or `undefined` for a request that came another way, which
42
+ * is offered every tool. */
43
+ export type Offers = (request: Request) => string[] | undefined
44
+
45
+ /** What a request that reached the host through a plugin's link is told
46
+ * before anything else a door says to read, such as the text of the persona
47
+ * it writes as, or `undefined` for a request told nothing of its own. */
48
+ export type Told = (
49
+ request: Request,
50
+ ) => string | undefined | Promise<string | undefined>
51
+
52
+ /** What a host says of a caller beside the actor `authenticate` named, which
53
+ * `/who` answers with it: whether they may read and write, say, or where they
54
+ * sign in. The host's own words; this package reads none of them. */
55
+ export type Standing = (
56
+ request: Request,
57
+ actor: Actor | null,
58
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>
59
+
60
+ /** How a handler is built: the graph it serves, the callbacks the
61
+ * application supplies, and what its apply door is made of ({@link Applying}). */
62
+ export type Options = Applying & {
63
+ /** what `/who` says of a caller beside its actor (default: nothing) */
64
+ standing?: Standing
65
+ /** Caller read context for queries, write replies and socket frames. */
66
+ read?: (
67
+ request: Request,
68
+ ) => ReadOpts | undefined | Promise<ReadOpts | undefined>
69
+ /** Shape the published bundles of a query, including a live snapshot. */
70
+ list?: ListQuery
71
+ /** the runtime's WebSocket upgrade (default: Deno's) */
72
+ upgrade?: Upgrade
73
+ /** schedule socket relay batches (default: setTimeout) */
74
+ socketTimer?: (fn: () => void, ms: number) => void
75
+ /** clock for socket relay admission (default: Date.now) */
76
+ socketNow?: () => number
77
+ /** the subscription registry (default: a fresh one over `graph`) */
78
+ subs?: Subs
79
+ /** where a request that broke goes, as its `request` bundle (default: the
80
+ * console) */
81
+ report?: Report
82
+ /** a path the doors answer under as well as at the root (`/api`, where a
83
+ * page's `./api/` client finds its store) */
84
+ under?: string
85
+ }
86
+
87
+ let nobody: Authenticate = () => null
88
+
89
+ let no = (message: string, code: number) =>
90
+ json({ error: code == 404 ? 'NotFound' : 'NotAllowed', message }, code)
91
+
92
+ // Who this door says is calling: the actor, for a graph that names its
93
+ // callers by asking this one (./actor.ts `asking`), and beside it what the
94
+ // host says of them, which never renames the actor.
95
+ let introduced = async (
96
+ request: Request,
97
+ actor: Actor | null,
98
+ standing: Standing | undefined,
99
+ ) =>
100
+ request.method != 'GET'
101
+ ? no('/who takes GET', 405)
102
+ : json(standing ? { ...await standing(request, actor), ...actor } : actor)
103
+
104
+ /**
105
+ * `GET /who` alone, as {@link api} answers it: the actor `authenticate` names
106
+ * and what `standing` says beside it, for a host whose other doors are its
107
+ * own.
108
+ *
109
+ * ```ts
110
+ * import { whoDoor } from '@yaks/api'
111
+ * import { assertEquals } from '@std/assert'
112
+ *
113
+ * let door = whoDoor({
114
+ * authenticate: () => ({ by: 'ada' }),
115
+ * standing: () => ({ writes: true }),
116
+ * })
117
+ * let answer = await door(new Request('http://notes.test/who'))
118
+ * assertEquals(await answer.json(), { by: 'ada', writes: true })
119
+ * ```
120
+ */
121
+ export let whoDoor = (
122
+ opts: Pick<Options, 'authenticate' | 'standing'>,
123
+ ): Handler =>
124
+ async (request) =>
125
+ await introduced(
126
+ request,
127
+ await (opts.authenticate ?? nobody)(request),
128
+ opts.standing,
129
+ )
130
+
131
+ /** The paths {@link api} answers itself. */
132
+ export let DOORS: string[] = ['/apply', '/query', '/ws', '/vocab', '/who']
133
+
134
+ /**
135
+ * Build the request handler for a graph: `POST /apply`, `GET|POST /query`,
136
+ * `/ws` for live subscriptions, `GET /vocab`, the vocabulary, and `GET /who`,
137
+ * the actor `authenticate` names for the request with what `standing` says
138
+ * beside it ({@link whoDoor}). Everything else is a 404, every thrown error
139
+ * becomes the refusal body it describes (see the README's Refusals), and an
140
+ * answer at 500 or over goes to `report` as a `request` bundle (./request.ts
141
+ * `served`).
142
+ *
143
+ * ```ts ignore
144
+ * Deno.serve(api({ graph, authenticate }))
145
+ * ```
146
+ */
147
+ export let api = (opts: Options): Handler => {
148
+ let { graph } = opts
149
+ let subs = opts.subs ??
150
+ subscriptions(graph, { activity: opts.activity ?? graph })
151
+ let authenticate = opts.authenticate ?? nobody
152
+ let upgrade = opts.upgrade ?? denoUpgrade
153
+ let apply = applier(opts)
154
+
155
+ let door: Handler = async (request) => {
156
+ let path = pathOf(request, opts.under)
157
+ // The apply door names its own writer: a request its host trusts names
158
+ // none here.
159
+ if (path == '/apply' && request.method == 'POST') {
160
+ return await apply.apply(request)
161
+ }
162
+ let who = await authenticate(request)
163
+ if (path == '/apply') return no('/apply takes POST', 405)
164
+ let context = opts.read && (path == '/query' || path == '/ws')
165
+ ? await opts.read(request)
166
+ : undefined
167
+ let readOpts: ReadOpts = { person: who?.by ?? null, ...context }
168
+ if (path == '/query') {
169
+ if (request.method != 'GET' && request.method != 'POST') {
170
+ return no('/query takes GET or POST', 405)
171
+ }
172
+ let url = new URL(request.url)
173
+ if (request.method == 'GET' && url.searchParams.get('live') == '1') {
174
+ let q = url.searchParams.get('q')
175
+ if (q == null) throw new Refused('/query needs a query: ?q=…')
176
+ let rows = await subs.snapshot(whole(q), {
177
+ ...readOpts,
178
+ signal: request.signal,
179
+ })
180
+ return json(
181
+ opts.list && Array.isArray(rows)
182
+ ? await opts.list(rows, request)
183
+ : rows,
184
+ )
185
+ }
186
+ return await ask(
187
+ graph,
188
+ request,
189
+ opts.activity ?? graph,
190
+ readOpts,
191
+ opts.list,
192
+ )
193
+ }
194
+ // What a client must load to read and write this graph as it does:
195
+ // the documents and the keyword sets they are written with, for
196
+ // @yaks/vocab `loadVocab(docs, keywords)`.
197
+ if (path == '/vocab') {
198
+ let { docs, keywords } = graph.vocab
199
+ return request.method == 'GET'
200
+ ? json({ docs, keywords })
201
+ : no('/vocab takes GET', 405)
202
+ }
203
+ if (path == '/who') return await introduced(request, who, opts.standing)
204
+ if (path == '/ws') {
205
+ if (
206
+ (request.headers.get('upgrade') ?? '').toLowerCase() != 'websocket'
207
+ ) {
208
+ return no('/ws is a WebSocket endpoint', 405)
209
+ }
210
+ let { socket, response } = upgrade(request)
211
+ attach(subs, socket, opts.socketTimer, opts.socketNow, readOpts, {
212
+ actor: who,
213
+ speaks: readOpts?.speaks,
214
+ })
215
+ return response
216
+ }
217
+ return no(`no route for ${path}`, 404)
218
+ }
219
+ return served(door, {
220
+ graph: opts.activity ?? graph,
221
+ report: opts.report,
222
+ tags: opts.tags,
223
+ route: (request) => {
224
+ let path = pathOf(request, opts.under)
225
+ return DOORS.includes(path) ? path : undefined
226
+ },
227
+ })
228
+ }
package/routed.js ADDED
@@ -0,0 +1,25 @@
1
+ // One route, and whether a request takes it: no graph, no socket and no
2
+ // subscription, so a router that only matches paths (@yaks/workerd's) loads
3
+ // nothing else of this package. Exported as `@yaks/api/routed`.
4
+ /** A web-standard request handler: a `Request` in, a `Response` out. */ /** Whether a route matches this request's method and path. A GET route
5
+ * matches a HEAD too, which is a GET answered without its body (RFC 9110
6
+ * §9.3.2): how a page asks a bundle's etag without fetching it. */ export let routed = (route, method, path)=>(route.method == '*' || route.method == method || route.method == 'GET' && method == 'HEAD') && (route.path.endsWith('*') ? path.startsWith(route.path.slice(0, -1)) : route.path == path);
7
+ /** The path a request names to doors that answer under `under` as well as at
8
+ * the root: its own path with `under` taken off its front where it starts
9
+ * there, so `/api/query` is `/query` to doors under `/api`, as a page's
10
+ * `./api/` finds them.
11
+ *
12
+ * ```ts
13
+ * import { pathOf } from '@yaks/api/routed'
14
+ * import { equal } from '@yaks/testing'
15
+ * let at = (path: string) => new Request(`http://box${path}`)
16
+ * equal(pathOf(at('/api/query'), '/api'), '/query')
17
+ * equal(pathOf(at('/query'), '/api'), '/query')
18
+ * equal(pathOf(at('/apiary'), '/api'), '/apiary')
19
+ * equal(pathOf(at('/api/query')), '/api/query')
20
+ * ```
21
+ */ export let pathOf = (request, under)=>{
22
+ let path = new URL(request.url).pathname;
23
+ return under && path.startsWith(`${under}/`) ? path.slice(under.length) : path;
24
+ };
25
+ //# sourceMappingURL=routed.js.map
package/routed.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routed.js","sources":["./routed.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,4EAA4E;AAC5E,gEAAgE;AAEhE,sEAAsE,GAoBtE;;iEAEiE,GACjE,OAAO,IAAI,SAAS,CAAC,OAAc,QAAgB,OACjD,CAAC,MAAM,MAAM,IAAI,OAAO,MAAM,MAAM,IAAI,UACtC,MAAM,MAAM,IAAI,SAAS,UAAU,MAAM,KAC3C,CAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,OACjB,KAAK,UAAU,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MACrC,MAAM,IAAI,IAAI,IAAI,EAAC;AAEzB;;;;;;;;;;;;;;CAcC,GACD,OAAO,IAAI,SAAS,CAAC,SAAkB;EACrC,IAAI,OAAO,IAAI,IAAI,QAAQ,GAAG,EAAE,QAAQ;EACxC,OAAO,SAAS,KAAK,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,KAAK,KAAK,CAAC,MAAM,MAAM,IAAI;AAC5E,EAAC"}