@livx.cc/iab-escape 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Elya Livshitz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,68 @@
1
- # Temporary Holding Version
1
+ # @livx.cc/iab-escape
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Move a user from the Facebook / Instagram in-app browser (IAB) to the device default browser. Zero dependencies, no logging, no analytics. Triggers mirror the ones tested on real devices.
4
+
5
+ ## Proven matrix
6
+
7
+ Tested 2026-11-16, organic links (not paid ads). The app always shows its own confirm dialog: the user taps once.
8
+
9
+ | App | OS | Scheme | Trigger tested | Result |
10
+ |---|---|---|---|---|
11
+ | Instagram 455.0.0.35.67 | iOS 26.7.3 | `instagram://extbrowser/?url=<enc>` | `<a>`, tap, and sync `location.href` while parsing (3/3 each) | Safari |
12
+ | Facebook 587.0.0.31.71 | iOS 26.7.3 | `x-safari-https://host/path` | `<a>`/tap (3/3); `setTimeout(1500)` from an inline script (3/3); sync firing while parsing fails | Safari |
13
+ | Facebook 587.0.0.39.55 | Android 16 | `intent://host/path#Intent;scheme=https;end` | `<a>`/tap: 1 run each; sync `location.href` while parsing: 3/3 | Chrome (default browser) |
14
+
15
+ Unproven, returned only with `includeUnproven: true`: Instagram Android (intent), Threads iOS (`barcelona://extbrowser`), Messenger iOS (`x-safari-https`).
16
+
17
+ ## Usage
18
+
19
+ It reopens the **same URL** in the default browser. In a normal browser it does nothing.
20
+
21
+ Script tag, placed early in the page (no code):
22
+
23
+ ```html
24
+ <script src="iab-escape.min.js" data-auto></script>
25
+ ```
26
+
27
+ The script tag shows a full-screen loader ("Opening in your browser…"), then an "Open in browser" button (a real link, works if the automatic fire was ignored) and a small "Continue here". Turn it off with `data-ui="false"`; in code it is the `ui: true` option, with text via `labels`. No loader when the app is not matched.
28
+
29
+ Re-entry: if the page comes back after it left (persisted `pageshow`, or hidden then visible), it fires again once per return, at most `maxAutoFires` (default 3) per page lifetime. If the user cancelled the app's dialog (the page never went away), it does not re-fire; the button stays. "Continue here" stops re-fires.
30
+
31
+ Optional attributes: `data-ui`, `data-delay-ms`, `data-mark-param` (empty = off), `data-include-unproven`, `data-url`.
32
+
33
+ npm:
34
+
35
+ ```ts
36
+ import { IabEscape } from '@livx.cc/iab-escape';
37
+
38
+ const esc = new IabEscape();
39
+ esc.auto(); // once per page load
40
+ esc.bindLink(document.querySelector('a#open')!); // fallback button/link
41
+ ```
42
+
43
+ The script build also exposes the global `IabEscape` class (`IabEscape.version`, `IabEscape.buildTime`). The ESM import has no side effects.
44
+
45
+ **Call `auto()` from an inline script**, as the probes did. If the document is still `loading`, it waits for `DOMContentLoaded` (never `load`), because navigating mid-parse leaves a half-loaded page when the user comes back (seen on Android Facebook). Then delay 0 fires synchronously and a longer delay starts a timer. If the document is already `interactive`/`complete`, the delay counts from the `auto()` call. So it fires at `DOMContentLoaded` at the earliest; on iOS Facebook the 1.5 s counts from then or from the call, whichever is later.
46
+
47
+ - `detect()` returns `{ app, os, inApp }`; `getRule()` the matrix row (with `testedOn`); `buildUrl()` the scheme URL or null.
48
+ - `escape()` fires now (call inside a tap for buttons). `auto()` returns a cancel function; cancelling before the fire re-arms the once-per-page guard (flag on the window, shared by all instances).
49
+ - `auto()` does nothing when the current page URL already carries the mark param (loop guard); `escape()` still works.
50
+ - Options: `url` (relative resolves against the page), `userAgent`, `delayMs`, `includeUnproven`, `markParam` (default `iab_escaped`, appended raw as `=1` only if absent, query otherwise byte-identical; `null` disables), `onAttempt`, `onResult`, `window`.
51
+
52
+ ## Limits
53
+
54
+ - The schemes are undocumented by Meta and an app update can break them: keep a fallback link and monitor.
55
+ - `data-auto` uses the same `auto()` path (unit-tested); the device runs used the inline `auto()` call.
56
+ - A bare `?iab_escaped` (no value) counts as "mark present": the URL is left untouched and `auto()` is skipped.
57
+ - Paid-ad clicks are untested (organic links only).
58
+ - A production domain with universal links may open the native app instead of the browser.
59
+ - Instagram passes no `fbclid` from a DM; Facebook rewrites the `fbclid` at the hand-off.
60
+ - Slow or heavy pages, and a late `auto()` call (after `load`, e.g. an SPA mount), are untested on devices.
61
+ - Matched by the rules but untested: Instagram on iPad, Facebook Lite, `http` targets on Android (`scheme=http`) and Instagram. On iOS Facebook `http` targets return null.
62
+ - Never uses meta refresh: it loops on Android when the user cancels.
63
+ - `onResult` watches `visibilitychange`/`pagehide` for 3 s. Meta webviews do not fire these reliably, so `stayed-or-unknown` is not proof of failure.
64
+ - The app's confirm dialog cannot be skipped.
65
+
66
+ ## Dev
67
+
68
+ `bun test`, `bun run build`. Open `demo/index.html` via a static server after building.
@@ -0,0 +1,79 @@
1
+ import { type Env } from './detect';
2
+ import { type Labels } from './loader';
3
+ import { type Rule } from './matrix';
4
+ export type { Env, Labels, Rule };
5
+ export interface AttemptInfo {
6
+ rule: Rule;
7
+ url: string;
8
+ }
9
+ export interface ResultInfo extends AttemptInfo {
10
+ /** 'stayed-or-unknown' is NOT proof of failure: Meta webviews do not fire visibilitychange/pagehide reliably. */
11
+ outcome: 'left' | 'stayed-or-unknown';
12
+ }
13
+ export declare class IabEscapeOptions {
14
+ /** Target URL; relative values resolve against the current location. Default: current location.href. */
15
+ url: string | null;
16
+ /** Default: navigator.userAgent. */
17
+ userAgent: string | null;
18
+ /** Overrides the per-rule delay used by auto(). */
19
+ delayMs: number | null;
20
+ includeUnproven: boolean;
21
+ /** Query param appended as `=1` to the target so the landing page can tell. null disables. */
22
+ markParam: string | null;
23
+ onAttempt: ((info: AttemptInfo) => void) | null;
24
+ onResult: ((info: ResultInfo) => void) | null;
25
+ /** Show the full-screen loader (spinner, then an "Open in browser" button) while auto() runs. */
26
+ ui: boolean;
27
+ labels: Partial<Labels>;
28
+ /** Max automatic fires per page lifetime (the first fire + re-entry re-fires). */
29
+ maxAutoFires: number;
30
+ /** Injectable for tests. Default: globalThis.window. */
31
+ window: Window | null;
32
+ }
33
+ /** Maps `data-*` attributes of a script tag (dataset keys) to options. Absent or invalid values are ignored. */
34
+ export declare function optionsFromDataset(d: Record<string, string | undefined>): Partial<IabEscapeOptions>;
35
+ export declare class IabEscape {
36
+ options?: Partial<IabEscapeOptions> | undefined;
37
+ /** Package version (injected at build time). */
38
+ static readonly version: string;
39
+ /** ISO build time (injected at build time), or null. */
40
+ static readonly buildTime: string | null;
41
+ private ldr;
42
+ private fires;
43
+ private watching;
44
+ private wentAway;
45
+ private locked;
46
+ private dismissed;
47
+ constructor(options?: Partial<IabEscapeOptions> | undefined);
48
+ private get o();
49
+ private get win();
50
+ detect(): Env;
51
+ getRule(): Rule | null;
52
+ buildUrl(): string | null;
53
+ /** Resolves the target (relative `url` against the current location); the query is never re-serialized. */
54
+ private target;
55
+ /** Fire now. Call inside a user gesture when wired to a button. */
56
+ escape(): boolean;
57
+ /**
58
+ * Fires escape() at most once per page load (flag on the window, shared by all instances).
59
+ * While the document is still `loading`, waits for DOMContentLoaded first (never `load`); then delay 0 fires
60
+ * synchronously, otherwise setTimeout. Never meta refresh (it loops on Android).
61
+ * No-op when the current page URL already carries the mark param (loop guard).
62
+ * Returns a cancel fn; cancelling before the fire re-arms the guard (StrictMode-safe).
63
+ */
64
+ auto(): () => void;
65
+ private loader;
66
+ private delay;
67
+ /** One automatic fire: escape(), count it, start watching for re-entry, reveal the button soon after. */
68
+ private fireNow;
69
+ /**
70
+ * Re-entry: the page is shown again after a fire that left (pagehide/hidden seen, or a persisted pageshow,
71
+ * i.e. bfcache / restored webview). Re-fires ONCE per re-entry, up to maxAutoFires per page lifetime.
72
+ * A page that never went away (user pressed Cancel) is not re-fired; the button stays.
73
+ */
74
+ private watchReentry;
75
+ private reenter;
76
+ /** Plain `<a>` tap path (proven on all three). Leaves the element untouched when there is no rule. */
77
+ bindLink(a: HTMLAnchorElement): boolean;
78
+ private watch;
79
+ }
@@ -0,0 +1,364 @@
1
+ // src/detect.ts
2
+ var APPS = [
3
+ ["threads", /Barcelona/],
4
+ ["instagram", /Instagram/],
5
+ ["messenger", /FBAN\/MessengerForiOS|FB_IAB\/MESSENGER|Orca/],
6
+ ["facebook", /FBAN|FBAV|FB_IAB/]
7
+ ];
8
+ function detectEnv(ua) {
9
+ const app = APPS.find(([, re]) => re.test(ua))?.[0] ?? null;
10
+ const os = /iPhone|iPad|iPod/.test(ua) ? "ios" : /Android/.test(ua) ? "android" : null;
11
+ return { app, os, inApp: app !== null };
12
+ }
13
+
14
+ // src/loader.ts
15
+ var DEFAULT_LABELS = { opening: "Opening in your browser…", open: "Open in browser", stay: "Continue here" };
16
+ var CSS = `
17
+ #iab-escape{position:fixed;inset:0;z-index:2147483647;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;
18
+ padding:max(24px,env(safe-area-inset-top)) max(24px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(24px,env(safe-area-inset-left));
19
+ background:#fff;color:#111;font:18px/1.35 -apple-system,system-ui,sans-serif;text-align:center}
20
+ #iab-escape .ie-spin{width:36px;height:36px;border:4px solid #8884;border-top-color:#07f;border-radius:50%;animation:ie-r 1s linear infinite}
21
+ #iab-escape a.ie-open{display:block;padding:14px 28px;border-radius:12px;background:#07f;color:#fff;text-decoration:none;font-weight:600}
22
+ #iab-escape a.ie-stay{font-size:14px;color:inherit;opacity:.7}
23
+ #iab-escape [hidden]{display:none}
24
+ @keyframes ie-r{to{transform:rotate(360deg)}}
25
+ @media (prefers-color-scheme:dark){#iab-escape{background:#111;color:#f2f2f2}}
26
+ @media (prefers-reduced-motion:reduce){#iab-escape .ie-spin{animation:none}}`;
27
+
28
+ class Loader {
29
+ doc;
30
+ labels;
31
+ onStay;
32
+ root = null;
33
+ open;
34
+ stay;
35
+ spin;
36
+ constructor(doc, labels, onStay) {
37
+ this.doc = doc;
38
+ this.labels = labels;
39
+ this.onStay = onStay;
40
+ }
41
+ get visible() {
42
+ return this.root !== null;
43
+ }
44
+ show() {
45
+ if (!this.root)
46
+ this.build();
47
+ this.spin.hidden = false;
48
+ this.open.hidden = true;
49
+ this.stay.hidden = true;
50
+ }
51
+ reveal(href) {
52
+ if (!this.root)
53
+ this.build();
54
+ this.open.href = href;
55
+ this.open.hidden = false;
56
+ this.stay.hidden = false;
57
+ }
58
+ hide() {
59
+ this.root?.remove();
60
+ this.root = null;
61
+ }
62
+ el(tag, cls, text) {
63
+ const e = this.doc.createElement(tag);
64
+ e.className = cls;
65
+ if (text)
66
+ e.textContent = text;
67
+ return e;
68
+ }
69
+ build() {
70
+ const root = this.el("div", "");
71
+ root.id = "iab-escape";
72
+ root.setAttribute("role", "status");
73
+ const style = this.doc.createElement("style");
74
+ style.textContent = CSS;
75
+ this.spin = this.el("div", "ie-spin");
76
+ const msg = this.el("div", "ie-msg", this.labels.opening);
77
+ this.open = this.el("a", "ie-open", this.labels.open);
78
+ this.stay = this.el("a", "ie-stay", this.labels.stay);
79
+ this.stay.href = "#";
80
+ this.stay.addEventListener("click", (ev) => {
81
+ ev.preventDefault();
82
+ this.hide();
83
+ this.onStay?.();
84
+ });
85
+ for (const c of [style, this.spin, msg, this.open, this.stay])
86
+ root.appendChild(c);
87
+ (this.doc.body ?? this.doc.documentElement).appendChild(root);
88
+ this.root = root;
89
+ }
90
+ }
91
+
92
+ // src/matrix.ts
93
+ var xSafari = (t) => t.protocol === "https:" ? "x-safari-" + t.href : null;
94
+ var extbrowser = (scheme) => (t) => `${scheme}://extbrowser/?url=${encodeURIComponent(t.href)}`;
95
+ var intent = (t) => `intent://${t.noHash.replace(/^https?:\/\//i, "")}#Intent;scheme=${t.protocol.slice(0, -1)};end`;
96
+ var T = "2026-11-16";
97
+ var MATRIX = [
98
+ {
99
+ app: "instagram",
100
+ os: "ios",
101
+ proven: true,
102
+ delayMs: 0,
103
+ build: extbrowser("instagram"),
104
+ testedOn: { date: T, os: "iOS 26.7.3", app: "Instagram 455.0.0.35.67" }
105
+ },
106
+ {
107
+ app: "facebook",
108
+ os: "ios",
109
+ proven: true,
110
+ delayMs: 1500,
111
+ build: xSafari,
112
+ testedOn: { date: T, os: "iOS 26.7.3", app: "Facebook 587.0.0.31.71" }
113
+ },
114
+ {
115
+ app: "facebook",
116
+ os: "android",
117
+ proven: true,
118
+ delayMs: 0,
119
+ build: intent,
120
+ testedOn: { date: T, os: "Android 16", app: "Facebook 587.0.0.39.55" }
121
+ },
122
+ { app: "instagram", os: "android", proven: false, delayMs: 0, build: intent, testedOn: null },
123
+ { app: "threads", os: "ios", proven: false, delayMs: 0, build: extbrowser("barcelona"), testedOn: null },
124
+ { app: "messenger", os: "ios", proven: false, delayMs: 1500, build: xSafari, testedOn: null }
125
+ ];
126
+
127
+ // src/IabEscape.ts
128
+ class IabEscapeOptions {
129
+ url = null;
130
+ userAgent = null;
131
+ delayMs = null;
132
+ includeUnproven = false;
133
+ markParam = "iab_escaped";
134
+ onAttempt = null;
135
+ onResult = null;
136
+ ui = false;
137
+ labels = {};
138
+ maxAutoFires = 3;
139
+ window = null;
140
+ }
141
+ function optionsFromDataset(d) {
142
+ const o = {};
143
+ const n = d.delayMs?.trim();
144
+ if (n && Number.isFinite(Number(n)) && Number(n) >= 0)
145
+ o.delayMs = Number(n);
146
+ if (d.markParam !== undefined)
147
+ o.markParam = d.markParam === "" ? null : d.markParam;
148
+ if (d.includeUnproven !== undefined)
149
+ o.includeUnproven = true;
150
+ if (d.url)
151
+ o.url = d.url;
152
+ if (d.ui !== undefined)
153
+ o.ui = d.ui !== "false";
154
+ return o;
155
+ }
156
+ var WATCH_MS = 3000;
157
+ var REVEAL_MS = 800;
158
+ var REENTER_LOCK_MS = 1000;
159
+ var FIRED = "__iabEscapeFired";
160
+ var hasParam = (url, key) => new URLSearchParams(url.split("#")[0].split("?")[1] ?? "").has(key);
161
+
162
+ class IabEscape {
163
+ options;
164
+ static version = "0.2.0";
165
+ static buildTime = "2026-11-16T20:26:43.863Z";
166
+ ldr = null;
167
+ fires = 0;
168
+ watching = false;
169
+ wentAway = false;
170
+ locked = false;
171
+ dismissed = false;
172
+ constructor(options) {
173
+ this.options = options;
174
+ this.options = { ...new IabEscapeOptions, ...options };
175
+ }
176
+ get o() {
177
+ return this.options;
178
+ }
179
+ get win() {
180
+ return this.o.window ?? globalThis.window;
181
+ }
182
+ detect() {
183
+ return detectEnv(this.o.userAgent ?? this.win.navigator.userAgent);
184
+ }
185
+ getRule() {
186
+ const { app, os } = this.detect();
187
+ const rule = MATRIX.find((r) => r.app === app && r.os === os);
188
+ return rule && (rule.proven || this.o.includeUnproven) ? rule : null;
189
+ }
190
+ buildUrl() {
191
+ const rule = this.getRule();
192
+ const target = rule && this.target();
193
+ return rule && target ? rule.build(target) : null;
194
+ }
195
+ target() {
196
+ const base = this.win.location.href;
197
+ const input = this.o.url ?? base;
198
+ let resolved;
199
+ try {
200
+ resolved = new URL(input, base);
201
+ } catch {
202
+ return null;
203
+ }
204
+ if (!/^https?:$/.test(resolved.protocol))
205
+ return null;
206
+ const raw = /^https?:\/\//i.test(input) ? input : resolved.href;
207
+ const h = raw.indexOf("#");
208
+ let noHash = h < 0 ? raw : raw.slice(0, h);
209
+ const hash = h < 0 ? "" : raw.slice(h);
210
+ const key = this.o.markParam;
211
+ if (key && !hasParam(noHash, key)) {
212
+ noHash += (noHash.includes("?") ? /[?&]$/.test(noHash) ? "" : "&" : "?") + key + "=1";
213
+ }
214
+ return { href: noHash + hash, noHash, protocol: resolved.protocol };
215
+ }
216
+ escape() {
217
+ const rule = this.getRule();
218
+ const url = this.buildUrl();
219
+ if (!rule || !url)
220
+ return false;
221
+ this.o.onAttempt?.({ rule, url });
222
+ this.win.location.href = url;
223
+ this.watch({ rule, url });
224
+ return true;
225
+ }
226
+ auto() {
227
+ const { win } = this;
228
+ const key = this.o.markParam;
229
+ const rule = this.getRule();
230
+ if (!rule || win[FIRED] || key && hasParam(win.location.href, key))
231
+ return () => {};
232
+ win[FIRED] = true;
233
+ const { document: doc } = win;
234
+ this.dismissed = false;
235
+ if (this.o.ui)
236
+ this.loader().show();
237
+ let done = false;
238
+ let id;
239
+ const fire = () => {
240
+ done = true;
241
+ if (!this.fireNow())
242
+ win[FIRED] = false;
243
+ };
244
+ const start = () => {
245
+ doc.removeEventListener("DOMContentLoaded", start);
246
+ if (this.delay(rule) <= 0)
247
+ fire();
248
+ else
249
+ id = win.setTimeout(fire, this.delay(rule));
250
+ };
251
+ if (doc.readyState === "loading")
252
+ doc.addEventListener("DOMContentLoaded", start);
253
+ else
254
+ start();
255
+ return () => {
256
+ if (done)
257
+ return;
258
+ doc.removeEventListener("DOMContentLoaded", start);
259
+ if (id !== undefined)
260
+ win.clearTimeout(id);
261
+ win[FIRED] = false;
262
+ this.ldr?.hide();
263
+ };
264
+ }
265
+ loader() {
266
+ return this.ldr ??= new Loader(this.win.document, { ...DEFAULT_LABELS, ...this.o.labels }, () => {
267
+ this.dismissed = true;
268
+ });
269
+ }
270
+ delay(rule) {
271
+ return this.o.delayMs ?? rule.delayMs;
272
+ }
273
+ fireNow() {
274
+ if (!this.escape()) {
275
+ this.ldr?.hide();
276
+ return false;
277
+ }
278
+ this.fires++;
279
+ this.watchReentry();
280
+ if (this.o.ui) {
281
+ const url = this.buildUrl();
282
+ this.win.setTimeout(() => {
283
+ if (url && this.ldr?.visible)
284
+ this.ldr.reveal(url);
285
+ }, REVEAL_MS);
286
+ }
287
+ return true;
288
+ }
289
+ watchReentry() {
290
+ if (this.watching)
291
+ return;
292
+ this.watching = true;
293
+ const { win } = this;
294
+ const doc = win.document;
295
+ win.addEventListener("pagehide", () => {
296
+ this.wentAway = true;
297
+ });
298
+ doc.addEventListener("visibilitychange", () => {
299
+ if (doc.visibilityState === "hidden")
300
+ this.wentAway = true;
301
+ else
302
+ this.reenter();
303
+ });
304
+ win.addEventListener("pageshow", (e) => {
305
+ if (e.persisted) {
306
+ this.wentAway = true;
307
+ this.reenter();
308
+ }
309
+ });
310
+ }
311
+ reenter() {
312
+ const { win } = this;
313
+ const rule = this.getRule();
314
+ if (!this.wentAway || this.locked || this.dismissed || !rule)
315
+ return;
316
+ this.wentAway = false;
317
+ this.locked = true;
318
+ win.setTimeout(() => {
319
+ this.locked = false;
320
+ }, REENTER_LOCK_MS);
321
+ if (this.fires >= this.o.maxAutoFires) {
322
+ const url = this.buildUrl();
323
+ if (this.o.ui && url)
324
+ this.loader().reveal(url);
325
+ return;
326
+ }
327
+ if (this.o.ui)
328
+ this.loader().show();
329
+ if (this.delay(rule) <= 0)
330
+ this.fireNow();
331
+ else
332
+ win.setTimeout(() => this.fireNow(), this.delay(rule));
333
+ }
334
+ bindLink(a) {
335
+ const url = this.buildUrl();
336
+ if (!url)
337
+ return false;
338
+ a.href = url;
339
+ return true;
340
+ }
341
+ watch(info) {
342
+ const { win } = this;
343
+ let left = false;
344
+ const mark = () => {
345
+ left = true;
346
+ };
347
+ const onVis = () => {
348
+ if (win.document.visibilityState === "hidden")
349
+ mark();
350
+ };
351
+ win.addEventListener("pagehide", mark);
352
+ win.document.addEventListener("visibilitychange", onVis);
353
+ win.setTimeout(() => {
354
+ win.removeEventListener("pagehide", mark);
355
+ win.document.removeEventListener("visibilitychange", onVis);
356
+ this.o.onResult?.({ ...info, outcome: left ? "left" : "stayed-or-unknown" });
357
+ }, WATCH_MS);
358
+ }
359
+ }
360
+ export {
361
+ IabEscape,
362
+ IabEscapeOptions,
363
+ optionsFromDataset
364
+ };
@@ -0,0 +1,8 @@
1
+ export type App = 'facebook' | 'instagram' | 'messenger' | 'threads';
2
+ export type Os = 'ios' | 'android';
3
+ export interface Env {
4
+ app: App | null;
5
+ os: Os | null;
6
+ inApp: boolean;
7
+ }
8
+ export declare function detectEnv(ua: string): Env;
@@ -0,0 +1,11 @@
1
+ (()=>{var{defineProperty:p,getOwnPropertyNames:L,getOwnPropertyDescriptor:A}=Object,T=Object.prototype.hasOwnProperty;function _(e){return this[e]}var I=(e)=>{var t=(c??=new WeakMap).get(e),i;if(t)return t;if(t=p({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var n of L(e))if(!T.call(t,n))p(t,n,{get:_.bind(e,n),enumerable:!(i=A(e,n))||i.enumerable})}return c.set(e,t),t},c;var O=(e)=>e;function R(e,t){this[e]=O.bind(null,t)}var M=(e,t)=>{for(var i in t)p(e,i,{get:t[i],enumerable:!0,configurable:!0,set:R.bind(t,i)})};var U={};M(U,{boot:()=>x});var k=[["threads",/Barcelona/],["instagram",/Instagram/],["messenger",/FBAN\/MessengerForiOS|FB_IAB\/MESSENGER|Orca/],["facebook",/FBAN|FBAV|FB_IAB/]];function h(e){let t=k.find(([,n])=>n.test(e))?.[0]??null,i=/iPhone|iPad|iPod/.test(e)?"ios":/Android/.test(e)?"android":null;return{app:t,os:i,inApp:t!==null}}var f={opening:"Opening in your browser…",open:"Open in browser",stay:"Continue here"};class u{doc;labels;onStay;root=null;open;stay;spin;constructor(e,t,i){this.doc=e;this.labels=t;this.onStay=i}get visible(){return this.root!==null}show(){if(!this.root)this.build();this.spin.hidden=!1,this.open.hidden=!0,this.stay.hidden=!0}reveal(e){if(!this.root)this.build();this.open.href=e,this.open.hidden=!1,this.stay.hidden=!1}hide(){this.root?.remove(),this.root=null}el(e,t,i){let n=this.doc.createElement(e);if(n.className=t,i)n.textContent=i;return n}build(){let e=this.el("div","");e.id="iab-escape",e.setAttribute("role","status");let t=this.doc.createElement("style");t.textContent=`
2
+ #iab-escape{position:fixed;inset:0;z-index:2147483647;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;
3
+ padding:max(24px,env(safe-area-inset-top)) max(24px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(24px,env(safe-area-inset-left));
4
+ background:#fff;color:#111;font:18px/1.35 -apple-system,system-ui,sans-serif;text-align:center}
5
+ #iab-escape .ie-spin{width:36px;height:36px;border:4px solid #8884;border-top-color:#07f;border-radius:50%;animation:ie-r 1s linear infinite}
6
+ #iab-escape a.ie-open{display:block;padding:14px 28px;border-radius:12px;background:#07f;color:#fff;text-decoration:none;font-weight:600}
7
+ #iab-escape a.ie-stay{font-size:14px;color:inherit;opacity:.7}
8
+ #iab-escape [hidden]{display:none}
9
+ @keyframes ie-r{to{transform:rotate(360deg)}}
10
+ @media (prefers-color-scheme:dark){#iab-escape{background:#111;color:#f2f2f2}}
11
+ @media (prefers-reduced-motion:reduce){#iab-escape .ie-spin{animation:none}}`,this.spin=this.el("div","ie-spin");let i=this.el("div","ie-msg",this.labels.opening);this.open=this.el("a","ie-open",this.labels.open),this.stay=this.el("a","ie-stay",this.labels.stay),this.stay.href="#",this.stay.addEventListener("click",(n)=>{n.preventDefault(),this.hide(),this.onStay?.()});for(let n of[t,this.spin,i,this.open,this.stay])e.appendChild(n);(this.doc.body??this.doc.documentElement).appendChild(e),this.root=e}}var m=(e)=>e.protocol==="https:"?"x-safari-"+e.href:null,b=(e)=>(t)=>`${e}://extbrowser/?url=${encodeURIComponent(t.href)}`,g=(e)=>`intent://${e.noHash.replace(/^https?:\/\//i,"")}#Intent;scheme=${e.protocol.slice(0,-1)};end`;var v=[{app:"instagram",os:"ios",proven:!0,delayMs:0,build:b("instagram"),testedOn:{date:"2026-11-16",os:"iOS 26.7.3",app:"Instagram 455.0.0.35.67"}},{app:"facebook",os:"ios",proven:!0,delayMs:1500,build:m,testedOn:{date:"2026-11-16",os:"iOS 26.7.3",app:"Facebook 587.0.0.31.71"}},{app:"facebook",os:"android",proven:!0,delayMs:0,build:g,testedOn:{date:"2026-11-16",os:"Android 16",app:"Facebook 587.0.0.39.55"}},{app:"instagram",os:"android",proven:!1,delayMs:0,build:g,testedOn:null},{app:"threads",os:"ios",proven:!1,delayMs:0,build:b("barcelona"),testedOn:null},{app:"messenger",os:"ios",proven:!1,delayMs:1500,build:m,testedOn:null}];class E{url=null;userAgent=null;delayMs=null;includeUnproven=!1;markParam="iab_escaped";onAttempt=null;onResult=null;ui=!1;labels={};maxAutoFires=3;window=null}function w(e){let t={},i=e.delayMs?.trim();if(i&&Number.isFinite(Number(i))&&Number(i)>=0)t.delayMs=Number(i);if(e.markParam!==void 0)t.markParam=e.markParam===""?null:e.markParam;if(e.includeUnproven!==void 0)t.includeUnproven=!0;if(e.url)t.url=e.url;if(e.ui!==void 0)t.ui=e.ui!=="false";return t}var S=3000,P=800,F=1000,l="__iabEscapeFired",y=(e,t)=>new URLSearchParams(e.split("#")[0].split("?")[1]??"").has(t);class d{options;static version="0.2.0";static buildTime="2026-11-16T20:26:43.863Z";ldr=null;fires=0;watching=!1;wentAway=!1;locked=!1;dismissed=!1;constructor(e){this.options=e;this.options={...new E,...e}}get o(){return this.options}get win(){return this.o.window??globalThis.window}detect(){return h(this.o.userAgent??this.win.navigator.userAgent)}getRule(){let{app:e,os:t}=this.detect(),i=v.find((n)=>n.app===e&&n.os===t);return i&&(i.proven||this.o.includeUnproven)?i:null}buildUrl(){let e=this.getRule(),t=e&&this.target();return e&&t?e.build(t):null}target(){let e=this.win.location.href,t=this.o.url??e,i;try{i=new URL(t,e)}catch{return null}if(!/^https?:$/.test(i.protocol))return null;let n=/^https?:\/\//i.test(t)?t:i.href,s=n.indexOf("#"),r=s<0?n:n.slice(0,s),a=s<0?"":n.slice(s),o=this.o.markParam;if(o&&!y(r,o))r+=(r.includes("?")?/[?&]$/.test(r)?"":"&":"?")+o+"=1";return{href:r+a,noHash:r,protocol:i.protocol}}escape(){let e=this.getRule(),t=this.buildUrl();if(!e||!t)return!1;return this.o.onAttempt?.({rule:e,url:t}),this.win.location.href=t,this.watch({rule:e,url:t}),!0}auto(){let{win:e}=this,t=this.o.markParam,i=this.getRule();if(!i||e[l]||t&&y(e.location.href,t))return()=>{};e[l]=!0;let{document:n}=e;if(this.dismissed=!1,this.o.ui)this.loader().show();let s=!1,r,a=()=>{if(s=!0,!this.fireNow())e[l]=!1},o=()=>{if(n.removeEventListener("DOMContentLoaded",o),this.delay(i)<=0)a();else r=e.setTimeout(a,this.delay(i))};if(n.readyState==="loading")n.addEventListener("DOMContentLoaded",o);else o();return()=>{if(s)return;if(n.removeEventListener("DOMContentLoaded",o),r!==void 0)e.clearTimeout(r);e[l]=!1,this.ldr?.hide()}}loader(){return this.ldr??=new u(this.win.document,{...f,...this.o.labels},()=>{this.dismissed=!0})}delay(e){return this.o.delayMs??e.delayMs}fireNow(){if(!this.escape())return this.ldr?.hide(),!1;if(this.fires++,this.watchReentry(),this.o.ui){let e=this.buildUrl();this.win.setTimeout(()=>{if(e&&this.ldr?.visible)this.ldr.reveal(e)},P)}return!0}watchReentry(){if(this.watching)return;this.watching=!0;let{win:e}=this,t=e.document;e.addEventListener("pagehide",()=>{this.wentAway=!0}),t.addEventListener("visibilitychange",()=>{if(t.visibilityState==="hidden")this.wentAway=!0;else this.reenter()}),e.addEventListener("pageshow",(i)=>{if(i.persisted)this.wentAway=!0,this.reenter()})}reenter(){let{win:e}=this,t=this.getRule();if(!this.wentAway||this.locked||this.dismissed||!t)return;if(this.wentAway=!1,this.locked=!0,e.setTimeout(()=>{this.locked=!1},F),this.fires>=this.o.maxAutoFires){let i=this.buildUrl();if(this.o.ui&&i)this.loader().reveal(i);return}if(this.o.ui)this.loader().show();if(this.delay(t)<=0)this.fireNow();else e.setTimeout(()=>this.fireNow(),this.delay(t))}bindLink(e){let t=this.buildUrl();if(!t)return!1;return e.href=t,!0}watch(e){let{win:t}=this,i=!1,n=()=>{i=!0},s=()=>{if(t.document.visibilityState==="hidden")n()};t.addEventListener("pagehide",n),t.document.addEventListener("visibilitychange",s),t.setTimeout(()=>{t.removeEventListener("pagehide",n),t.document.removeEventListener("visibilitychange",s),this.o.onResult?.({...e,outcome:i?"left":"stayed-or-unknown"})},S)}}function x(e,t,i={}){t.IabEscape=d;let n=e?.currentScript;if(n?.hasAttribute("data-auto"))new d({ui:!0,...w(n.dataset),...i}).auto()}if(typeof document<"u")x(document,globalThis);})();
package/dist/iife.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { type IabEscapeOptions } from './IabEscape';
2
+ /** Browser-script entry: exposes the global `IabEscape`; `<script data-auto>` runs auto() right away. */
3
+ export declare function boot(doc: Document | undefined, g: any, extra?: Partial<IabEscapeOptions>): void;
@@ -0,0 +1,25 @@
1
+ export interface Labels {
2
+ opening: string;
3
+ open: string;
4
+ stay: string;
5
+ }
6
+ export declare const DEFAULT_LABELS: Labels;
7
+ /** Full-screen "opening in your browser" overlay. No deps; built with createElement only. */
8
+ export declare class Loader {
9
+ private doc;
10
+ private labels;
11
+ private onStay?;
12
+ private root;
13
+ private open;
14
+ private stay;
15
+ private spin;
16
+ constructor(doc: Document, labels: Labels, onStay?: (() => void) | undefined);
17
+ get visible(): boolean;
18
+ /** Spinner state (also resets a previously revealed button). */
19
+ show(): void;
20
+ /** Reveals the real `<a>` (so a tap works if the automatic fire was ignored) and the "stay" link. */
21
+ reveal(href: string): void;
22
+ hide(): void;
23
+ private el;
24
+ private build;
25
+ }
@@ -0,0 +1,26 @@
1
+ import type { App, Os } from './detect';
2
+ export interface TestedOn {
3
+ date: string;
4
+ os: string;
5
+ app: string;
6
+ }
7
+ /** The target URL, kept as the raw string (mark param already applied). */
8
+ export interface Target {
9
+ /** Full URL incl. fragment. */
10
+ href: string;
11
+ /** `href` without the fragment. */
12
+ noHash: string;
13
+ /** 'http:' | 'https:' */
14
+ protocol: string;
15
+ }
16
+ export interface Rule {
17
+ app: App;
18
+ os: Os;
19
+ proven: boolean;
20
+ /** Delay used by auto(). 0 = fire synchronously inside auto(). */
21
+ delayMs: number;
22
+ testedOn: TestedOn | null;
23
+ /** Returns the scheme URL or null when the target is not supported by this row. */
24
+ build(target: Target): string | null;
25
+ }
26
+ export declare const MATRIX: Rule[];
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@livx.cc/iab-escape",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Move users from the Facebook / Instagram in-app browser to the device default browser, using only trigger methods proven on real devices.",
6
+ "license": "MIT",
7
+ "author": "Elya Livshitz",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Livshitz/iab-escape.git"
11
+ },
12
+ "homepage": "https://github.com/Livshitz/iab-escape#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/Livshitz/iab-escape/issues"
15
+ },
16
+ "keywords": ["in-app-browser", "facebook", "instagram", "webview", "deep-link", "open-in-browser"],
17
+ "sideEffects": false,
18
+ "main": "./dist/IabEscape.js",
19
+ "module": "./dist/IabEscape.js",
20
+ "types": "./dist/IabEscape.d.ts",
21
+ "exports": {
22
+ ".": { "types": "./dist/IabEscape.d.ts", "import": "./dist/IabEscape.js" },
23
+ "./iife": "./dist/iab-escape.min.js"
24
+ },
25
+ "files": ["dist", "README.md"],
26
+ "publishConfig": { "access": "public" },
27
+ "scripts": {
28
+ "build": "rm -rf dist && bun build.ts && tsc -p tsconfig.build.json",
29
+ "test": "timeout 120 bun test",
30
+ "prepublishOnly": "bun run build && bun run test",
31
+ "typecheck": "tsc --noEmit"
32
+ },
33
+ "devDependencies": {
34
+ "@types/bun": "latest",
35
+ "typescript": "^5.7.0"
36
+ }
37
+ }