@livx.cc/native-kit 0.17.0 → 0.18.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.17.0",
3
+ "version": "0.18.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",
@@ -26,6 +26,7 @@ import { ShareModule } from '../modules/share';
26
26
  import { StorageModule } from '../modules/storage';
27
27
  import { ToastModule } from '../modules/toast';
28
28
  import { UiModule } from '../modules/ui';
29
+ import { UpdatesModule } from '../modules/updates';
29
30
 
30
31
  export class NativeKitOptions {
31
32
  /** Priority order; first adapter whose detect() passes wins. */
@@ -91,6 +92,7 @@ export class NativeKit {
91
92
  public readonly browser = new BrowserModule(this);
92
93
  public readonly oauth = new OAuthModule(this);
93
94
  public readonly billing = new BillingModule(this);
95
+ public readonly updates = new UpdatesModule(this);
94
96
 
95
97
  public handshakeInfo: Handshake | null = null;
96
98
  public options: NativeKitOptions;
@@ -121,6 +123,8 @@ export class NativeKit {
121
123
  );
122
124
  }
123
125
  this.handshakeInfo = handshake;
126
+ // Zero-config: a native server-loader app begins polling for remote updates.
127
+ this.updates.__autostart();
124
128
  return this.handshakeInfo;
125
129
  })();
126
130
  }
package/src/core/types.ts CHANGED
@@ -14,6 +14,9 @@ export interface AppInfo {
14
14
  name: string;
15
15
  version: string;
16
16
  build?: string;
17
+ /** How the shell loads content: 'app'/'file' (bundled) or 'server' (remote URL). Drives
18
+ * remote-update detection (only meaningful for 'server'). Absent on web/older shells. */
19
+ loader?: 'app' | 'file' | 'server';
17
20
  }
18
21
 
19
22
  export interface Handshake {
package/src/index.ts CHANGED
@@ -31,6 +31,7 @@ export type { AudioMode, MediaDeviceLite } from './modules/media';
31
31
  export type { NetworkStatus } from './modules/network';
32
32
  export type { ActionOptions, AlertOptions, ConfirmOptions, SafeAreaInsets } from './modules/ui';
33
33
  export type { MotionSample } from './modules/motion';
34
+ export type { UpdateStatus, UpdatesOptions } from './modules/updates';
34
35
  export type { PickedContact } from './modules/contacts';
35
36
  export type { CalendarEventOptions } from './modules/calendar';
36
37
  export type { BrowserOptions } from './modules/browser';
@@ -0,0 +1,164 @@
1
+ import type { NativeKit } from '../core/NativeKit';
2
+ import type { Unsubscribe } from '../core/types';
3
+
4
+ export interface UpdateStatus {
5
+ /** Version the running bundle BOOTED with (embedded), or '' if it couldn't be determined. */
6
+ current: string;
7
+ /** Version advertised by the live manifest, or '' if the fetch failed. */
8
+ latest: string;
9
+ /** Optional build identifier from the manifest. */
10
+ build?: string | number;
11
+ /** True only when both versions are known AND differ — never on an unknown `current`. */
12
+ updateAvailable: boolean;
13
+ }
14
+
15
+ export interface UpdatesOptions {
16
+ /** Version-manifest URL — a tiny JSON `{ version: string, build?: string|number }`.
17
+ * Default: `${location.origin}/version.json`. */
18
+ manifestUrl?: string;
19
+ /** Poll cadence (ms). Always also checks on app resume. 0 = resume-only. Default 60_000. */
20
+ pollIntervalMs?: number;
21
+ /** Version the running bundle booted with. Default: `window.__APP_VERSION__` →
22
+ * `<meta name="app-version">`. Supplying the bundle's OWN embedded version is what
23
+ * makes the prompt trustworthy (see class doc). */
24
+ currentVersion?: string;
25
+ /** Auto-show a persistent native "tap to reload" banner when an update is detected. Default true. */
26
+ autoPrompt?: boolean;
27
+ }
28
+
29
+ /**
30
+ * Remote-update detection for `loader:'server'` apps.
31
+ *
32
+ * Polls a version manifest and compares it to the version the running bundle **booted with**
33
+ * (its embedded `__APP_VERSION__`), NOT to a previous manifest read. That distinction is the
34
+ * whole point: comparing manifest-to-manifest gives a phantom "update available" the moment a
35
+ * deploy bumps the manifest but ships the old bundle (a real bug we've hit). Embedded-vs-manifest
36
+ * only fires when the bytes actually running are behind the deploy.
37
+ *
38
+ * Auto-starts for server-loader native apps (zero app code); apps can also drive it manually via
39
+ * {@link check}/{@link onAvailable}/{@link reload} or re-{@link start} with their own options.
40
+ */
41
+ export class UpdatesModule {
42
+ private started = false;
43
+ private opts: Required<UpdatesOptions> | null = null;
44
+ private timer: ReturnType<typeof setInterval> | null = null;
45
+ private unsubs: Unsubscribe[] = [];
46
+ private listeners = new Set<(s: UpdateStatus) => void>();
47
+ private prompted = false;
48
+
49
+ constructor(private kit: NativeKit) {}
50
+
51
+ get capability() {
52
+ return this.kit.capability('updates');
53
+ }
54
+
55
+ /** Fetch the manifest and compare to the boot version. Reports the result up to the shell
56
+ * (for the dev-menu App Info screen) and fires {@link onAvailable} listeners on a fresh update. */
57
+ async check(): Promise<UpdateStatus> {
58
+ const o = this.opts ?? this.resolveOptions();
59
+ const current = o.currentVersion;
60
+ let latest = '';
61
+ let build: string | number | undefined;
62
+ try {
63
+ // `no-store` skips the HTTP cache — but a cache-first service worker would still intercept and
64
+ // serve a stale manifest, so the SW recipe must let `version.json` pass through to the network.
65
+ const res = await fetch(o.manifestUrl, { cache: 'no-store' });
66
+ if (res.ok) {
67
+ const j = (await res.json()) as { version?: string; build?: string | number };
68
+ latest = String(j?.version ?? '');
69
+ build = j?.build;
70
+ }
71
+ } catch (e) {
72
+ // Offline or no manifest deployed — not fatal; log and report "unknown latest".
73
+ console.warn('[updates] manifest fetch failed:', (e as Error)?.message ?? e);
74
+ }
75
+ const updateAvailable = !!current && !!latest && current !== latest;
76
+ const status: UpdateStatus = { current, latest, build, updateAvailable };
77
+
78
+ // Surface to native so the shake → App Info screen can show "got the latest?".
79
+ this.kit.invoke('app.reportWebVersion', status).catch((e) =>
80
+ console.warn('[updates] reportWebVersion failed:', (e as Error)?.message ?? e)
81
+ );
82
+
83
+ if (updateAvailable) {
84
+ this.listeners.forEach((cb) => cb(status));
85
+ if (o.autoPrompt && !this.prompted) {
86
+ this.prompted = true;
87
+ this.kit
88
+ .invoke('toast.banner', { id: 'appwrap.update', message: 'New version available — tap to reload' })
89
+ .catch((e) => console.warn('[updates] banner failed:', (e as Error)?.message ?? e));
90
+ }
91
+ }
92
+ return status;
93
+ }
94
+
95
+ /** Notify whenever a manifest check finds the running bundle is behind. */
96
+ onAvailable(cb: (s: UpdateStatus) => void): Unsubscribe {
97
+ this.listeners.add(cb);
98
+ return () => this.listeners.delete(cb);
99
+ }
100
+
101
+ /** Hard reload the WebView, bypassing cache (iOS `reloadFromOrigin`, Android cache-clear + reload). */
102
+ reload(): Promise<void> {
103
+ return this.kit.invoke('app.reload');
104
+ }
105
+
106
+ /** Begin polling + resume/banner wiring. Idempotent; re-calling replaces options. */
107
+ start(options?: UpdatesOptions): void {
108
+ this.opts = this.resolveOptions(options);
109
+ if (this.started) {
110
+ this.stop(/* keepStarted */ true);
111
+ }
112
+ this.started = true;
113
+ // A reload picks up the new bundle → allow a fresh prompt next time.
114
+ this.unsubs.push(this.kit.on('app.resume', () => void this.check()));
115
+ // Banner tap (or any 'appwrap.update' action) → reload.
116
+ this.unsubs.push(
117
+ this.kit.on('toast.action', (p) => {
118
+ if ((p as { id?: string })?.id === 'appwrap.update') void this.reload();
119
+ })
120
+ );
121
+ if (this.opts.pollIntervalMs > 0) {
122
+ this.timer = setInterval(() => void this.check(), this.opts.pollIntervalMs);
123
+ }
124
+ void this.check();
125
+ }
126
+
127
+ stop(keepStarted = false): void {
128
+ if (this.timer) clearInterval(this.timer);
129
+ this.timer = null;
130
+ this.unsubs.forEach((u) => u());
131
+ this.unsubs = [];
132
+ if (!keepStarted) this.started = false;
133
+ }
134
+
135
+ /** Called by NativeKit.ready() — self-starts only for a native server-loader app. */
136
+ __autostart(): void {
137
+ if (this.started) return;
138
+ if (this.kit.is.native && this.kit.handshakeInfo?.app?.loader === 'server') this.start();
139
+ }
140
+
141
+ private resolveOptions(o?: UpdatesOptions): Required<UpdatesOptions> {
142
+ const origin = typeof location !== 'undefined' ? location.origin : '';
143
+ return {
144
+ manifestUrl: o?.manifestUrl ?? `${origin}/version.json`,
145
+ pollIntervalMs: o?.pollIntervalMs ?? 60_000,
146
+ currentVersion: o?.currentVersion ?? bootVersion(),
147
+ autoPrompt: o?.autoPrompt ?? true,
148
+ };
149
+ }
150
+ }
151
+
152
+ /** Embedded version the running bundle shipped with: `window.__APP_VERSION__`, then a
153
+ * `<meta name="app-version">` tag. '' (unknown) when neither is present — in which case we never
154
+ * raise a false update prompt. */
155
+ function bootVersion(): string {
156
+ const g = typeof window !== 'undefined' ? (window as any).__APP_VERSION__ : undefined;
157
+ if (g) return String(g);
158
+ if (typeof document !== 'undefined') {
159
+ const meta = document.querySelector('meta[name="app-version"]');
160
+ const c = meta?.getAttribute('content');
161
+ if (c) return c;
162
+ }
163
+ return '';
164
+ }