@tarve/core 0.4.0 → 0.6.0

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 (122) hide show
  1. package/CHANGELOG.md +126 -1
  2. package/README.md +121 -12
  3. package/dist/npm/build.js +1401 -85
  4. package/dist/npm/cli.js +1940 -117
  5. package/dist/npm/embedded-assets.js +22 -3
  6. package/dist/npm/index.js +5274 -975
  7. package/dist/npm/jsx-dev-runtime.js +1268 -0
  8. package/dist/npm/jsx-runtime.js +1268 -0
  9. package/dist/npm/native-runtime.json +3 -3
  10. package/dist/npm/node-build.js +1159 -0
  11. package/dist/npm/protocol.js +1 -1
  12. package/dist/npm/runtime.js +5 -5
  13. package/dist/npm/txiki/fetch.ts +228 -0
  14. package/dist/npm/txiki/intl-data.ts +7 -0
  15. package/dist/npm/txiki/intl.test.ts +53 -0
  16. package/dist/npm/txiki/intl.ts +249 -0
  17. package/dist/npm/txiki/prelude.ts +132 -0
  18. package/dist/npm/txiki/runtime.ts +6 -0
  19. package/dist/npm/txiki/shims/buffer.ts +112 -0
  20. package/dist/npm/txiki/shims/child-process.ts +151 -0
  21. package/dist/npm/txiki/shims/crypto.ts +30 -0
  22. package/dist/npm/txiki/shims/events.ts +75 -0
  23. package/dist/npm/txiki/shims/fs-promises.ts +77 -0
  24. package/dist/npm/txiki/shims/fs.ts +231 -0
  25. package/dist/npm/txiki/shims/module.ts +8 -0
  26. package/dist/npm/txiki/shims/net.ts +69 -0
  27. package/dist/npm/txiki/shims/os.ts +72 -0
  28. package/dist/npm/txiki/shims/path.ts +4 -0
  29. package/dist/npm/txiki/shims/timers-promises.ts +9 -0
  30. package/dist/npm/txiki/shims/zlib.ts +9 -0
  31. package/dist/npm/txiki/tjs.d.ts +58 -0
  32. package/dist/npm/txiki/unavailable.ts +10 -0
  33. package/dist/types/core/build.d.ts +24 -0
  34. package/dist/types/core/cli.d.ts +1 -1
  35. package/dist/types/core/esbuild-file-imports.d.ts +8 -0
  36. package/dist/types/core/jsx-compile.d.ts +7 -0
  37. package/dist/types/core/node-build.d.ts +7 -0
  38. package/dist/types/core/node-dev.d.ts +4 -0
  39. package/dist/types/core/node-target.d.ts +10 -0
  40. package/dist/types/core/package-metadata.d.ts +49 -0
  41. package/dist/types/core/runtime-select.d.ts +8 -0
  42. package/dist/types/core/src/advanced-controls.d.ts +1 -1
  43. package/dist/types/core/src/app/element-events.d.ts +18 -0
  44. package/dist/types/core/src/app/media.d.ts +15 -0
  45. package/dist/types/core/src/app/requests.d.ts +25 -0
  46. package/dist/types/core/src/app/shadow.d.ts +7 -0
  47. package/dist/types/core/src/app/stats.d.ts +12 -0
  48. package/dist/types/core/src/app/tray.d.ts +40 -0
  49. package/dist/types/core/src/app-metadata.d.ts +18 -0
  50. package/dist/types/core/src/app.d.ts +89 -2
  51. package/dist/types/core/src/assets.d.ts +4 -0
  52. package/dist/types/core/src/bridge/binding.d.ts +10 -34
  53. package/dist/types/core/src/bridge/index.d.ts +1 -1
  54. package/dist/types/core/src/canvas.d.ts +161 -0
  55. package/dist/types/core/src/chat-controls.d.ts +2 -1
  56. package/dist/types/core/src/components/button.d.ts +1 -1
  57. package/dist/types/core/src/components/glass.d.ts +52 -0
  58. package/dist/types/core/src/components/icon.d.ts +1 -1
  59. package/dist/types/core/src/components/image.d.ts +8 -4
  60. package/dist/types/core/src/components/layout.d.ts +5 -4
  61. package/dist/types/core/src/components/pressable.d.ts +3 -3
  62. package/dist/types/core/src/components/rich-content.d.ts +1 -1
  63. package/dist/types/core/src/components/scroll.d.ts +2 -2
  64. package/dist/types/core/src/components/svg.d.ts +1 -1
  65. package/dist/types/core/src/components/titlebar.d.ts +15 -1
  66. package/dist/types/core/src/components/window.d.ts +21 -1
  67. package/dist/types/core/src/components.d.ts +2 -0
  68. package/dist/types/core/src/css-shadow.d.ts +1 -1
  69. package/dist/types/core/src/desktop-controls.d.ts +2 -2
  70. package/dist/types/core/src/embedded-assets.d.ts +3 -2
  71. package/dist/types/core/src/extra-controls.d.ts +2 -2
  72. package/dist/types/core/src/form-controls.d.ts +1 -1
  73. package/dist/types/core/src/html-elements.d.ts +26 -0
  74. package/dist/types/core/src/index.d.ts +23 -11
  75. package/dist/types/core/src/inline-text.d.ts +25 -0
  76. package/dist/types/core/src/intrinsic-style.d.ts +1 -1
  77. package/dist/types/core/src/jsx-runtime.d.ts +182 -5
  78. package/dist/types/core/src/media-element.d.ts +70 -0
  79. package/dist/types/core/src/memo.d.ts +28 -0
  80. package/dist/types/core/src/motion.d.ts +1 -1
  81. package/dist/types/core/src/png.d.ts +29 -0
  82. package/dist/types/core/src/popups.d.ts +4 -3
  83. package/dist/types/core/src/protocol.d.ts +6 -0
  84. package/dist/types/core/src/reconciler/diff.d.ts +11 -0
  85. package/dist/types/core/src/reconciler/intrinsics.d.ts +24 -0
  86. package/dist/types/core/src/reconciler.d.ts +33 -10
  87. package/dist/types/core/src/render-scope.d.ts +8 -0
  88. package/dist/types/core/src/style.d.ts +1 -1
  89. package/dist/types/core/src/tailwind-palette.d.ts +1 -0
  90. package/dist/types/core/src/tailwind.d.ts +8 -0
  91. package/dist/types/core/src/test-renderer.d.ts +3 -1
  92. package/dist/types/core/src/text-search.d.ts +1 -1
  93. package/dist/types/core/src/theme.d.ts +10 -2
  94. package/dist/types/core/src/updates.d.ts +87 -0
  95. package/dist/types/core/src/virtual-list.d.ts +8 -2
  96. package/dist/types/core/txiki/fetch.d.ts +1 -0
  97. package/dist/types/core/txiki/intl-data.d.ts +6 -0
  98. package/dist/types/core/txiki/intl.d.ts +92 -0
  99. package/dist/types/core/txiki/prelude.d.ts +1 -0
  100. package/dist/types/core/txiki/runtime.d.ts +2 -0
  101. package/dist/types/core/txiki/shims/buffer.d.ts +37 -0
  102. package/dist/types/core/txiki/shims/child-process.d.ts +46 -0
  103. package/dist/types/core/txiki/shims/crypto.d.ts +16 -0
  104. package/dist/types/core/txiki/shims/events.d.ts +21 -0
  105. package/dist/types/core/txiki/shims/fs-promises.d.ts +41 -0
  106. package/dist/types/core/txiki/shims/fs.d.ts +44 -0
  107. package/dist/types/core/txiki/shims/module.d.ts +5 -0
  108. package/dist/types/core/txiki/shims/net.d.ts +22 -0
  109. package/dist/types/core/txiki/shims/os.d.ts +52 -0
  110. package/dist/types/core/txiki/shims/path.d.ts +3 -0
  111. package/dist/types/core/txiki/shims/timers-promises.d.ts +7 -0
  112. package/dist/types/core/txiki/shims/zlib.d.ts +11 -0
  113. package/dist/types/core/txiki/unavailable.d.ts +5 -0
  114. package/dist/types/core/txiki-build.d.ts +23 -0
  115. package/dist/types/core/updates-build.d.ts +35 -0
  116. package/dist/types/core/windows-executable.d.ts +16 -0
  117. package/dist/types/protocol/src/index.d.ts +344 -11
  118. package/native/linux-x64/libtarve_native.so +0 -0
  119. package/native/linux-x64/runtime.json +4 -4
  120. package/native/win32-x64/runtime.json +4 -4
  121. package/native/win32-x64/tarve_native.dll +0 -0
  122. package/package.json +13 -3
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Intl for txiki.js: QuickJS-ng has none. Numbers and the common date and time
3
+ * formats follow ICU (as Bun and Node format them) for the locales in intl-data.ts,
4
+ * generated from ICU by scripts/generate-txiki-intl.ts. Other locales use the
5
+ * closest one (same language, else en-US); unusual date option sets fall back to
6
+ * an en-US style composition.
7
+ */
8
+ import { dlopen } from "tjs:ffi";
9
+ import { DATE_KEYS, LOCALES, NAMES, TEMPLATES, type LocaleData } from "./intl-data";
10
+
11
+ declare const TARVE_TXIKI_PLATFORM: "win32" | "linux";
12
+
13
+ let systemLocale: string | undefined;
14
+ function defaultLocale(): string {
15
+ if (systemLocale) return systemLocale;
16
+ let found: string | undefined;
17
+ try {
18
+ if (TARVE_TXIKI_PLATFORM === "win32") {
19
+ const buffer = new Uint8Array(85 * 2);
20
+ const length = dlopen("kernel32.dll", { GetUserDefaultLocaleName: { args: ["buffer", "i32"], returns: "i32" } }).symbols.GetUserDefaultLocaleName(buffer, 85);
21
+ if (length > 1) found = String.fromCharCode(...new Uint16Array(buffer.buffer, 0, length - 1));
22
+ } else {
23
+ found = (tjs.env.LC_ALL || tjs.env.LC_NUMERIC || tjs.env.LANG || "").split(".")[0];
24
+ }
25
+ } catch { /* en-US */ }
26
+ return systemLocale = resolveLocale(found || "en-US");
27
+ }
28
+
29
+ const LOCALE_NAMES = Object.keys(LOCALES);
30
+ function resolveLocale(requested: string | readonly string[] | undefined): string {
31
+ const list = requested === undefined ? [] : typeof requested === "string" ? [requested] : requested;
32
+ for (const item of list) {
33
+ const tag = String(item).replace(/_/g, "-").toLowerCase();
34
+ const exact = LOCALE_NAMES.find(name => name.toLowerCase() === tag);
35
+ if (exact) return exact;
36
+ const language = LOCALE_NAMES.find(name => name.split("-")[0]!.toLowerCase() === tag.split("-")[0]);
37
+ if (language) return language;
38
+ }
39
+ return list.length ? "en-US" : defaultLocale();
40
+ }
41
+
42
+ interface NumberOptions {
43
+ style?: "decimal" | "percent" | "unit" | "currency";
44
+ minimumFractionDigits?: number;
45
+ maximumFractionDigits?: number;
46
+ useGrouping?: boolean;
47
+ unit?: string;
48
+ currency?: string;
49
+ }
50
+
51
+ function groupDigits(whole: string, data: LocaleData): string {
52
+ const [group, , minGroup, secondary] = data;
53
+ if (!group || whole.length < 3 + minGroup) return whole;
54
+ let out = whole.slice(-3);
55
+ let rest = whole.slice(0, -3);
56
+ while (rest.length > secondary) {
57
+ out = rest.slice(-secondary) + group + out;
58
+ rest = rest.slice(0, -secondary);
59
+ }
60
+ return rest ? rest + group + out : out;
61
+ }
62
+
63
+ class NumberFormat {
64
+ private readonly locale: string;
65
+ private readonly data: LocaleData;
66
+
67
+ constructor(locales?: string | string[], private readonly options: NumberOptions = {}) {
68
+ this.locale = resolveLocale(locales);
69
+ this.data = LOCALES[this.locale]!;
70
+ }
71
+
72
+ format(input: number | bigint): string {
73
+ let value = Number(input);
74
+ const o = this.options;
75
+ const [, decimal, , , percent, minus] = this.data;
76
+ if (Number.isNaN(value)) return "NaN";
77
+ if (o.style === "percent") value *= 100;
78
+ const maximum = o.maximumFractionDigits ?? Math.max(o.minimumFractionDigits ?? 0, o.style === "percent" ? 0 : o.style === "currency" ? 2 : 3);
79
+ const minimum = Math.min(o.minimumFractionDigits ?? (o.style === "currency" ? 2 : 0), maximum);
80
+ let digits: string;
81
+ if (!Number.isFinite(value)) digits = "∞";
82
+ else {
83
+ let [whole, fraction = ""] = Math.abs(value).toFixed(maximum).split(".") as [string, string?];
84
+ while (fraction.length > minimum && fraction.endsWith("0")) fraction = fraction.slice(0, -1);
85
+ if (o.useGrouping !== false) whole = groupDigits(whole, this.data);
86
+ digits = fraction ? whole + decimal + fraction : whole;
87
+ }
88
+ // ICU keeps the sign of a negative value that rounds to zero ("-0").
89
+ const negative = value < 0 || Object.is(value, -0);
90
+ const sign = negative ? minus : "";
91
+ if (o.style === "percent") return sign + percent.replace("{n}", digits);
92
+ if (o.style === "currency") return `${sign}${o.currency === "USD" || !o.currency ? "$" : `${o.currency} `}${digits}`;
93
+ if (o.style === "unit" && o.unit) return `${sign}${digits} ${o.unit}`;
94
+ return sign + digits;
95
+ }
96
+
97
+ formatToParts(input: number | bigint) {
98
+ return [{ type: "literal", value: this.format(input) }];
99
+ }
100
+
101
+ resolvedOptions() {
102
+ return { locale: this.locale, numberingSystem: "latn", ...this.options };
103
+ }
104
+
105
+ static supportedLocalesOf(locales: string | string[]): string[] {
106
+ return (typeof locales === "string" ? [locales] : locales).filter(locale => LOCALE_NAMES.includes(resolveLocale(locale)));
107
+ }
108
+ }
109
+
110
+ type Width = "numeric" | "2-digit" | "short" | "long" | "narrow";
111
+ interface DateTimeOptions {
112
+ weekday?: Width; era?: Width; year?: Width; month?: Width; day?: Width;
113
+ hour?: Width; minute?: Width; second?: Width; hour12?: boolean; timeZone?: string;
114
+ dateStyle?: "full" | "long" | "medium" | "short"; timeStyle?: "full" | "long" | "medium" | "short";
115
+ }
116
+ const DATE_FIELDS = ["weekday", "year", "month", "day", "hour", "minute", "second", "hour12", "dateStyle", "timeStyle"] as const;
117
+
118
+ function dateKey(options: DateTimeOptions): string {
119
+ const picked: Record<string, unknown> = {};
120
+ for (const field of DATE_FIELDS) {
121
+ let value = options[field];
122
+ // ICU always pads minutes and seconds.
123
+ if ((field === "minute" || field === "second") && value === "numeric") value = "2-digit";
124
+ if (value !== undefined) picked[field] = value;
125
+ }
126
+ return Object.keys(picked).sort().map(key => key + "=" + String(picked[key])).join(",");
127
+ }
128
+
129
+ const pad2 = (value: number) => String(value).padStart(2, "0");
130
+ const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
131
+ const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
132
+
133
+ class DateTimeFormat {
134
+ private readonly locale: string;
135
+ private readonly options: DateTimeOptions;
136
+ private readonly entry: number[] | undefined;
137
+
138
+ constructor(locales?: string | string[], options: DateTimeOptions = {}) {
139
+ this.locale = resolveLocale(locales);
140
+ this.options = { ...options };
141
+ const index = DATE_KEYS.indexOf(dateKey(options));
142
+ this.entry = index >= 0 ? LOCALES[this.locale]![6][index] : undefined;
143
+ }
144
+
145
+ format(value: Date | number = Date.now()): string {
146
+ const date = value instanceof Date ? value : new Date(value);
147
+ if (Number.isNaN(date.getTime())) return "Invalid Date";
148
+ const utc = this.options.timeZone === "UTC";
149
+ const fields = {
150
+ year: utc ? date.getUTCFullYear() : date.getFullYear(), month: utc ? date.getUTCMonth() : date.getMonth(),
151
+ day: utc ? date.getUTCDate() : date.getDate(), weekday: utc ? date.getUTCDay() : date.getDay(),
152
+ hour: utc ? date.getUTCHours() : date.getHours(), minute: utc ? date.getUTCMinutes() : date.getMinutes(), second: utc ? date.getUTCSeconds() : date.getSeconds(),
153
+ };
154
+ if (!this.entry) return this.fallback(fields);
155
+ const [template, months, weekdays, periods] = this.entry as [number, number, number, number];
156
+ const source = TEMPLATES[template]!;
157
+ const cycle = Number(/\{c(\d+)\}/.exec(source)?.[1] ?? 23);
158
+ return source.replace(/\{([wMdyhmsaGc])(\d+)\}/g, (_, token: string, flag: string) => {
159
+ const padded = flag === "1";
160
+ switch (token) {
161
+ case "w": return NAMES[weekdays]![fields.weekday]!;
162
+ case "M": return months >= 0 ? NAMES[months]![fields.month]! : padded ? pad2(fields.month + 1) : String(fields.month + 1);
163
+ case "d": return padded ? pad2(fields.day) : String(fields.day);
164
+ case "y": return padded ? pad2(fields.year % 100) : String(fields.year);
165
+ case "h": {
166
+ const hour = cycle === 23 ? fields.hour : cycle === 24 ? fields.hour || 24 : cycle === 11 ? fields.hour % 12 : fields.hour % 12 || 12;
167
+ return padded ? pad2(hour) : String(hour);
168
+ }
169
+ case "m": return pad2(fields.minute);
170
+ case "s": return pad2(fields.second);
171
+ case "a": return NAMES[periods]![fields.hour]!;
172
+ default: return "";
173
+ }
174
+ });
175
+ }
176
+
177
+ /** en-US composition for option sets intl-data.ts does not carry. */
178
+ private fallback(f: { year: number; month: number; day: number; weekday: number; hour: number; minute: number; second: number }): string {
179
+ const o = this.options;
180
+ const name = (names: string[], index: number, width?: Width) => width === "long" ? names[index]! : width === "narrow" ? names[index]![0]! : names[index]!.slice(0, 3);
181
+ const any = o.weekday || o.year || o.month || o.day || o.hour || o.minute || o.second;
182
+ const d = any ? o : { year: "numeric", month: "numeric", day: "numeric" } as DateTimeOptions;
183
+ const numeric = d.month === "numeric" || d.month === "2-digit";
184
+ const day = numeric
185
+ ? [d.month && String(f.month + 1), d.day && String(f.day), d.year && String(f.year)].filter(Boolean).join("/")
186
+ : [[d.month && name(MONTHS, f.month, d.month), d.day && String(f.day)].filter(Boolean).join(" "), d.year && String(f.year)].filter(Boolean).join(", ");
187
+ let time = "";
188
+ if (d.hour || d.minute || d.second) {
189
+ const twelve = d.hour12 ?? true;
190
+ time = [d.hour && String(twelve ? f.hour % 12 || 12 : f.hour), d.minute && pad2(f.minute), d.second && pad2(f.second)].filter(Boolean).join(":");
191
+ if (twelve && d.hour) time += f.hour < 12 ? " AM" : " PM";
192
+ }
193
+ return [[d.weekday ? name(WEEKDAYS, f.weekday, d.weekday) : "", day].filter(Boolean).join(", "), time].filter(Boolean).join(", ");
194
+ }
195
+
196
+ formatToParts(value?: Date | number) {
197
+ return [{ type: "literal", value: this.format(value) }];
198
+ }
199
+
200
+ resolvedOptions() {
201
+ return { locale: this.locale, calendar: "gregory", numberingSystem: "latn", timeZone: this.options.timeZone ?? "UTC", ...this.options };
202
+ }
203
+
204
+ static supportedLocalesOf(locales: string | string[]): string[] {
205
+ return NumberFormat.supportedLocalesOf(locales);
206
+ }
207
+ }
208
+
209
+ class Collator {
210
+ constructor(_locales?: string | string[], private readonly options: { numeric?: boolean; sensitivity?: string } = {}) {}
211
+
212
+ compare = (left: string, right: string): number => {
213
+ const fold = (value: string) => this.options.sensitivity === "base" || this.options.sensitivity === "accent" ? value.toLowerCase() : value;
214
+ if (this.options.numeric) {
215
+ const a = fold(left).split(/(\d+)/);
216
+ const b = fold(right).split(/(\d+)/);
217
+ for (let index = 0; index < Math.min(a.length, b.length); index++) {
218
+ const order = index % 2 ? Number(a[index]) - Number(b[index]) : a[index]!.localeCompare(b[index]!);
219
+ if (order) return Math.sign(order);
220
+ }
221
+ return a.length - b.length;
222
+ }
223
+ return fold(left).localeCompare(fold(right));
224
+ };
225
+ }
226
+
227
+ export function installIntl(): void {
228
+ if (typeof globalThis.Intl !== "undefined") return;
229
+ (globalThis as Record<string, unknown>).Intl = {
230
+ DateTimeFormat, NumberFormat, Collator,
231
+ getCanonicalLocales: (locales?: string | string[]) => (locales === undefined ? [] : typeof locales === "string" ? [locales] : locales).map(resolveLocale),
232
+ };
233
+ // QuickJS's own toLocale* ignore the locale (no grouping, English dates).
234
+ Number.prototype.toLocaleString = function (this: number, locales?: string | string[], options?: NumberOptions) {
235
+ return new NumberFormat(locales, options).format(Number(this));
236
+ };
237
+ Date.prototype.toLocaleString = function (this: Date, locales?: string | string[], options?: DateTimeOptions) {
238
+ return new DateTimeFormat(locales, options && dateKey(options) ? options : { year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "2-digit", second: "2-digit", ...options }).format(this);
239
+ };
240
+ Date.prototype.toLocaleDateString = function (this: Date, locales?: string | string[], options?: DateTimeOptions) {
241
+ return new DateTimeFormat(locales, options && dateKey(options) ? options : { year: "numeric", month: "numeric", day: "numeric", ...options }).format(this);
242
+ };
243
+ Date.prototype.toLocaleTimeString = function (this: Date, locales?: string | string[], options?: DateTimeOptions) {
244
+ return new DateTimeFormat(locales, options && dateKey(options) ? options : { hour: "numeric", minute: "2-digit", second: "2-digit", ...options }).format(this);
245
+ };
246
+ }
247
+
248
+ /** For tests: the shim's classes, without installing them. */
249
+ export const txikiIntl = { DateTimeFormat, NumberFormat, Collator };
@@ -0,0 +1,132 @@
1
+ /**
2
+ * First module of a Tarve txiki.js executable. It gives the core the Node globals it
3
+ * expects, then extracts the native library and assets embedded in the executable into
4
+ * the shared asset cache, before any app module runs (the bundle keeps this order, and
5
+ * the top-level await holds the modules after it).
6
+ */
7
+ import * as ffi from "tjs:ffi";
8
+ import { createHash } from "tjs:hashing";
9
+ import path from "tjs:path";
10
+ import { createFetch } from "./fetch";
11
+ import { installIntl } from "./intl";
12
+ import { Buffer } from "./shims/buffer";
13
+
14
+ declare const TARVE_TXIKI_PLATFORM: "win32" | "linux";
15
+ declare const TARVE_TXIKI_NATIVE_NAME: string;
16
+
17
+ /** One file of the blob txiki-build.ts places before the txiki.js payload. */
18
+ interface EmbeddedFile {
19
+ name: string;
20
+ offset: number;
21
+ length: number;
22
+ size: number;
23
+ sha256: string;
24
+ gzip: boolean;
25
+ }
26
+
27
+ const TXIKI_MAGIC = "tx1k1.js";
28
+ const BLOB_MAGIC = "TARVEBLB";
29
+ const decoder = new TextDecoder();
30
+ const globals = globalThis as Record<string, unknown>;
31
+
32
+ installIntl();
33
+ globals.fetch = createFetch(globalThis.fetch.bind(globalThis));
34
+ globals.Buffer = Buffer;
35
+ globals.__tarveTxikiFfi = ffi;
36
+ globals.__tarveDirname = path.dirname(tjs.exePath);
37
+ globals.setImmediate ??= (callback: (...args: unknown[]) => void, ...args: unknown[]) => setTimeout(callback, 0, ...args);
38
+ const process = {
39
+ platform: TARVE_TXIKI_PLATFORM,
40
+ arch: "x64",
41
+ env: tjs.env,
42
+ // A compiled app: [exe, ...args]. `tjs run app.js ...args` (debugging a bundle): [tjs, "run", app.js, ...args].
43
+ argv: tjs.args[1] === "run" ? [tjs.exePath, ...tjs.args.slice(2)] : [tjs.exePath, tjs.exePath, ...tjs.args.slice(1)],
44
+ execArgv: [],
45
+ execPath: tjs.exePath,
46
+ versions: { tjs: tjs.version, quickjs: String(tjs.engine.versions.quickjs) },
47
+ exitCode: undefined as number | undefined,
48
+ exit(code?: number): never {
49
+ return tjs.exit(code ?? this.exitCode ?? 0);
50
+ },
51
+ cwd: () => tjs.cwd,
52
+ chdir: (directory: string) => tjs.chdir(directory),
53
+ memoryUsage: () => ({ rss: 0, heapTotal: 0, heapUsed: 0, external: 0, arrayBuffers: 0 }),
54
+ nextTick: (callback: (...args: unknown[]) => void, ...args: unknown[]) => queueMicrotask(() => callback(...args)),
55
+ on() { return this; },
56
+ once() { return this; },
57
+ off() { return this; },
58
+ };
59
+ globals.process = process;
60
+
61
+ async function readAt(file: TjsFileHandle, position: number, length: number): Promise<Uint8Array> {
62
+ const bytes = new Uint8Array(length);
63
+ let read = 0;
64
+ while (read < length) {
65
+ const count = await file.read(bytes.subarray(read), position + read);
66
+ if (!count) throw new Error("The executable is truncated: rebuild it.");
67
+ read += count;
68
+ }
69
+ return bytes;
70
+ }
71
+
72
+ function uint32(bytes: Uint8Array, offset: number): number {
73
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(offset, true);
74
+ }
75
+
76
+ async function embeddedFiles(): Promise<{ files: EmbeddedFile[]; read(file: EmbeddedFile): Promise<Uint8Array>; close(): Promise<void> }> {
77
+ const exe = await tjs.open(tjs.exePath, "r");
78
+ const blob = { read: (file: EmbeddedFile) => readAt(exe, file.offset, file.length), close: () => exe.close() };
79
+ const { size } = await exe.stat();
80
+ const trailer = await readAt(exe, size - 12, 12);
81
+ if (decoder.decode(trailer.subarray(0, 8)) !== TXIKI_MAGIC) return { files: [], ...blob };
82
+ const payload = uint32(trailer, 8);
83
+ const header = await readAt(exe, payload - 16, 16);
84
+ if (decoder.decode(header.subarray(8)) !== BLOB_MAGIC) return { files: [], ...blob };
85
+ const indexLength = uint32(header, 0);
86
+ const index = await readAt(exe, payload - 16 - indexLength, indexLength);
87
+ return { files: JSON.parse(decoder.decode(index)) as EmbeddedFile[], ...blob };
88
+ }
89
+
90
+ async function gunzip(bytes: Uint8Array): Promise<Uint8Array> {
91
+ const stream = new Blob([bytes as Uint8Array<ArrayBuffer>]).stream().pipeThrough(new DecompressionStream("gzip"));
92
+ return new Uint8Array(await new Response(stream).arrayBuffer());
93
+ }
94
+
95
+ async function sizeOf(file: string): Promise<number | undefined> {
96
+ try { return (await tjs.stat(file)).size; } catch { return undefined; }
97
+ }
98
+
99
+ /** Same cache layout as materializeAsset: <tmp>/tarve-assets/<sha256>/<name>, written once. */
100
+ async function materialize(file: EmbeddedFile, read: (file: EmbeddedFile) => Promise<Uint8Array>): Promise<string> {
101
+ const directory = path.join(tjs.tmpDir, "tarve-assets", file.sha256);
102
+ const target = path.join(directory, file.name);
103
+ if (await sizeOf(target) === file.size) return target;
104
+ const stored = await read(file);
105
+ const bytes = file.gzip ? await gunzip(stored) : stored;
106
+ const hash = createHash("sha256");
107
+ hash.update(bytes);
108
+ if (bytes.length !== file.size || hash.digest("hex") !== file.sha256) {
109
+ throw new Error(`Embedded file ${file.name} does not match its build-time digest; rebuild the executable.`);
110
+ }
111
+ await tjs.makeDir(directory, { recursive: true });
112
+ const temporary = `${target}.${crypto.randomUUID()}.tmp`;
113
+ await tjs.writeFile(temporary, bytes);
114
+ try {
115
+ await tjs.rename(temporary, target);
116
+ } catch (error) {
117
+ // A simultaneous launch published it first (Windows refuses to replace a loaded DLL).
118
+ await tjs.remove(temporary).catch(() => {});
119
+ if (await sizeOf(target) !== file.size) throw error;
120
+ }
121
+ return target;
122
+ }
123
+
124
+ const blob = await embeddedFiles();
125
+ try {
126
+ const paths: Record<string, string> = {};
127
+ for (const file of blob.files) paths[file.name] = await materialize(file, blob.read);
128
+ globals.__tarveAssets = paths;
129
+ globals.__tarveNativePath = paths[TARVE_TXIKI_NATIVE_NAME] ?? tjs.env.TARVE_NATIVE;
130
+ } finally {
131
+ await blob.close();
132
+ }
@@ -0,0 +1,6 @@
1
+ /** #tarve/runtime in a txiki.js executable: the prelude extracted the native library. */
2
+ export function nativePath(): string {
3
+ const path = (globalThis as { __tarveNativePath?: string }).__tarveNativePath;
4
+ if (!path) throw new Error("Tarve native library is not available: this txiki.js executable carries no runtime and TARVE_NATIVE is unset.");
5
+ return path;
6
+ }
@@ -0,0 +1,112 @@
1
+ /** The part of Node's Buffer the Tarve core uses, over Uint8Array. */
2
+ type Encoding = "utf8" | "utf-8" | "base64" | "hex" | "latin1" | "binary" | "ascii";
3
+
4
+ const encoder = new TextEncoder();
5
+ const decoder = new TextDecoder();
6
+
7
+ function encode(value: string, encoding: Encoding = "utf8"): Uint8Array {
8
+ switch (encoding) {
9
+ case "base64": return Uint8Array.fromBase64(value.replace(/[\s=]+$/g, "").replace(/\s/g, ""), { lastChunkHandling: "loose" });
10
+ case "hex": return Uint8Array.fromHex(value);
11
+ case "latin1": case "binary": case "ascii": return Uint8Array.from(value, character => character.charCodeAt(0) & 0xff);
12
+ default: return encoder.encode(value);
13
+ }
14
+ }
15
+
16
+ class BufferBytes extends Uint8Array {
17
+ static fromValue(value: string | ArrayBufferLike | ArrayLike<number> | ArrayBufferView, encodingOrOffset?: Encoding | number, length?: number): BufferBytes {
18
+ if (typeof value === "string") return BufferBytes.wrap(encode(value, encodingOrOffset as Encoding | undefined));
19
+ if (value instanceof ArrayBuffer || value instanceof SharedArrayBuffer) {
20
+ const offset = (encodingOrOffset as number | undefined) ?? 0;
21
+ return new BufferBytes(value as ArrayBuffer, offset, length ?? value.byteLength - offset);
22
+ }
23
+ if (ArrayBuffer.isView(value)) {
24
+ const copy = new BufferBytes(value.byteLength);
25
+ copy.set(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
26
+ return copy;
27
+ }
28
+ const copy = new BufferBytes(value.length);
29
+ copy.set(value);
30
+ return copy;
31
+ }
32
+
33
+ static alloc(size: number, fill = 0): BufferBytes {
34
+ const buffer = new BufferBytes(size);
35
+ if (fill) buffer.fill(fill);
36
+ return buffer;
37
+ }
38
+
39
+ static concat(list: readonly Uint8Array[], totalLength?: number): BufferBytes {
40
+ const total = totalLength ?? list.reduce((sum, item) => sum + item.length, 0);
41
+ const out = new BufferBytes(total);
42
+ let offset = 0;
43
+ for (const item of list) {
44
+ if (offset >= total) break;
45
+ out.set(item.subarray(0, total - offset), offset);
46
+ offset += item.length;
47
+ }
48
+ return out;
49
+ }
50
+
51
+ static isBuffer(value: unknown): value is BufferBytes {
52
+ return value instanceof BufferBytes;
53
+ }
54
+
55
+ static byteLength(value: string | ArrayBufferView | ArrayBuffer, encoding?: Encoding): number {
56
+ return typeof value === "string" ? encode(value, encoding).length : value.byteLength;
57
+ }
58
+
59
+ private static wrap(bytes: Uint8Array): BufferBytes {
60
+ return new BufferBytes(bytes.buffer as ArrayBuffer, bytes.byteOffset, bytes.byteLength);
61
+ }
62
+
63
+ override toString(encoding: Encoding = "utf8", start = 0, end = this.length): string {
64
+ const bytes = this.subarray(start, end);
65
+ switch (encoding) {
66
+ case "base64": return Uint8Array.prototype.toBase64.call(bytes);
67
+ case "hex": return Uint8Array.prototype.toHex.call(bytes);
68
+ case "latin1": case "binary": case "ascii": {
69
+ let out = "";
70
+ for (let index = 0; index < bytes.length; index += 0x8000) out += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
71
+ return out;
72
+ }
73
+ default: return decoder.decode(bytes);
74
+ }
75
+ }
76
+
77
+ write(value: string, offset = 0, encoding: Encoding = "utf8"): number {
78
+ const bytes = encode(value, encoding).subarray(0, this.length - offset);
79
+ this.set(bytes, offset);
80
+ return bytes.length;
81
+ }
82
+
83
+ private view(): DataView {
84
+ return new DataView(this.buffer, this.byteOffset, this.byteLength);
85
+ }
86
+
87
+ writeUInt8(value: number, offset = 0): number { this[offset] = value; return offset + 1; }
88
+ writeUInt16LE(value: number, offset = 0): number { this.view().setUint16(offset, value, true); return offset + 2; }
89
+ writeUInt16BE(value: number, offset = 0): number { this.view().setUint16(offset, value); return offset + 2; }
90
+ writeUInt32LE(value: number, offset = 0): number { this.view().setUint32(offset, value, true); return offset + 4; }
91
+ writeUInt32BE(value: number, offset = 0): number { this.view().setUint32(offset, value); return offset + 4; }
92
+ writeInt32LE(value: number, offset = 0): number { this.view().setInt32(offset, value, true); return offset + 4; }
93
+ writeInt32BE(value: number, offset = 0): number { this.view().setInt32(offset, value); return offset + 4; }
94
+ readUInt8(offset = 0): number { return this[offset]!; }
95
+ readUInt16LE(offset = 0): number { return this.view().getUint16(offset, true); }
96
+ readUInt16BE(offset = 0): number { return this.view().getUint16(offset); }
97
+ readUInt32LE(offset = 0): number { return this.view().getUint32(offset, true); }
98
+ readUInt32BE(offset = 0): number { return this.view().getUint32(offset); }
99
+ readInt32LE(offset = 0): number { return this.view().getInt32(offset, true); }
100
+ readInt32BE(offset = 0): number { return this.view().getInt32(offset); }
101
+ }
102
+
103
+ /** Node's Buffer: `Buffer.from` takes encodings and offsets, unlike Uint8Array.from. */
104
+ type BufferConstructor = Omit<typeof BufferBytes, "from" | "prototype"> & {
105
+ from: typeof BufferBytes.fromValue;
106
+ prototype: BufferBytes;
107
+ new (length: number): BufferBytes;
108
+ new (buffer: ArrayBuffer, byteOffset?: number, length?: number): BufferBytes;
109
+ };
110
+ export const Buffer = BufferBytes as unknown as BufferConstructor;
111
+ Object.defineProperty(Buffer, "from", { value: BufferBytes.fromValue, writable: true, configurable: true });
112
+ export type Buffer = BufferBytes;
@@ -0,0 +1,151 @@
1
+ /** node:child_process spawn over tjs.spawn: exit/error events and stream-like stdio. */
2
+ import { Buffer } from "./buffer";
3
+ import { EventEmitter } from "./events";
4
+
5
+ type Stdio = "pipe" | "ignore" | "inherit";
6
+
7
+ export interface SpawnOptions {
8
+ cwd?: string;
9
+ env?: Record<string, string | undefined>;
10
+ stdio?: Stdio | Stdio[];
11
+ windowsHide?: boolean;
12
+ }
13
+
14
+ /** A Node-style readable over a web stream: "data"/"end" events or async iteration. */
15
+ class Readable extends EventEmitter {
16
+ private encoding?: string;
17
+ private started = false;
18
+
19
+ constructor(private readonly stream: ReadableStream<Uint8Array>) {
20
+ super();
21
+ }
22
+
23
+ setEncoding(encoding: string): this {
24
+ this.encoding = encoding;
25
+ return this;
26
+ }
27
+
28
+ private chunk(bytes: Uint8Array): Buffer | string {
29
+ const buffer = Buffer.from(bytes);
30
+ return this.encoding ? buffer.toString(this.encoding as "utf8") : buffer;
31
+ }
32
+
33
+ override on(event: string | symbol, listener: (...args: any[]) => void): this {
34
+ super.on(event, listener);
35
+ if (event === "data" && !this.started) void this.pump();
36
+ return this;
37
+ }
38
+
39
+ private async pump(): Promise<void> {
40
+ this.started = true;
41
+ try {
42
+ for await (const chunk of this) this.emit("data", chunk);
43
+ this.emit("end");
44
+ } catch (error) {
45
+ if (this.listenerCount("error")) this.emit("error", error);
46
+ }
47
+ this.emit("close");
48
+ }
49
+
50
+ async *[Symbol.asyncIterator](): AsyncGenerator<Buffer | string> {
51
+ const reader = this.stream.getReader();
52
+ try {
53
+ for (;;) {
54
+ const { done, value } = await reader.read();
55
+ if (done) return;
56
+ yield this.chunk(value);
57
+ }
58
+ } finally {
59
+ reader.releaseLock();
60
+ }
61
+ }
62
+ }
63
+
64
+ class Writable extends EventEmitter {
65
+ private readonly writer: WritableStreamDefaultWriter<Uint8Array>;
66
+
67
+ constructor(stream: WritableStream<Uint8Array>) {
68
+ super();
69
+ this.writer = stream.getWriter();
70
+ }
71
+
72
+ write(data: string | Uint8Array, callback?: (error?: Error) => void): boolean {
73
+ this.writer.write(typeof data === "string" ? Buffer.from(data) : data).then(() => callback?.(), error => {
74
+ callback?.(error);
75
+ if (this.listenerCount("error")) this.emit("error", error);
76
+ });
77
+ return true;
78
+ }
79
+
80
+ end(data?: string | Uint8Array): this {
81
+ if (data !== undefined) this.write(data);
82
+ this.writer.close().catch(() => {});
83
+ return this;
84
+ }
85
+ }
86
+
87
+ interface TjsProcess {
88
+ pid: number;
89
+ stdin?: WritableStream<Uint8Array>;
90
+ stdout?: ReadableStream<Uint8Array>;
91
+ stderr?: ReadableStream<Uint8Array>;
92
+ kill(signal?: string): void;
93
+ wait(): Promise<{ exit_status: number; term_signal: string | null }>;
94
+ }
95
+
96
+ export class ChildProcess extends EventEmitter {
97
+ pid?: number;
98
+ exitCode: number | null = null;
99
+ signalCode: string | null = null;
100
+ killed = false;
101
+ stdin: Writable | null = null;
102
+ stdout: Readable | null = null;
103
+ stderr: Readable | null = null;
104
+ private process?: TjsProcess;
105
+
106
+ constructor(command: string, args: readonly string[], options: SpawnOptions = {}) {
107
+ super();
108
+ const stdio = typeof options.stdio === "string" || options.stdio === undefined
109
+ ? [options.stdio ?? "pipe", options.stdio ?? "pipe", options.stdio ?? "pipe"]
110
+ : options.stdio;
111
+ try {
112
+ const spawn = (tjs as unknown as { spawn(args: string[], options: object): TjsProcess }).spawn;
113
+ this.process = spawn([command, ...args], {
114
+ ...(options.cwd ? { cwd: options.cwd } : {}),
115
+ ...(options.env ? { env: Object.fromEntries(Object.entries(options.env).filter(([, value]) => value !== undefined)) } : {}),
116
+ stdin: stdio[0] ?? "pipe", stdout: stdio[1] ?? "pipe", stderr: stdio[2] ?? "pipe",
117
+ });
118
+ } catch (error) {
119
+ queueMicrotask(() => this.emit("error", error));
120
+ return;
121
+ }
122
+ const child = this.process;
123
+ this.pid = child.pid;
124
+ if (child.stdin) this.stdin = new Writable(child.stdin);
125
+ if (child.stdout) this.stdout = new Readable(child.stdout);
126
+ if (child.stderr) this.stderr = new Readable(child.stderr);
127
+ child.wait().then(status => {
128
+ this.exitCode = status.term_signal ? null : status.exit_status;
129
+ this.signalCode = status.term_signal;
130
+ this.emit("exit", this.exitCode, this.signalCode);
131
+ this.emit("close", this.exitCode, this.signalCode);
132
+ }, error => this.emit("error", error));
133
+ }
134
+
135
+ kill(signal: string = "SIGTERM"): boolean {
136
+ if (!this.process || this.exitCode !== null) return false;
137
+ try {
138
+ this.process.kill(signal);
139
+ this.killed = true;
140
+ return true;
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+ }
146
+
147
+ export function spawn(command: string, args: readonly string[] | SpawnOptions = [], options?: SpawnOptions): ChildProcess {
148
+ return Array.isArray(args) ? new ChildProcess(command, args, options) : new ChildProcess(command, [], args as SpawnOptions);
149
+ }
150
+
151
+ export default { ChildProcess, spawn };
@@ -0,0 +1,30 @@
1
+ import { createHash as createNativeHash } from "tjs:hashing";
2
+ import { Buffer } from "./buffer";
3
+
4
+ const encoder = new TextEncoder();
5
+
6
+ export function createHash(algorithm: string) {
7
+ const hash = createNativeHash(algorithm);
8
+ return {
9
+ update(data: string | Uint8Array) {
10
+ hash.update(typeof data === "string" ? encoder.encode(data) : data);
11
+ return this;
12
+ },
13
+ digest(encoding?: "hex" | "base64"): any {
14
+ const hex = hash.digest("hex");
15
+ if (encoding === "hex") return hex;
16
+ const bytes = Buffer.fromValue(hex, "hex");
17
+ return encoding === "base64" ? bytes.toString("base64") : bytes;
18
+ },
19
+ };
20
+ }
21
+
22
+ export function randomUUID(): string {
23
+ return crypto.randomUUID();
24
+ }
25
+
26
+ export function randomBytes(size: number): Buffer {
27
+ return Buffer.fromValue(crypto.getRandomValues(new Uint8Array(size)));
28
+ }
29
+
30
+ export default { createHash, randomBytes, randomUUID };