@glassly/miniapp 0.4.1 → 0.4.2-beta.1188

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 (83) hide show
  1. package/README.md +1 -0
  2. package/dist/display/index.d.ts +14 -4
  3. package/dist/display/index.d.ts.map +1 -1
  4. package/dist/display/index.js +11 -4
  5. package/dist/display/index.js.map +1 -1
  6. package/dist/display/measurer/script-detection.d.ts +1 -1
  7. package/dist/display/measurer/script-detection.d.ts.map +1 -1
  8. package/dist/display/measurer/script-detection.js +46 -10
  9. package/dist/display/measurer/script-detection.js.map +1 -1
  10. package/dist/display/profiles/index.d.ts +1 -1
  11. package/dist/display/profiles/index.d.ts.map +1 -1
  12. package/dist/display/profiles/index.js +1 -1
  13. package/dist/display/profiles/index.js.map +1 -1
  14. package/dist/display/profiles/nimo.d.ts +6 -0
  15. package/dist/display/profiles/nimo.d.ts.map +1 -1
  16. package/dist/display/profiles/nimo.js +17 -0
  17. package/dist/display/profiles/nimo.js.map +1 -1
  18. package/dist/display/scene/anchor.d.ts +16 -0
  19. package/dist/display/scene/anchor.d.ts.map +1 -0
  20. package/dist/display/scene/anchor.js +32 -0
  21. package/dist/display/scene/anchor.js.map +1 -0
  22. package/dist/display/scene/degrade.d.ts +25 -0
  23. package/dist/display/scene/degrade.d.ts.map +1 -0
  24. package/dist/display/scene/degrade.js +67 -0
  25. package/dist/display/scene/degrade.js.map +1 -0
  26. package/dist/display/scene/differ.d.ts +50 -0
  27. package/dist/display/scene/differ.d.ts.map +1 -0
  28. package/dist/display/scene/differ.js +129 -0
  29. package/dist/display/scene/differ.js.map +1 -0
  30. package/dist/display/scene/process.d.ts +41 -0
  31. package/dist/display/scene/process.d.ts.map +1 -0
  32. package/dist/display/scene/process.js +408 -0
  33. package/dist/display/scene/process.js.map +1 -0
  34. package/dist/display/scene/store.d.ts +48 -0
  35. package/dist/display/scene/store.d.ts.map +1 -0
  36. package/dist/display/scene/store.js +0 -0
  37. package/dist/display/scene/store.js.map +1 -0
  38. package/dist/display/scene/svgPath.d.ts +9 -0
  39. package/dist/display/scene/svgPath.d.ts.map +1 -0
  40. package/dist/display/scene/svgPath.js +167 -0
  41. package/dist/display/scene/svgPath.js.map +1 -0
  42. package/dist/host/index.d.ts +7 -0
  43. package/dist/host/index.d.ts.map +1 -0
  44. package/dist/host/index.js +7 -0
  45. package/dist/host/index.js.map +1 -0
  46. package/dist/host/uiShim.d.ts +38 -0
  47. package/dist/host/uiShim.d.ts.map +1 -0
  48. package/dist/host/uiShim.js +383 -0
  49. package/dist/host/uiShim.js.map +1 -0
  50. package/dist/host/webviewGlobals.d.ts +60 -0
  51. package/dist/host/webviewGlobals.d.ts.map +1 -0
  52. package/dist/host/webviewGlobals.js +211 -0
  53. package/dist/host/webviewGlobals.js.map +1 -0
  54. package/dist/mirror/canvas.d.ts +13 -2
  55. package/dist/mirror/canvas.d.ts.map +1 -1
  56. package/dist/mirror/canvas.js +42 -21
  57. package/dist/mirror/canvas.js.map +1 -1
  58. package/dist/mirror/index.d.ts +1 -1
  59. package/dist/mirror/index.d.ts.map +1 -1
  60. package/dist/mirror/index.js.map +1 -1
  61. package/dist/modules/display.d.ts +10 -0
  62. package/dist/modules/display.d.ts.map +1 -1
  63. package/dist/modules/display.js.map +1 -1
  64. package/dist/ui/index.d.ts +1 -1
  65. package/dist/ui/index.js +1 -1
  66. package/package.json +6 -2
  67. package/src/display/index.ts +15 -3
  68. package/src/display/measurer/script-detection.ts +47 -10
  69. package/src/display/profiles/index.ts +1 -1
  70. package/src/display/profiles/nimo.ts +18 -0
  71. package/src/display/scene/anchor.ts +38 -0
  72. package/src/display/scene/degrade.ts +83 -0
  73. package/src/display/scene/differ.ts +152 -0
  74. package/src/display/scene/process.ts +443 -0
  75. package/src/display/scene/store.ts +0 -0
  76. package/src/display/scene/svgPath.ts +163 -0
  77. package/src/host/index.ts +14 -0
  78. package/src/host/uiShim.ts +389 -0
  79. package/src/host/webviewGlobals.ts +251 -0
  80. package/src/mirror/canvas.ts +86 -43
  81. package/src/mirror/index.ts +1 -1
  82. package/src/modules/display.ts +4 -0
  83. package/src/ui/index.ts +1 -1
@@ -0,0 +1,383 @@
1
+ /**
2
+ * window.glassly — WebView-side bridge to the per-miniapp background JSContext.
3
+ *
4
+ * Injected into every UI WebView via `injectedJavaScriptBeforeContentLoaded`
5
+ * (iOS) or `injectedJavaScriptObject` + a bundler-emitted inline `<script>`
6
+ * (Android, where the `BeforeContentLoaded` prop is documented unreliable
7
+ * per react-native-webview issues #1099 / #1609).
8
+ *
9
+ * The shim:
10
+ * - Buffers `glassly.send(channel, payload)` calls until `glassly.ready()`
11
+ * fires + the host acks the channel is open. WebView-side BUFFERS (the
12
+ * WebView is the short-lived side and shouldn't drop user input).
13
+ * - Installs `window.__host.recv(envelope)` for the host to push
14
+ * background → WebView messages via `webview.injectJavaScript(...)`.
15
+ * - Sends `__heartbeat__` every 5s; host considers the WebView gone
16
+ * after 15s of silence.
17
+ * - Maintains monotonic seq numbers; the host's per-WebView dedup window
18
+ * drops replays during reconnect.
19
+ *
20
+ * This file exports a `buildUiShim()` function returning the JS
21
+ * source as a string. The host's UIRouter wraps it inside the
22
+ * existing WebView setup so a single bundler-time string emission covers
23
+ * both platforms.
24
+ *
25
+ * IMPORTANT: the shim runs in the WebView's bare ECMAScript scope before
26
+ * the miniapp's bundle. It must not import anything; the source is one
27
+ * IIFE. The only injected dependencies are
28
+ * `window.ReactNativeWebView.postMessage` (provided by react-native-webview)
29
+ * and (on Android) `window.ReactNativeWebView.injectedObjectJson()`
30
+ * (provided when the host sets `injectedJavaScriptObject`).
31
+ */
32
+ export function buildUiShim(options) {
33
+ const packageNameJson = JSON.stringify(options.packageName);
34
+ // The IIFE assembles a typed `glassly` global plus an internal
35
+ // `__host` for host inbound calls. Quoted strings are JSON-safe so
36
+ // direct injection inside another JS literal also works.
37
+ return `
38
+ (function () {
39
+ if (typeof window === 'undefined') return;
40
+ if (window.glassly && window.__host) return;
41
+ var packageName = ${packageNameJson};
42
+ // Resolve window.ReactNativeWebView.postMessage LAZILY, not once at shim-eval.
43
+ // On Android the shim is injected as a WebViewCompat document-start script
44
+ // (so it beats the page bundle and the ready handshake can't be raced — see
45
+ // the react-native-webview patch). But the order in which that document-start
46
+ // script runs vs. the WebMessageListener that installs
47
+ // window.ReactNativeWebView is not contractually fixed on Android the way it
48
+ // is on iOS (postMessageScript is registered before atStartScript there). If
49
+ // we captured rnPost once and the bridge object wasn't installed yet, every
50
+ // postMessage — including {type:'ready'} — would be silently dropped and the
51
+ // splash would hang forever. Resolving per-call means we always pick up the
52
+ // bridge once it exists, which it reliably does by the time the bundle mounts
53
+ // and calls glassly.ready().
54
+ function getRnPost() {
55
+ try {
56
+ return window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === 'function'
57
+ ? window.ReactNativeWebView.postMessage.bind(window.ReactNativeWebView)
58
+ : null;
59
+ } catch (e) { return null; }
60
+ }
61
+
62
+ // Outbound seq number — purely a log-correlation aid (the host's
63
+ // router doesn't dedup anymore since reconnect can't happen: one
64
+ // WebView, foreground-only, destroyed on close → fresh shim on
65
+ // next open).
66
+ var outboundSeq = 1;
67
+ var ready = false;
68
+ var channelHandlers = Object.create(null);
69
+ var openHandlers = [];
70
+ var closeHandlers = [];
71
+ // Queued glassly.send calls before glassly.ready() acks. FIFO drained
72
+ // on ack. Buffered so user input (button taps, etc.) isn't dropped
73
+ // when the WebView mounts faster than the host expects.
74
+ var outboundQueue = [];
75
+ // Inbound payloads that arrived before any glassly.on subscriber was
76
+ // registered for the channel. The background side fires
77
+ // session.ui.onOpen handlers as soon as the WebView posts {type:'ready'},
78
+ // and on a fast bridge the resulting ui.send round-trips back before
79
+ // React useEffects have had a chance to attach listeners. Without
80
+ // buffering, the very first snapshot (the one a controller pushes from
81
+ // its ui.onOpen handler to hydrate the fresh UI) is silently dropped.
82
+ //
83
+ // Drain policy: the queue for a channel is flushed into the FIRST
84
+ // glassly.on(channel, ...) subscriber, then discarded. Subsequent
85
+ // sends with no listener fall back to the old drop-on-floor behaviour
86
+ // — we don't want a re-subscribe to replay stale state.
87
+ //
88
+ // Cap: 32 entries per channel, oldest dropped on overflow. Bounds the
89
+ // memory cost when a controller pushes to a channel that no UI page
90
+ // ever subscribes to.
91
+ var pendingByChannel = Object.create(null);
92
+ var PENDING_CAP_PER_CHANNEL = 32;
93
+
94
+ function postEnvelope(envelope) {
95
+ var rnPost = getRnPost();
96
+ if (!rnPost) return;
97
+ try { rnPost(JSON.stringify(envelope)); } catch (_) {}
98
+ }
99
+
100
+ function send(channel, payload) {
101
+ var seq = outboundSeq++;
102
+ var envelope = { type: 'msg', seq: seq, channel: String(channel), payload: payload };
103
+ if (!ready) {
104
+ outboundQueue.push(envelope);
105
+ return;
106
+ }
107
+ postEnvelope(envelope);
108
+ }
109
+
110
+ function flushQueue() {
111
+ while (outboundQueue.length > 0) {
112
+ postEnvelope(outboundQueue.shift());
113
+ }
114
+ }
115
+
116
+ // NOTE: console.* tap lives in webviewGlobals.ts (injected alongside
117
+ // this shim for every UI WebView, two-layer or single-bundle). That
118
+ // shim posts {payload:{type:"dev_log", ...}} envelopes which
119
+ // LocalMiniappRuntime forwards to the dev sidecar tagged source:"ui".
120
+ // We don't re-wrap here to avoid double-delivery.
121
+
122
+ function on(channel, cb) {
123
+ if (typeof cb !== 'function') return function () {};
124
+ var list = channelHandlers[channel];
125
+ var firstSubscriber = !list || list.length === 0;
126
+ if (!list) { list = []; channelHandlers[channel] = list; }
127
+ list.push(cb);
128
+ // Drain any payloads buffered before this channel had a listener.
129
+ // Only fired on the first subscriber for the channel — a later
130
+ // re-subscribe (after an unsubscribe) does NOT replay history.
131
+ if (firstSubscriber) {
132
+ var pending = pendingByChannel[channel];
133
+ if (pending) {
134
+ delete pendingByChannel[channel];
135
+ for (var i = 0; i < pending.length; i++) {
136
+ try { cb(pending[i]); } catch (e) {}
137
+ }
138
+ }
139
+ }
140
+ return function () {
141
+ var idx = list.indexOf(cb);
142
+ if (idx >= 0) list.splice(idx, 1);
143
+ };
144
+ }
145
+
146
+ // ── RPC ─────────────────────────────────────────────────────────────
147
+ // Outbound RPC: every glassly.request() generates a request id, sends a
148
+ // 'msg' envelope tagged with requestId, and stashes a one-shot resolver
149
+ // keyed on the id. The background-side reply is a recv('msg') with the
150
+ // same channel + requestId; we route it directly to the resolver.
151
+ //
152
+ // Cancellation: caller's AbortSignal triggers a 'cancel' envelope to
153
+ // background and rejects the local promise with a DOM-standard
154
+ // AbortError. The background side's UI_CANCEL handler aborts the
155
+ // handler's ctx.signal and drops the reply.
156
+ var rpcCounter = 0;
157
+ var rpcInflight = Object.create(null);
158
+
159
+ function makeRequestId() {
160
+ rpcCounter += 1;
161
+ return 'r' + rpcCounter + '-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
162
+ }
163
+
164
+ function RpcError(message, code, stage, transport) {
165
+ var e = new Error(message);
166
+ e.name = 'RpcError';
167
+ if (code) {
168
+ try { e.cause = {code: code}; } catch (_) { /* old runtimes */ }
169
+ e.code = code;
170
+ }
171
+ // Diagnostic fields ride as own props so a miniapp can show exactly which
172
+ // pipeline stage and transport failed, not just a message string.
173
+ if (stage) e.stage = stage;
174
+ if (transport) e.transport = transport;
175
+ return e;
176
+ }
177
+
178
+ function RpcTimeoutError(message) {
179
+ var e = new Error(message || 'RPC timed out');
180
+ e.name = 'RpcTimeoutError';
181
+ return e;
182
+ }
183
+
184
+ function makeAbortError() {
185
+ var e;
186
+ try { e = new DOMException('aborted', 'AbortError'); } catch (_) {
187
+ e = new Error('aborted');
188
+ e.name = 'AbortError';
189
+ }
190
+ return e;
191
+ }
192
+
193
+ function request(channel, payload, options) {
194
+ var opts = options || {};
195
+ var signal = opts.signal;
196
+ var timeoutMs = typeof opts.timeout === 'number' ? opts.timeout : null;
197
+ var id = makeRequestId();
198
+
199
+ return new Promise(function (resolve, reject) {
200
+ var done = false;
201
+ var timeoutHandle = null;
202
+ var abortListener = null;
203
+
204
+ function cleanup() {
205
+ if (done) return;
206
+ done = true;
207
+ delete rpcInflight[id];
208
+ if (timeoutHandle != null) { clearTimeout(timeoutHandle); timeoutHandle = null; }
209
+ if (signal && abortListener) {
210
+ try { signal.removeEventListener('abort', abortListener); } catch (_) {}
211
+ }
212
+ }
213
+
214
+ function settle(envelope) {
215
+ if (done) return;
216
+ cleanup();
217
+ if (envelope && envelope.ok === true) {
218
+ resolve(envelope.result);
219
+ } else if (envelope && envelope.ok === false) {
220
+ reject(RpcError(envelope.error && envelope.error.message || 'RPC failed', envelope.error && envelope.error.code, envelope.error && envelope.error.stage, envelope.error && envelope.error.transport));
221
+ } else {
222
+ reject(RpcError('malformed RPC reply'));
223
+ }
224
+ }
225
+
226
+ rpcInflight[id] = settle;
227
+
228
+ if (signal) {
229
+ if (signal.aborted) {
230
+ cleanup();
231
+ reject(makeAbortError());
232
+ return;
233
+ }
234
+ abortListener = function () {
235
+ if (done) return;
236
+ cleanup();
237
+ postEnvelope({type: 'cancel', requestId: id});
238
+ reject(makeAbortError());
239
+ };
240
+ try { signal.addEventListener('abort', abortListener); } catch (_) {}
241
+ }
242
+
243
+ if (timeoutMs != null) {
244
+ timeoutHandle = setTimeout(function () {
245
+ if (done) return;
246
+ cleanup();
247
+ postEnvelope({type: 'cancel', requestId: id});
248
+ reject(RpcTimeoutError());
249
+ }, timeoutMs);
250
+ }
251
+
252
+ var envelope = {type: 'msg', seq: outboundSeq++, channel: String(channel), payload: payload, requestId: id};
253
+ if (!ready) {
254
+ outboundQueue.push(envelope);
255
+ return;
256
+ }
257
+ postEnvelope(envelope);
258
+ });
259
+ }
260
+
261
+ function onOpen(cb) {
262
+ if (typeof cb !== 'function') return function () {};
263
+ openHandlers.push(cb);
264
+ if (ready) {
265
+ try { cb(); } catch (e) {}
266
+ }
267
+ return function () {
268
+ var idx = openHandlers.indexOf(cb);
269
+ if (idx >= 0) openHandlers.splice(idx, 1);
270
+ };
271
+ }
272
+
273
+ function onClose(cb) {
274
+ if (typeof cb !== 'function') return function () {};
275
+ closeHandlers.push(cb);
276
+ return function () {
277
+ var idx = closeHandlers.indexOf(cb);
278
+ if (idx >= 0) closeHandlers.splice(idx, 1);
279
+ };
280
+ }
281
+
282
+ function readyFn() {
283
+ if (ready) return;
284
+ ready = true;
285
+ postEnvelope({ type: 'ready' });
286
+ flushQueue();
287
+ for (var i = 0; i < openHandlers.length; i++) {
288
+ try { openHandlers[i](); } catch (e) {}
289
+ }
290
+ }
291
+
292
+ function setBackgroundColorFn(color) {
293
+ // Tells the host what to paint the native WebView layer (the surface
294
+ // exposed during keyboard push-up / resize animations, which page CSS
295
+ // cannot reach). Host validates and falls back to its theme background.
296
+ if (typeof color !== 'string' || !color) return;
297
+ postEnvelope({ type: 'set_background', color: color });
298
+ }
299
+
300
+ var backHandler = null;
301
+
302
+ function setBackActionFn(handler) {
303
+ backHandler = typeof handler === 'function' ? handler : null;
304
+ postEnvelope({ type: 'set_back_action', shown: backHandler !== null });
305
+ }
306
+
307
+ function fireChannel(channel, payload) {
308
+ var list = channelHandlers[channel];
309
+ if (!list || list.length === 0) {
310
+ // No subscriber yet — stash for the first glassly.on(channel, ...).
311
+ // Bounded FIFO: drop the oldest when capped so a stuck channel
312
+ // can't grow unbounded.
313
+ var q = pendingByChannel[channel];
314
+ if (!q) { q = []; pendingByChannel[channel] = q; }
315
+ q.push(payload);
316
+ if (q.length > PENDING_CAP_PER_CHANNEL) q.shift();
317
+ return;
318
+ }
319
+ for (var i = 0; i < list.length; i++) {
320
+ try { list[i](payload); } catch (e) {}
321
+ }
322
+ }
323
+
324
+ function recv(envelope) {
325
+ if (!envelope || typeof envelope !== 'object') return;
326
+ var type = envelope.type;
327
+ if (type === 'msg' && typeof envelope.channel === 'string') {
328
+ // RPC frames carry a requestId; broadcast frames don't. Treat them
329
+ // as disjoint — never fall through from RPC to broadcast. An orphan
330
+ // RPC reply (caller already aborted/timed out) is silently dropped.
331
+ if (typeof envelope.requestId === 'string') {
332
+ var settle = rpcInflight[envelope.requestId];
333
+ if (settle) settle(envelope.payload);
334
+ return;
335
+ }
336
+ fireChannel(envelope.channel, envelope.payload);
337
+ return;
338
+ }
339
+ if (type === 'open') {
340
+ for (var j = 0; j < openHandlers.length; j++) {
341
+ try { openHandlers[j](); } catch (e) {}
342
+ }
343
+ return;
344
+ }
345
+ if (type === 'close') {
346
+ for (var k = 0; k < closeHandlers.length; k++) {
347
+ try { closeHandlers[k](); } catch (e) {}
348
+ }
349
+ return;
350
+ }
351
+ if (type === 'back') {
352
+ if (backHandler) {
353
+ try { backHandler(); } catch (e) {}
354
+ }
355
+ return;
356
+ }
357
+ if (type === 'cancel' && typeof envelope.requestId === 'string') {
358
+ // Background-side cancel (reserved; currently unused). If we had a
359
+ // future bidirectional RPC this would abort an in-flight UI handler.
360
+ return;
361
+ }
362
+ if (type === 'ack') {
363
+ return;
364
+ }
365
+ }
366
+
367
+ window.glassly = {
368
+ send: send,
369
+ on: on,
370
+ request: request,
371
+ onOpen: onOpen,
372
+ onClose: onClose,
373
+ ready: readyFn,
374
+ setBackgroundColor: setBackgroundColorFn,
375
+ setBackAction: setBackActionFn,
376
+ /** @internal — packageName for diagnostic logs only. */
377
+ _packageName: packageName,
378
+ };
379
+ window.__host = { recv: recv };
380
+ })();
381
+ `.trim();
382
+ }
383
+ //# sourceMappingURL=uiShim.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uiShim.js","sourceRoot":"","sources":["../../src/host/uiShim.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAQH,MAAM,UAAU,WAAW,CAAC,OAAsB;IAChD,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,WAAW,CAAC,CAAA;IAC3D,+DAA+D;IAC/D,mEAAmE;IACnE,yDAAyD;IACzD,OAAO;;;;sBAIa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoVpC,CAAC,IAAI,EAAE,CAAA;AACR,CAAC"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Builder for the window.Glassly globals a host injects into every miniapp
3
+ * WebView before its content loads. The Glassly App and the desktop simulator
4
+ * both inject this script, so a page sees the same API surface in either.
5
+ */
6
+ import type { MiniappColorScheme } from "../globals";
7
+ export type { MiniappColorScheme };
8
+ export interface MiniappSafeArea {
9
+ top: number;
10
+ bottom: number;
11
+ left: number;
12
+ right: number;
13
+ }
14
+ /**
15
+ * The host's capsule menu in the WebView's own coordinate space. `corner`
16
+ * floats over the page's top-right; `rail` sits in the iPhone Duo's status
17
+ * rail, inside the side safe-area inset and clear of the page content.
18
+ */
19
+ export interface CapsuleMenuRect {
20
+ top: number;
21
+ right: number;
22
+ bottom: number;
23
+ left: number;
24
+ width: number;
25
+ height: number;
26
+ placement: "corner" | "rail";
27
+ }
28
+ export interface BuildWebviewGlobalsOptions {
29
+ platform: string;
30
+ packageName?: string;
31
+ capabilities?: string[];
32
+ miniappLocal?: boolean;
33
+ miniappDeveloperMode?: boolean;
34
+ safeAreaInsets: MiniappSafeArea;
35
+ /** Where the host draws its capsule menu over this WebView. */
36
+ capsuleMenu: CapsuleMenuRect;
37
+ /** Current host color scheme. Miniapps may follow this to match the phone. */
38
+ colorScheme?: MiniappColorScheme;
39
+ }
40
+ /**
41
+ * JS to inject into a running miniapp when the host's safe area or capsule
42
+ * menu moves (an iPhone Duo folding, or its rail's reserved regions growing):
43
+ * updates window.Glassly and the CSS variables, then fires
44
+ * `glassly:safe-area-change`.
45
+ */
46
+ export declare function buildSafeAreaUpdateScript(insets: MiniappSafeArea, capsuleMenu: CapsuleMenuRect): string;
47
+ /**
48
+ * Returns the JS string to inject into a miniapp WebView before its content
49
+ * loads. Sets window.Glassly with the standard fields miniapps read:
50
+ *
51
+ * window.Glassly = {
52
+ * platform, packageName?, capabilities, safeAreaInsets, capsuleMenu,
53
+ * miniappLocal?, miniappDeveloperMode?
54
+ * }
55
+ *
56
+ * Also defines a stub window.receiveNativeMessage so the miniapp can safely
57
+ * assign to it before the native bridge wires in.
58
+ */
59
+ export declare function buildWebviewGlobalsScript(opts: BuildWebviewGlobalsOptions): string;
60
+ //# sourceMappingURL=webviewGlobals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webviewGlobals.d.ts","sourceRoot":"","sources":["../../src/host/webviewGlobals.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,YAAY,CAAA;AAElD,YAAY,EAAC,kBAAkB,EAAC,CAAA;AAEhC,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAA;IACX,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;CACd;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,QAAQ,GAAG,MAAM,CAAA;CAC7B;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,EAAE,MAAM,CAAA;IAChB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;IACvB,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,cAAc,EAAE,eAAe,CAAA;IAC/B,+DAA+D;IAC/D,WAAW,EAAE,eAAe,CAAA;IAC5B,8EAA8E;IAC9E,WAAW,CAAC,EAAE,kBAAkB,CAAA;CACjC;AAwBD;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,GAAG,MAAM,CAcvG;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,0BAA0B,GAAG,MAAM,CAqJlF"}
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Builder for the window.Glassly globals a host injects into every miniapp
3
+ * WebView before its content loads. The Glassly App and the desktop simulator
4
+ * both inject this script, so a page sees the same API surface in either.
5
+ */
6
+ // CSS custom properties that mirror the safe-area and capsule menu data, so
7
+ // miniapp CSS (or Tailwind arbitrary values) can read them without touching
8
+ // JS: e.g. `style="margin-top: var(--glassly-capsule-top)"`.
9
+ function layoutCssVars(insets, capsule) {
10
+ return {
11
+ "--glassly-safe-top": `${insets.top}px`,
12
+ "--glassly-safe-bottom": `${insets.bottom}px`,
13
+ "--glassly-safe-left": `${insets.left}px`,
14
+ "--glassly-safe-right": `${insets.right}px`,
15
+ "--glassly-capsule-top": `${capsule.top}px`,
16
+ "--glassly-capsule-bottom": `${capsule.bottom}px`,
17
+ "--glassly-capsule-left": `${capsule.left}px`,
18
+ "--glassly-capsule-right": `${capsule.right}px`,
19
+ "--glassly-capsule-width": `${capsule.width}px`,
20
+ "--glassly-capsule-height": `${capsule.height}px`,
21
+ "--glassly-capsule-center-y": `${capsule.top + capsule.height / 2}px`,
22
+ // Right-side gutter to reserve so content doesn't slide under the
23
+ // capsule: its width + 16px breathing room, none when it sits in the rail.
24
+ "--glassly-capsule-gutter": `${capsule.placement === "rail" ? 0 : capsule.width + 16}px`,
25
+ };
26
+ }
27
+ /**
28
+ * JS to inject into a running miniapp when the host's safe area or capsule
29
+ * menu moves (an iPhone Duo folding, or its rail's reserved regions growing):
30
+ * updates window.Glassly and the CSS variables, then fires
31
+ * `glassly:safe-area-change`.
32
+ */
33
+ export function buildSafeAreaUpdateScript(insets, capsuleMenu) {
34
+ const sets = Object.entries(layoutCssVars(insets, capsuleMenu))
35
+ .map(([k, v]) => `document.documentElement.style.setProperty(${JSON.stringify(k)}, ${JSON.stringify(v)});`)
36
+ .join("\n ");
37
+ return `
38
+ window.Glassly = window.Glassly || {};
39
+ window.Glassly.safeAreaInsets = ${JSON.stringify(insets)};
40
+ window.Glassly.capsuleMenu = ${JSON.stringify(capsuleMenu)};
41
+ try {
42
+ ${sets}
43
+ } catch (e) { /* ignore */ }
44
+ window.dispatchEvent(new Event("glassly:safe-area-change"));
45
+ true;
46
+ `;
47
+ }
48
+ /**
49
+ * Returns the JS string to inject into a miniapp WebView before its content
50
+ * loads. Sets window.Glassly with the standard fields miniapps read:
51
+ *
52
+ * window.Glassly = {
53
+ * platform, packageName?, capabilities, safeAreaInsets, capsuleMenu,
54
+ * miniappLocal?, miniappDeveloperMode?
55
+ * }
56
+ *
57
+ * Also defines a stub window.receiveNativeMessage so the miniapp can safely
58
+ * assign to it before the native bridge wires in.
59
+ */
60
+ export function buildWebviewGlobalsScript(opts) {
61
+ const globals = {
62
+ platform: opts.platform,
63
+ capabilities: opts.capabilities ?? ["share", "open_url", "copy_clipboard", "download"],
64
+ safeAreaInsets: opts.safeAreaInsets,
65
+ capsuleMenu: opts.capsuleMenu,
66
+ };
67
+ if (opts.packageName)
68
+ globals.packageName = opts.packageName;
69
+ if (opts.miniappLocal)
70
+ globals.miniappLocal = true;
71
+ if (opts.miniappDeveloperMode)
72
+ globals.miniappDeveloperMode = true;
73
+ if (opts.colorScheme)
74
+ globals.colorScheme = opts.colorScheme;
75
+ const cssVars = layoutCssVars(opts.safeAreaInsets, opts.capsuleMenu);
76
+ const cssVarsBlock = Object.entries(cssVars)
77
+ .map(([k, v]) => `${k}: ${v};`)
78
+ .join(" ");
79
+ // Console-tap shim: wrap console.log/warn/error/info/debug so each call
80
+ // also forwards a `dev_log` envelope back to the phone via
81
+ // ReactNativeWebView.postMessage. Dev mode forwards to the laptop's
82
+ // `glassly dev` terminal; non-dev mode falls back to the React
83
+ // Native log stream (Metro / Xcode console / adb logcat) so installed-
84
+ // miniapp errors are still inspectable when there's no laptop sidecar.
85
+ //
86
+ // Also tap window.onerror and window.onunhandledrejection so synchronous
87
+ // throws and unhandled promise rejections surface even when the bundle
88
+ // never gets a chance to call console.error itself.
89
+ const consoleTapBlock = `
90
+ (function() {
91
+ try {
92
+ var levels = ["log", "warn", "error", "info", "debug"];
93
+ var seen = new WeakSet();
94
+ function safeSerialize(arg) {
95
+ if (arg instanceof Error) return {__error: true, message: arg.message, stack: arg.stack};
96
+ if (arg === null || typeof arg !== "object") return arg;
97
+ try {
98
+ return JSON.parse(JSON.stringify(arg, function(k, v) {
99
+ if (v !== null && typeof v === "object") {
100
+ if (seen.has(v)) return "[Circular]";
101
+ seen.add(v);
102
+ }
103
+ return v;
104
+ }));
105
+ } catch (e) {
106
+ try { return String(arg); } catch (_) { return "[unserializable]"; }
107
+ }
108
+ }
109
+ levels.forEach(function(level) {
110
+ var original = console[level];
111
+ if (typeof original !== "function") return;
112
+ console[level] = function() {
113
+ try { original.apply(console, arguments); } catch (_) {}
114
+ try {
115
+ var args = Array.prototype.slice.call(arguments).map(safeSerialize);
116
+ if (window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === "function") {
117
+ window.ReactNativeWebView.postMessage(JSON.stringify({
118
+ payload: {
119
+ type: "dev_log",
120
+ level: level,
121
+ args: args,
122
+ packageName: (window.Glassly && window.Glassly.packageName) || null,
123
+ timestamp: Date.now()
124
+ }
125
+ }));
126
+ }
127
+ } catch (_) { /* swallow */ }
128
+ };
129
+ });
130
+ } catch (_) { /* ignore */ }
131
+
132
+ // Surface synchronous errors and unhandled promise rejections via the
133
+ // same dev_log channel — many bundle-startup crashes never get to call
134
+ // console.error themselves.
135
+ try {
136
+ window.addEventListener("error", function(e) {
137
+ try {
138
+ if (window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === "function") {
139
+ window.ReactNativeWebView.postMessage(JSON.stringify({
140
+ payload: {
141
+ type: "dev_log",
142
+ level: "error",
143
+ args: ["[window.error] " + (e.message || "unknown"), {filename: e.filename, lineno: e.lineno, colno: e.colno, stack: e.error && e.error.stack}],
144
+ packageName: (window.Glassly && window.Glassly.packageName) || null,
145
+ timestamp: Date.now()
146
+ }
147
+ }));
148
+ }
149
+ } catch (_) {}
150
+ });
151
+ window.addEventListener("unhandledrejection", function(e) {
152
+ try {
153
+ if (window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === "function") {
154
+ var reason = e.reason;
155
+ var serialized = reason instanceof Error
156
+ ? {__error: true, message: reason.message, stack: reason.stack}
157
+ : (typeof reason === "object" ? JSON.stringify(reason) : String(reason));
158
+ window.ReactNativeWebView.postMessage(JSON.stringify({
159
+ payload: {
160
+ type: "dev_log",
161
+ level: "error",
162
+ args: ["[unhandledrejection]", serialized],
163
+ packageName: (window.Glassly && window.Glassly.packageName) || null,
164
+ timestamp: Date.now()
165
+ }
166
+ }));
167
+ }
168
+ } catch (_) {}
169
+ });
170
+ } catch (_) {}
171
+ })();
172
+ `;
173
+ // Lock zoom so miniapps feel like apps, not pages: force a non-scalable
174
+ // viewport meta (overriding whatever the miniapp shipped) and disable
175
+ // double-tap-zoom via CSS. Re-applies on DOMContentLoaded in case the
176
+ // miniapp re-writes <head> during boot.
177
+ return `
178
+ window.Glassly = ${JSON.stringify(globals)};
179
+ window.receiveNativeMessage = window.receiveNativeMessage || function() {};
180
+ (function() {
181
+ try {
182
+ var styleEl = document.createElement("style");
183
+ styleEl.setAttribute("data-glassly-injected", "1");
184
+ styleEl.textContent =
185
+ ":root { ${cssVarsBlock} }" +
186
+ "html, body { touch-action: manipulation; -ms-content-zooming: none; }";
187
+ (document.head || document.documentElement).appendChild(styleEl);
188
+ } catch (e) { /* ignore */ }
189
+
190
+ function lockViewport() {
191
+ try {
192
+ var content = "width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, viewport-fit=cover";
193
+ var existing = document.querySelector('meta[name="viewport"]');
194
+ if (existing) {
195
+ existing.setAttribute("content", content);
196
+ } else {
197
+ var meta = document.createElement("meta");
198
+ meta.setAttribute("name", "viewport");
199
+ meta.setAttribute("content", content);
200
+ (document.head || document.documentElement).appendChild(meta);
201
+ }
202
+ } catch (e) { /* ignore */ }
203
+ }
204
+ lockViewport();
205
+ document.addEventListener("DOMContentLoaded", lockViewport);
206
+ })();
207
+ ${consoleTapBlock}
208
+ true;
209
+ `;
210
+ }
211
+ //# sourceMappingURL=webviewGlobals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webviewGlobals.js","sourceRoot":"","sources":["../../src/host/webviewGlobals.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAyCH,4EAA4E;AAC5E,4EAA4E;AAC5E,6DAA6D;AAC7D,SAAS,aAAa,CAAC,MAAuB,EAAE,OAAwB;IACtE,OAAO;QACL,oBAAoB,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI;QACvC,uBAAuB,EAAE,GAAG,MAAM,CAAC,MAAM,IAAI;QAC7C,qBAAqB,EAAE,GAAG,MAAM,CAAC,IAAI,IAAI;QACzC,sBAAsB,EAAE,GAAG,MAAM,CAAC,KAAK,IAAI;QAC3C,uBAAuB,EAAE,GAAG,OAAO,CAAC,GAAG,IAAI;QAC3C,0BAA0B,EAAE,GAAG,OAAO,CAAC,MAAM,IAAI;QACjD,wBAAwB,EAAE,GAAG,OAAO,CAAC,IAAI,IAAI;QAC7C,yBAAyB,EAAE,GAAG,OAAO,CAAC,KAAK,IAAI;QAC/C,yBAAyB,EAAE,GAAG,OAAO,CAAC,KAAK,IAAI;QAC/C,0BAA0B,EAAE,GAAG,OAAO,CAAC,MA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