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.
- package/README.md +18 -3
- package/dist/cli.js +13790 -11417
- package/dist/fonts/OFL.txt +93 -0
- package/dist/fonts/inter-cyrillic-ext.woff2 +0 -0
- package/dist/fonts/inter-cyrillic.woff2 +0 -0
- package/dist/fonts/inter-greek-ext.woff2 +0 -0
- package/dist/fonts/inter-greek.woff2 +0 -0
- package/dist/fonts/inter-latin-ext.woff2 +0 -0
- package/dist/fonts/inter-latin.woff2 +0 -0
- package/dist/fonts/inter-vietnamese.woff2 +0 -0
- package/dist/lib/core/access.d.ts +10 -0
- package/dist/lib/core/access.js +210 -0
- package/dist/lib/core/base.d.ts +4 -0
- package/dist/lib/core/base.js +50 -0
- package/dist/lib/core/bitset.d.ts +9 -0
- package/dist/lib/core/bitset.js +75 -0
- package/dist/lib/core/boot.d.ts +18 -0
- package/dist/lib/core/boot.js +73 -0
- package/dist/lib/core/compare.d.ts +9 -0
- package/dist/lib/core/compare.js +156 -0
- package/dist/lib/core/ctx.d.ts +36 -0
- package/dist/lib/core/ctx.js +251 -0
- package/dist/lib/core/dec.d.ts +28 -0
- package/dist/lib/core/dec.js +158 -0
- package/dist/lib/core/errors.d.ts +15 -0
- package/dist/lib/core/errors.js +44 -0
- package/dist/lib/core/escapes.d.ts +14 -0
- package/dist/lib/core/escapes.js +80 -0
- package/dist/lib/core/eval.d.ts +220 -0
- package/dist/lib/core/eval.js +666 -0
- package/dist/lib/core/func.d.ts +68 -0
- package/dist/lib/core/func.js +129 -0
- package/dist/lib/core/hash.d.ts +5 -0
- package/dist/lib/core/hash.js +155 -0
- package/dist/lib/core/index.d.ts +18 -0
- package/dist/lib/core/index.js +20 -0
- package/dist/lib/core/int64.d.ts +22 -0
- package/dist/lib/core/int64.js +113 -0
- package/dist/lib/core/kinds.d.ts +67 -0
- package/dist/lib/core/kinds.js +134 -0
- package/dist/lib/core/lexer.d.ts +13 -0
- package/dist/lib/core/lexer.js +702 -0
- package/dist/lib/core/mezz.d.ts +1 -0
- package/dist/lib/core/mezz.js +360 -0
- package/dist/lib/core/mold.d.ts +20 -0
- package/dist/lib/core/mold.js +434 -0
- package/dist/lib/core/natives/control.d.ts +1 -0
- package/dist/lib/core/natives/control.js +374 -0
- package/dist/lib/core/natives/csv.d.ts +15 -0
- package/dist/lib/core/natives/csv.js +315 -0
- package/dist/lib/core/natives/data.d.ts +11 -0
- package/dist/lib/core/natives/data.js +367 -0
- package/dist/lib/core/natives/define.d.ts +17 -0
- package/dist/lib/core/natives/define.js +47 -0
- package/dist/lib/core/natives/encode.d.ts +3 -0
- package/dist/lib/core/natives/encode.js +187 -0
- package/dist/lib/core/natives/json.d.ts +5 -0
- package/dist/lib/core/natives/json.js +273 -0
- package/dist/lib/core/natives/math.d.ts +3 -0
- package/dist/lib/core/natives/math.js +500 -0
- package/dist/lib/core/natives/parse.d.ts +1 -0
- package/dist/lib/core/natives/parse.js +600 -0
- package/dist/lib/core/natives/series.d.ts +4 -0
- package/dist/lib/core/natives/series.js +519 -0
- package/dist/lib/core/natives/text.d.ts +1 -0
- package/dist/lib/core/natives/text.js +487 -0
- package/dist/lib/core/natives/xml.d.ts +9 -0
- package/dist/lib/core/natives/xml.js +242 -0
- package/dist/lib/core/series.d.ts +26 -0
- package/dist/lib/core/series.js +73 -0
- package/dist/lib/core/symbols.d.ts +9 -0
- package/dist/lib/core/symbols.js +44 -0
- package/dist/lib/core/values.d.ts +206 -0
- package/dist/lib/core/values.js +223 -0
- package/dist/lib/host/browser.d.ts +4 -0
- package/dist/lib/host/browser.js +4974 -0
- package/dist/lib/host/chart.d.ts +26 -0
- package/dist/lib/host/chart.js +158 -0
- package/dist/lib/host/compress.d.ts +1 -0
- package/dist/lib/host/compress.js +37 -0
- package/dist/lib/host/devlog.d.ts +11 -0
- package/dist/lib/host/devlog.js +13 -0
- package/dist/lib/host/devtools.d.ts +23 -0
- package/dist/lib/host/devtools.js +626 -0
- package/dist/lib/host/draw.d.ts +31 -0
- package/dist/lib/host/draw.js +348 -0
- package/dist/lib/host/fonts/OFL.txt +93 -0
- package/dist/lib/host/fonts/inter-cyrillic-ext.woff2 +0 -0
- package/dist/lib/host/fonts/inter-cyrillic.woff2 +0 -0
- package/dist/lib/host/fonts/inter-greek-ext.woff2 +0 -0
- package/dist/lib/host/fonts/inter-greek.woff2 +0 -0
- package/dist/lib/host/fonts/inter-latin-ext.woff2 +0 -0
- package/dist/lib/host/fonts/inter-latin.woff2 +0 -0
- package/dist/lib/host/fonts/inter-vietnamese.woff2 +0 -0
- package/dist/lib/host/fonts.d.ts +11 -0
- package/dist/lib/host/fonts.js +29 -0
- package/dist/lib/host/icons.d.ts +3 -0
- package/dist/lib/host/icons.js +97 -0
- package/dist/lib/host/index.d.ts +40 -0
- package/dist/lib/host/index.js +192 -0
- package/dist/lib/host/js.d.ts +5 -0
- package/dist/lib/host/js.js +130 -0
- package/dist/lib/host/locale.d.ts +40 -0
- package/dist/lib/host/locale.js +241 -0
- package/dist/lib/host/markdown.d.ts +30 -0
- package/dist/lib/host/markdown.js +161 -0
- package/dist/lib/host/modules.d.ts +14 -0
- package/dist/lib/host/modules.js +300 -0
- package/dist/lib/host/natives.d.ts +6 -0
- package/dist/lib/host/natives.js +98 -0
- package/dist/lib/host/net.d.ts +12 -0
- package/dist/lib/host/net.js +549 -0
- package/dist/lib/host/orbit.d.ts +121 -0
- package/dist/lib/host/orbit.js +374 -0
- package/dist/lib/host/page.d.ts +9 -0
- package/dist/lib/host/page.js +55 -0
- package/dist/lib/host/rows.d.ts +29 -0
- package/dist/lib/host/rows.js +109 -0
- package/dist/lib/host/scheduler.d.ts +51 -0
- package/dist/lib/host/scheduler.js +197 -0
- package/dist/lib/host/theme.d.ts +58 -0
- package/dist/lib/host/theme.js +1667 -0
- package/dist/lib/ui/i18n.trb +117 -0
- package/dist/lib/ui/test.trb +565 -0
- package/dist/lib/ui/ui.trb +1678 -0
- package/dist/trebol.js +1427 -138
- package/editors/vscode/README.md +15 -0
- package/editors/vscode/language-configuration.json +28 -0
- package/editors/vscode/package.json +42 -0
- package/editors/vscode/syntaxes/trebol.tmLanguage.json +237 -0
- package/package.json +23 -7
- package/src/core/boot.ts +1 -1
- package/src/core/func.ts +4 -0
- package/src/core/natives/control.ts +1 -1
- package/src/core/natives/series.ts +9 -1
- package/src/core/natives/text.ts +2 -0
- package/src/host/browser.ts +1235 -83
- package/src/host/devlog.ts +16 -0
- package/src/host/devtools.ts +641 -0
- package/src/host/fonts/OFL.txt +93 -0
- package/src/host/fonts/inter-cyrillic-ext.woff2 +0 -0
- package/src/host/fonts/inter-cyrillic.woff2 +0 -0
- package/src/host/fonts/inter-greek-ext.woff2 +0 -0
- package/src/host/fonts/inter-greek.woff2 +0 -0
- package/src/host/fonts/inter-latin-ext.woff2 +0 -0
- package/src/host/fonts/inter-latin.woff2 +0 -0
- package/src/host/fonts/inter-vietnamese.woff2 +0 -0
- package/src/host/fonts.ts +39 -0
- package/src/host/index.ts +5 -3
- package/src/host/js.ts +127 -0
- package/src/host/markdown.ts +9 -0
- package/src/host/modules.ts +41 -2
- package/src/host/net.ts +9 -1
- package/src/host/orbit.ts +432 -0
- package/src/host/rows.ts +30 -0
- package/src/host/scheduler.ts +62 -36
- package/src/host/theme.ts +270 -6
- package/src/ui/i18n.trb +10 -0
- package/src/ui/test.trb +565 -0
- package/src/ui/ui.trb +564 -90
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// The host: registers console, time, task and network natives, builds a
|
|
2
|
+
// runtime and a scheduler, and runs programs as tasks.
|
|
3
|
+
import "./natives.js";
|
|
4
|
+
import "./net.js";
|
|
5
|
+
import "./page.js";
|
|
6
|
+
import "./compress.js";
|
|
7
|
+
import "./locale.js";
|
|
8
|
+
import { setLoader, defaultLoader } from "./modules.js";
|
|
9
|
+
import { K, makeRuntime, load, bindSeries, doSource, scriptStart, errorMessage, form, mold, LIBRARY_FILES, } from "../core/index.js";
|
|
10
|
+
import { makeScheduler, spawn, taskResult } from "./scheduler.js";
|
|
11
|
+
export { output } from "./natives.js";
|
|
12
|
+
export { fileHandle } from "./net.js";
|
|
13
|
+
export { page } from "./page.js";
|
|
14
|
+
export { mapAt, formatLocal, activeLanguage, shown, translate, uiText, editLocal, readLocal, readDate, weekStart, fileSize, LOCAL_KINDS } from "./locale.js";
|
|
15
|
+
export * from "./scheduler.js";
|
|
16
|
+
/** Host mezzanines: the Trebol side of the host natives. */
|
|
17
|
+
const HOST_MEZZANINES = String.raw `
|
|
18
|
+
print: func ["Prints a value; a block is reduced first." value [any-type!]] [
|
|
19
|
+
write-line either block? :value [reduce value] [:value]
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
fetch: func [
|
|
23
|
+
"Requests a URL. JSON answers come back as maps and blocks."
|
|
24
|
+
url [url! string!]
|
|
25
|
+
/with "method, headers, body, form, multipart, timeout, full"
|
|
26
|
+
options [block! object!]
|
|
27
|
+
][
|
|
28
|
+
http-request url either with [either block? options [make object! options] [options]] [none]
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
show-progress: func [
|
|
32
|
+
"Shows how far a request went on a face: a progress bar's value, or the bar of an upload or a photo."
|
|
33
|
+
face [object!]
|
|
34
|
+
done [integer! none!] "Bytes done; none once the request is over"
|
|
35
|
+
total [integer! none!] "Bytes in all, when known"
|
|
36
|
+
/local part
|
|
37
|
+
][
|
|
38
|
+
part: either all [done total total > 0] [done / to decimal! total] [none]
|
|
39
|
+
either find [upload photo] select face 'style [face/sent: part] [if done [face/value: part]]
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
save: func [
|
|
43
|
+
"Gives the user a file with a value written so load reads it back; .json, .csv and .xml are written as such."
|
|
44
|
+
where [file! none!] "The name of the file, or none for the bytes"
|
|
45
|
+
value [any-type!]
|
|
46
|
+
/all "Kept for R3 code: values are always written so load gives them back"
|
|
47
|
+
/local data
|
|
48
|
+
][
|
|
49
|
+
; /all names the refinement here, not the native
|
|
50
|
+
data: switch/default either file? where [suffix? where] [none] [
|
|
51
|
+
%.json [to-json :value]
|
|
52
|
+
%.csv [to-csv :value]
|
|
53
|
+
%.xml [to-xml :value]
|
|
54
|
+
] [
|
|
55
|
+
append either block? :value [mold/all/only value] [mold/all :value] newline
|
|
56
|
+
]
|
|
57
|
+
either where [download where data] [to binary! data]
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
help: func [
|
|
61
|
+
"Shows how to call a function, or what a word holds."
|
|
62
|
+
'word [any-type!] "The word to explain"
|
|
63
|
+
/local value name about entry args refs ret target usage describe kind
|
|
64
|
+
][
|
|
65
|
+
unless word? :word [
|
|
66
|
+
print "Type help and a word: help print, help round"
|
|
67
|
+
exit
|
|
68
|
+
]
|
|
69
|
+
name: uppercase form word
|
|
70
|
+
unless value? word [
|
|
71
|
+
print [name "has no value."]
|
|
72
|
+
exit
|
|
73
|
+
]
|
|
74
|
+
value: get word
|
|
75
|
+
; "a block!", "an object!"
|
|
76
|
+
kind: mold type? :value
|
|
77
|
+
kind: rejoin [either find "aeiou" first kind ["an "] ["a "] kind]
|
|
78
|
+
unless any-function? :value [
|
|
79
|
+
about: mold :value
|
|
80
|
+
if 60 < length? about [about: append copy/part about 57 "..."]
|
|
81
|
+
print rejoin [name " is " kind " of value: " about]
|
|
82
|
+
exit
|
|
83
|
+
]
|
|
84
|
+
; read the spec: a description, then arguments, refinements and their
|
|
85
|
+
; arguments, each with its types and its own description
|
|
86
|
+
about: none args: copy [] refs: copy [] ret: none target: args entry: none
|
|
87
|
+
foreach item spec-of :value [
|
|
88
|
+
case [
|
|
89
|
+
item = /local [break]
|
|
90
|
+
string? item [either entry [entry/doc: item] [about: item]]
|
|
91
|
+
block? item [if entry [entry/types: item]]
|
|
92
|
+
refinement? item [
|
|
93
|
+
append refs entry: make object! [name: item doc: none types: none args: copy []]
|
|
94
|
+
target: entry/args
|
|
95
|
+
]
|
|
96
|
+
set-word? item [entry: ret: make object! [name: item doc: none types: none]]
|
|
97
|
+
any [word? item lit-word? item get-word? item] [
|
|
98
|
+
append target entry: make object! [name: item doc: none types: none]
|
|
99
|
+
]
|
|
100
|
+
]
|
|
101
|
+
]
|
|
102
|
+
describe: func [e] [
|
|
103
|
+
rejoin [
|
|
104
|
+
mold e/name
|
|
105
|
+
either e/doc [rejoin [" -- " e/doc]] [""]
|
|
106
|
+
either e/types [rejoin [" (" form e/types ")"]] [""]
|
|
107
|
+
]
|
|
108
|
+
]
|
|
109
|
+
usage: copy name
|
|
110
|
+
foreach a args [append append usage " " mold a/name]
|
|
111
|
+
; an operator goes between its arguments
|
|
112
|
+
if op? :value [usage: rejoin [mold args/1/name " " name " " mold args/2/name]]
|
|
113
|
+
print "USAGE:"
|
|
114
|
+
print rejoin [" " usage]
|
|
115
|
+
print ""
|
|
116
|
+
print "DESCRIPTION:"
|
|
117
|
+
if about [print rejoin [" " about]]
|
|
118
|
+
print rejoin [" " name " is " kind " value."]
|
|
119
|
+
unless empty? args [
|
|
120
|
+
print ""
|
|
121
|
+
print "ARGUMENTS:"
|
|
122
|
+
foreach a args [print rejoin [" " describe a]]
|
|
123
|
+
]
|
|
124
|
+
unless empty? refs [
|
|
125
|
+
print ""
|
|
126
|
+
print "REFINEMENTS:"
|
|
127
|
+
foreach r refs [
|
|
128
|
+
print rejoin [" " describe r]
|
|
129
|
+
foreach a r/args [print rejoin [" " describe a]]
|
|
130
|
+
]
|
|
131
|
+
]
|
|
132
|
+
if all [ret ret/types] [
|
|
133
|
+
print ""
|
|
134
|
+
print "RETURNS:"
|
|
135
|
+
print rejoin [" " form ret/types]
|
|
136
|
+
]
|
|
137
|
+
exit
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
?: :help
|
|
141
|
+
|
|
142
|
+
??: func ["Prints a word and its value." 'word [any-word!]] [
|
|
143
|
+
print rejoin [form word ": " mold get word]
|
|
144
|
+
]
|
|
145
|
+
|
|
146
|
+
source: func ["Prints the source of a function." 'word [any-word!] /local value] [
|
|
147
|
+
value: get word
|
|
148
|
+
print rejoin [
|
|
149
|
+
form word ": " case [
|
|
150
|
+
function? :value [rejoin ["func " mold spec-of :value " " mold body-of :value]]
|
|
151
|
+
any-function? :value [rejoin ["native " mold spec-of :value]]
|
|
152
|
+
true [mold :value]
|
|
153
|
+
]
|
|
154
|
+
]
|
|
155
|
+
]
|
|
156
|
+
`;
|
|
157
|
+
/** Rebol-style multi-line report of an error. */
|
|
158
|
+
export function report(e) {
|
|
159
|
+
return form(e);
|
|
160
|
+
}
|
|
161
|
+
export function startHost(opts = {}) {
|
|
162
|
+
const onError = opts.onError ?? (e => console.error(report(e)));
|
|
163
|
+
const rt = makeRuntime();
|
|
164
|
+
setLoader(rt, opts.loader ?? defaultLoader());
|
|
165
|
+
const r = doSource(rt, HOST_MEZZANINES, 'host');
|
|
166
|
+
// Host mezzanines failing to load is a bug in Trebol itself.
|
|
167
|
+
if (r.k === 'error')
|
|
168
|
+
throw new Error(`host mezzanines failed: ${errorMessage(r.e)}`);
|
|
169
|
+
const sch = makeScheduler(rt, e => onError(e));
|
|
170
|
+
return { rt, sch };
|
|
171
|
+
}
|
|
172
|
+
/** URL of the UI dialect source, next to this file. */
|
|
173
|
+
export const UI_SOURCE = new URL('../ui/ui.trb', import.meta.url).href;
|
|
174
|
+
/** URL of the languages module (i18n, tr, translated). */
|
|
175
|
+
export const I18N_SOURCE = new URL('../ui/i18n.trb', import.meta.url).href;
|
|
176
|
+
/** URL of the words of screen tests (click, type, see...), which `trebol test` loads. */
|
|
177
|
+
export const TEST_SOURCE = new URL('../ui/test.trb', import.meta.url).href;
|
|
178
|
+
// Trebol's own code: its errors point at the program's call (see LIBRARY_FILES).
|
|
179
|
+
LIBRARY_FILES.add('host').add(UI_SOURCE).add(I18N_SOURCE).add(TEST_SOURCE);
|
|
180
|
+
/** Loads languages and the UI dialect (view, layout, stylize, theme...) into the user context. */
|
|
181
|
+
export function startUi(host) {
|
|
182
|
+
return runSource(host, `import ${I18N_SOURCE} import ${UI_SOURCE}`);
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Loads source into the user context and runs it as a task. Resolves with
|
|
186
|
+
* its value; rejects with the error! if it fails. Load errors throw LoadError.
|
|
187
|
+
*/
|
|
188
|
+
export function runSource(host, src, file) {
|
|
189
|
+
const code = load(src, file !== undefined ? { file } : {});
|
|
190
|
+
bindSeries(code.s, host.rt.user, true);
|
|
191
|
+
return taskResult(spawn(host.sch, code.s, scriptStart(code).start));
|
|
192
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type ObjectCell } from '../core/index.ts';
|
|
2
|
+
/** countPages is count-pages, as Trebol names words. */
|
|
3
|
+
export declare function trebolName(js: string): string;
|
|
4
|
+
/** The object for a loaded JavaScript module, or an error message. */
|
|
5
|
+
export declare function jsModule(ns: Record<string, unknown>): ObjectCell | string;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// JavaScript modules as Trebol modules.
|
|
2
|
+
//
|
|
3
|
+
// `import %pdf-tools.js` loads a JavaScript module and gives an object with a
|
|
4
|
+
// function for each function it exports, named in Trebol's way (countPages is
|
|
5
|
+
// count-pages), and the other exports as values:
|
|
6
|
+
//
|
|
7
|
+
// pdf: import %pdf-tools.js
|
|
8
|
+
// pages: pdf/count-pages %contract.pdf
|
|
9
|
+
//
|
|
10
|
+
// Arguments and results cross as JSON, so text, numbers, blocks, maps, logic
|
|
11
|
+
// and none keep their shape; a promise is awaited while other tasks run, and
|
|
12
|
+
// a JavaScript exception is a Trebol error. A function's spec comes from its
|
|
13
|
+
// parameters, or from a `spec` property written as Trebol source:
|
|
14
|
+
//
|
|
15
|
+
// export function countPages(file) { ... }
|
|
16
|
+
// countPages.spec = '["The pages of a PDF." file [file! url!]]';
|
|
17
|
+
//
|
|
18
|
+
// No Trebol value holds the JavaScript function: each is a native built on one
|
|
19
|
+
// hidden native, carrying the function's index in a table here as its data.
|
|
20
|
+
import { K, NONE, registerNative, load, parseSpec, parseJson, toJson, context, ctxAdd, intern, makeError, value, throwError, } from "../core/index.js";
|
|
21
|
+
const functions = [];
|
|
22
|
+
const call = registerNative({
|
|
23
|
+
name: 'js-function', hidden: true, spec: parseSpec(load('[]').s.data[0]),
|
|
24
|
+
specBlock: load('[]').s.data[0],
|
|
25
|
+
}, (_t, f, v) => {
|
|
26
|
+
if (f.phase === 1)
|
|
27
|
+
return value(v);
|
|
28
|
+
const fn = functions[f.def.data];
|
|
29
|
+
const name = f.def.name;
|
|
30
|
+
let result;
|
|
31
|
+
try {
|
|
32
|
+
result = fn(...f.args.map(a => JSON.parse(toJson(a))));
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
return throwError('script', 'js-error', `${name}: ${e?.message ?? String(e)}`);
|
|
36
|
+
}
|
|
37
|
+
if (!(result instanceof Promise))
|
|
38
|
+
return toTrebol(result, name);
|
|
39
|
+
f.phase = 1;
|
|
40
|
+
return {
|
|
41
|
+
k: 'await',
|
|
42
|
+
p: result.then(r => {
|
|
43
|
+
const step = toTrebol(r, name);
|
|
44
|
+
if (step.k === 'value')
|
|
45
|
+
return step.v;
|
|
46
|
+
throw step.e.v;
|
|
47
|
+
}, (e) => {
|
|
48
|
+
throw makeError('script', 'js-error', `${name}: ${e?.message ?? String(e)}`);
|
|
49
|
+
}),
|
|
50
|
+
};
|
|
51
|
+
}).p;
|
|
52
|
+
function toTrebol(r, name) {
|
|
53
|
+
if (r === undefined)
|
|
54
|
+
return value(NONE);
|
|
55
|
+
let json;
|
|
56
|
+
try {
|
|
57
|
+
json = JSON.stringify(r);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
json = undefined;
|
|
61
|
+
}
|
|
62
|
+
if (json === undefined)
|
|
63
|
+
return throwError('script', 'js-error', `${name} gave a value that is not JSON`);
|
|
64
|
+
const v = parseJson(json);
|
|
65
|
+
return typeof v === 'string' ? throwError('script', 'js-error', `${name}: ${v}`) : value(v);
|
|
66
|
+
}
|
|
67
|
+
/** countPages is count-pages, as Trebol names words. */
|
|
68
|
+
export function trebolName(js) {
|
|
69
|
+
return js.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/_/g, '-').toLowerCase();
|
|
70
|
+
}
|
|
71
|
+
/** The parameter names of a plain function or an arrow, or none when they cannot be read. */
|
|
72
|
+
function params(fn) {
|
|
73
|
+
const src = fn.toString();
|
|
74
|
+
const m = /^\s*(?:async\s+)?([\w$]+)\s*=>/.exec(src) ?? /^[^(=]*\(([^)]*)\)/.exec(src);
|
|
75
|
+
if (m === null)
|
|
76
|
+
return null;
|
|
77
|
+
const names = m[1].split(',').map(p => p.trim()).filter(p => p !== '');
|
|
78
|
+
return names.every(p => /^[A-Za-z_$][\w$]*$/.test(p)) ? names.map(trebolName) : null;
|
|
79
|
+
}
|
|
80
|
+
function specOf(fn, name) {
|
|
81
|
+
const own = fn.spec;
|
|
82
|
+
const src = typeof own === 'string' ? own
|
|
83
|
+
: `[${(params(fn) ?? Array.from({ length: fn.length }, (_, i) => `arg${i + 1}`)).join(' ')}]`;
|
|
84
|
+
let specBlock;
|
|
85
|
+
try {
|
|
86
|
+
specBlock = load(src).s.data[0];
|
|
87
|
+
}
|
|
88
|
+
catch (e) {
|
|
89
|
+
return `${name}: bad spec: ${e.message}`;
|
|
90
|
+
}
|
|
91
|
+
if (specBlock?.t !== K.Block)
|
|
92
|
+
return `${name}: its spec is not a block`;
|
|
93
|
+
const spec = parseSpec(specBlock);
|
|
94
|
+
return typeof spec === 'string' ? `${name}: ${spec}` : { spec, specBlock };
|
|
95
|
+
}
|
|
96
|
+
/** The object for a loaded JavaScript module, or an error message. */
|
|
97
|
+
export function jsModule(ns) {
|
|
98
|
+
const ctx = context();
|
|
99
|
+
ctx.self = true;
|
|
100
|
+
for (const [key, x] of Object.entries(ns)) {
|
|
101
|
+
if (key === 'default')
|
|
102
|
+
continue;
|
|
103
|
+
const name = trebolName(key);
|
|
104
|
+
let v;
|
|
105
|
+
if (typeof x === 'function') {
|
|
106
|
+
const spec = specOf(x, name);
|
|
107
|
+
if (typeof spec === 'string')
|
|
108
|
+
return spec;
|
|
109
|
+
functions.push(x);
|
|
110
|
+
v = { t: K.Native, p: { ...call, ...spec, name, data: functions.length - 1, hidden: true } };
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
let json;
|
|
114
|
+
try {
|
|
115
|
+
json = JSON.stringify(x);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
json = undefined;
|
|
119
|
+
}
|
|
120
|
+
if (json === undefined)
|
|
121
|
+
continue;
|
|
122
|
+
const parsed = parseJson(json);
|
|
123
|
+
if (typeof parsed === 'string')
|
|
124
|
+
continue;
|
|
125
|
+
v = parsed;
|
|
126
|
+
}
|
|
127
|
+
ctxAdd(ctx, intern(name), v);
|
|
128
|
+
}
|
|
129
|
+
return { t: K.Object, ctx };
|
|
130
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type Cell, type MapCell, type Runtime } from '../core/index.ts';
|
|
2
|
+
/** The kinds `localize` formats; anything else shows as `form` gives it. */
|
|
3
|
+
export declare const LOCAL_KINDS: ReadonlySet<number>;
|
|
4
|
+
/** A value in the format of a language tag (`es`, `en-GB`); null when it has no local format. */
|
|
5
|
+
export declare function formatLocal(c: Cell, lang: string): string | null;
|
|
6
|
+
/** An amount as it is edited in a language: no thousands, the local decimal separator (`1234,50`). */
|
|
7
|
+
export declare function editLocal(c: Cell, lang: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* An amount typed in a language as Trebol reads it (`1234.5`), or null when it is not one.
|
|
10
|
+
* Currency signs and spaces are dropped. Thousands only count in groups of three; a single
|
|
11
|
+
* other separator is the decimal one, so `12.5` is twelve and a half in `es` too.
|
|
12
|
+
*/
|
|
13
|
+
export declare function readLocal(s: string, lang: string): string | null;
|
|
14
|
+
/**
|
|
15
|
+
* A date typed in a language as Trebol reads it (`2026-11-03`), or null when it is not one.
|
|
16
|
+
* Day, month and year go in the order of the language with any separator; `2026-11-03`
|
|
17
|
+
* reads in every language, and a two-digit year is in this century.
|
|
18
|
+
*/
|
|
19
|
+
export declare function readDate(s: string, lang: string): string | null;
|
|
20
|
+
/** The first day of the week in a language, 1 for Monday to 7 for Sunday. */
|
|
21
|
+
export declare function weekStart(lang: string): number;
|
|
22
|
+
/** The active language: `i18n/language` of the user context, `en` if there is none. */
|
|
23
|
+
export declare function activeLanguage(rt: Runtime): string;
|
|
24
|
+
/** The value under a key of a map (a word or a string key, any case), or null. */
|
|
25
|
+
export declare function mapAt(m: MapCell, key: string): Cell | null;
|
|
26
|
+
/**
|
|
27
|
+
* A text of the interface in the active language, as `tr` gives it: a string
|
|
28
|
+
* as is, a text per language (a map) in the active language, then the main
|
|
29
|
+
* one, then any, and a word through the dictionary `i18n/texts`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function translate(c: Cell, rt: Runtime): string;
|
|
32
|
+
/**
|
|
33
|
+
* One of Trebol's own texts (the map `i18n/ui`) in the active language, with
|
|
34
|
+
* `#1`, `#2`... replaced by the arguments. A key that is missing shows as is.
|
|
35
|
+
*/
|
|
36
|
+
export declare function uiText(rt: Runtime, key: string, ...args: string[]): string;
|
|
37
|
+
/** A value as it shows on screen in a language: local format, or `form`. */
|
|
38
|
+
export declare function shown(c: Cell, lang: string): string;
|
|
39
|
+
/** A size in bytes as it reads in a language: 89 bytes, 12 kB, 3.4 MB. */
|
|
40
|
+
export declare function fileSize(bytes: number, lang: string): string;
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// Values in the format of a language: dates, times, numbers, percents and
|
|
2
|
+
// money, through Intl. It works wherever Intl does (browser or Node); the
|
|
3
|
+
// core keeps its own language-neutral form/mold.
|
|
4
|
+
import { K, native, value, string, form, text, formatDec, spell, ctxFind, intern, } from "../core/index.js";
|
|
5
|
+
/** The kinds `localize` formats; anything else shows as `form` gives it. */
|
|
6
|
+
export const LOCAL_KINDS = new Set([K.Date, K.Time, K.Integer, K.Decimal, K.Percent, K.Money]);
|
|
7
|
+
const NS_PER_MS = 1e6;
|
|
8
|
+
const DAY_NS = 24 * 3600 * 1e9;
|
|
9
|
+
function safe(fn) {
|
|
10
|
+
try {
|
|
11
|
+
return fn();
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** A value in the format of a language tag (`es`, `en-GB`); null when it has no local format. */
|
|
18
|
+
export function formatLocal(c, lang) {
|
|
19
|
+
switch (c.t) {
|
|
20
|
+
case K.Integer:
|
|
21
|
+
return safe(() => new Intl.NumberFormat(lang).format(c.v));
|
|
22
|
+
case K.Decimal:
|
|
23
|
+
return safe(() => new Intl.NumberFormat(lang, { maximumSignificantDigits: 15 }).format(c.v));
|
|
24
|
+
case K.Percent:
|
|
25
|
+
return safe(() => new Intl.NumberFormat(lang, { style: 'percent', maximumFractionDigits: 2 }).format(c.v));
|
|
26
|
+
case K.Money: {
|
|
27
|
+
// a decimal string keeps every digit; Intl never goes through a float
|
|
28
|
+
const amount = formatDec(c.v);
|
|
29
|
+
const frac = { minimumFractionDigits: 2, maximumFractionDigits: Math.max(2, c.v.e) };
|
|
30
|
+
return safe(() => new Intl.NumberFormat(lang, c.cur !== ''
|
|
31
|
+
? { style: 'currency', currency: c.cur, ...frac }
|
|
32
|
+
: frac).format(amount));
|
|
33
|
+
}
|
|
34
|
+
case K.Date: {
|
|
35
|
+
const d = c.v;
|
|
36
|
+
const ms = Date.UTC(d.y, d.m - 1, d.d) + (d.time ?? 0) / NS_PER_MS;
|
|
37
|
+
const opts = { year: 'numeric', month: 'numeric', day: 'numeric', timeZone: 'UTC' };
|
|
38
|
+
if (d.time !== null)
|
|
39
|
+
Object.assign(opts, { hour: 'numeric', minute: '2-digit' });
|
|
40
|
+
// years before 100 would be read as 19xx
|
|
41
|
+
if (d.y < 100)
|
|
42
|
+
return null;
|
|
43
|
+
return safe(() => new Intl.DateTimeFormat(lang, opts).format(ms));
|
|
44
|
+
}
|
|
45
|
+
case K.Time: {
|
|
46
|
+
if (c.v < 0 || c.v >= DAY_NS)
|
|
47
|
+
return null;
|
|
48
|
+
const opts = { hour: 'numeric', minute: '2-digit', timeZone: 'UTC' };
|
|
49
|
+
if (c.v % 6e10 !== 0)
|
|
50
|
+
opts.second = '2-digit';
|
|
51
|
+
return safe(() => new Intl.DateTimeFormat(lang, opts).format(c.v / NS_PER_MS));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
/** The decimal and group separators of a language: `,` and `.` in `es`. */
|
|
57
|
+
function separators(lang) {
|
|
58
|
+
let parts = [];
|
|
59
|
+
try {
|
|
60
|
+
parts = new Intl.NumberFormat(lang).formatToParts(12345.6);
|
|
61
|
+
}
|
|
62
|
+
catch { /* unknown language tag */ }
|
|
63
|
+
const find = (type) => parts.find(p => p.type === type)?.value;
|
|
64
|
+
return { decimal: find('decimal') ?? '.', group: find('group') ?? ',' };
|
|
65
|
+
}
|
|
66
|
+
/** An amount as it is edited in a language: no thousands, the local decimal separator (`1234,50`). */
|
|
67
|
+
export function editLocal(c, lang) {
|
|
68
|
+
if (c.t !== K.Money)
|
|
69
|
+
return c.t === K.None ? '' : form(c);
|
|
70
|
+
const amount = formatDec(c.v);
|
|
71
|
+
const opts = { useGrouping: false, minimumFractionDigits: 2, maximumFractionDigits: Math.max(2, c.v.e) };
|
|
72
|
+
return safe(() => new Intl.NumberFormat(lang, opts).format(amount)) ?? formatDec(c.v);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* An amount typed in a language as Trebol reads it (`1234.5`), or null when it is not one.
|
|
76
|
+
* Currency signs and spaces are dropped. Thousands only count in groups of three; a single
|
|
77
|
+
* other separator is the decimal one, so `12.5` is twelve and a half in `es` too.
|
|
78
|
+
*/
|
|
79
|
+
export function readLocal(s, lang) {
|
|
80
|
+
const { decimal, group } = separators(lang);
|
|
81
|
+
const sep = (ch) => ch === decimal || ch === group || ch === '.' || ch === ',';
|
|
82
|
+
let t = [...s].filter(ch => /[0-9+-]/.test(ch) || sep(ch)).join('');
|
|
83
|
+
if (t.includes(decimal)) {
|
|
84
|
+
const [whole, ...rest] = t.split(decimal);
|
|
85
|
+
if (rest.length > 1)
|
|
86
|
+
return null;
|
|
87
|
+
t = `${grouped(whole, group)}.${rest[0]}`;
|
|
88
|
+
}
|
|
89
|
+
else if (/^[+-]?\d{1,3}([.,]\d{3})+$/.test(t) && [...t].filter(sep).every(ch => ch === group)) {
|
|
90
|
+
t = grouped(t, group);
|
|
91
|
+
}
|
|
92
|
+
else if ([...t].filter(sep).length === 1) {
|
|
93
|
+
t = t.replace(/[.,]/, '.');
|
|
94
|
+
}
|
|
95
|
+
return /^[+-]?(\d+\.?\d*|\.\d+)$/.test(t) ? t : null;
|
|
96
|
+
}
|
|
97
|
+
/** The whole part of an amount without its thousands separators. */
|
|
98
|
+
function grouped(whole, group) {
|
|
99
|
+
return whole.split(group).join('');
|
|
100
|
+
}
|
|
101
|
+
/** The order of day, month and year in the dates of a language: `dmy` in `es`, `mdy` in `en`. */
|
|
102
|
+
function dateOrder(lang) {
|
|
103
|
+
let parts = [];
|
|
104
|
+
try {
|
|
105
|
+
parts = new Intl.DateTimeFormat(lang, { timeZone: 'UTC' }).formatToParts(Date.UTC(2026, 10, 23));
|
|
106
|
+
}
|
|
107
|
+
catch { /* unknown language tag */ }
|
|
108
|
+
const order = parts.map(p => p.type[0]).filter(c => c === 'd' || c === 'm' || c === 'y').join('');
|
|
109
|
+
return order.length === 3 ? order : 'dmy';
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* A date typed in a language as Trebol reads it (`2026-11-03`), or null when it is not one.
|
|
113
|
+
* Day, month and year go in the order of the language with any separator; `2026-11-03`
|
|
114
|
+
* reads in every language, and a two-digit year is in this century.
|
|
115
|
+
*/
|
|
116
|
+
export function readDate(s, lang) {
|
|
117
|
+
const nums = s.trim().split(/[^0-9]+/).filter(n => n !== '');
|
|
118
|
+
if (nums.length !== 3)
|
|
119
|
+
return null;
|
|
120
|
+
const order = nums[0].length === 4 ? 'ymd' : dateOrder(lang);
|
|
121
|
+
const at = (c) => Number(nums[order.indexOf(c)]);
|
|
122
|
+
let y = at('y');
|
|
123
|
+
const m = at('m'), d = at('d');
|
|
124
|
+
if (nums[order.indexOf('y')].length <= 2)
|
|
125
|
+
y += 2000;
|
|
126
|
+
const t = new Date(Date.UTC(y, m - 1, d));
|
|
127
|
+
if (y < 100 || t.getUTCFullYear() !== y || t.getUTCMonth() !== m - 1 || t.getUTCDate() !== d)
|
|
128
|
+
return null;
|
|
129
|
+
return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
|
|
130
|
+
}
|
|
131
|
+
/** The first day of the week in a language, 1 for Monday to 7 for Sunday. */
|
|
132
|
+
export function weekStart(lang) {
|
|
133
|
+
try {
|
|
134
|
+
const loc = new Intl.Locale(lang);
|
|
135
|
+
const first = (loc.getWeekInfo?.() ?? loc.weekInfo)?.firstDay;
|
|
136
|
+
if (first !== undefined)
|
|
137
|
+
return first;
|
|
138
|
+
// without week data, only regions known to start on Sunday
|
|
139
|
+
return ['US', 'CA', 'MX', 'BR', 'JP', 'IL', 'PH'].includes(loc.maximize().region ?? '') ? 7 : 1;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return 1;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** The active language: `i18n/language` of the user context, `en` if there is none. */
|
|
146
|
+
export function activeLanguage(rt) {
|
|
147
|
+
const i = ctxFind(rt.user, intern('i18n'));
|
|
148
|
+
const obj = i < 0 ? null : rt.user.vals[i];
|
|
149
|
+
if (obj === null || obj.t !== K.Object)
|
|
150
|
+
return 'en';
|
|
151
|
+
const o = obj;
|
|
152
|
+
const j = ctxFind(o.ctx, intern('language'));
|
|
153
|
+
const lang = j < 0 ? null : o.ctx.vals[j];
|
|
154
|
+
if (lang?.t === K.Word || lang?.t === K.LitWord)
|
|
155
|
+
return spell(lang.sym);
|
|
156
|
+
if (lang?.t === K.String)
|
|
157
|
+
return text(lang);
|
|
158
|
+
return 'en';
|
|
159
|
+
}
|
|
160
|
+
/** A field of the user's `i18n` object, or null. */
|
|
161
|
+
function i18nField(rt, name) {
|
|
162
|
+
const i = ctxFind(rt.user, intern('i18n'));
|
|
163
|
+
const obj = i < 0 ? null : rt.user.vals[i];
|
|
164
|
+
if (obj === null || obj.t !== K.Object)
|
|
165
|
+
return null;
|
|
166
|
+
const j = ctxFind(obj.ctx, intern(name));
|
|
167
|
+
return j < 0 ? null : obj.ctx.vals[j];
|
|
168
|
+
}
|
|
169
|
+
/** The value under a key of a map (a word or a string key, any case), or null. */
|
|
170
|
+
export function mapAt(m, key) {
|
|
171
|
+
const d = m.s.data;
|
|
172
|
+
const k = key.toLowerCase();
|
|
173
|
+
for (let i = 0; i + 1 < d.length; i += 2) {
|
|
174
|
+
const c = d[i];
|
|
175
|
+
const name = c.t === K.String ? text(c) : 'sym' in c ? spell(c.sym) : null;
|
|
176
|
+
if (name !== null && name.toLowerCase() === k)
|
|
177
|
+
return d[i + 1];
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* A text of the interface in the active language, as `tr` gives it: a string
|
|
183
|
+
* as is, a text per language (a map) in the active language, then the main
|
|
184
|
+
* one, then any, and a word through the dictionary `i18n/texts`.
|
|
185
|
+
*/
|
|
186
|
+
export function translate(c, rt) {
|
|
187
|
+
if (c.t === K.String)
|
|
188
|
+
return text(c);
|
|
189
|
+
if (c.t === K.Map) {
|
|
190
|
+
const main = i18nField(rt, 'main');
|
|
191
|
+
const t = mapAt(c, activeLanguage(rt))
|
|
192
|
+
?? (main !== null && 'sym' in main ? mapAt(c, spell(main.sym)) : null)
|
|
193
|
+
?? c.s.data.find((v, i) => i % 2 === 1 && v.t === K.String)
|
|
194
|
+
?? null;
|
|
195
|
+
return t === null ? '' : translate(t, rt);
|
|
196
|
+
}
|
|
197
|
+
if (c.t === K.Word || c.t === K.LitWord) {
|
|
198
|
+
const texts = i18nField(rt, 'texts');
|
|
199
|
+
const t = texts?.t === K.Map ? mapAt(texts, spell(c.sym)) : null;
|
|
200
|
+
return t === null ? spell(c.sym) : translate(t, rt);
|
|
201
|
+
}
|
|
202
|
+
return form(c);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* One of Trebol's own texts (the map `i18n/ui`) in the active language, with
|
|
206
|
+
* `#1`, `#2`... replaced by the arguments. A key that is missing shows as is.
|
|
207
|
+
*/
|
|
208
|
+
export function uiText(rt, key, ...args) {
|
|
209
|
+
const ui = i18nField(rt, 'ui');
|
|
210
|
+
const t = ui?.t === K.Map ? mapAt(ui, key) : null;
|
|
211
|
+
let out = t === null ? key : translate(t, rt);
|
|
212
|
+
args.forEach((a, i) => { out = out.replaceAll(`#${i + 1}`, a); });
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
/** A value as it shows on screen in a language: local format, or `form`. */
|
|
216
|
+
export function shown(c, lang) {
|
|
217
|
+
return formatLocal(c, lang) ?? form(c);
|
|
218
|
+
}
|
|
219
|
+
/** A size in bytes as it reads in a language: 89 bytes, 12 kB, 3.4 MB. */
|
|
220
|
+
export function fileSize(bytes, lang) {
|
|
221
|
+
const units = ['byte', 'kilobyte', 'megabyte', 'gigabyte'];
|
|
222
|
+
let n = bytes;
|
|
223
|
+
let u = 0;
|
|
224
|
+
while (n >= 1000 && u < units.length - 1) {
|
|
225
|
+
n /= 1000;
|
|
226
|
+
u++;
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
// short bytes read "89 byte" in English: whole words for bytes, symbols above
|
|
230
|
+
const display = u === 0 ? 'long' : 'short';
|
|
231
|
+
return new Intl.NumberFormat(lang, { style: 'unit', unit: units[u], unitDisplay: display, maximumFractionDigits: u === 0 ? 0 : 1 }).format(n);
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
return `${bytes} B`;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
native('format-local', '["The value as text in the way of a language: dates, numbers, money." value [any-type!] language [word! string!]]', (_t, f) => {
|
|
238
|
+
const l = f.args[1];
|
|
239
|
+
const lang = l.t === K.String ? text(l) : spell(l.sym);
|
|
240
|
+
return value(string(shown(f.args[0], lang)));
|
|
241
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type Inline = {
|
|
2
|
+
k: 'text';
|
|
3
|
+
text: string;
|
|
4
|
+
} | {
|
|
5
|
+
k: 'br';
|
|
6
|
+
} | {
|
|
7
|
+
k: 'b' | 'i';
|
|
8
|
+
kids: Inline[];
|
|
9
|
+
} | {
|
|
10
|
+
k: 'a';
|
|
11
|
+
href: string;
|
|
12
|
+
kids: Inline[];
|
|
13
|
+
};
|
|
14
|
+
export type Block = {
|
|
15
|
+
k: 'p';
|
|
16
|
+
kids: Inline[];
|
|
17
|
+
} | {
|
|
18
|
+
k: 'h';
|
|
19
|
+
level: number;
|
|
20
|
+
kids: Inline[];
|
|
21
|
+
} | {
|
|
22
|
+
k: 'ul' | 'ol';
|
|
23
|
+
items: Inline[][];
|
|
24
|
+
};
|
|
25
|
+
export declare function parseMd(src: string): Block[];
|
|
26
|
+
export declare function printMd(blocks: Block[]): string;
|
|
27
|
+
/** Markdown with plain text added at its end, in its last paragraph or a new one after a heading or list. */
|
|
28
|
+
export declare function appendText(src: string, text: string): string;
|
|
29
|
+
/** Only web and mail links open; anything else (javascript:...) is shown as plain text. */
|
|
30
|
+
export declare function safeHref(href: string): boolean;
|