@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,163 @@
1
+ /** SVG path compiler shared by scene validation and native wire encoding.
2
+ * Ported from g2flash revision 21; no DOM, Node or mobile-platform dependencies. */
3
+ const u16 = (v: number) => [v & 255, (v >>> 8) & 255]
4
+ function integer(v: number, min: number, max: number, name: string): number {
5
+ if (!Number.isInteger(v) || v < min || v > max) throw new Error(`${name} outside ${min}..${max}: ${v}`)
6
+ return v
7
+ }
8
+ /** SVG d subset: absolute/relative M L H V Q C S T Z; implicit repetitions.
9
+ * Unsupported syntax is rejected. Each filled contour must explicitly close. */
10
+ export function svgPath(d: string): number[] {
11
+ const tokens = d.match(/[a-zA-Z]|[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?/g) ?? []
12
+ const residue = d.replace(/[a-zA-Z]|[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?/g, "")
13
+ if (/[^\s,]/.test(residue)) throw new Error("Invalid SVG path syntax")
14
+ let i = 0,
15
+ cmd = "",
16
+ x = 0,
17
+ y = 0,
18
+ sx = 0,
19
+ sy = 0,
20
+ open = false,
21
+ previous = ""
22
+ let cx = 0,
23
+ cy = 0
24
+ const out: number[] = []
25
+ const emit = (op: number, ...coords: number[]) => {
26
+ out.push(op, ...coords.flatMap((v) => u16(integer(Math.round(v * 16), -32768, 32767, "Q4 coordinate"))))
27
+ }
28
+ const number = () => {
29
+ if (i >= tokens.length || /^[a-z]$/i.test(tokens[i])) throw new Error("Missing SVG coordinate")
30
+ const v = Number(tokens[i++])
31
+ if (!Number.isFinite(v)) throw new Error("Invalid number")
32
+ return v
33
+ }
34
+ while (i < tokens.length) {
35
+ if (/^[a-z]$/i.test(tokens[i])) cmd = tokens[i++]
36
+ if (!cmd || !/^[MLHVQCSTZ]$/i.test(cmd)) throw new Error(`Unsupported SVG command: ${cmd}`)
37
+ const op = cmd.toUpperCase(),
38
+ rel = cmd !== op
39
+ const pair = (): [number, number] => [number() + (rel ? x : 0), number() + (rel ? y : 0)]
40
+ if (op === "Z") {
41
+ if (!open) throw new Error("Z without an open contour")
42
+ emit(4)
43
+ x = sx
44
+ y = sy
45
+ open = false
46
+ previous = "Z"
47
+ cmd = ""
48
+ continue
49
+ }
50
+ if (op !== "M" && !open) throw new Error("Path must start with M")
51
+ if (op === "M") {
52
+ if (open) throw new Error("Filled contours must close with Z before another M")
53
+ ;[x, y] = pair()
54
+ sx = x
55
+ sy = y
56
+ open = true
57
+ emit(0, x, y)
58
+ cmd = rel ? "l" : "L"
59
+ } else if (op === "L" || op === "H" || op === "V") {
60
+ if (op === "L") [x, y] = pair()
61
+ else if (op === "H") x = number() + (rel ? x : 0)
62
+ else y = number() + (rel ? y : 0)
63
+ emit(1, x, y)
64
+ } else if (op === "Q" || op === "T") {
65
+ const c = op === "Q" ? pair() : previous === "Q" || previous === "T" ? [2 * x - cx, 2 * y - cy] : [x, y]
66
+ const end = pair()
67
+ emit(2, ...c, ...end)
68
+ ;[cx, cy] = c
69
+ ;[x, y] = end
70
+ } else {
71
+ const a = op === "C" ? pair() : previous === "C" || previous === "S" ? [2 * x - cx, 2 * y - cy] : [x, y]
72
+ const b = pair(),
73
+ end = pair()
74
+ emit(3, ...a, ...b, ...end)
75
+ ;[cx, cy] = b
76
+ ;[x, y] = end
77
+ }
78
+ previous = op
79
+ }
80
+ if (open || !out.length) throw new Error("Expected explicitly closed filled path")
81
+ return out
82
+ }
83
+
84
+ /** Check the same fixed-point subdivision and budgets as revision 21 firmware. */
85
+ export function compileSvgPath(d: string): {commands: number[]; edges: number} {
86
+ if (typeof d !== "string" || d.length > 65536) throw new Error("Invalid SVG path data")
87
+ const commands = svgPath(d)
88
+ if (commands.length > 8192) throw new Error("SVG path exceeds 8192 command bytes")
89
+ let edges = 0,
90
+ count = 0,
91
+ x = 0,
92
+ y = 0,
93
+ sx = 0,
94
+ sy = 0
95
+ const edge = (ax: number, ay: number, bx: number, by: number) => {
96
+ if ((ax !== bx || ay !== by) && ++edges > 512) throw new Error("SVG path exceeds 512 compiled edges")
97
+ }
98
+ const curve = (p: number[], depth: number): void => {
99
+ const u = [
100
+ 3 * p[2] - 2 * p[0] - p[6],
101
+ 3 * p[3] - 2 * p[1] - p[7],
102
+ 3 * p[4] - 2 * p[6] - p[0],
103
+ 3 * p[5] - 2 * p[7] - p[1],
104
+ ]
105
+ if (u.every((v) => Math.abs(v) <= 16)) {
106
+ edge(p[0], p[1], p[6], p[7])
107
+ return
108
+ }
109
+ if (depth === 8) throw new Error("SVG curve exceeds subdivision limit")
110
+ const a = new Array<number>(8),
111
+ b = new Array<number>(8)
112
+ for (let k = 0; k < 2; k++) {
113
+ const ab = Math.trunc((p[k] + p[k + 2]) / 2),
114
+ bc = Math.trunc((p[k + 2] + p[k + 4]) / 2),
115
+ cd = Math.trunc((p[k + 4] + p[k + 6]) / 2)
116
+ const abc = Math.trunc((ab + bc) / 2),
117
+ bcd = Math.trunc((bc + cd) / 2),
118
+ mid = Math.trunc((abc + bcd) / 2)
119
+ a[k] = p[k]
120
+ a[k + 2] = ab
121
+ a[k + 4] = abc
122
+ a[k + 6] = mid
123
+ b[k] = mid
124
+ b[k + 2] = bcd
125
+ b[k + 4] = cd
126
+ b[k + 6] = p[k + 6]
127
+ }
128
+ curve(a, depth + 1)
129
+ curve(b, depth + 1)
130
+ }
131
+ for (let i = 0; i < commands.length;) {
132
+ const op = commands[i++],
133
+ pairs = op === 4 ? 0 : op === 3 ? 3 : op === 2 ? 2 : 1
134
+ if (++count > 1024) throw new Error("SVG path exceeds 1024 commands")
135
+ const p = [x, y]
136
+ for (let k = 0; k < pairs * 2; k++, i += 2) p.push(((commands[i] | (commands[i + 1] << 8)) << 16) >> 16)
137
+ if (op === 0) {
138
+ x = sx = p[2]
139
+ y = sy = p[3]
140
+ } else if (op === 4) {
141
+ edge(x, y, sx, sy)
142
+ x = sx
143
+ y = sy
144
+ } else if (op === 1) {
145
+ edge(x, y, p[2], p[3])
146
+ x = p[2]
147
+ y = p[3]
148
+ } else {
149
+ if (op === 2) {
150
+ p[6] = p[4]
151
+ p[7] = p[5]
152
+ for (let k = 0; k < 2; k++) {
153
+ p[k + 4] = Math.trunc((p[k + 6] + 2 * p[k + 2]) / 3)
154
+ p[k + 2] = Math.trunc((p[k] + 2 * p[k + 2]) / 3)
155
+ }
156
+ }
157
+ curve(p, 0)
158
+ x = p[6]
159
+ y = p[7]
160
+ }
161
+ }
162
+ return {commands, edges}
163
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * What a host injects into a miniapp's UI WebView. Used by the Glassly App's
3
+ * engine and the desktop simulator; miniapps never import this.
4
+ */
5
+
6
+ export {buildUiShim, type UiShimOptions} from "./uiShim"
7
+ export {
8
+ buildWebviewGlobalsScript,
9
+ buildSafeAreaUpdateScript,
10
+ type BuildWebviewGlobalsOptions,
11
+ type CapsuleMenuRect,
12
+ type MiniappColorScheme,
13
+ type MiniappSafeArea,
14
+ } from "./webviewGlobals"
@@ -0,0 +1,389 @@
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
+
33
+ export interface UiShimOptions {
34
+ packageName: string
35
+ /** @deprecated No longer used — heartbeat removed since WebViews are foreground-only. */
36
+ heartbeatIntervalMs?: number
37
+ }
38
+
39
+ export function buildUiShim(options: UiShimOptions): string {
40
+ const packageNameJson = JSON.stringify(options.packageName)
41
+ // The IIFE assembles a typed `glassly` global plus an internal
42
+ // `__host` for host inbound calls. Quoted strings are JSON-safe so
43
+ // direct injection inside another JS literal also works.
44
+ return `
45
+ (function () {
46
+ if (typeof window === 'undefined') return;
47
+ if (window.glassly && window.__host) return;
48
+ var packageName = ${packageNameJson};
49
+ // Resolve window.ReactNativeWebView.postMessage LAZILY, not once at shim-eval.
50
+ // On Android the shim is injected as a WebViewCompat document-start script
51
+ // (so it beats the page bundle and the ready handshake can't be raced — see
52
+ // the react-native-webview patch). But the order in which that document-start
53
+ // script runs vs. the WebMessageListener that installs
54
+ // window.ReactNativeWebView is not contractually fixed on Android the way it
55
+ // is on iOS (postMessageScript is registered before atStartScript there). If
56
+ // we captured rnPost once and the bridge object wasn't installed yet, every
57
+ // postMessage — including {type:'ready'} — would be silently dropped and the
58
+ // splash would hang forever. Resolving per-call means we always pick up the
59
+ // bridge once it exists, which it reliably does by the time the bundle mounts
60
+ // and calls glassly.ready().
61
+ function getRnPost() {
62
+ try {
63
+ return window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === 'function'
64
+ ? window.ReactNativeWebView.postMessage.bind(window.ReactNativeWebView)
65
+ : null;
66
+ } catch (e) { return null; }
67
+ }
68
+
69
+ // Outbound seq number — purely a log-correlation aid (the host's
70
+ // router doesn't dedup anymore since reconnect can't happen: one
71
+ // WebView, foreground-only, destroyed on close → fresh shim on
72
+ // next open).
73
+ var outboundSeq = 1;
74
+ var ready = false;
75
+ var channelHandlers = Object.create(null);
76
+ var openHandlers = [];
77
+ var closeHandlers = [];
78
+ // Queued glassly.send calls before glassly.ready() acks. FIFO drained
79
+ // on ack. Buffered so user input (button taps, etc.) isn't dropped
80
+ // when the WebView mounts faster than the host expects.
81
+ var outboundQueue = [];
82
+ // Inbound payloads that arrived before any glassly.on subscriber was
83
+ // registered for the channel. The background side fires
84
+ // session.ui.onOpen handlers as soon as the WebView posts {type:'ready'},
85
+ // and on a fast bridge the resulting ui.send round-trips back before
86
+ // React useEffects have had a chance to attach listeners. Without
87
+ // buffering, the very first snapshot (the one a controller pushes from
88
+ // its ui.onOpen handler to hydrate the fresh UI) is silently dropped.
89
+ //
90
+ // Drain policy: the queue for a channel is flushed into the FIRST
91
+ // glassly.on(channel, ...) subscriber, then discarded. Subsequent
92
+ // sends with no listener fall back to the old drop-on-floor behaviour
93
+ // — we don't want a re-subscribe to replay stale state.
94
+ //
95
+ // Cap: 32 entries per channel, oldest dropped on overflow. Bounds the
96
+ // memory cost when a controller pushes to a channel that no UI page
97
+ // ever subscribes to.
98
+ var pendingByChannel = Object.create(null);
99
+ var PENDING_CAP_PER_CHANNEL = 32;
100
+
101
+ function postEnvelope(envelope) {
102
+ var rnPost = getRnPost();
103
+ if (!rnPost) return;
104
+ try { rnPost(JSON.stringify(envelope)); } catch (_) {}
105
+ }
106
+
107
+ function send(channel, payload) {
108
+ var seq = outboundSeq++;
109
+ var envelope = { type: 'msg', seq: seq, channel: String(channel), payload: payload };
110
+ if (!ready) {
111
+ outboundQueue.push(envelope);
112
+ return;
113
+ }
114
+ postEnvelope(envelope);
115
+ }
116
+
117
+ function flushQueue() {
118
+ while (outboundQueue.length > 0) {
119
+ postEnvelope(outboundQueue.shift());
120
+ }
121
+ }
122
+
123
+ // NOTE: console.* tap lives in webviewGlobals.ts (injected alongside
124
+ // this shim for every UI WebView, two-layer or single-bundle). That
125
+ // shim posts {payload:{type:"dev_log", ...}} envelopes which
126
+ // LocalMiniappRuntime forwards to the dev sidecar tagged source:"ui".
127
+ // We don't re-wrap here to avoid double-delivery.
128
+
129
+ function on(channel, cb) {
130
+ if (typeof cb !== 'function') return function () {};
131
+ var list = channelHandlers[channel];
132
+ var firstSubscriber = !list || list.length === 0;
133
+ if (!list) { list = []; channelHandlers[channel] = list; }
134
+ list.push(cb);
135
+ // Drain any payloads buffered before this channel had a listener.
136
+ // Only fired on the first subscriber for the channel — a later
137
+ // re-subscribe (after an unsubscribe) does NOT replay history.
138
+ if (firstSubscriber) {
139
+ var pending = pendingByChannel[channel];
140
+ if (pending) {
141
+ delete pendingByChannel[channel];
142
+ for (var i = 0; i < pending.length; i++) {
143
+ try { cb(pending[i]); } catch (e) {}
144
+ }
145
+ }
146
+ }
147
+ return function () {
148
+ var idx = list.indexOf(cb);
149
+ if (idx >= 0) list.splice(idx, 1);
150
+ };
151
+ }
152
+
153
+ // ── RPC ─────────────────────────────────────────────────────────────
154
+ // Outbound RPC: every glassly.request() generates a request id, sends a
155
+ // 'msg' envelope tagged with requestId, and stashes a one-shot resolver
156
+ // keyed on the id. The background-side reply is a recv('msg') with the
157
+ // same channel + requestId; we route it directly to the resolver.
158
+ //
159
+ // Cancellation: caller's AbortSignal triggers a 'cancel' envelope to
160
+ // background and rejects the local promise with a DOM-standard
161
+ // AbortError. The background side's UI_CANCEL handler aborts the
162
+ // handler's ctx.signal and drops the reply.
163
+ var rpcCounter = 0;
164
+ var rpcInflight = Object.create(null);
165
+
166
+ function makeRequestId() {
167
+ rpcCounter += 1;
168
+ return 'r' + rpcCounter + '-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
169
+ }
170
+
171
+ function RpcError(message, code, stage, transport) {
172
+ var e = new Error(message);
173
+ e.name = 'RpcError';
174
+ if (code) {
175
+ try { e.cause = {code: code}; } catch (_) { /* old runtimes */ }
176
+ e.code = code;
177
+ }
178
+ // Diagnostic fields ride as own props so a miniapp can show exactly which
179
+ // pipeline stage and transport failed, not just a message string.
180
+ if (stage) e.stage = stage;
181
+ if (transport) e.transport = transport;
182
+ return e;
183
+ }
184
+
185
+ function RpcTimeoutError(message) {
186
+ var e = new Error(message || 'RPC timed out');
187
+ e.name = 'RpcTimeoutError';
188
+ return e;
189
+ }
190
+
191
+ function makeAbortError() {
192
+ var e;
193
+ try { e = new DOMException('aborted', 'AbortError'); } catch (_) {
194
+ e = new Error('aborted');
195
+ e.name = 'AbortError';
196
+ }
197
+ return e;
198
+ }
199
+
200
+ function request(channel, payload, options) {
201
+ var opts = options || {};
202
+ var signal = opts.signal;
203
+ var timeoutMs = typeof opts.timeout === 'number' ? opts.timeout : null;
204
+ var id = makeRequestId();
205
+
206
+ return new Promise(function (resolve, reject) {
207
+ var done = false;
208
+ var timeoutHandle = null;
209
+ var abortListener = null;
210
+
211
+ function cleanup() {
212
+ if (done) return;
213
+ done = true;
214
+ delete rpcInflight[id];
215
+ if (timeoutHandle != null) { clearTimeout(timeoutHandle); timeoutHandle = null; }
216
+ if (signal && abortListener) {
217
+ try { signal.removeEventListener('abort', abortListener); } catch (_) {}
218
+ }
219
+ }
220
+
221
+ function settle(envelope) {
222
+ if (done) return;
223
+ cleanup();
224
+ if (envelope && envelope.ok === true) {
225
+ resolve(envelope.result);
226
+ } else if (envelope && envelope.ok === false) {
227
+ reject(RpcError(envelope.error && envelope.error.message || 'RPC failed', envelope.error && envelope.error.code, envelope.error && envelope.error.stage, envelope.error && envelope.error.transport));
228
+ } else {
229
+ reject(RpcError('malformed RPC reply'));
230
+ }
231
+ }
232
+
233
+ rpcInflight[id] = settle;
234
+
235
+ if (signal) {
236
+ if (signal.aborted) {
237
+ cleanup();
238
+ reject(makeAbortError());
239
+ return;
240
+ }
241
+ abortListener = function () {
242
+ if (done) return;
243
+ cleanup();
244
+ postEnvelope({type: 'cancel', requestId: id});
245
+ reject(makeAbortError());
246
+ };
247
+ try { signal.addEventListener('abort', abortListener); } catch (_) {}
248
+ }
249
+
250
+ if (timeoutMs != null) {
251
+ timeoutHandle = setTimeout(function () {
252
+ if (done) return;
253
+ cleanup();
254
+ postEnvelope({type: 'cancel', requestId: id});
255
+ reject(RpcTimeoutError());
256
+ }, timeoutMs);
257
+ }
258
+
259
+ var envelope = {type: 'msg', seq: outboundSeq++, channel: String(channel), payload: payload, requestId: id};
260
+ if (!ready) {
261
+ outboundQueue.push(envelope);
262
+ return;
263
+ }
264
+ postEnvelope(envelope);
265
+ });
266
+ }
267
+
268
+ function onOpen(cb) {
269
+ if (typeof cb !== 'function') return function () {};
270
+ openHandlers.push(cb);
271
+ if (ready) {
272
+ try { cb(); } catch (e) {}
273
+ }
274
+ return function () {
275
+ var idx = openHandlers.indexOf(cb);
276
+ if (idx >= 0) openHandlers.splice(idx, 1);
277
+ };
278
+ }
279
+
280
+ function onClose(cb) {
281
+ if (typeof cb !== 'function') return function () {};
282
+ closeHandlers.push(cb);
283
+ return function () {
284
+ var idx = closeHandlers.indexOf(cb);
285
+ if (idx >= 0) closeHandlers.splice(idx, 1);
286
+ };
287
+ }
288
+
289
+ function readyFn() {
290
+ if (ready) return;
291
+ ready = true;
292
+ postEnvelope({ type: 'ready' });
293
+ flushQueue();
294
+ for (var i = 0; i < openHandlers.length; i++) {
295
+ try { openHandlers[i](); } catch (e) {}
296
+ }
297
+ }
298
+
299
+ function setBackgroundColorFn(color) {
300
+ // Tells the host what to paint the native WebView layer (the surface
301
+ // exposed during keyboard push-up / resize animations, which page CSS
302
+ // cannot reach). Host validates and falls back to its theme background.
303
+ if (typeof color !== 'string' || !color) return;
304
+ postEnvelope({ type: 'set_background', color: color });
305
+ }
306
+
307
+ var backHandler = null;
308
+
309
+ function setBackActionFn(handler) {
310
+ backHandler = typeof handler === 'function' ? handler : null;
311
+ postEnvelope({ type: 'set_back_action', shown: backHandler !== null });
312
+ }
313
+
314
+ function fireChannel(channel, payload) {
315
+ var list = channelHandlers[channel];
316
+ if (!list || list.length === 0) {
317
+ // No subscriber yet — stash for the first glassly.on(channel, ...).
318
+ // Bounded FIFO: drop the oldest when capped so a stuck channel
319
+ // can't grow unbounded.
320
+ var q = pendingByChannel[channel];
321
+ if (!q) { q = []; pendingByChannel[channel] = q; }
322
+ q.push(payload);
323
+ if (q.length > PENDING_CAP_PER_CHANNEL) q.shift();
324
+ return;
325
+ }
326
+ for (var i = 0; i < list.length; i++) {
327
+ try { list[i](payload); } catch (e) {}
328
+ }
329
+ }
330
+
331
+ function recv(envelope) {
332
+ if (!envelope || typeof envelope !== 'object') return;
333
+ var type = envelope.type;
334
+ if (type === 'msg' && typeof envelope.channel === 'string') {
335
+ // RPC frames carry a requestId; broadcast frames don't. Treat them
336
+ // as disjoint — never fall through from RPC to broadcast. An orphan
337
+ // RPC reply (caller already aborted/timed out) is silently dropped.
338
+ if (typeof envelope.requestId === 'string') {
339
+ var settle = rpcInflight[envelope.requestId];
340
+ if (settle) settle(envelope.payload);
341
+ return;
342
+ }
343
+ fireChannel(envelope.channel, envelope.payload);
344
+ return;
345
+ }
346
+ if (type === 'open') {
347
+ for (var j = 0; j < openHandlers.length; j++) {
348
+ try { openHandlers[j](); } catch (e) {}
349
+ }
350
+ return;
351
+ }
352
+ if (type === 'close') {
353
+ for (var k = 0; k < closeHandlers.length; k++) {
354
+ try { closeHandlers[k](); } catch (e) {}
355
+ }
356
+ return;
357
+ }
358
+ if (type === 'back') {
359
+ if (backHandler) {
360
+ try { backHandler(); } catch (e) {}
361
+ }
362
+ return;
363
+ }
364
+ if (type === 'cancel' && typeof envelope.requestId === 'string') {
365
+ // Background-side cancel (reserved; currently unused). If we had a
366
+ // future bidirectional RPC this would abort an in-flight UI handler.
367
+ return;
368
+ }
369
+ if (type === 'ack') {
370
+ return;
371
+ }
372
+ }
373
+
374
+ window.glassly = {
375
+ send: send,
376
+ on: on,
377
+ request: request,
378
+ onOpen: onOpen,
379
+ onClose: onClose,
380
+ ready: readyFn,
381
+ setBackgroundColor: setBackgroundColorFn,
382
+ setBackAction: setBackActionFn,
383
+ /** @internal — packageName for diagnostic logs only. */
384
+ _packageName: packageName,
385
+ };
386
+ window.__host = { recv: recv };
387
+ })();
388
+ `.trim()
389
+ }