@power-plant/schema 0.0.25 → 0.0.26

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.
@@ -0,0 +1,934 @@
1
+ const require_rolldown_runtime = require('./rolldown-runtime-C_NdSu1c.cjs');
2
+ let node_events = require("node:events");
3
+ let node_fs = require("node:fs");
4
+ node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
5
+ let node_util = require("node:util");
6
+ let node_buffer = require("node:buffer");
7
+ let node_worker_threads = require("node:worker_threads");
8
+ let node_stream = require("node:stream");
9
+
10
+ //#region src/storage/helpers.ts
11
+ function toPathInput(path) {
12
+ if (path instanceof URL) return decodeURIComponent(path.pathname);
13
+ if (node_buffer.Buffer.isBuffer(path)) return path.toString();
14
+ return path;
15
+ }
16
+ function normalizeKey(path) {
17
+ let value = toPathInput(path).replace(/\\/g, "/");
18
+ while (value.startsWith("./")) value = value.slice(2);
19
+ value = value.replace(/^\/+/, "");
20
+ value = value.replace(/\/+/g, "/");
21
+ if (value.length > 1 && value.endsWith("/")) value = value.slice(0, -1);
22
+ return value;
23
+ }
24
+ function resolveKey(...segments) {
25
+ const parts = [];
26
+ for (const segment of segments) for (const part of normalizeKey(segment).split("/")) {
27
+ if (!part || part === ".") continue;
28
+ if (part === "..") {
29
+ parts.pop();
30
+ continue;
31
+ }
32
+ parts.push(part);
33
+ }
34
+ return parts.join("/");
35
+ }
36
+ function dirname(key) {
37
+ const index = key.lastIndexOf("/");
38
+ return index === -1 ? "" : key.slice(0, index);
39
+ }
40
+ function basename(key) {
41
+ const index = key.lastIndexOf("/");
42
+ return index === -1 ? key : key.slice(index + 1);
43
+ }
44
+ function isMetaStorageKey(key) {
45
+ return key.endsWith("$");
46
+ }
47
+ function parentPrefix(key) {
48
+ return key ? `${key}/` : "";
49
+ }
50
+ function getImmediateChildren(base, keys) {
51
+ const prefix = parentPrefix(base);
52
+ const children = /* @__PURE__ */ new Set();
53
+ for (const key of keys) {
54
+ if (isMetaStorageKey(key)) continue;
55
+ const relative = prefix ? key.startsWith(prefix) ? key.slice(prefix.length) : "" : key;
56
+ if (!relative || relative === key) continue;
57
+ const slashIndex = relative.indexOf("/");
58
+ children.add(slashIndex === -1 ? relative : relative.slice(0, slashIndex));
59
+ }
60
+ return [...children].sort();
61
+ }
62
+ function createFsError(code, syscall, path, message) {
63
+ const suffix = path ? ` '${path}'` : "";
64
+ const error = new Error(message ?? `${code}: ${syscall}${suffix}`);
65
+ error.code = code;
66
+ error.syscall = syscall;
67
+ if (path) error.path = path;
68
+ return error;
69
+ }
70
+ function runSync(operation) {
71
+ const { port1, port2 } = new node_worker_threads.MessageChannel();
72
+ operation().then((value) => {
73
+ port1.postMessage({
74
+ ok: true,
75
+ value
76
+ });
77
+ }, (error) => {
78
+ port1.postMessage({
79
+ ok: false,
80
+ error
81
+ });
82
+ });
83
+ const response = (0, node_worker_threads.receiveMessageOnPort)(port2);
84
+ port1.close();
85
+ port2.close();
86
+ if (!response) throw new Error("Storage operation did not complete.");
87
+ if (!response.message.ok) throw response.message.error;
88
+ return response.message.value;
89
+ }
90
+ function toBuffer(value) {
91
+ if (value == null) return node_buffer.Buffer.alloc(0);
92
+ if (node_buffer.Buffer.isBuffer(value)) return value;
93
+ if (value instanceof Uint8Array) return node_buffer.Buffer.from(value);
94
+ return node_buffer.Buffer.from(value);
95
+ }
96
+ function getEncoding(options) {
97
+ if (typeof options === "string") return options;
98
+ if (options == null) return;
99
+ return options.encoding ?? void 0;
100
+ }
101
+ function shouldReadRaw(options) {
102
+ const encoding = getEncoding(options);
103
+ return encoding === void 0 || encoding === null || encoding === "buffer";
104
+ }
105
+ function decodeStoredValue(value, encoding) {
106
+ const buffer = toBuffer(typeof value === "string" || node_buffer.Buffer.isBuffer(value) || value instanceof Uint8Array ? value : value == null ? "" : JSON.stringify(value));
107
+ if (encoding === void 0 || encoding === null || encoding === "buffer") return buffer;
108
+ return buffer.toString(encoding);
109
+ }
110
+ function encodeWriteValue(data) {
111
+ if (typeof data === "string") return data;
112
+ return toBuffer(node_buffer.Buffer.from(data.buffer, data.byteOffset, data.byteLength));
113
+ }
114
+ function createStats(type, meta, size = 0) {
115
+ const now = Date.now();
116
+ const atime = meta?.atime instanceof Date ? meta.atime : new Date(now);
117
+ const mtime = meta?.mtime instanceof Date ? meta.mtime : new Date(now);
118
+ const mode = type === "directory" ? 16877 : type === "symlink" ? 41471 : 33188;
119
+ const stat = Object.create(node_fs.Stats.prototype);
120
+ Object.assign(stat, {
121
+ dev: 0,
122
+ ino: 0,
123
+ mode,
124
+ nlink: 1,
125
+ uid: typeof meta?.uid === "number" ? meta.uid : 0,
126
+ gid: typeof meta?.gid === "number" ? meta.gid : 0,
127
+ rdev: 0,
128
+ size,
129
+ blksize: 4096,
130
+ blocks: Math.ceil(size / 512),
131
+ atimeMs: atime.getTime(),
132
+ mtimeMs: mtime.getTime(),
133
+ ctimeMs: mtime.getTime(),
134
+ birthtimeMs: mtime.getTime(),
135
+ atime,
136
+ mtime,
137
+ ctime: mtime,
138
+ birthtime: mtime
139
+ });
140
+ return stat;
141
+ }
142
+ function matchesGlobPattern(pattern, value) {
143
+ return new RegExp(`^${pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*").replace(/\?/g, ".")}$`).test(value);
144
+ }
145
+ function randomSuffix(length = 6) {
146
+ return Array.from({ length }, () => "abcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random() * 36))).join("");
147
+ }
148
+
149
+ //#endregion
150
+ //#region src/storage/promises.ts
151
+ const SYMLINK_META_KEY = "symlinkTarget";
152
+ function createStoragePromises(storage) {
153
+ const openDescriptors = /* @__PURE__ */ new Map();
154
+ let nextDescriptor = 3;
155
+ async function getMetaSafe(key) {
156
+ try {
157
+ return await storage.getMeta(key) ?? null;
158
+ } catch {
159
+ return null;
160
+ }
161
+ }
162
+ async function getEntry(path, followSymlinks = true) {
163
+ const key = normalizeKey(path);
164
+ if (!key && path !== "." && path !== "/") return null;
165
+ const meta = await getMetaSafe(key);
166
+ if (meta?.[SYMLINK_META_KEY] && typeof meta[SYMLINK_META_KEY] === "string") {
167
+ if (!followSymlinks) return {
168
+ key,
169
+ type: "symlink",
170
+ meta
171
+ };
172
+ return getEntry(meta[SYMLINK_META_KEY], true);
173
+ }
174
+ if (await storage.hasItem(key)) return {
175
+ key,
176
+ type: "file",
177
+ meta
178
+ };
179
+ if (getImmediateChildren(key, (await storage.getKeys(key)).filter((storageKey) => storageKey !== key && !isMetaStorageKey(storageKey))).length > 0) return {
180
+ key,
181
+ type: "directory",
182
+ meta
183
+ };
184
+ return null;
185
+ }
186
+ async function requireEntry(path, followSymlinks = true) {
187
+ const entry = await getEntry(path, followSymlinks);
188
+ if (!entry) throw createFsError("ENOENT", "stat", normalizeKey(path));
189
+ return entry;
190
+ }
191
+ async function getFileSize(key) {
192
+ const meta = await getMetaSafe(key);
193
+ if (typeof meta?.size === "number") return meta.size;
194
+ if (shouldReadRaw()) {
195
+ const raw = await storage.getItemRaw(key);
196
+ return raw == null ? 0 : toBuffer(raw).byteLength;
197
+ }
198
+ const value = await storage.getItem(key);
199
+ return value == null ? 0 : toBuffer(String(value)).byteLength;
200
+ }
201
+ async function readStoredFile(path, options) {
202
+ const key = normalizeKey(path);
203
+ if ((await requireEntry(key, true)).type !== "file") throw createFsError("EISDIR", "read", key, "EISDIR: illegal operation on a directory, read");
204
+ const encoding = getEncoding(options);
205
+ const value = shouldReadRaw(options) ? await storage.getItemRaw(key) : await storage.getItem(key);
206
+ if (value == null) throw createFsError("ENOENT", "open", key);
207
+ return decodeStoredValue(value, encoding);
208
+ }
209
+ async function writeStoredFile(path, data, options) {
210
+ const key = normalizeKey(path);
211
+ const encoding = getEncoding(options);
212
+ const payload = typeof data === "string" ? data : encoding && encoding !== "buffer" ? toBuffer(encodeWriteValue(data)).toString(encoding) : encodeWriteValue(data);
213
+ await storage.setItem(key, payload);
214
+ await storage.setMeta(key, {
215
+ mtime: /* @__PURE__ */ new Date(),
216
+ atime: /* @__PURE__ */ new Date(),
217
+ size: toBuffer(payload).byteLength
218
+ });
219
+ }
220
+ async function removePath(path, options) {
221
+ const key = normalizeKey(path);
222
+ const entry = await getEntry(key, false);
223
+ if (!entry) {
224
+ if (typeof options === "object" && options && "recursive" in options && options.recursive) return;
225
+ throw createFsError("ENOENT", "unlink", key);
226
+ }
227
+ if (entry.type === "directory") {
228
+ const recursive = options === true || (typeof options === "object" && options && "recursive" in options ? Boolean(options.recursive) : false);
229
+ const descendants = (await storage.getKeys(key)).filter((storageKey) => storageKey !== key && !isMetaStorageKey(storageKey) && storageKey.startsWith(parentPrefix(key)));
230
+ if (!recursive && descendants.length > 0) throw createFsError("ENOTEMPTY", "rmdir", key);
231
+ await Promise.all(descendants.map(async (descendant) => storage.removeItem(descendant)));
232
+ if (await storage.hasItem(key)) await storage.removeItem(key);
233
+ return;
234
+ }
235
+ await storage.removeItem(key);
236
+ }
237
+ async function copyEntry(source, destination, recursive = false) {
238
+ if ((await requireEntry(source, true)).type === "directory") {
239
+ if (!recursive) throw createFsError("EISDIR", "copy", source, "EISDIR: illegal operation on a directory, copy");
240
+ const keys = await storage.getKeys(source);
241
+ for (const key of keys) {
242
+ if (isMetaStorageKey(key) || key === source) continue;
243
+ await copyEntry(key, resolveKey(destination, key.slice(source.length).replace(/^\//, "")), true);
244
+ }
245
+ return;
246
+ }
247
+ const content = await readStoredFile(source);
248
+ await writeStoredFile(destination, typeof content === "string" ? content : toBuffer(content));
249
+ const meta = await getMetaSafe(source);
250
+ if (meta) await storage.setMeta(normalizeKey(destination), meta);
251
+ }
252
+ async function statPath(path, followSymlinks = true) {
253
+ const entry = await requireEntry(path, followSymlinks);
254
+ const size = entry.type === "file" ? await getFileSize(entry.key) : 4096;
255
+ return createStats(entry.type, entry.meta, size);
256
+ }
257
+ async function chmodPath(path, mode) {
258
+ const key = normalizeKey(path);
259
+ await requireEntry(key, true);
260
+ await storage.setMeta(key, { mode });
261
+ }
262
+ async function chownPath(path, uid, gid) {
263
+ const key = normalizeKey(path);
264
+ await requireEntry(key, true);
265
+ await storage.setMeta(key, {
266
+ uid,
267
+ gid
268
+ });
269
+ }
270
+ async function mkdirPath(path, options) {
271
+ const key = normalizeKey(path);
272
+ const recursive = typeof options === "object" && options ? Boolean(options.recursive) : false;
273
+ if (!key) return;
274
+ const parent = dirname(key);
275
+ if (parent) {
276
+ const parentEntry = await getEntry(parent, true);
277
+ if (!parentEntry && !recursive) throw createFsError("ENOENT", "mkdir", key);
278
+ if (!parentEntry && recursive) await mkdirPath(parent, { recursive: true });
279
+ }
280
+ if ((await getEntry(key, true))?.type === "file") throw createFsError("EEXIST", "mkdir", key);
281
+ }
282
+ async function mkdtempPath(prefix, options) {
283
+ const directory = `${normalizeKey(prefix)}${randomSuffix()}`;
284
+ await mkdirPath(directory, { recursive: true });
285
+ if (options?.encoding === "buffer") return node_buffer.Buffer.from(directory);
286
+ return directory;
287
+ }
288
+ function createDir(path, options) {
289
+ const key = normalizeKey(path);
290
+ let entries = [];
291
+ let loaded = false;
292
+ let index = 0;
293
+ let closed = false;
294
+ const loadEntries = async () => {
295
+ if (loaded) return;
296
+ await requireEntry(key, true);
297
+ const keys = await storage.getKeys(key);
298
+ entries = getImmediateChildren(key, keys.filter((storageKey) => !isMetaStorageKey(storageKey)));
299
+ loaded = true;
300
+ };
301
+ const toDirent = (name) => ({
302
+ name,
303
+ isFile: () => true,
304
+ isDirectory: () => false,
305
+ isBlockDevice: () => false,
306
+ isCharacterDevice: () => false,
307
+ isSymbolicLink: () => false,
308
+ isFIFO: () => false,
309
+ isSocket: () => false
310
+ });
311
+ return {
312
+ path: key,
313
+ async read() {
314
+ if (closed) throw createFsError("EBADF", "readdir", key);
315
+ await loadEntries();
316
+ if (index >= entries.length) return null;
317
+ const name = entries[index++];
318
+ if (options?.encoding === "buffer") return node_buffer.Buffer.from(name);
319
+ return toDirent(name);
320
+ },
321
+ async close() {
322
+ closed = true;
323
+ },
324
+ async *[Symbol.asyncIterator]() {
325
+ while (true) {
326
+ const entry = await this.read();
327
+ if (!entry) break;
328
+ yield entry;
329
+ }
330
+ }
331
+ };
332
+ }
333
+ function createReadStream(path, options) {
334
+ const key = normalizeKey(path);
335
+ const start = options?.start ?? 0;
336
+ const end = options?.end;
337
+ return node_stream.Readable.from((async function* () {
338
+ let content = toBuffer(await readStoredFile(key));
339
+ if (start > 0) content = content.subarray(start);
340
+ if (end != null) {
341
+ yield content.subarray(0, Math.max(0, end - start + 1));
342
+ return;
343
+ }
344
+ yield content;
345
+ })());
346
+ }
347
+ function createWriteStream(path, options) {
348
+ const key = normalizeKey(path);
349
+ const chunks = [];
350
+ return new node_stream.Writable({
351
+ write(chunk, _encoding, callback) {
352
+ chunks.push(toBuffer(chunk));
353
+ callback();
354
+ },
355
+ final: (callback) => {
356
+ const content = node_buffer.Buffer.concat(chunks);
357
+ const payload = options?.encoding && options.encoding !== "buffer" ? content.toString(options.encoding) : content;
358
+ writeStoredFile(key, payload, options).then(() => callback()).catch((error) => callback(error));
359
+ }
360
+ });
361
+ }
362
+ function createFileHandle(descriptor, key) {
363
+ const getDescriptor = () => {
364
+ const current = openDescriptors.get(descriptor);
365
+ if (!current) throw createFsError("EBADF", "read", key);
366
+ return current;
367
+ };
368
+ return {
369
+ fd: descriptor,
370
+ async appendFile(data, options) {
371
+ const current = await readStoredFile(key).catch(() => node_buffer.Buffer.alloc(0));
372
+ await writeStoredFile(key, node_buffer.Buffer.concat([toBuffer(current), toBuffer(typeof data === "string" ? data : encodeWriteValue(data))]), options);
373
+ },
374
+ async chmod(_mode) {},
375
+ async chown(_uid, _gid) {},
376
+ async close() {
377
+ openDescriptors.delete(descriptor);
378
+ },
379
+ createReadStream(options) {
380
+ return createReadStream(key, options);
381
+ },
382
+ createWriteStream(options) {
383
+ return createWriteStream(key, options);
384
+ },
385
+ async datasync() {},
386
+ async read(buffer, offset, length, position) {
387
+ const current = getDescriptor();
388
+ const content = toBuffer(await readStoredFile(key, { encoding: void 0 }));
389
+ const readPosition = position ?? current.position;
390
+ const readOffset = offset ?? 0;
391
+ const readLength = length ?? buffer.length - readOffset;
392
+ const bytesRead = content.copy(buffer, readOffset, readPosition, readPosition + readLength);
393
+ if (position === null || position === void 0) current.position += bytesRead;
394
+ return {
395
+ bytesRead,
396
+ buffer
397
+ };
398
+ },
399
+ async readFile(options) {
400
+ return readStoredFile(key, options);
401
+ },
402
+ async stat(_options) {
403
+ return statPath(key);
404
+ },
405
+ async sync() {},
406
+ async truncate(len = 0) {
407
+ await writeStoredFile(key, toBuffer(await readStoredFile(key)).subarray(0, len));
408
+ },
409
+ async utimes(_atime, _mtime) {
410
+ await storage.setMeta(key, {
411
+ atime: new Date(_atime),
412
+ mtime: new Date(_mtime)
413
+ });
414
+ },
415
+ async write(buffer, offset, length, position) {
416
+ const current = getDescriptor();
417
+ const content = toBuffer(await readStoredFile(key).catch(() => ""));
418
+ const writeOffset = offset ?? 0;
419
+ const writeLength = length ?? buffer.length - writeOffset;
420
+ const writePosition = position ?? current.position;
421
+ buffer.copy(content, writePosition, writeOffset, writeOffset + writeLength);
422
+ await writeStoredFile(key, content);
423
+ if (position === null || position === void 0) current.position += writeLength;
424
+ return {
425
+ bytesWritten: writeLength,
426
+ buffer
427
+ };
428
+ },
429
+ async writeFile(data, options) {
430
+ await writeStoredFile(key, typeof data === "string" ? data : encodeWriteValue(data), options);
431
+ }
432
+ };
433
+ }
434
+ const promises = {
435
+ async access(path, mode = node_fs.constants.F_OK) {
436
+ const entry = await getEntry(path, true);
437
+ if (!entry) throw createFsError("ENOENT", "access", normalizeKey(path));
438
+ if (mode & node_fs.constants.W_OK && entry.type === "directory") throw createFsError("EISDIR", "access", normalizeKey(path));
439
+ },
440
+ async appendFile(path, data, options) {
441
+ const key = normalizeKey(path);
442
+ const current = await readStoredFile(key).catch(() => "");
443
+ await writeStoredFile(key, node_buffer.Buffer.concat([toBuffer(current), toBuffer(typeof data === "string" ? data : encodeWriteValue(data))]), options);
444
+ },
445
+ async chmod(path, mode) {
446
+ const key = normalizeKey(path);
447
+ await requireEntry(key, true);
448
+ await storage.setMeta(key, { mode });
449
+ },
450
+ async chown(path, uid, gid) {
451
+ const key = normalizeKey(path);
452
+ await requireEntry(key, true);
453
+ await storage.setMeta(key, {
454
+ uid,
455
+ gid
456
+ });
457
+ },
458
+ async copyFile(src, dest, _mode) {
459
+ await copyEntry(normalizeKey(src), normalizeKey(dest), false);
460
+ },
461
+ async cp(src, dest, options) {
462
+ await copyEntry(normalizeKey(src), normalizeKey(dest), Boolean(options?.recursive));
463
+ },
464
+ async glob(pattern, options) {
465
+ const cwd = normalizeKey(options?.cwd ?? ".");
466
+ const matches = (await storage.getKeys(cwd)).filter((key) => !isMetaStorageKey(key)).filter((key) => matchesGlobPattern(String(pattern), key));
467
+ async function* iterator() {
468
+ for (const match of matches) if (options && "withFileTypes" in options && options.withFileTypes) {
469
+ const entry = await getEntry(match, true);
470
+ yield {
471
+ name: basename(match),
472
+ relative: match.slice(cwd.length).replace(/^\//, ""),
473
+ absolute: match,
474
+ isFile: () => entry?.type === "file",
475
+ isDirectory: () => entry?.type === "directory",
476
+ isSymbolicLink: () => entry?.type === "symlink"
477
+ };
478
+ } else yield match;
479
+ }
480
+ return iterator();
481
+ },
482
+ async lchmod(path, mode) {
483
+ await chmodPath(path, mode);
484
+ },
485
+ async lchown(path, uid, gid) {
486
+ await chownPath(path, uid, gid);
487
+ },
488
+ async lutimes(path, atime, mtime) {
489
+ const key = normalizeKey(path);
490
+ await requireEntry(key, false);
491
+ await storage.setMeta(key, {
492
+ atime: new Date(atime),
493
+ mtime: new Date(mtime)
494
+ });
495
+ },
496
+ async link(existingPath, newPath) {
497
+ const source = normalizeKey(existingPath);
498
+ const destination = normalizeKey(newPath);
499
+ const content = await readStoredFile(source);
500
+ await writeStoredFile(destination, typeof content === "string" ? content : toBuffer(content));
501
+ },
502
+ async lstat(path, _options) {
503
+ return statPath(path, false);
504
+ },
505
+ async mkdir(path, options) {
506
+ return mkdirPath(path, options);
507
+ },
508
+ async mkdtemp(prefix, options) {
509
+ return mkdtempPath(prefix, options);
510
+ },
511
+ async mkdtempDisposable(prefix, options) {
512
+ const directory = await mkdtempPath(prefix, options);
513
+ return {
514
+ path: directory,
515
+ async [Symbol.asyncDispose]() {
516
+ await removePath(directory, {
517
+ recursive: true,
518
+ force: true
519
+ });
520
+ },
521
+ [Symbol.dispose]() {
522
+ runSync(async () => removePath(directory, {
523
+ recursive: true,
524
+ force: true
525
+ }));
526
+ }
527
+ };
528
+ },
529
+ async open(path, _flags, _mode) {
530
+ const key = normalizeKey(path);
531
+ await requireEntry(key, true).catch(async (error) => {
532
+ if (error.code === "ENOENT") {
533
+ await writeStoredFile(key, "");
534
+ return;
535
+ }
536
+ throw error;
537
+ });
538
+ const descriptor = nextDescriptor++;
539
+ openDescriptors.set(descriptor, {
540
+ key,
541
+ position: 0
542
+ });
543
+ return createFileHandle(descriptor, key);
544
+ },
545
+ async opendir(path, options) {
546
+ return createDir(path, options);
547
+ },
548
+ async readdir(path, options) {
549
+ const key = normalizeKey(path);
550
+ await requireEntry(key, true);
551
+ const keys = await storage.getKeys(key);
552
+ let children = getImmediateChildren(key, keys.filter((storageKey) => !isMetaStorageKey(storageKey)));
553
+ if (options && typeof options === "object" && "recursive" in options && options.recursive) children = keys.filter((storageKey) => !isMetaStorageKey(storageKey)).map((storageKey) => storageKey.slice(key.length).replace(/^\//, "")).filter(Boolean);
554
+ if (options && typeof options === "object" && "withFileTypes" in options && options.withFileTypes) return await Promise.all(children.map(async (name) => {
555
+ const entry = await getEntry(resolveKey(key, name), true);
556
+ return {
557
+ name,
558
+ isFile: () => entry?.type === "file",
559
+ isDirectory: () => entry?.type === "directory",
560
+ isBlockDevice: () => false,
561
+ isCharacterDevice: () => false,
562
+ isSymbolicLink: () => entry?.type === "symlink",
563
+ isFIFO: () => false,
564
+ isSocket: () => false
565
+ };
566
+ }));
567
+ if (options && typeof options === "object" && "encoding" in options && options.encoding === "buffer") return children.map((name) => node_buffer.Buffer.from(name));
568
+ return children;
569
+ },
570
+ async readFile(path, options) {
571
+ return readStoredFile(path, options);
572
+ },
573
+ async readlink(path, options) {
574
+ const key = normalizeKey(path);
575
+ const entry = await requireEntry(key, false);
576
+ if (entry.type !== "symlink") throw createFsError("EINVAL", "readlink", key);
577
+ const target = entry.meta?.[SYMLINK_META_KEY];
578
+ if (typeof target !== "string") throw createFsError("EINVAL", "readlink", key);
579
+ if (options && typeof options === "object" && options.encoding === "buffer") return node_buffer.Buffer.from(target);
580
+ return target;
581
+ },
582
+ async realpath(path, options) {
583
+ const resolved = resolveKey(path);
584
+ if (!await getEntry(resolved, true)) throw createFsError("ENOENT", "realpath", resolved);
585
+ if (options && typeof options === "object" && options.encoding === "buffer") return node_buffer.Buffer.from(resolved);
586
+ return resolved;
587
+ },
588
+ async rename(oldPath, newPath) {
589
+ const source = normalizeKey(oldPath);
590
+ const destination = normalizeKey(newPath);
591
+ if ((await requireEntry(source, true)).type === "directory") {
592
+ const keys = await storage.getKeys(source);
593
+ for (const key of keys) {
594
+ if (isMetaStorageKey(key)) continue;
595
+ const relative = key === source ? "" : key.slice(source.length).replace(/^\//, "");
596
+ const target = relative ? resolveKey(destination, relative) : destination;
597
+ if (key === source && await storage.hasItem(key)) {
598
+ const value = await storage.getItem(key);
599
+ if (value != null) await storage.setItem(target, value);
600
+ } else if (key !== source) {
601
+ const value = await storage.getItem(key);
602
+ if (value != null) await storage.setItem(target, value);
603
+ const meta = await getMetaSafe(key);
604
+ if (meta) await storage.setMeta(target, meta);
605
+ await storage.removeItem(key);
606
+ }
607
+ }
608
+ if (await storage.hasItem(source)) await storage.removeItem(source);
609
+ return;
610
+ }
611
+ const content = await storage.getItem(source);
612
+ if (content != null) await storage.setItem(destination, content);
613
+ const meta = await getMetaSafe(source);
614
+ if (meta) await storage.setMeta(destination, meta);
615
+ await storage.removeItem(source);
616
+ },
617
+ async rm(path, options) {
618
+ await removePath(path, options);
619
+ },
620
+ async rmdir(path, options) {
621
+ await removePath(path, options);
622
+ },
623
+ async stat(path, _options) {
624
+ return statPath(path);
625
+ },
626
+ async statfs(path, _options) {
627
+ const keys = await storage.getKeys(normalizeKey(path));
628
+ const stats = Object.create(node_fs.Stats.prototype);
629
+ Object.assign(stats, {
630
+ type: 0,
631
+ bsize: 4096,
632
+ blocks: keys.length,
633
+ bfree: 0,
634
+ bavail: 0,
635
+ files: keys.length,
636
+ ffree: 0
637
+ });
638
+ return stats;
639
+ },
640
+ async symlink(target, path, _type) {
641
+ const key = normalizeKey(path);
642
+ await storage.setMeta(key, {
643
+ [SYMLINK_META_KEY]: normalizeKey(target),
644
+ mtime: /* @__PURE__ */ new Date(),
645
+ atime: /* @__PURE__ */ new Date()
646
+ });
647
+ },
648
+ async truncate(path, len = 0) {
649
+ const key = normalizeKey(path);
650
+ await writeStoredFile(key, toBuffer(await readStoredFile(key)).subarray(0, len));
651
+ },
652
+ async unlink(path) {
653
+ const key = normalizeKey(path);
654
+ const entry = await getEntry(key, false);
655
+ if (!entry) throw createFsError("ENOENT", "unlink", key);
656
+ if (entry.type === "directory") throw createFsError("EISDIR", "unlink", key);
657
+ await storage.removeItem(key);
658
+ },
659
+ async utimes(path, atime, mtime) {
660
+ const key = normalizeKey(path);
661
+ await requireEntry(key, true);
662
+ await storage.setMeta(key, {
663
+ atime: new Date(atime),
664
+ mtime: new Date(mtime)
665
+ });
666
+ },
667
+ async watch(path, options) {
668
+ const key = normalizeKey(path);
669
+ const unwatch = await storage.watch((event, watchedKey) => {
670
+ if (watchedKey === key || watchedKey.startsWith(parentPrefix(key))) (typeof options === "function" ? options : options.listener)?.(event, watchedKey);
671
+ });
672
+ return {
673
+ async close() {
674
+ await unwatch();
675
+ },
676
+ [Symbol.asyncDispose]: async () => {
677
+ await unwatch();
678
+ }
679
+ };
680
+ },
681
+ async writeFile(path, data, options) {
682
+ await writeStoredFile(path, data, options);
683
+ }
684
+ };
685
+ async function openFd(path, flags, mode) {
686
+ return (await promises.open(path, flags, mode)).fd;
687
+ }
688
+ async function closeFd(fd) {
689
+ if (!openDescriptors.has(fd)) throw createFsError("EBADF", "close");
690
+ openDescriptors.delete(fd);
691
+ }
692
+ async function fstatFd(fd, _options) {
693
+ const descriptor = openDescriptors.get(fd);
694
+ if (!descriptor) throw createFsError("EBADF", "fstat");
695
+ return statPath(descriptor.key);
696
+ }
697
+ async function readFd(fd, buffer, offset, length, position) {
698
+ const descriptor = openDescriptors.get(fd);
699
+ if (!descriptor) throw createFsError("EBADF", "read");
700
+ return createFileHandle(fd, descriptor.key).read(buffer, offset, length, position);
701
+ }
702
+ async function writeFd(fd, buffer, offset, length, position) {
703
+ const descriptor = openDescriptors.get(fd);
704
+ if (!descriptor) throw createFsError("EBADF", "write");
705
+ return createFileHandle(fd, descriptor.key).write(buffer, offset, length, position);
706
+ }
707
+ async function ftruncateFd(fd, len = 0) {
708
+ const descriptor = openDescriptors.get(fd);
709
+ if (!descriptor) throw createFsError("EBADF", "ftruncate");
710
+ await promises.truncate(descriptor.key, len);
711
+ }
712
+ async function futimesFd(fd, atime, mtime) {
713
+ const descriptor = openDescriptors.get(fd);
714
+ if (!descriptor) throw createFsError("EBADF", "futimes");
715
+ await promises.utimes(descriptor.key, atime, mtime);
716
+ }
717
+ async function readvFd(fd, buffers, position) {
718
+ let offset = 0;
719
+ let readPosition = position ?? openDescriptors.get(fd)?.position ?? 0;
720
+ for (const view of buffers) {
721
+ const buffer = node_buffer.Buffer.from(view.buffer, view.byteOffset, view.byteLength);
722
+ const result = await readFd(fd, buffer, 0, buffer.length, readPosition);
723
+ offset += result.bytesRead;
724
+ readPosition += result.bytesRead;
725
+ }
726
+ return {
727
+ bytesRead: offset,
728
+ buffers
729
+ };
730
+ }
731
+ async function writevFd(fd, buffers, position) {
732
+ const content = node_buffer.Buffer.concat(buffers.map((view) => node_buffer.Buffer.from(view.buffer, view.byteOffset, view.byteLength)));
733
+ const descriptor = openDescriptors.get(fd);
734
+ if (!descriptor) throw createFsError("EBADF", "writev");
735
+ const writePosition = position ?? descriptor.position;
736
+ const existing = toBuffer(await readStoredFile(descriptor.key).catch(() => ""));
737
+ content.copy(existing, writePosition);
738
+ await writeStoredFile(descriptor.key, existing);
739
+ if (position == null) descriptor.position += content.byteLength;
740
+ return {
741
+ bytesWritten: content.byteLength,
742
+ buffers
743
+ };
744
+ }
745
+ return {
746
+ promises,
747
+ createReadStream,
748
+ createWriteStream,
749
+ openFd,
750
+ closeFd,
751
+ fstatFd,
752
+ readFd,
753
+ writeFd,
754
+ ftruncateFd,
755
+ futimesFd,
756
+ readvFd,
757
+ writevFd
758
+ };
759
+ }
760
+
761
+ //#endregion
762
+ //#region src/storage/index.ts
763
+ function bindCallback(fn) {
764
+ const callback = (0, node_util.callbackify)(fn);
765
+ callback.__promisify__ = fn;
766
+ return callback;
767
+ }
768
+ function createNoopAsync() {
769
+ return async () => void 0;
770
+ }
771
+ function createNoopSync() {
772
+ return () => void 0;
773
+ }
774
+ function mapStorageToFileSystem(storage) {
775
+ const core = createStoragePromises(storage);
776
+ const { promises } = core;
777
+ const globAsync = async (...args) => {
778
+ const iterator = promises.glob(...args);
779
+ const results = [];
780
+ for await (const entry of iterator) results.push(typeof entry === "string" ? entry : "absolute" in entry ? String(entry.absolute) : String(entry));
781
+ return results;
782
+ };
783
+ const watchEmitter = (path) => {
784
+ const watcher = new node_events.EventEmitter();
785
+ storage.watch((event, key) => {
786
+ const normalized = normalizeKey(path);
787
+ if (key === normalized || key.startsWith(`${normalized}/`)) watcher.emit("change", event, key);
788
+ }).then((unwatch) => {
789
+ watcher.on("close", () => {
790
+ unwatch();
791
+ });
792
+ });
793
+ return watcher;
794
+ };
795
+ return {
796
+ promises,
797
+ access: bindCallback(promises.access),
798
+ appendFile: bindCallback(promises.appendFile),
799
+ chmod: bindCallback(promises.chmod),
800
+ chown: bindCallback(promises.chown),
801
+ close: bindCallback(core.closeFd),
802
+ copyFile: bindCallback(promises.copyFile),
803
+ cp: bindCallback(promises.cp),
804
+ createReadStream: core.createReadStream,
805
+ createWriteStream: core.createWriteStream,
806
+ exists: ((path, callback) => {
807
+ promises.access(path).then(() => callback(true)).catch(() => callback(false));
808
+ }),
809
+ fchmod: bindCallback(createNoopAsync()),
810
+ fchown: bindCallback(createNoopAsync()),
811
+ fdatasync: bindCallback(createNoopAsync()),
812
+ fstat: bindCallback(core.fstatFd),
813
+ fsync: bindCallback(createNoopAsync()),
814
+ ftruncate: bindCallback(core.ftruncateFd),
815
+ futimes: bindCallback(core.futimesFd),
816
+ glob: bindCallback(globAsync),
817
+ lchmod: bindCallback(promises.lchmod),
818
+ lchown: bindCallback(promises.lchown),
819
+ lutimes: bindCallback(promises.lutimes),
820
+ link: bindCallback(promises.link),
821
+ lstat: bindCallback(promises.lstat),
822
+ mkdir: bindCallback(promises.mkdir),
823
+ mkdtemp: bindCallback(promises.mkdtemp),
824
+ open: bindCallback(core.openFd),
825
+ openAsBlob: bindCallback(async (path) => {
826
+ const content = await promises.readFile(path);
827
+ return new Blob([content]);
828
+ }),
829
+ opendir: bindCallback(promises.opendir),
830
+ read: bindCallback(core.readFd),
831
+ readdir: bindCallback(promises.readdir),
832
+ readFile: bindCallback(promises.readFile),
833
+ readlink: bindCallback(promises.readlink),
834
+ readv: bindCallback(core.readvFd),
835
+ realpath: bindCallback(promises.realpath),
836
+ rename: bindCallback(promises.rename),
837
+ rmdir: bindCallback(promises.rmdir),
838
+ rm: bindCallback(promises.rm),
839
+ stat: bindCallback(promises.stat),
840
+ statfs: bindCallback(promises.statfs),
841
+ symlink: bindCallback(promises.symlink),
842
+ truncate: bindCallback(promises.truncate),
843
+ unlink: bindCallback(promises.unlink),
844
+ unwatchFile: node_fs.unwatchFile,
845
+ utimes: bindCallback(promises.utimes),
846
+ watch: ((path, options, listener) => {
847
+ const watcher = watchEmitter(path);
848
+ const attachListener = (handler) => {
849
+ watcher.on("change", handler);
850
+ };
851
+ if (typeof options === "function") {
852
+ attachListener(options);
853
+ return watcher;
854
+ }
855
+ if (typeof listener === "function") attachListener(listener);
856
+ else if (options && typeof options === "object" && "listener" in options && typeof options.listener === "function") attachListener(options.listener);
857
+ return watcher;
858
+ }),
859
+ watchFile: node_fs.watchFile,
860
+ write: bindCallback(core.writeFd),
861
+ writeFile: bindCallback(promises.writeFile),
862
+ writev: bindCallback(core.writevFd),
863
+ accessSync: ((path, mode) => runSync(async () => promises.access(path, mode))),
864
+ appendFileSync: ((path, data, options) => runSync(async () => promises.appendFile(path, data, options))),
865
+ chmodSync: ((path, mode) => runSync(async () => promises.chmod(path, mode))),
866
+ chownSync: ((path, uid, gid) => runSync(async () => promises.chown(path, uid, gid))),
867
+ closeSync: ((fd) => runSync(async () => core.closeFd(fd))),
868
+ copyFileSync: ((src, dest, mode) => runSync(async () => promises.copyFile(src, dest, mode))),
869
+ cpSync: ((src, dest, options) => runSync(async () => promises.cp(src, dest, options))),
870
+ existsSync: ((path) => {
871
+ try {
872
+ runSync(async () => promises.access(path));
873
+ return true;
874
+ } catch {
875
+ return false;
876
+ }
877
+ }),
878
+ fchmodSync: createNoopSync(),
879
+ fchownSync: createNoopSync(),
880
+ fdatasyncSync: createNoopSync(),
881
+ fstatSync: ((fd, options) => runSync(async () => core.fstatFd(fd, options))),
882
+ fsyncSync: createNoopSync(),
883
+ ftruncateSync: ((fd, len) => runSync(async () => core.ftruncateFd(fd, len))),
884
+ futimesSync: ((fd, atime, mtime) => runSync(async () => core.futimesFd(fd, atime, mtime))),
885
+ globSync: ((pattern, options) => runSync(async () => globAsync(pattern, options))),
886
+ lchmodSync: ((path, mode) => runSync(async () => promises.lchmod(path, mode))),
887
+ lchownSync: ((path, uid, gid) => runSync(async () => promises.lchown(path, uid, gid))),
888
+ lutimesSync: ((path, atime, mtime) => runSync(async () => promises.lutimes(path, atime, mtime))),
889
+ linkSync: ((existingPath, newPath) => runSync(async () => promises.link(existingPath, newPath))),
890
+ lstatSync: ((path, options) => runSync(async () => promises.lstat(path, options))),
891
+ mkdirSync: ((path, options) => runSync(async () => promises.mkdir(path, options))),
892
+ mkdtempSync: ((prefix, options) => runSync(async () => promises.mkdtemp(prefix, options))),
893
+ openSync: ((path, flags, mode) => runSync(async () => core.openFd(path, flags, mode ?? void 0))),
894
+ opendirSync: ((path, options) => runSync(async () => promises.opendir(path, options))),
895
+ readdirSync: ((path, options) => runSync(async () => promises.readdir(path, options))),
896
+ readFileSync: ((path, options) => runSync(async () => promises.readFile(path, options))),
897
+ readlinkSync: ((path, options) => runSync(async () => promises.readlink(path, options))),
898
+ readSync: ((fd, buffer, offset, length, position) => runSync(async () => core.readFd(fd, buffer, offset ?? 0, length ?? buffer.byteLength, position == null ? null : Number(position))).bytesRead),
899
+ readvSync: ((fd, buffers, position) => runSync(async () => core.readvFd(fd, [...buffers], position)).bytesRead),
900
+ realpathSync: ((path, options) => runSync(async () => promises.realpath(path, options))),
901
+ renameSync: ((oldPath, newPath) => runSync(async () => promises.rename(oldPath, newPath))),
902
+ rmdirSync: ((path) => runSync(async () => promises.rm(path, { recursive: false }))),
903
+ rmSync: ((path, options) => runSync(async () => promises.rm(path, options))),
904
+ statSync: ((path, options) => runSync(async () => promises.stat(path, options))),
905
+ statfsSync: ((path, options) => runSync(async () => promises.statfs(path, options))),
906
+ symlinkSync: ((target, path, type) => runSync(async () => promises.symlink(target, path, type))),
907
+ truncateSync: ((path, len) => runSync(async () => promises.truncate(path, len))),
908
+ unlinkSync: ((path) => runSync(async () => promises.unlink(path))),
909
+ utimesSync: ((path, atime, mtime) => runSync(async () => promises.utimes(path, atime, mtime))),
910
+ writeFileSync: ((file, data, options) => runSync(async () => promises.writeFile(file, data, options))),
911
+ writeSync: ((fd, buffer, offset, length, position) => runSync(async () => core.writeFd(fd, buffer, offset ?? 0, length ?? buffer.byteLength, position == null ? null : Number(position))).bytesWritten),
912
+ writevSync: ((fd, buffers, position) => runSync(async () => core.writevFd(fd, [...buffers], position)).bytesWritten)
913
+ };
914
+ }
915
+
916
+ //#endregion
917
+ Object.defineProperty(exports, 'createStoragePromises', {
918
+ enumerable: true,
919
+ get: function () {
920
+ return createStoragePromises;
921
+ }
922
+ });
923
+ Object.defineProperty(exports, 'mapStorageToFileSystem', {
924
+ enumerable: true,
925
+ get: function () {
926
+ return mapStorageToFileSystem;
927
+ }
928
+ });
929
+ Object.defineProperty(exports, 'normalizeKey', {
930
+ enumerable: true,
931
+ get: function () {
932
+ return normalizeKey;
933
+ }
934
+ });