@tarve/core 0.5.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 (109) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +54 -2
  3. package/dist/npm/build.js +714 -138
  4. package/dist/npm/cli.js +1013 -161
  5. package/dist/npm/embedded-assets.js +7 -2
  6. package/dist/npm/index.js +3096 -1084
  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 +299 -5
  11. package/dist/npm/protocol.js +1 -1
  12. package/dist/npm/txiki/fetch.ts +228 -0
  13. package/dist/npm/txiki/intl-data.ts +7 -0
  14. package/dist/npm/txiki/intl.test.ts +53 -0
  15. package/dist/npm/txiki/intl.ts +249 -0
  16. package/dist/npm/txiki/prelude.ts +132 -0
  17. package/dist/npm/txiki/runtime.ts +6 -0
  18. package/dist/npm/txiki/shims/buffer.ts +112 -0
  19. package/dist/npm/txiki/shims/child-process.ts +151 -0
  20. package/dist/npm/txiki/shims/crypto.ts +30 -0
  21. package/dist/npm/txiki/shims/events.ts +75 -0
  22. package/dist/npm/txiki/shims/fs-promises.ts +77 -0
  23. package/dist/npm/txiki/shims/fs.ts +231 -0
  24. package/dist/npm/txiki/shims/module.ts +8 -0
  25. package/dist/npm/txiki/shims/net.ts +69 -0
  26. package/dist/npm/txiki/shims/os.ts +72 -0
  27. package/dist/npm/txiki/shims/path.ts +4 -0
  28. package/dist/npm/txiki/shims/timers-promises.ts +9 -0
  29. package/dist/npm/txiki/shims/zlib.ts +9 -0
  30. package/dist/npm/txiki/tjs.d.ts +58 -0
  31. package/dist/npm/txiki/unavailable.ts +10 -0
  32. package/dist/types/core/build.d.ts +5 -2
  33. package/dist/types/core/jsx-compile.d.ts +7 -0
  34. package/dist/types/core/src/advanced-controls.d.ts +1 -1
  35. package/dist/types/core/src/app/element-events.d.ts +18 -0
  36. package/dist/types/core/src/app/media.d.ts +15 -0
  37. package/dist/types/core/src/app/requests.d.ts +25 -0
  38. package/dist/types/core/src/app/shadow.d.ts +7 -0
  39. package/dist/types/core/src/app/stats.d.ts +12 -0
  40. package/dist/types/core/src/app/tray.d.ts +40 -0
  41. package/dist/types/core/src/app-metadata.d.ts +2 -0
  42. package/dist/types/core/src/app.d.ts +29 -27
  43. package/dist/types/core/src/bridge/index.d.ts +1 -1
  44. package/dist/types/core/src/chat-controls.d.ts +2 -1
  45. package/dist/types/core/src/components/button.d.ts +1 -1
  46. package/dist/types/core/src/components/glass.d.ts +52 -0
  47. package/dist/types/core/src/components/icon.d.ts +1 -1
  48. package/dist/types/core/src/components/image.d.ts +1 -1
  49. package/dist/types/core/src/components/layout.d.ts +1 -1
  50. package/dist/types/core/src/components/pressable.d.ts +1 -1
  51. package/dist/types/core/src/components/rich-content.d.ts +1 -1
  52. package/dist/types/core/src/components/scroll.d.ts +2 -2
  53. package/dist/types/core/src/components/svg.d.ts +1 -1
  54. package/dist/types/core/src/components/titlebar.d.ts +15 -1
  55. package/dist/types/core/src/components/window.d.ts +21 -1
  56. package/dist/types/core/src/components.d.ts +2 -0
  57. package/dist/types/core/src/css-shadow.d.ts +1 -1
  58. package/dist/types/core/src/desktop-controls.d.ts +2 -2
  59. package/dist/types/core/src/embedded-assets.d.ts +3 -2
  60. package/dist/types/core/src/extra-controls.d.ts +1 -1
  61. package/dist/types/core/src/form-controls.d.ts +1 -1
  62. package/dist/types/core/src/index.d.ts +20 -11
  63. package/dist/types/core/src/inline-text.d.ts +7 -3
  64. package/dist/types/core/src/intrinsic-style.d.ts +1 -1
  65. package/dist/types/core/src/jsx-runtime.d.ts +10 -4
  66. package/dist/types/core/src/media-element.d.ts +3 -4
  67. package/dist/types/core/src/memo.d.ts +10 -0
  68. package/dist/types/core/src/motion.d.ts +1 -1
  69. package/dist/types/core/src/popups.d.ts +1 -1
  70. package/dist/types/core/src/protocol.d.ts +6 -0
  71. package/dist/types/core/src/reconciler/diff.d.ts +11 -0
  72. package/dist/types/core/src/reconciler/intrinsics.d.ts +24 -0
  73. package/dist/types/core/src/reconciler.d.ts +10 -11
  74. package/dist/types/core/src/render-scope.d.ts +8 -0
  75. package/dist/types/core/src/style.d.ts +1 -1
  76. package/dist/types/core/src/tailwind-palette.d.ts +1 -0
  77. package/dist/types/core/src/tailwind.d.ts +8 -0
  78. package/dist/types/core/src/test-renderer.d.ts +1 -1
  79. package/dist/types/core/src/text-search.d.ts +1 -1
  80. package/dist/types/core/src/theme.d.ts +8 -1
  81. package/dist/types/core/src/updates.d.ts +87 -0
  82. package/dist/types/core/src/virtual-list.d.ts +3 -1
  83. package/dist/types/core/txiki/fetch.d.ts +1 -0
  84. package/dist/types/core/txiki/intl-data.d.ts +6 -0
  85. package/dist/types/core/txiki/intl.d.ts +92 -0
  86. package/dist/types/core/txiki/prelude.d.ts +1 -0
  87. package/dist/types/core/txiki/runtime.d.ts +2 -0
  88. package/dist/types/core/txiki/shims/buffer.d.ts +37 -0
  89. package/dist/types/core/txiki/shims/child-process.d.ts +46 -0
  90. package/dist/types/core/txiki/shims/crypto.d.ts +16 -0
  91. package/dist/types/core/txiki/shims/events.d.ts +21 -0
  92. package/dist/types/core/txiki/shims/fs-promises.d.ts +41 -0
  93. package/dist/types/core/txiki/shims/fs.d.ts +44 -0
  94. package/dist/types/core/txiki/shims/module.d.ts +5 -0
  95. package/dist/types/core/txiki/shims/net.d.ts +22 -0
  96. package/dist/types/core/txiki/shims/os.d.ts +52 -0
  97. package/dist/types/core/txiki/shims/path.d.ts +3 -0
  98. package/dist/types/core/txiki/shims/timers-promises.d.ts +7 -0
  99. package/dist/types/core/txiki/shims/zlib.d.ts +11 -0
  100. package/dist/types/core/txiki/unavailable.d.ts +5 -0
  101. package/dist/types/core/txiki-build.d.ts +23 -0
  102. package/dist/types/core/updates-build.d.ts +35 -0
  103. package/dist/types/protocol/src/index.d.ts +159 -8
  104. package/native/linux-x64/libtarve_native.so +0 -0
  105. package/native/linux-x64/runtime.json +4 -4
  106. package/native/win32-x64/runtime.json +4 -4
  107. package/native/win32-x64/tarve_native.dll +0 -0
  108. package/package.json +3 -2
  109. /package/dist/types/core/{app-metadata.d.ts → package-metadata.d.ts} +0 -0
@@ -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 };
@@ -0,0 +1,75 @@
1
+ /** node:events: the EventEmitter subset apps and the shims use. */
2
+ type Listener = (...args: any[]) => void;
3
+
4
+ export class EventEmitter {
5
+ private readonly events = new Map<string | symbol, Listener[]>();
6
+
7
+ on(event: string | symbol, listener: Listener): this {
8
+ this.events.set(event, [...this.events.get(event) ?? [], listener]);
9
+ return this;
10
+ }
11
+
12
+ addListener(event: string | symbol, listener: Listener): this {
13
+ return this.on(event, listener);
14
+ }
15
+
16
+ once(event: string | symbol, listener: Listener): this {
17
+ const wrapper: Listener = (...args) => {
18
+ this.off(event, wrapper);
19
+ listener(...args);
20
+ };
21
+ return this.on(event, wrapper);
22
+ }
23
+
24
+ off(event: string | symbol, listener: Listener): this {
25
+ const listeners = this.events.get(event);
26
+ if (listeners) this.events.set(event, listeners.filter(item => item !== listener));
27
+ return this;
28
+ }
29
+
30
+ removeListener(event: string | symbol, listener: Listener): this {
31
+ return this.off(event, listener);
32
+ }
33
+
34
+ removeAllListeners(event?: string | symbol): this {
35
+ if (event === undefined) this.events.clear();
36
+ else this.events.delete(event);
37
+ return this;
38
+ }
39
+
40
+ emit(event: string | symbol, ...args: unknown[]): boolean {
41
+ const listeners = this.events.get(event);
42
+ if (!listeners?.length) {
43
+ if (event === "error") throw args[0] instanceof Error ? args[0] : new Error(String(args[0]));
44
+ return false;
45
+ }
46
+ for (const listener of [...listeners]) listener(...args);
47
+ return true;
48
+ }
49
+
50
+ listenerCount(event: string | symbol): number {
51
+ return this.events.get(event)?.length ?? 0;
52
+ }
53
+
54
+ setMaxListeners(_count: number): this {
55
+ return this;
56
+ }
57
+ }
58
+
59
+ /** Resolves with the event's arguments; rejects on "error" (except when waiting for "error"). */
60
+ export function once(emitter: EventEmitter, event: string): Promise<unknown[]> {
61
+ return new Promise((resolve, reject) => {
62
+ const done = (...args: unknown[]) => {
63
+ emitter.off("error", fail);
64
+ resolve(args);
65
+ };
66
+ const fail = (error: unknown) => {
67
+ emitter.off(event, done);
68
+ reject(error);
69
+ };
70
+ emitter.once(event, done);
71
+ if (event !== "error") emitter.once("error", fail);
72
+ });
73
+ }
74
+
75
+ export default Object.assign(EventEmitter, { EventEmitter, once });
@@ -0,0 +1,77 @@
1
+ /** node:fs/promises over the asynchronous tjs file API. */
2
+ import { Buffer } from "./buffer";
3
+
4
+ type Encoding = BufferEncoding | { encoding?: BufferEncoding | null } | null | undefined;
5
+
6
+ function encodingOf(options: Encoding): BufferEncoding | undefined {
7
+ return typeof options === "string" ? options : options?.encoding ?? undefined;
8
+ }
9
+
10
+ interface TjsFiles {
11
+ readFile(path: string): Promise<Uint8Array>;
12
+ writeFile(path: string, data: Uint8Array): Promise<void>;
13
+ makeDir(path: string, options?: { recursive?: boolean }): Promise<void>;
14
+ makeTempDir(template: string): Promise<string>;
15
+ remove(path: string): Promise<void>;
16
+ rename(from: string, to: string): Promise<void>;
17
+ copyFile(from: string, to: string): Promise<void>;
18
+ stat(path: string): Promise<{ size: number; isFile: boolean; isDirectory: boolean; mtim: Date }>;
19
+ readDir(path: string): Promise<AsyncIterable<{ name: string; isFile: boolean; isDirectory: boolean }> & { close(): Promise<void> }>;
20
+ }
21
+ const files = tjs as unknown as TjsFiles;
22
+
23
+ export async function readFile(path: string, options?: Encoding): Promise<any> {
24
+ const bytes = Buffer.from(await files.readFile(path));
25
+ const encoding = encodingOf(options);
26
+ return encoding ? bytes.toString(encoding as "utf8") : bytes;
27
+ }
28
+
29
+ export async function writeFile(path: string, data: string | Uint8Array): Promise<void> {
30
+ await files.writeFile(path, typeof data === "string" ? Buffer.from(data) : data);
31
+ }
32
+
33
+ export async function mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
34
+ await files.makeDir(path, options);
35
+ }
36
+
37
+ export async function mkdtemp(prefix: string): Promise<string> {
38
+ return files.makeTempDir(`${prefix}XXXXXX`);
39
+ }
40
+
41
+ export async function rm(path: string, options?: { force?: boolean; recursive?: boolean }): Promise<void> {
42
+ try {
43
+ await files.stat(path);
44
+ } catch (error) {
45
+ if (options?.force) return;
46
+ throw error;
47
+ }
48
+ await files.remove(path);
49
+ }
50
+
51
+ export const unlink = (path: string) => files.remove(path);
52
+ export const rename = (from: string, to: string) => files.rename(from, to);
53
+ export const copyFile = (from: string, to: string) => files.copyFile(from, to);
54
+
55
+ export async function stat(path: string) {
56
+ const info = await files.stat(path);
57
+ return { size: info.size, mtimeMs: info.mtim.getTime(), mtime: info.mtim, isFile: () => info.isFile, isDirectory: () => info.isDirectory };
58
+ }
59
+
60
+ export async function access(path: string): Promise<void> {
61
+ await files.stat(path);
62
+ }
63
+
64
+ export async function readdir(path: string, options?: { withFileTypes?: boolean }): Promise<any[]> {
65
+ const directory = await files.readDir(path);
66
+ const entries: any[] = [];
67
+ try {
68
+ for await (const entry of directory) {
69
+ entries.push(options?.withFileTypes ? { name: entry.name, isFile: () => entry.isFile, isDirectory: () => entry.isDirectory } : entry.name);
70
+ }
71
+ } finally {
72
+ await directory.close();
73
+ }
74
+ return entries;
75
+ }
76
+
77
+ export default { access, copyFile, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, unlink, writeFile };
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Synchronous node:fs over the C runtime, through tjs:ffi: txiki.js only has an
3
+ * asynchronous file API, and the core reads icons, fonts and assets synchronously.
4
+ */
5
+ import { dlopen } from "tjs:ffi";
6
+ import { Buffer } from "./buffer";
7
+
8
+ declare const TARVE_TXIKI_PLATFORM: "win32" | "linux";
9
+ const windows = TARVE_TXIKI_PLATFORM === "win32";
10
+
11
+ const S_IFMT = 0xf000;
12
+ const S_IFDIR = 0x4000;
13
+ const S_IFREG = 0x8000;
14
+
15
+ function load() {
16
+ if (windows) {
17
+ const c = dlopen("ucrtbase.dll", {
18
+ _wfopen: { args: ["buffer", "buffer"], returns: "ptr" },
19
+ fclose: { args: ["ptr"], returns: "i32" },
20
+ fread: { args: ["buffer", "size_t", "size_t", "ptr"], returns: "size_t" },
21
+ fwrite: { args: ["buffer", "size_t", "size_t", "ptr"], returns: "size_t" },
22
+ _wstat64: { args: ["buffer", "buffer"], returns: "i32" },
23
+ _wmkdir: { args: ["buffer"], returns: "i32" },
24
+ _wremove: { args: ["buffer"], returns: "i32" },
25
+ _wrmdir: { args: ["buffer"], returns: "i32" },
26
+ }).symbols;
27
+ const kernel = dlopen("kernel32.dll", {
28
+ MoveFileExW: { args: ["buffer", "buffer", "u32"], returns: "i32" },
29
+ FindFirstFileW: { args: ["buffer", "buffer"], returns: "ptr" },
30
+ FindNextFileW: { args: ["ptr", "buffer"], returns: "i32" },
31
+ FindClose: { args: ["ptr"], returns: "i32" },
32
+ }).symbols;
33
+ const wide = (value: string) => {
34
+ const units = new Uint16Array(value.length + 1);
35
+ for (let index = 0; index < value.length; index++) units[index] = value.charCodeAt(index);
36
+ return new Uint8Array(units.buffer);
37
+ };
38
+ return {
39
+ open: (path: string, mode: string) => c._wfopen(wide(path), wide(mode)),
40
+ close: c.fclose, read: c.fread, write: c.fwrite,
41
+ // struct _stat64: st_mode is a u16 at 6, st_size an i64 at 24, st_mtime an i64 at 40.
42
+ stat(path: string) {
43
+ const buffer = new Uint8Array(56);
44
+ if (c._wstat64(wide(path), buffer) !== 0) return undefined;
45
+ const view = new DataView(buffer.buffer);
46
+ return { mode: view.getUint16(6, true), size: Number(view.getBigInt64(24, true)), mtimeMs: Number(view.getBigInt64(40, true)) * 1000 };
47
+ },
48
+ mkdir: (path: string) => c._wmkdir(wide(path)),
49
+ remove: (path: string) => c._wremove(wide(path)),
50
+ rmdir: (path: string) => c._wrmdir(wide(path)),
51
+ // MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED, like Node's renameSync.
52
+ rename: (from: string, to: string) => kernel.MoveFileExW(wide(from), wide(to), 3) !== 0 ? 0 : -1,
53
+ chmod: (_path: string, _mode: number) => 0,
54
+ // WIN32_FIND_DATAW: dwFileAttributes at 0, cFileName (WCHAR[260]) at 44.
55
+ readdir(path: string): { name: string; directory: boolean }[] | undefined {
56
+ const data = new Uint8Array(592);
57
+ const handle = kernel.FindFirstFileW(wide(path.replace(/[\\/]*$/, "\\*")), data);
58
+ if (isNull(handle) || (handle as { addr?: bigint | number }).addr === -1n || BigInt((handle as { addr?: bigint | number }).addr ?? 0) === 0xffffffffffffffffn) return undefined;
59
+ const entries: { name: string; directory: boolean }[] = [];
60
+ const view = new DataView(data.buffer);
61
+ try {
62
+ do {
63
+ const units = new Uint16Array(data.buffer, 44, 260);
64
+ const name = String.fromCharCode(...units.subarray(0, units.indexOf(0)));
65
+ if (name !== "." && name !== "..") entries.push({ name, directory: (view.getUint32(0, true) & 0x10) !== 0 });
66
+ } while (kernel.FindNextFileW(handle, data) !== 0);
67
+ } finally {
68
+ kernel.FindClose(handle);
69
+ }
70
+ return entries;
71
+ },
72
+ };
73
+ }
74
+ const c = dlopen("c", {
75
+ fopen: { args: ["string", "string"], returns: "ptr" },
76
+ fclose: { args: ["ptr"], returns: "i32" },
77
+ fread: { args: ["buffer", "size_t", "size_t", "ptr"], returns: "size_t" },
78
+ fwrite: { args: ["buffer", "size_t", "size_t", "ptr"], returns: "size_t" },
79
+ stat: { args: ["string", "buffer"], returns: "i32" },
80
+ mkdir: { args: ["string", "u32"], returns: "i32" },
81
+ remove: { args: ["string"], returns: "i32" },
82
+ rmdir: { args: ["string"], returns: "i32" },
83
+ rename: { args: ["string", "string"], returns: "i32" },
84
+ }).symbols;
85
+ return {
86
+ open: c.fopen, close: c.fclose, read: c.fread, write: c.fwrite,
87
+ // x86-64 glibc struct stat: st_mode is a u32 at 24, st_size an i64 at 48, st_mtime an i64 at 88.
88
+ stat(path: string) {
89
+ const buffer = new Uint8Array(144);
90
+ if (c.stat(path, buffer) !== 0) return undefined;
91
+ const view = new DataView(buffer.buffer);
92
+ return { mode: view.getUint32(24, true), size: Number(view.getBigInt64(48, true)), mtimeMs: Number(view.getBigInt64(88, true)) * 1000 };
93
+ },
94
+ mkdir: (path: string) => c.mkdir(path, 0o777),
95
+ remove: c.remove, rmdir: c.rmdir, rename: c.rename,
96
+ chmod: (path: string, mode: number) => dlopen("c", { chmod: { args: ["string", "u32"], returns: "i32" } }).symbols.chmod(path, mode),
97
+ readdir(_path: string): { name: string; directory: boolean }[] | undefined {
98
+ throw new Error("fs.readdirSync is not available in the Tarve txiki.js runtime on Linux; use fs/promises readdir.");
99
+ },
100
+ };
101
+ }
102
+
103
+ let native: ReturnType<typeof load> | undefined;
104
+ const crt = () => (native ??= load());
105
+
106
+ function failure(code: string, syscall: string, path: string): Error {
107
+ return Object.assign(new Error(`${code}: ${syscall} '${path}'`), { code, syscall, path });
108
+ }
109
+
110
+ function isNull(pointer: unknown): boolean {
111
+ return pointer == null || pointer === 0 || pointer === 0n || (typeof pointer === "object" && (pointer as { isNull?: boolean }).isNull === true);
112
+ }
113
+
114
+ type Encoding = BufferEncoding | { encoding?: BufferEncoding | null; flag?: string } | null | undefined;
115
+
116
+ function encodingOf(options: Encoding): BufferEncoding | undefined {
117
+ return typeof options === "string" ? options : options?.encoding ?? undefined;
118
+ }
119
+
120
+ export interface Stats {
121
+ size: number;
122
+ mtimeMs: number;
123
+ isFile(): boolean;
124
+ isDirectory(): boolean;
125
+ }
126
+
127
+ export function statSync(path: string, options?: { throwIfNoEntry?: boolean }): Stats {
128
+ const stat = crt().stat(path);
129
+ if (!stat) {
130
+ if (options?.throwIfNoEntry === false) return undefined as unknown as Stats;
131
+ throw failure("ENOENT", "stat", path);
132
+ }
133
+ return { size: stat.size, mtimeMs: stat.mtimeMs, isFile: () => (stat.mode & S_IFMT) === S_IFREG, isDirectory: () => (stat.mode & S_IFMT) === S_IFDIR };
134
+ }
135
+
136
+ export function existsSync(path: string): boolean {
137
+ return typeof path === "string" && crt().stat(path) !== undefined;
138
+ }
139
+
140
+ export function readFileSync(path: string, options?: Encoding): any {
141
+ const stat = statSync(path);
142
+ if (stat.isDirectory()) throw failure("EISDIR", "read", path);
143
+ const file = crt().open(path, "rb");
144
+ if (isNull(file)) throw failure("EACCES", "open", path);
145
+ const bytes = new Buffer(stat.size);
146
+ let read = 0;
147
+ try {
148
+ while (read < bytes.length) {
149
+ const count = Number(crt().read(bytes.subarray(read), 1, bytes.length - read, file));
150
+ if (count <= 0) break;
151
+ read += count;
152
+ }
153
+ } finally {
154
+ crt().close(file);
155
+ }
156
+ // subarray keeps the Buffer subclass (Symbol.species).
157
+ const result = (read === bytes.length ? bytes : bytes.subarray(0, read)) as Buffer;
158
+ const encoding = encodingOf(options);
159
+ return encoding ? result.toString(encoding as "utf8") : result;
160
+ }
161
+
162
+ export function writeFileSync(path: string, data: string | Uint8Array, options?: Encoding): void {
163
+ const flag = typeof options === "object" && options ? options.flag ?? "w" : "w";
164
+ const exclusive = flag.includes("x");
165
+ if (exclusive && existsSync(path)) throw failure("EEXIST", "open", path);
166
+ const bytes = typeof data === "string" ? Buffer.from(data, (encodingOf(options) ?? "utf8") as "utf8") : data;
167
+ const file = crt().open(path, flag.startsWith("a") ? "ab" : "wb");
168
+ if (isNull(file)) throw failure("EACCES", "open", path);
169
+ try {
170
+ if (bytes.length && Number(crt().write(bytes, 1, bytes.length, file)) !== bytes.length) throw failure("EIO", "write", path);
171
+ } finally {
172
+ crt().close(file);
173
+ }
174
+ }
175
+
176
+ export function mkdirSync(path: string, options?: { recursive?: boolean }): void {
177
+ if (options?.recursive) {
178
+ const stat = crt().stat(path);
179
+ if (stat && (stat.mode & S_IFMT) === S_IFDIR) return;
180
+ const parent = path.replace(/[\\/]+[^\\/]*[\\/]*$/, "");
181
+ if (parent && parent !== path && !/^[A-Za-z]:$/.test(parent)) mkdirSync(parent, options);
182
+ }
183
+ if (crt().mkdir(path) !== 0 && !(options?.recursive && existsSync(path))) throw failure("EEXIST", "mkdir", path);
184
+ }
185
+
186
+ export function renameSync(from: string, to: string): void {
187
+ if (crt().rename(from, to) !== 0) throw failure(existsSync(from) ? "EPERM" : "ENOENT", "rename", from);
188
+ }
189
+
190
+ export function rmSync(path: string, options?: { force?: boolean; recursive?: boolean }): void {
191
+ const stat = crt().stat(path);
192
+ if (!stat) {
193
+ if (options?.force) return;
194
+ throw failure("ENOENT", "rm", path);
195
+ }
196
+ const directory = (stat.mode & S_IFMT) === S_IFDIR;
197
+ if (directory && !options?.recursive) throw failure("ERR_FS_EISDIR", "rm", path);
198
+ // Recursive, like Node: empty the directory first.
199
+ if (directory) for (const name of readdirSync(path) as string[]) rmSync(path + "/" + name, { recursive: true, force: true });
200
+ if ((directory ? crt().rmdir(path) : crt().remove(path)) !== 0) throw failure(directory ? "ENOTEMPTY" : "EPERM", "rm", path);
201
+ }
202
+
203
+ export function readdirSync(path: string, options?: { withFileTypes?: boolean }): any[] {
204
+ // Check first: an invalid FindFirstFileW handle is not reliably recognisable through tjs:ffi.
205
+ const stat = crt().stat(path);
206
+ if (!stat) throw failure("ENOENT", "scandir", path);
207
+ if ((stat.mode & S_IFMT) !== S_IFDIR) throw failure("ENOTDIR", "scandir", path);
208
+ const entries = crt().readdir(path);
209
+ if (!entries) throw failure("ENOENT", "scandir", path);
210
+ return options?.withFileTypes
211
+ ? entries.map(entry => ({ name: entry.name, isFile: () => !entry.directory, isDirectory: () => entry.directory }))
212
+ : entries.map(entry => entry.name);
213
+ }
214
+
215
+ export function mkdtempSync(prefix: string): string {
216
+ for (let attempt = 0; attempt < 16; attempt++) {
217
+ const path = prefix + crypto.randomUUID().replace(/-/g, "").slice(0, 6);
218
+ if (crt().mkdir(path) === 0) return path;
219
+ }
220
+ throw failure("EEXIST", "mkdtemp", prefix);
221
+ }
222
+
223
+ export function chmodSync(path: string, mode: number): void {
224
+ if (crt().chmod(path, mode) !== 0) throw failure("ENOENT", "chmod", path);
225
+ }
226
+
227
+ export function unlinkSync(path: string): void {
228
+ if (crt().remove(path) !== 0) throw failure("ENOENT", "unlink", path);
229
+ }
230
+
231
+ export default { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync };
@@ -0,0 +1,8 @@
1
+ export function createRequire(_from: string | URL) {
2
+ return (id: string): unknown => {
3
+ if (id === "node:sea") return { isSea: () => false };
4
+ throw new Error(`require("${id}") is not available in the Tarve txiki.js runtime`);
5
+ };
6
+ }
7
+
8
+ export default { createRequire };