@livx.cc/native-kit 0.22.0 → 0.23.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livx.cc/native-kit",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Isomorphic native-capabilities kit for PWAs — same API in browser and in an appwrap native shell. Zero dependencies.",
5
5
  "license": "MIT",
6
6
  "author": "Elya Livshitz",
@@ -9,6 +9,7 @@ import { CalendarModule } from '../modules/calendar';
9
9
  import { ClipboardModule } from '../modules/clipboard';
10
10
  import { ContactsModule } from '../modules/contacts';
11
11
  import { DeviceModule } from '../modules/device';
12
+ import { FsModule } from '../modules/fs';
12
13
  import { GeoModule } from '../modules/geo';
13
14
  import { HapticsModule } from '../modules/haptics';
14
15
  import { HealthModule } from '../modules/health';
@@ -73,6 +74,7 @@ export class NativeKit {
73
74
  public readonly screen = new ScreenModule(this);
74
75
  public readonly keyboard = new KeyboardModule(this);
75
76
  public readonly storage = new StorageModule(this);
77
+ public readonly fs = new FsModule(this);
76
78
  public readonly toast = new ToastModule(this);
77
79
  public readonly ui = new UiModule(this);
78
80
  public readonly device = new DeviceModule(this);
@@ -8,6 +8,14 @@ function base64ToBuffer(b64: string): ArrayBuffer {
8
8
  return out.buffer;
9
9
  }
10
10
 
11
+ /** Encode an ArrayBuffer → raw base64 (no `data:` prefix). */
12
+ function bufferToBase64(buf: ArrayBuffer): string {
13
+ const bytes = new Uint8Array(buf);
14
+ let bin = '';
15
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
16
+ return btoa(bin);
17
+ }
18
+
11
19
  /** Map our lock vocabulary to valid ScreenOrientation `OrientationLockType` values. */
12
20
  function toWebOrientation(o: string): any {
13
21
  switch (o) {
@@ -44,6 +52,9 @@ export class WebAdapter implements NativeKitAdapter {
44
52
  orientation: (screen as any)?.orientation ? 'web' : 'none', // Screen Orientation API (lock needs fullscreen)
45
53
  storage: 'web',
46
54
  secureStorage: 'none',
55
+ // OPFS (navigator.storage.getDirectory) backs read/write/list; pickFile falls back to
56
+ // <input type=file> even without OPFS, so 'web' whenever either surface exists.
57
+ fs: n.storage?.getDirectory || typeof document !== 'undefined' ? 'web' : 'none',
47
58
  toast: 'web',
48
59
  statusBar: 'none',
49
60
  device: 'web',
@@ -315,6 +326,26 @@ export class WebAdapter implements NativeKitAdapter {
315
326
  case 'camera.capture':
316
327
  return this.pickImageFile(true, !!p.dataUrl, p.maxSize) as Promise<T>;
317
328
 
329
+ case 'fs.read':
330
+ return this.opfsRead(p.path, p.encoding === 'base64' ? 'base64' : 'utf8') as Promise<T>;
331
+ case 'fs.write':
332
+ return this.opfsWrite(p.path, p.data, p.encoding === 'base64' ? 'base64' : 'utf8', false, !!p.recursive) as Promise<T>;
333
+ case 'fs.append':
334
+ return this.opfsWrite(p.path, p.data, p.encoding === 'base64' ? 'base64' : 'utf8', true, true) as Promise<T>;
335
+ case 'fs.delete':
336
+ return this.opfsDelete(p.path) as Promise<T>;
337
+ case 'fs.list':
338
+ return this.opfsList(p.path) as Promise<T>;
339
+ case 'fs.mkdir':
340
+ return this.opfsMkdir(p.path) as Promise<T>;
341
+ case 'fs.stat':
342
+ return this.opfsStat(p.path) as Promise<T>;
343
+ case 'fs.getUri':
344
+ // OPFS files have no URL the page can hand around — be honest rather than fake one.
345
+ throw new KitError('UNSUPPORTED', 'No file URI on web (OPFS is opaque) — read the bytes instead');
346
+ case 'fs.pickFile':
347
+ return this.pickDocuments(p.types, !!p.multiple) as Promise<T>;
348
+
318
349
  case 'media.configureAudio':
319
350
  return undefined as T; // browser owns the audio session — nothing to tune
320
351
 
@@ -455,6 +486,105 @@ export class WebAdapter implements NativeKitAdapter {
455
486
  });
456
487
  }
457
488
 
489
+ // ── filesystem (Origin Private File System) ─────────────────────────
490
+ // OPFS is one private root per origin — our `dir` enum has no meaning here, so paths resolve
491
+ // straight off the root. Slash-separated paths walk nested dirs.
492
+
493
+ private async opfsRoot(): Promise<any> {
494
+ const dir = (navigator as any).storage?.getDirectory;
495
+ if (!dir) throw new KitError('UNSUPPORTED', 'No OPFS in this browser');
496
+ return (navigator as any).storage.getDirectory();
497
+ }
498
+
499
+ /** Split a path into clean segments, rejecting any `..` so it can't escape the OPFS root. */
500
+ private opfsSegments(path: string): string[] {
501
+ const parts = String(path).split('/').filter(Boolean);
502
+ if (parts.some((seg) => seg === '..')) throw new KitError('NATIVE_ERROR', `Path traversal rejected: ${path}`);
503
+ return parts;
504
+ }
505
+
506
+ /** Walk `path` to its parent dir handle + leaf name. `create` makes intermediate dirs. */
507
+ private async opfsResolveParent(path: string, create: boolean): Promise<{ parent: any; name: string }> {
508
+ const parts = this.opfsSegments(path);
509
+ const name = parts.pop();
510
+ if (!name) throw new KitError('NATIVE_ERROR', 'Empty path');
511
+ let dir = await this.opfsRoot();
512
+ for (const seg of parts) dir = await dir.getDirectoryHandle(seg, { create });
513
+ return { parent: dir, name };
514
+ }
515
+
516
+ private async opfsRead(path: string, encoding: 'utf8' | 'base64'): Promise<string> {
517
+ const { parent, name } = await this.opfsResolveParent(path, false);
518
+ const handle = await parent.getFileHandle(name).catch(() => { throw new KitError('NATIVE_ERROR', `No such file: ${path}`); });
519
+ const file = await handle.getFile();
520
+ if (encoding === 'base64') return bufferToBase64(await file.arrayBuffer());
521
+ return file.text();
522
+ }
523
+
524
+ private async opfsWrite(path: string, data: string, encoding: 'utf8' | 'base64', append: boolean, recursive: boolean): Promise<{ uri: string }> {
525
+ const { parent, name } = await this.opfsResolveParent(path, recursive);
526
+ const handle = await parent.getFileHandle(name, { create: true });
527
+ const writable = await handle.createWritable({ keepExistingData: append });
528
+ if (append) writable.seek?.((await handle.getFile()).size);
529
+ const payload: BlobPart = encoding === 'base64' ? base64ToBuffer(data) : data;
530
+ await writable.write(payload);
531
+ await writable.close();
532
+ return { uri: `opfs:/${path}` };
533
+ }
534
+
535
+ private async opfsDelete(path: string): Promise<void> {
536
+ const { parent, name } = await this.opfsResolveParent(path, false);
537
+ await parent.removeEntry(name, { recursive: false }).catch(() => {}); // no-throw if absent
538
+ }
539
+
540
+ private async opfsList(path: string): Promise<Array<{ name: string; type: 'file' | 'dir' }>> {
541
+ let dir = await this.opfsRoot();
542
+ for (const seg of this.opfsSegments(path)) dir = await dir.getDirectoryHandle(seg);
543
+ const out: Array<{ name: string; type: 'file' | 'dir' }> = [];
544
+ for await (const [name, handle] of (dir as any).entries()) {
545
+ out.push({ name, type: handle.kind === 'directory' ? 'dir' : 'file' });
546
+ }
547
+ return out;
548
+ }
549
+
550
+ private async opfsMkdir(path: string): Promise<void> {
551
+ let dir = await this.opfsRoot();
552
+ for (const seg of this.opfsSegments(path)) dir = await dir.getDirectoryHandle(seg, { create: true });
553
+ }
554
+
555
+ private async opfsStat(path: string): Promise<{ name: string; type: 'file' | 'dir'; size?: number; mtime?: number }> {
556
+ const { parent, name } = await this.opfsResolveParent(path, false);
557
+ const fileHandle = await parent.getFileHandle(name).catch(() => null);
558
+ if (fileHandle) {
559
+ const f = await fileHandle.getFile();
560
+ return { name, type: 'file', size: f.size, mtime: f.lastModified };
561
+ }
562
+ await parent.getDirectoryHandle(name).catch(() => { throw new KitError('NATIVE_ERROR', `No such path: ${path}`); });
563
+ return { name, type: 'dir' };
564
+ }
565
+
566
+ /** Document picker via a hidden `<input type=file>` (works everywhere; reuses the photos pattern). */
567
+ private pickDocuments(types?: string[], multiple = false): Promise<Array<{ name: string; mimeType: string; size: number; base64: string }>> {
568
+ const toPicked = async (file: File) => ({
569
+ name: file.name,
570
+ mimeType: file.type || 'application/octet-stream',
571
+ size: file.size,
572
+ base64: bufferToBase64(await file.arrayBuffer()),
573
+ });
574
+ return new Promise((resolve) => {
575
+ const input = document.createElement('input');
576
+ input.type = 'file';
577
+ if (multiple) input.multiple = true;
578
+ if (types?.length) input.accept = types.join(',');
579
+ input.onchange = async () => {
580
+ const files = Array.from(input.files ?? []);
581
+ resolve(await Promise.all(files.map(toPicked)));
582
+ };
583
+ input.oncancel = () => resolve([]);
584
+ input.click();
585
+ });
586
+ }
587
+
458
588
  /** Minimal action sheet — fixed bottom panel, resolves option index or null on cancel. */
459
589
  private showActionSheet(title: string | undefined, options: string[], cancel: string): Promise<number | null> {
460
590
  return new Promise((resolve) => {
package/src/index.ts CHANGED
@@ -23,6 +23,7 @@ export type { ImpactStyle, NotifyType } from './modules/haptics';
23
23
  export type { SharePayload, ShareFile } from './modules/share';
24
24
  export type { Orientation, OrientationLock } from './modules/screen';
25
25
  export type { KeyboardInfo } from './modules/keyboard';
26
+ export type { FsDirectory, FsEncoding, FsEntry, PickedFile } from './modules/fs';
26
27
  export type { DeviceInfo } from './modules/device';
27
28
  export type { ScheduleOptions } from './modules/notifications';
28
29
  export type { PushMessage, PushPlatform, PushToken } from './modules/push';
@@ -0,0 +1,109 @@
1
+ import type { NativeKit } from '../core/NativeKit';
2
+
3
+ /** App-scoped storage roots — paths are resolved relative to one of these.
4
+ * - `documents`: user-visible (iOS Documents — iCloud-backed-up · Android getExternalFilesDir —
5
+ * NOT auto-backed-up, lives on shared/external storage).
6
+ * - `data`: app-private (iOS Application Support — backed up · Android getFilesDir — included in
7
+ * Auto Backup by default, subject to the app's backup rules). Default.
8
+ * - `cache`: evictable, the OS may purge it and it isn't backed up (iOS Caches · Android getCacheDir). */
9
+ export type FsDirectory = 'documents' | 'data' | 'cache';
10
+
11
+ /** Text vs binary payload encoding. `utf8` reads/writes a string; `base64` a raw byte blob. */
12
+ export type FsEncoding = 'utf8' | 'base64';
13
+
14
+ /** One entry returned by {@link FsModule.list} / {@link FsModule.stat}. */
15
+ export interface FsEntry {
16
+ /** Base name (list) or full relative path (stat input echo). */
17
+ name: string;
18
+ type: 'file' | 'dir';
19
+ /** Bytes for a file; omitted/0 for a dir. */
20
+ size?: number;
21
+ /** Last-modified epoch ms. */
22
+ mtime?: number;
23
+ /** Native URI (`file://` on native, omitted on web). */
24
+ uri?: string;
25
+ }
26
+
27
+ /** A document chosen via {@link FsModule.pickFile}. `base64` carries the bytes inline. */
28
+ export interface PickedFile {
29
+ name: string;
30
+ mimeType: string;
31
+ size: number;
32
+ base64?: string;
33
+ }
34
+
35
+ export interface FsReadOptions { dir?: FsDirectory; encoding?: FsEncoding }
36
+ export interface FsWriteOptions { dir?: FsDirectory; encoding?: FsEncoding; recursive?: boolean }
37
+ export interface FsDirOptions { dir?: FsDirectory }
38
+ export interface FsMkdirOptions { dir?: FsDirectory; recursive?: boolean }
39
+ export interface FsPickOptions {
40
+ /** MIME types / extensions to allow (e.g. `['application/pdf', 'image/*']`). Omit = any. */
41
+ types?: string[];
42
+ /** Allow multi-select (default false). */
43
+ multiple?: boolean;
44
+ }
45
+
46
+ /**
47
+ * Native filesystem + document picker — ONE API across platforms.
48
+ *
49
+ * Read/write/list/stat files under three app-scoped roots ({@link FsDirectory}) plus a system
50
+ * document picker. No runtime permission is needed: every root lives inside the app sandbox and
51
+ * the picker hands back security-scoped (iOS) / SAF (Android) URIs the user explicitly chose.
52
+ *
53
+ * Native (iOS `FileManager`, Android `java.io.File`) → `capability === 'native'`. Web maps file
54
+ * I/O to the Origin Private File System (`'web'` where present, else `'none'`) and `pickFile` to
55
+ * the File System Access API / a hidden `<input type=file>` fallback. Branch on {@link capability}.
56
+ */
57
+ export class FsModule {
58
+ constructor(private kit: NativeKit) {}
59
+
60
+ /** 'native' on a shell · 'web' where OPFS exists · else 'none'. */
61
+ get capability() {
62
+ return this.kit.capability('fs');
63
+ }
64
+
65
+ /** Read a file. `utf8` (default) → string; `base64` → base64 string. */
66
+ read(path: string, opts: FsReadOptions = {}): Promise<string> {
67
+ return this.kit.invoke('fs.read', { path, ...opts });
68
+ }
69
+
70
+ /** Write `data` to `path` (overwrites). `recursive` creates missing parent dirs. → `{ uri }`. */
71
+ write(path: string, data: string, opts: FsWriteOptions = {}): Promise<{ uri: string }> {
72
+ return this.kit.invoke('fs.write', { path, data, ...opts });
73
+ }
74
+
75
+ /** Append `data` to `path` (creates it if absent). */
76
+ append(path: string, data: string, opts: FsWriteOptions = {}): Promise<void> {
77
+ return this.kit.invoke('fs.append', { path, data, ...opts });
78
+ }
79
+
80
+ /** Delete a file or empty directory. No-throw if it doesn't exist. */
81
+ delete(path: string, opts: FsDirOptions = {}): Promise<void> {
82
+ return this.kit.invoke('fs.delete', { path, ...opts });
83
+ }
84
+
85
+ /** List a directory's immediate children. */
86
+ list(path: string, opts: FsDirOptions = {}): Promise<FsEntry[]> {
87
+ return this.kit.invoke('fs.list', { path, ...opts });
88
+ }
89
+
90
+ /** Create a directory. `recursive` (default true) makes intermediate dirs. */
91
+ mkdir(path: string, opts: FsMkdirOptions = {}): Promise<void> {
92
+ return this.kit.invoke('fs.mkdir', { path, ...opts });
93
+ }
94
+
95
+ /** Stat a file/dir → `{ name, type, size, mtime, uri }`. */
96
+ stat(path: string, opts: FsDirOptions = {}): Promise<FsEntry> {
97
+ return this.kit.invoke('fs.stat', { path, ...opts });
98
+ }
99
+
100
+ /** Resolve a path to a URI suitable for `kit.share` (`file://` native, content:// Android). */
101
+ getUri(path: string, opts: FsDirOptions = {}): Promise<string> {
102
+ return this.kit.invoke('fs.getUri', { path, ...opts });
103
+ }
104
+
105
+ /** Open the system document picker. Resolves with the chosen files (bytes inline as base64). */
106
+ pickFile(opts: FsPickOptions = {}): Promise<PickedFile[]> {
107
+ return this.kit.invoke('fs.pickFile', opts);
108
+ }
109
+ }