trebol 0.1.0 → 0.1.2

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 (160) hide show
  1. package/README.md +18 -3
  2. package/dist/cli.js +13790 -11417
  3. package/dist/fonts/OFL.txt +93 -0
  4. package/dist/fonts/inter-cyrillic-ext.woff2 +0 -0
  5. package/dist/fonts/inter-cyrillic.woff2 +0 -0
  6. package/dist/fonts/inter-greek-ext.woff2 +0 -0
  7. package/dist/fonts/inter-greek.woff2 +0 -0
  8. package/dist/fonts/inter-latin-ext.woff2 +0 -0
  9. package/dist/fonts/inter-latin.woff2 +0 -0
  10. package/dist/fonts/inter-vietnamese.woff2 +0 -0
  11. package/dist/lib/core/access.d.ts +10 -0
  12. package/dist/lib/core/access.js +210 -0
  13. package/dist/lib/core/base.d.ts +4 -0
  14. package/dist/lib/core/base.js +50 -0
  15. package/dist/lib/core/bitset.d.ts +9 -0
  16. package/dist/lib/core/bitset.js +75 -0
  17. package/dist/lib/core/boot.d.ts +18 -0
  18. package/dist/lib/core/boot.js +73 -0
  19. package/dist/lib/core/compare.d.ts +9 -0
  20. package/dist/lib/core/compare.js +156 -0
  21. package/dist/lib/core/ctx.d.ts +36 -0
  22. package/dist/lib/core/ctx.js +251 -0
  23. package/dist/lib/core/dec.d.ts +28 -0
  24. package/dist/lib/core/dec.js +158 -0
  25. package/dist/lib/core/errors.d.ts +15 -0
  26. package/dist/lib/core/errors.js +44 -0
  27. package/dist/lib/core/escapes.d.ts +14 -0
  28. package/dist/lib/core/escapes.js +80 -0
  29. package/dist/lib/core/eval.d.ts +220 -0
  30. package/dist/lib/core/eval.js +666 -0
  31. package/dist/lib/core/func.d.ts +68 -0
  32. package/dist/lib/core/func.js +129 -0
  33. package/dist/lib/core/hash.d.ts +5 -0
  34. package/dist/lib/core/hash.js +155 -0
  35. package/dist/lib/core/index.d.ts +18 -0
  36. package/dist/lib/core/index.js +20 -0
  37. package/dist/lib/core/int64.d.ts +22 -0
  38. package/dist/lib/core/int64.js +113 -0
  39. package/dist/lib/core/kinds.d.ts +67 -0
  40. package/dist/lib/core/kinds.js +134 -0
  41. package/dist/lib/core/lexer.d.ts +13 -0
  42. package/dist/lib/core/lexer.js +702 -0
  43. package/dist/lib/core/mezz.d.ts +1 -0
  44. package/dist/lib/core/mezz.js +360 -0
  45. package/dist/lib/core/mold.d.ts +20 -0
  46. package/dist/lib/core/mold.js +434 -0
  47. package/dist/lib/core/natives/control.d.ts +1 -0
  48. package/dist/lib/core/natives/control.js +374 -0
  49. package/dist/lib/core/natives/csv.d.ts +15 -0
  50. package/dist/lib/core/natives/csv.js +315 -0
  51. package/dist/lib/core/natives/data.d.ts +11 -0
  52. package/dist/lib/core/natives/data.js +367 -0
  53. package/dist/lib/core/natives/define.d.ts +17 -0
  54. package/dist/lib/core/natives/define.js +47 -0
  55. package/dist/lib/core/natives/encode.d.ts +3 -0
  56. package/dist/lib/core/natives/encode.js +187 -0
  57. package/dist/lib/core/natives/json.d.ts +5 -0
  58. package/dist/lib/core/natives/json.js +273 -0
  59. package/dist/lib/core/natives/math.d.ts +3 -0
  60. package/dist/lib/core/natives/math.js +500 -0
  61. package/dist/lib/core/natives/parse.d.ts +1 -0
  62. package/dist/lib/core/natives/parse.js +600 -0
  63. package/dist/lib/core/natives/series.d.ts +4 -0
  64. package/dist/lib/core/natives/series.js +519 -0
  65. package/dist/lib/core/natives/text.d.ts +1 -0
  66. package/dist/lib/core/natives/text.js +487 -0
  67. package/dist/lib/core/natives/xml.d.ts +9 -0
  68. package/dist/lib/core/natives/xml.js +242 -0
  69. package/dist/lib/core/series.d.ts +26 -0
  70. package/dist/lib/core/series.js +73 -0
  71. package/dist/lib/core/symbols.d.ts +9 -0
  72. package/dist/lib/core/symbols.js +44 -0
  73. package/dist/lib/core/values.d.ts +206 -0
  74. package/dist/lib/core/values.js +223 -0
  75. package/dist/lib/host/browser.d.ts +4 -0
  76. package/dist/lib/host/browser.js +4974 -0
  77. package/dist/lib/host/chart.d.ts +26 -0
  78. package/dist/lib/host/chart.js +158 -0
  79. package/dist/lib/host/compress.d.ts +1 -0
  80. package/dist/lib/host/compress.js +37 -0
  81. package/dist/lib/host/devlog.d.ts +11 -0
  82. package/dist/lib/host/devlog.js +13 -0
  83. package/dist/lib/host/devtools.d.ts +23 -0
  84. package/dist/lib/host/devtools.js +626 -0
  85. package/dist/lib/host/draw.d.ts +31 -0
  86. package/dist/lib/host/draw.js +348 -0
  87. package/dist/lib/host/fonts/OFL.txt +93 -0
  88. package/dist/lib/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  89. package/dist/lib/host/fonts/inter-cyrillic.woff2 +0 -0
  90. package/dist/lib/host/fonts/inter-greek-ext.woff2 +0 -0
  91. package/dist/lib/host/fonts/inter-greek.woff2 +0 -0
  92. package/dist/lib/host/fonts/inter-latin-ext.woff2 +0 -0
  93. package/dist/lib/host/fonts/inter-latin.woff2 +0 -0
  94. package/dist/lib/host/fonts/inter-vietnamese.woff2 +0 -0
  95. package/dist/lib/host/fonts.d.ts +11 -0
  96. package/dist/lib/host/fonts.js +29 -0
  97. package/dist/lib/host/icons.d.ts +3 -0
  98. package/dist/lib/host/icons.js +97 -0
  99. package/dist/lib/host/index.d.ts +40 -0
  100. package/dist/lib/host/index.js +192 -0
  101. package/dist/lib/host/js.d.ts +5 -0
  102. package/dist/lib/host/js.js +130 -0
  103. package/dist/lib/host/locale.d.ts +40 -0
  104. package/dist/lib/host/locale.js +241 -0
  105. package/dist/lib/host/markdown.d.ts +30 -0
  106. package/dist/lib/host/markdown.js +161 -0
  107. package/dist/lib/host/modules.d.ts +14 -0
  108. package/dist/lib/host/modules.js +300 -0
  109. package/dist/lib/host/natives.d.ts +6 -0
  110. package/dist/lib/host/natives.js +98 -0
  111. package/dist/lib/host/net.d.ts +12 -0
  112. package/dist/lib/host/net.js +549 -0
  113. package/dist/lib/host/orbit.d.ts +121 -0
  114. package/dist/lib/host/orbit.js +374 -0
  115. package/dist/lib/host/page.d.ts +9 -0
  116. package/dist/lib/host/page.js +55 -0
  117. package/dist/lib/host/rows.d.ts +29 -0
  118. package/dist/lib/host/rows.js +109 -0
  119. package/dist/lib/host/scheduler.d.ts +51 -0
  120. package/dist/lib/host/scheduler.js +197 -0
  121. package/dist/lib/host/theme.d.ts +58 -0
  122. package/dist/lib/host/theme.js +1667 -0
  123. package/dist/lib/ui/i18n.trb +117 -0
  124. package/dist/lib/ui/test.trb +565 -0
  125. package/dist/lib/ui/ui.trb +1678 -0
  126. package/dist/trebol.js +1427 -138
  127. package/editors/vscode/README.md +15 -0
  128. package/editors/vscode/language-configuration.json +28 -0
  129. package/editors/vscode/package.json +42 -0
  130. package/editors/vscode/syntaxes/trebol.tmLanguage.json +237 -0
  131. package/package.json +23 -7
  132. package/src/core/boot.ts +1 -1
  133. package/src/core/func.ts +4 -0
  134. package/src/core/natives/control.ts +1 -1
  135. package/src/core/natives/series.ts +9 -1
  136. package/src/core/natives/text.ts +2 -0
  137. package/src/host/browser.ts +1235 -83
  138. package/src/host/devlog.ts +16 -0
  139. package/src/host/devtools.ts +641 -0
  140. package/src/host/fonts/OFL.txt +93 -0
  141. package/src/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  142. package/src/host/fonts/inter-cyrillic.woff2 +0 -0
  143. package/src/host/fonts/inter-greek-ext.woff2 +0 -0
  144. package/src/host/fonts/inter-greek.woff2 +0 -0
  145. package/src/host/fonts/inter-latin-ext.woff2 +0 -0
  146. package/src/host/fonts/inter-latin.woff2 +0 -0
  147. package/src/host/fonts/inter-vietnamese.woff2 +0 -0
  148. package/src/host/fonts.ts +39 -0
  149. package/src/host/index.ts +5 -3
  150. package/src/host/js.ts +127 -0
  151. package/src/host/markdown.ts +9 -0
  152. package/src/host/modules.ts +41 -2
  153. package/src/host/net.ts +9 -1
  154. package/src/host/orbit.ts +432 -0
  155. package/src/host/rows.ts +30 -0
  156. package/src/host/scheduler.ts +62 -36
  157. package/src/host/theme.ts +270 -6
  158. package/src/ui/i18n.trb +10 -0
  159. package/src/ui/test.trb +565 -0
  160. package/src/ui/ui.trb +564 -90
@@ -0,0 +1,549 @@
1
+ // Network natives: HTTP with JSON built in, WebSocket and server-sent events.
2
+ //
3
+ // All of them are asynchronous by default: they return `await` and the task
4
+ // continues with the result, so from Trebol `data: fetch url` just reads.
5
+ // Failures (network, timeout, HTTP status >= 400) are access errors that
6
+ // `try` can catch. `cancel` on the task aborts the request in flight.
7
+ import { K, NONE, I64, native, value, string, stringOf, text, binary, makeError, throwError, form, spell, ctxFind, intern, parseJson, toJson, queryText, } from "../core/index.js";
8
+ import { schedulerOf, spawn, spawnHandler, makeHandle, handleOf } from "./scheduler.js";
9
+ import { cancellers } from "./natives.js";
10
+ import { devLog } from "./devlog.js";
11
+ // --- files -----------------------------------------------------------------------
12
+ //
13
+ // A file the user chose (an upload field) is a handle of kind 'file' over a
14
+ // Blob: Trebol never holds its bytes until it asks with read-file.
15
+ /** A handle for a file the user chose. */
16
+ export function fileHandle(file) {
17
+ return makeHandle('file', file);
18
+ }
19
+ native('read-file', '["The bytes of a file the user chose." file [handle!]]', (_t, f, v) => {
20
+ if (f.phase === 1)
21
+ return value(v);
22
+ f.phase = 1;
23
+ const file = handleOf(f.args[0], 'file');
24
+ if (file === null)
25
+ return throwError('script', 'bad-handle', 'read-file needs a file from an upload field');
26
+ const p = file.arrayBuffer().then(buf => binary([...new Uint8Array(buf)]), (e) => { throw makeError('access', 'read', `cannot read ${file instanceof File ? file.name : 'the file'}: ${e.message}`); });
27
+ return { k: 'await', p };
28
+ });
29
+ // The other way, `download` gives the user a file made by the program: the
30
+ // browser saves it with its usual dialog or into Downloads.
31
+ const TYPES = {
32
+ csv: 'text/csv', txt: 'text/plain', json: 'application/json', xml: 'application/xml', html: 'text/html',
33
+ trb: 'text/plain', md: 'text/markdown', svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg',
34
+ pdf: 'application/pdf', zip: 'application/zip',
35
+ };
36
+ /** Where `download` hands a file; false when this host has no browser. Tests point it elsewhere. */
37
+ export const saver = {
38
+ save: (name, blob) => {
39
+ const doc = globalThis.document;
40
+ if (doc === undefined)
41
+ return false;
42
+ const url = URL.createObjectURL(blob);
43
+ const a = doc.createElement('a');
44
+ a.href = url;
45
+ a.download = name;
46
+ a.style.display = 'none';
47
+ doc.body.append(a);
48
+ a.click();
49
+ a.remove();
50
+ // the browser reads the blob after the click returns
51
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
52
+ return true;
53
+ },
54
+ };
55
+ /**
56
+ * The file name a server gives in content-disposition: filename*=UTF-8''... (which
57
+ * carries accents) wins over filename=...; '' when there is none.
58
+ */
59
+ export function dispositionName(header) {
60
+ const star = /filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(header);
61
+ if (star !== null) {
62
+ try {
63
+ const raw = star[2].trim();
64
+ if (/^utf-8$/i.test(star[1].trim()))
65
+ return decodeURIComponent(raw);
66
+ // ISO-8859-1: each escaped byte is its own character
67
+ return raw.replace(/%([0-9a-f]{2})/gi, (_m, h) => String.fromCharCode(parseInt(h, 16)));
68
+ }
69
+ catch { /* a bad escape: try the plain name */ }
70
+ }
71
+ const plain = /filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]+))/i.exec(header);
72
+ if (plain === null)
73
+ return '';
74
+ return plain[1] !== undefined ? plain[1].replace(/\\(.)/g, '$1') : plain[2].trim();
75
+ }
76
+ /** The field of an answer of fetch/with [full: true]; undefined when it has none. */
77
+ function answerField(o, name) {
78
+ const i = ctxFind(o.ctx, intern(name));
79
+ return i < 0 ? undefined : o.ctx.vals[i];
80
+ }
81
+ /** A header of an answer, by its name in lowercase as fetch gives them. */
82
+ function answerHeader(headers, name) {
83
+ if (headers === undefined || headers.t !== K.Map)
84
+ return '';
85
+ const d = headers.s.data;
86
+ for (let i = 0; i + 1 < d.length; i += 2) {
87
+ if (d[i].t === K.String && text(d[i]).toLowerCase() === name)
88
+ return form(d[i + 1]);
89
+ }
90
+ return '';
91
+ }
92
+ native('download', '["Gives the user a file to save: text (as UTF-8), bytes, or the answer of fetch/with [full: true], under the name the server gives." name [file! string!] data [string! binary! object!]]', (_t, f) => {
93
+ let name = text(f.args[0]).split('/').pop() ?? '';
94
+ let data = f.args[1];
95
+ let given = '';
96
+ let renamed = false;
97
+ if (data.t === K.Object) {
98
+ const status = answerField(data, 'status');
99
+ const headers = answerField(data, 'headers');
100
+ const body = answerField(data, 'body');
101
+ if (status === undefined || status.t !== K.Integer || body === undefined) {
102
+ return throwError('script', 'bad-answer', 'download needs an answer of fetch/with [full: true]');
103
+ }
104
+ const code = I64.toNumber(status.v);
105
+ if (code >= 400)
106
+ return throwError('access', 'http', `HTTP ${code}: no file to save`);
107
+ const server = dispositionName(answerHeader(headers, 'content-disposition')).split(/[/\\]/).pop() ?? '';
108
+ if (server !== '') {
109
+ name = server;
110
+ renamed = true;
111
+ }
112
+ given = answerHeader(headers, 'content-type');
113
+ data = body.t === K.Binary || body.t === K.String ? body : string(toJson(body));
114
+ }
115
+ if (name === '')
116
+ return throwError('script', 'bad-file', 'download needs a file name');
117
+ const ext = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : '';
118
+ const type = TYPES[ext] ?? 'application/octet-stream';
119
+ // a byte order mark lets spreadsheets read a CSV's accents as UTF-8
120
+ const body = data.t === K.Binary
121
+ ? new Uint8Array(data.s.data.slice(data.i))
122
+ : (ext === 'csv' ? '\ufeff' : '') + text(data);
123
+ const blob = new Blob([body], { type: given !== '' ? given : data.t === K.Binary ? type : `${type};charset=utf-8` });
124
+ if (!saver.save(name, blob))
125
+ return throwError('access', 'no-download', 'this host cannot give the user files');
126
+ // the name it was saved under, when the server gave one
127
+ return value(renamed ? stringOf(f.args[0].t === K.File ? K.File : K.String, name) : f.args[0]);
128
+ });
129
+ // --- HTTP ------------------------------------------------------------------------
130
+ function field(opts, name) {
131
+ if (opts === null)
132
+ return null;
133
+ const i = ctxFind(opts.ctx, intern(name));
134
+ const v = i < 0 ? undefined : opts.ctx.vals[i];
135
+ return v === undefined || v.t === K.None ? null : v;
136
+ }
137
+ /** A yes-or-no option: on unless it is missing, none or false. */
138
+ const isOn = (v) => v !== null && !(v.t === K.Logic && !v.v);
139
+ /** Pairs from a block [name value ...], a map or an object, as strings. */
140
+ function pairs(c) {
141
+ const out = [];
142
+ const name = (k) => (k.t >= K.Word && k.t <= K.Issue ? spell(k.sym) : form(k));
143
+ if (c.t === K.Block || c.t === K.Map) {
144
+ const d = c.s.data.slice(c.t === K.Block ? c.i : 0);
145
+ for (let i = 0; i + 1 < d.length; i += 2)
146
+ out.push([name(d[i]), form(d[i + 1])]);
147
+ }
148
+ else if (c.t === K.Object) {
149
+ c.ctx.keys.forEach((k, i) => out.push([spell(k), form(c.ctx.vals[i])]));
150
+ }
151
+ return out;
152
+ }
153
+ /** Turns a decoded body into a value: JSON when the server says so, text, or binary. */
154
+ function decodeBody(type, bytes) {
155
+ if (/json/i.test(type)) {
156
+ const r = parseJson(new TextDecoder().decode(bytes));
157
+ return typeof r === 'string' ? string(new TextDecoder().decode(bytes)) : r;
158
+ }
159
+ // xml only as the subtype or its +xml suffix: the type of an Excel file (…openxmlformats…) is binary
160
+ if (/^text\/|^[^;]*\/(?:xml|[^;]*\+xml)\s*(?:;|$)|javascript|x-www-form-urlencoded/i.test(type) || type === '') {
161
+ return string(new TextDecoder().decode(bytes));
162
+ }
163
+ return { t: K.Binary, s: { data: [...bytes] }, i: 0 };
164
+ }
165
+ function toSeconds(c) {
166
+ if (c.t === K.Time)
167
+ return c.v / 1e9;
168
+ if (c.t === K.Integer)
169
+ return I64.toNumber(c.v);
170
+ return c.v;
171
+ }
172
+ /**
173
+ * Sends a request with fetch. With progress, the body of the answer is read
174
+ * as it comes, so the bytes received can be told.
175
+ */
176
+ async function sendFetch(url, init, progress) {
177
+ const res = await fetch(url, init);
178
+ const headers = [];
179
+ res.headers.forEach((val, k) => headers.push([k, val]));
180
+ let bytes;
181
+ if (progress === null || res.body === null) {
182
+ bytes = new Uint8Array(await res.arrayBuffer());
183
+ }
184
+ else {
185
+ const size = Number(res.headers.get('content-length') ?? NaN);
186
+ const total = Number.isFinite(size) && res.headers.get('content-encoding') === null ? size : null;
187
+ const parts = [];
188
+ let done = 0;
189
+ progress(0, total);
190
+ for (const reader = res.body.getReader();;) {
191
+ const { value: part, done: end } = await reader.read();
192
+ if (end)
193
+ break;
194
+ parts.push(part);
195
+ done += part.length;
196
+ progress(done, total);
197
+ }
198
+ // at the end the total is known: what came
199
+ if (total === null)
200
+ progress(done, done);
201
+ bytes = new Uint8Array(done);
202
+ let at = 0;
203
+ for (const part of parts) {
204
+ bytes.set(part, at);
205
+ at += part.length;
206
+ }
207
+ }
208
+ return { status: res.status, statusText: res.statusText, ok: res.ok, headers, bytes };
209
+ }
210
+ /**
211
+ * Sends a request with XMLHttpRequest, the one way a browser tells how much
212
+ * of the body went up: first the bytes sent, then the bytes received.
213
+ */
214
+ function sendXhr(url, init, progress) {
215
+ return new Promise((resolve, reject) => {
216
+ const xhr = new XMLHttpRequest();
217
+ xhr.open(init.method ?? 'GET', url);
218
+ init.headers.forEach((val, k) => xhr.setRequestHeader(k, val));
219
+ xhr.withCredentials = init.credentials === 'include';
220
+ xhr.responseType = 'arraybuffer';
221
+ const tell = (e) => progress(e.loaded, e.lengthComputable ? e.total : null);
222
+ if (init.body !== undefined)
223
+ xhr.upload.onprogress = tell;
224
+ xhr.onprogress = tell;
225
+ xhr.onload = () => {
226
+ const headers = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/).filter(l => l.includes(':'))
227
+ .map(l => [l.slice(0, l.indexOf(':')).trim().toLowerCase(), l.slice(l.indexOf(':') + 1).trim()]);
228
+ const ok = xhr.status >= 200 && xhr.status < 300;
229
+ const got = xhr.response.byteLength;
230
+ progress(got, got);
231
+ resolve({ status: xhr.status, statusText: xhr.statusText, ok, headers, bytes: new Uint8Array(xhr.response) });
232
+ };
233
+ xhr.onerror = () => reject(new Error('network error'));
234
+ xhr.onabort = () => reject(new Error('aborted'));
235
+ init.signal?.addEventListener('abort', () => xhr.abort());
236
+ xhr.send((init.body ?? null));
237
+ });
238
+ }
239
+ /**
240
+ * What runs as a request goes: a block, with done and total set, or a face,
241
+ * through the host's show-progress. Calls come at most every tenth of a
242
+ * second, and always at the end; `end` says the request is over.
243
+ */
244
+ function progressOf(t, target) {
245
+ const sch = schedulerOf(t);
246
+ let last = 0;
247
+ const run = (done, total) => {
248
+ if (target.t === K.Block) {
249
+ spawnHandler(sch, target, { done, total });
250
+ return;
251
+ }
252
+ // a host mezzanine: in user, where the host's Trebol code is loaded
253
+ const i = ctxFind(t.rt.user, intern('show-progress'));
254
+ const fn = i < 0 ? undefined : t.rt.user.vals[i];
255
+ if (fn !== undefined)
256
+ spawn(sch, { data: [fn, target, done, total] }, 0);
257
+ };
258
+ const count = (n) => ({ t: K.Integer, v: n });
259
+ return {
260
+ tell: (done, total) => {
261
+ const now = Date.now();
262
+ if (now - last < 100 && done !== total)
263
+ return;
264
+ last = now;
265
+ run(count(done), total === null ? NONE : count(total));
266
+ },
267
+ end: () => { if (target.t !== K.Block)
268
+ run(NONE, NONE); },
269
+ };
270
+ }
271
+ native('http-request', '["Sends an HTTP request; used by fetch." url [url! string!] options [object! none!]]', (t, f, v) => {
272
+ if (f.phase === 1)
273
+ return value(v);
274
+ f.phase = 1;
275
+ const opts = f.args[1].t === K.Object ? f.args[1] : null;
276
+ let url = text(f.args[0]);
277
+ const q = field(opts, 'query');
278
+ if (q !== null) {
279
+ const qs = queryText(q);
280
+ if (qs === null)
281
+ return throwError('script', 'bad-query', 'a query takes words or strings as names');
282
+ const hash = url.includes('#') ? url.slice(url.indexOf('#')) : '';
283
+ const base = url.slice(0, url.length - hash.length);
284
+ if (qs !== '')
285
+ url = base + (base.includes('?') ? '&' : '?') + qs + hash;
286
+ }
287
+ const method = field(opts, 'method');
288
+ const headers = new Headers();
289
+ const h = field(opts, 'headers');
290
+ if (h !== null)
291
+ for (const [k, val] of pairs(h))
292
+ headers.set(k, val);
293
+ let body;
294
+ const b = field(opts, 'body');
295
+ const formFields = field(opts, 'form');
296
+ const multipart = field(opts, 'multipart');
297
+ if (formFields !== null) {
298
+ body = new URLSearchParams(pairs(formFields));
299
+ }
300
+ else if (multipart !== null) {
301
+ const fd = new FormData();
302
+ const d = multipart.t === K.Block ? multipart.s.data.slice(multipart.i) : [];
303
+ for (let i = 0; i + 1 < d.length; i += 2) {
304
+ const k = d[i];
305
+ const val = d[i + 1];
306
+ const key = k.t >= K.Word && k.t <= K.Issue ? spell(k.sym) : form(k);
307
+ const file = handleOf(val, 'file');
308
+ if (val.t === K.Binary)
309
+ fd.append(key, new Blob([new Uint8Array(val.s.data.slice(val.i))]), key);
310
+ else if (file !== null)
311
+ fd.append(key, file, file instanceof File ? file.name : key);
312
+ else
313
+ fd.append(key, form(val));
314
+ }
315
+ body = fd;
316
+ }
317
+ else if (b !== null) {
318
+ if (b.t === K.String) {
319
+ body = text(b);
320
+ }
321
+ else if (b.t === K.Binary) {
322
+ body = new Uint8Array(b.s.data.slice(b.i));
323
+ }
324
+ else {
325
+ body = toJson(b);
326
+ if (!headers.has('content-type'))
327
+ headers.set('content-type', 'application/json');
328
+ }
329
+ }
330
+ if (!headers.has('accept'))
331
+ headers.set('accept', 'application/json, text/*;q=0.9, */*;q=0.8');
332
+ const timeout = field(opts, 'timeout');
333
+ const full = isOn(field(opts, 'full'));
334
+ // without cookies the browser's own rule: sent to the page's own server only
335
+ const cookies = field(opts, 'cookies');
336
+ const credentials = cookies === null ? 'same-origin' : isOn(cookies) ? 'include' : 'omit';
337
+ const ctl = new AbortController();
338
+ let timedOut = false;
339
+ const timer = timeout !== null ? setTimeout(() => { timedOut = true; ctl.abort(); }, toSeconds(timeout) * 1000) : null;
340
+ const me = schedulerOf(t).byTask.get(t);
341
+ if (me)
342
+ me.abort = () => ctl.abort();
343
+ const verb = method === null ? (body === undefined ? 'GET' : 'POST') : form(method).toUpperCase();
344
+ const watch = field(opts, 'progress');
345
+ const shown = watch === null ? null : progressOf(t, watch);
346
+ const p = (async () => {
347
+ const started = Date.now();
348
+ let status = null;
349
+ let problem = null;
350
+ try {
351
+ const init = { method: verb, headers, body, credentials, signal: ctl.signal };
352
+ const res = shown !== null && typeof XMLHttpRequest !== 'undefined'
353
+ ? await sendXhr(url, init, shown.tell)
354
+ : await sendFetch(url, init, shown === null ? null : shown.tell);
355
+ status = res.status;
356
+ const type = res.headers.find(([k]) => k === 'content-type')?.[1] ?? '';
357
+ const data = decodeBody(type, res.bytes);
358
+ if (full) {
359
+ const hs = [];
360
+ for (const [k, val] of res.headers)
361
+ hs.push(string(k), string(val));
362
+ return {
363
+ t: K.Object,
364
+ ctx: {
365
+ keys: ['status', 'headers', 'body'].map(n => intern(n)),
366
+ vals: [{ t: K.Integer, v: res.status }, { t: K.Map, s: { data: hs } }, data],
367
+ parent: null,
368
+ },
369
+ };
370
+ }
371
+ if (!res.ok)
372
+ throw makeError('access', 'http', `HTTP ${res.status} ${res.statusText} for ${url}`);
373
+ return data;
374
+ }
375
+ catch (e) {
376
+ if (e.t === K.Error)
377
+ throw e;
378
+ problem = timedOut ? 'timed out' : ctl.signal.aborted ? 'cancelled' : e.message;
379
+ if (timedOut)
380
+ throw makeError('access', 'timeout', `request to ${url} timed out`);
381
+ if (ctl.signal.aborted)
382
+ throw makeError('access', 'cancelled', `request to ${url} was cancelled`);
383
+ throw makeError('access', 'network', `cannot reach ${url}: ${e.message}`);
384
+ }
385
+ finally {
386
+ if (timer !== null)
387
+ clearTimeout(timer);
388
+ shown?.end();
389
+ devLog.request(verb, url, status, Date.now() - started, problem);
390
+ }
391
+ })();
392
+ return { k: 'await', p };
393
+ });
394
+ /** A message as a value: JSON objects and arrays load, anything else stays text. */
395
+ function messageValue(data) {
396
+ const s = data.trimStart();
397
+ if (s.startsWith('{') || s.startsWith('[')) {
398
+ const r = parseJson(data);
399
+ if (typeof r !== 'string')
400
+ return r;
401
+ }
402
+ return string(data);
403
+ }
404
+ function emit(st, kind, words) {
405
+ const bodies = st.handlers[kind];
406
+ if (bodies === undefined) {
407
+ st.pending.push([kind, words]);
408
+ return;
409
+ }
410
+ for (const body of bodies)
411
+ spawnHandler(st.sch, body, words);
412
+ }
413
+ native('open-socket', '["Opens a WebSocket; gives a handle once it is open." url [url! string!]]', (t, f, v) => {
414
+ if (f.phase === 1)
415
+ return value(v);
416
+ f.phase = 1;
417
+ const url = text(f.args[0]);
418
+ const sch = schedulerOf(t);
419
+ const p = new Promise((resolve, reject) => {
420
+ let ws;
421
+ try {
422
+ ws = new WebSocket(url);
423
+ }
424
+ catch (e) {
425
+ reject(makeError('access', 'network', `cannot open ${url}: ${e.message}`));
426
+ return;
427
+ }
428
+ ws.binaryType = 'arraybuffer';
429
+ const st = {
430
+ sch,
431
+ handlers: {},
432
+ pending: [],
433
+ close: () => ws.close(),
434
+ send: data => ws.send(data),
435
+ };
436
+ let opened = false;
437
+ ws.onopen = () => {
438
+ opened = true;
439
+ resolve(makeHandle('stream', st));
440
+ };
441
+ ws.onmessage = ev => {
442
+ const val = typeof ev.data === 'string'
443
+ ? messageValue(ev.data)
444
+ : { t: K.Binary, s: { data: [...new Uint8Array(ev.data)] }, i: 0 };
445
+ emit(st, 'message', { value: val });
446
+ };
447
+ ws.onerror = () => {
448
+ if (!opened)
449
+ reject(makeError('access', 'network', `cannot open ${url}`));
450
+ else
451
+ emit(st, 'error', { value: makeError('access', 'network', `socket error on ${url}`) });
452
+ };
453
+ ws.onclose = ev => {
454
+ if (opened)
455
+ emit(st, 'close', { value: { t: K.Integer, v: ev.code } });
456
+ };
457
+ });
458
+ return { k: 'await', p };
459
+ });
460
+ /** Splits a server-sent events stream into events. */
461
+ function parseSse(buffer, onEvent) {
462
+ let rest = buffer;
463
+ for (;;) {
464
+ const m = /\r?\n\r?\n/.exec(rest);
465
+ if (m === null)
466
+ return rest;
467
+ const block = rest.slice(0, m.index);
468
+ rest = rest.slice(m.index + m[0].length);
469
+ let event = 'message';
470
+ const data = [];
471
+ for (const line of block.split(/\r?\n/)) {
472
+ if (line.startsWith(':'))
473
+ continue;
474
+ const colon = line.indexOf(':');
475
+ const name = colon < 0 ? line : line.slice(0, colon);
476
+ const val = colon < 0 ? '' : line.slice(colon + 1).replace(/^ /, '');
477
+ if (name === 'event')
478
+ event = val;
479
+ else if (name === 'data')
480
+ data.push(val);
481
+ }
482
+ if (data.length > 0)
483
+ onEvent(event, data.join('\n'));
484
+ }
485
+ }
486
+ native('open-events', '["Opens a stream of server-sent events; gives a handle." url [url! string!]]', (t, f) => {
487
+ const url = text(f.args[0]);
488
+ const sch = schedulerOf(t);
489
+ const ctl = new AbortController();
490
+ const st = { sch, handlers: {}, pending: [], close: () => ctl.abort() };
491
+ const handle = makeHandle('stream', st);
492
+ void (async () => {
493
+ try {
494
+ const res = await fetch(url, { headers: { accept: 'text/event-stream' }, signal: ctl.signal });
495
+ if (!res.ok || res.body === null)
496
+ throw new Error(`HTTP ${res.status}`);
497
+ const reader = res.body.getReader();
498
+ const dec = new TextDecoder();
499
+ let buf = '';
500
+ for (;;) {
501
+ const { done, value: chunk } = await reader.read();
502
+ if (done)
503
+ break;
504
+ buf = parseSse(buf + dec.decode(chunk, { stream: true }), (event, data) => {
505
+ emit(st, 'message', { value: messageValue(data), event: { t: K.Word, sym: intern(event), bind: null } });
506
+ });
507
+ }
508
+ emit(st, 'close', { value: NONE });
509
+ }
510
+ catch (e) {
511
+ if (!ctl.signal.aborted)
512
+ emit(st, 'error', { value: makeError('access', 'network', `event stream ${url}: ${e.message}`) });
513
+ }
514
+ })();
515
+ return value(handle);
516
+ });
517
+ function onEvent(kind) {
518
+ return (_t, f) => {
519
+ const st = handleOf(f.args[0], 'stream');
520
+ if (st === null)
521
+ return throwError('script', 'bad-handle', `on-${kind} needs a socket or event stream`);
522
+ (st.handlers[kind] ??= []).push(f.args[1]);
523
+ const waiting = st.pending.filter(([k]) => k === kind);
524
+ st.pending = st.pending.filter(([k]) => k !== kind);
525
+ for (const [, words] of waiting)
526
+ emit(st, kind, words);
527
+ return value(f.args[0]);
528
+ };
529
+ }
530
+ native('on-message', '["Runs a block for each message that comes on a stream." stream [handle!] body [block!]]', onEvent('message'));
531
+ native('on-close', '["Runs a block when a stream closes." stream [handle!] body [block!]]', onEvent('close'));
532
+ native('on-error', '["Runs a block when a stream fails." stream [handle!] body [block!]]', onEvent('error'));
533
+ native('send', '["Sends a value on a socket." stream [handle!] data [any-value!]]', (_t, f) => {
534
+ const st = handleOf(f.args[0], 'stream');
535
+ if (st === null || st.send === undefined) {
536
+ return throwError('script', 'bad-handle', 'send needs an open socket');
537
+ }
538
+ const d = f.args[1];
539
+ st.send(d.t === K.String ? text(d) : d.t === K.Binary ? new Uint8Array(d.s.data.slice(d.i)) : toJson(d));
540
+ return value(f.args[0]);
541
+ });
542
+ cancellers['stream'] = obj => obj.close();
543
+ const closeStream = (_t, f) => {
544
+ handleOf(f.args[0], 'stream')?.close();
545
+ return value(f.args[0]);
546
+ };
547
+ native('close', '["Closes a stream, or hides a dialog." stream [handle!]]', closeStream);
548
+ // the UI dialect redefines close for dialogs and falls back to this one
549
+ native('close-stream', '["Closes a socket or a stream of events." stream [handle!]]', closeStream);
@@ -0,0 +1,121 @@
1
+ import { type Cell } from '../core/index.ts';
2
+ import { type El } from './draw.ts';
3
+ export type EdgeLook = 'solid' | 'dashed' | 'faint';
4
+ export interface OrbitNode {
5
+ key: string;
6
+ /** The id as the app gave it: what face/value is when the person picks it. */
7
+ id: Cell;
8
+ /** A string, or a text per language. */
9
+ title: Cell;
10
+ color: string;
11
+ /** How many it holds: small moons around it and a number under its title. */
12
+ count: number | null;
13
+ /** It stands for many: a second ring. */
14
+ many: boolean;
15
+ /** A shortcut or link: a dashed border. */
16
+ dashed: boolean;
17
+ /** A ring of steps around it, the one at `at` the current one (1-based); 0 for none. */
18
+ steps: number;
19
+ at: number;
20
+ }
21
+ export interface OrbitEdge {
22
+ from: string;
23
+ to: string;
24
+ label: Cell | null;
25
+ look: EdgeLook;
26
+ }
27
+ export interface OrbitSpec {
28
+ focus: string | null;
29
+ nodes: Map<string, OrbitNode>;
30
+ edges: OrbitEdge[];
31
+ /** The nodes the person came from, most recent last. */
32
+ trail: string[];
33
+ }
34
+ /** What tells nodes apart: an id is a word, an integer, a string or an issue. */
35
+ export declare function idKey(c: Cell): string | null;
36
+ /** The orbit a block describes, and what was wrong with it; what is wrong is left out. */
37
+ export declare function readOrbit(data: Cell): {
38
+ spec: OrbitSpec;
39
+ error: string | null;
40
+ };
41
+ export type Role = 'focus' | 'near' | 'more' | 'trail';
42
+ /** Where a bubble is, in the orbit's own space with the focus at 0,0: its centre, radius and opacity. */
43
+ export interface Place {
44
+ x: number;
45
+ y: number;
46
+ r: number;
47
+ o: number;
48
+ }
49
+ export interface Placed extends Place {
50
+ key: string;
51
+ role: Role;
52
+ }
53
+ export declare const FOCUS_R = 92;
54
+ /** Neighbours on show at once; past that, a "+N more" bubble pages through them. */
55
+ export declare const PAGE = 30;
56
+ /** Past this many neighbours, edge labels show only on hover. */
57
+ export declare const MANY = 18;
58
+ /** The key of the "+N more" bubble: no id gives it. */
59
+ export declare const MORE = "\0more";
60
+ export interface Box {
61
+ x0: number;
62
+ y0: number;
63
+ x1: number;
64
+ y1: number;
65
+ }
66
+ export interface OrbitLayout {
67
+ placed: Placed[];
68
+ /** The box everything drawn fits in, titles too: the camera fits it. */
69
+ box: Box;
70
+ /** The neighbours not on this page; 0 when they all fit. */
71
+ left: number;
72
+ pages: number;
73
+ }
74
+ /** The neighbours of the focus: every node given that is neither it nor in the trail, in the order given. */
75
+ export declare function neighbours(spec: OrbitSpec): string[];
76
+ /** Places the focus, its neighbours on rings (the given page of them) and the last few of the trail. */
77
+ export declare function layoutOrbit(spec: OrbitSpec, page?: number): OrbitLayout;
78
+ /** The edges to draw between bubbles on show: those given between the focus and its neighbours, and the trail's dotted line. */
79
+ export declare function shownEdges(spec: OrbitSpec, placed: Placed[]): Array<OrbitEdge & {
80
+ curve: number;
81
+ trail: boolean;
82
+ }>;
83
+ /** The label of the edge between the focus and a neighbour, either way round; null if none. */
84
+ export declare function edgeLabel(spec: OrbitSpec, key: string): Cell | null;
85
+ /** A title in lines of at most `max` characters, three lines at most. */
86
+ export declare function wrapTitle(title: string, max: number): string[];
87
+ /** An arc of a circle of radius r from angle a0 to a1, as path data. */
88
+ export declare function arcPath(r: number, a0: number, a1: number): string;
89
+ export interface BubbleLook {
90
+ role: Role;
91
+ r: number;
92
+ /** The camera's zoom once it fits: titles are sized for the screen at it, as the rest of the page's text. */
93
+ scale: number;
94
+ /** A title outside the bubble goes above it rather than under it: for bubbles above the focus, away from their edge. */
95
+ above: boolean;
96
+ title: string;
97
+ color: string;
98
+ /** The ids of the gradients for this color: body and halo. */
99
+ body: string;
100
+ halo: string;
101
+ node: OrbitNode | null;
102
+ }
103
+ /** What a bubble draws, in unit space: halo, body, its rings, moons, title and count. */
104
+ export declare function bubble(b: BubbleLook): El[];
105
+ /** The two gradients of a color: a body lighter in the middle and a soft halo. */
106
+ export declare function gradients(color: string, body: string, halo: string): El[];
107
+ /** Where an edge's line goes, from bubble a to bubble b, cut at their borders; and the middle and angle for its label. */
108
+ export declare function edgePath(a: Place, b: Place, curve: number): {
109
+ d: string;
110
+ x: number;
111
+ y: number;
112
+ angle: number;
113
+ };
114
+ /** The ease of a move: slow at both ends. */
115
+ export declare const ease: (k: number) => number;
116
+ /** Where the camera goes to show the whole box in a view of w by h: centred on it, zoomed to fit, within limits. */
117
+ export declare function fitCamera(w: number, h: number, box: Box): {
118
+ x: number;
119
+ y: number;
120
+ s: number;
121
+ };