@ait-co/polyfill 0.1.1 → 0.1.2

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/dist/auto.js ADDED
@@ -0,0 +1,775 @@
1
+ //#region src/detect.ts
2
+ /**
3
+ * Environment detection: are we running inside Apps in Toss, or a plain browser?
4
+ *
5
+ * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export
6
+ * that returns the runtime's Toss globals (deploymentId, brand name, …)
7
+ * inside the Apps in Toss runtime and throws (RN bridge unavailable)
8
+ * anywhere else. The SDK itself is an **optional** peer dependency; if its
9
+ * module can't be imported we are definitely not inside Toss.
10
+ *
11
+ * Just having the SDK module resolvable is not enough — apps can bundle it
12
+ * and still run in a plain browser. We need the bridge probe to confirm.
13
+ *
14
+ * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but
15
+ * that's a constant read from the bridge — no permission dialogs, no
16
+ * analytics fire. In a plain browser the bridge lookup fails fast (sync
17
+ * throw, microsecond-scale), so the startup cost is negligible.
18
+ */
19
+ let cached;
20
+ /**
21
+ * Synchronous read of the cached detection result. Returns:
22
+ * - `true` / `false` if an override is active or the async detection has
23
+ * already resolved
24
+ * - `undefined` if detection hasn't run yet
25
+ *
26
+ * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`
27
+ * detection.
28
+ */
29
+ function isTossEnvironmentCached() {
30
+ const force = globalThis.__AIT_POLYFILL_FORCE__;
31
+ if (force === "toss") return true;
32
+ if (force === "browser") return false;
33
+ return cached;
34
+ }
35
+ /**
36
+ * Returns `true` iff we detect we are running in an environment where the
37
+ * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.
38
+ *
39
+ * Async because we use dynamic `import()` to probe the optional peer dep
40
+ * without forcing it into the consumer's bundle.
41
+ */
42
+ async function isTossEnvironment() {
43
+ const force = globalThis.__AIT_POLYFILL_FORCE__;
44
+ if (force === "toss") return true;
45
+ if (force === "browser") return false;
46
+ if (cached !== void 0) return cached;
47
+ const mod = await loadTossSdk();
48
+ if (typeof mod?.getAppsInTossGlobals !== "function") {
49
+ cached = false;
50
+ return cached;
51
+ }
52
+ try {
53
+ const globals = mod.getAppsInTossGlobals();
54
+ cached = Boolean(globals) && typeof globals === "object";
55
+ } catch {
56
+ cached = false;
57
+ }
58
+ return cached;
59
+ }
60
+ /**
61
+ * Lazy SDK accessor — returns the module if available, else `null`. Callers
62
+ * are expected to `await` and null-check. Never throws.
63
+ */
64
+ async function loadTossSdk() {
65
+ try {
66
+ return await import("@apps-in-toss/web-framework");
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+ //#endregion
72
+ //#region src/shims/clipboard.ts
73
+ /**
74
+ * `navigator.clipboard` shim.
75
+ *
76
+ * Inside Apps in Toss → routes `readText` / `writeText` through the SDK
77
+ * (`getClipboardText` / `setClipboardText`).
78
+ *
79
+ * Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.
80
+ * If the browser doesn't implement it, the standard `TypeError` / `DOMException`
81
+ * surfaces unchanged — we don't paper over missing support.
82
+ */
83
+ const BACKUP_KEY$2 = Symbol.for("@ait-co/polyfill/clipboard.original");
84
+ const HAD_KEY$1 = Symbol.for("@ait-co/polyfill/clipboard.hadOriginal");
85
+ /**
86
+ * Produces a Clipboard-compatible object whose `readText` / `writeText` methods
87
+ * route to the SDK when in Toss, else fall through to the supplied `fallback`.
88
+ */
89
+ function createClipboardShim(fallback) {
90
+ return {
91
+ async readText() {
92
+ if (await isTossEnvironment()) {
93
+ const sdk = await loadTossSdk();
94
+ if (sdk?.getClipboardText) return sdk.getClipboardText();
95
+ }
96
+ if (!fallback) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.readText is not available in this environment.", "NotSupportedError");
97
+ return fallback.readText();
98
+ },
99
+ async writeText(text) {
100
+ if (await isTossEnvironment()) {
101
+ const sdk = await loadTossSdk();
102
+ if (sdk?.setClipboardText) return sdk.setClipboardText(text);
103
+ }
104
+ if (!fallback) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.writeText is not available in this environment.", "NotSupportedError");
105
+ return fallback.writeText(text);
106
+ },
107
+ async read() {
108
+ if (await isTossEnvironment()) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.read (rich content) is not supported in the Apps in Toss environment. Use readText instead.", "NotSupportedError");
109
+ if (!fallback?.read) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.read is not available.", "NotSupportedError");
110
+ return fallback.read();
111
+ },
112
+ async write(items) {
113
+ if (await isTossEnvironment()) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.write (rich content) is not supported in the Apps in Toss environment. Use writeText instead.", "NotSupportedError");
114
+ if (!fallback?.write) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.write is not available.", "NotSupportedError");
115
+ return fallback.write(items);
116
+ },
117
+ addEventListener: (...args) => fallback?.addEventListener(...args),
118
+ removeEventListener: (...args) => fallback?.removeEventListener(...args),
119
+ dispatchEvent: (event) => fallback?.dispatchEvent(event) ?? false
120
+ };
121
+ }
122
+ /**
123
+ * Install the `navigator.clipboard` shim.
124
+ *
125
+ * @returns an uninstall function that restores the original `navigator.clipboard`.
126
+ * Calling install twice without uninstalling is a no-op on the second call
127
+ * and returns the same uninstall function.
128
+ */
129
+ function installClipboardShim() {
130
+ if (typeof navigator === "undefined") return () => {};
131
+ const host = navigator;
132
+ if (BACKUP_KEY$2 in host) return () => uninstallClipboardShim();
133
+ const original = navigator.clipboard;
134
+ host[BACKUP_KEY$2] = original;
135
+ host[HAD_KEY$1] = "clipboard" in navigator;
136
+ const shim = createClipboardShim(original);
137
+ Object.defineProperty(navigator, "clipboard", {
138
+ value: shim,
139
+ configurable: true,
140
+ writable: true
141
+ });
142
+ return uninstallClipboardShim;
143
+ }
144
+ /**
145
+ * Remove the shim and restore the pre-install shape. Uses delete + conditional
146
+ * redefine so a prototype-level `navigator.clipboard` (non-configurable in real
147
+ * browsers) becomes visible again instead of being permanently shadowed.
148
+ */
149
+ function uninstallClipboardShim() {
150
+ if (typeof navigator === "undefined") return;
151
+ const host = navigator;
152
+ if (!(BACKUP_KEY$2 in host)) return;
153
+ const original = host[BACKUP_KEY$2];
154
+ const had = host[HAD_KEY$1];
155
+ delete navigator.clipboard;
156
+ if (had && navigator.clipboard !== original) Object.defineProperty(navigator, "clipboard", {
157
+ value: original,
158
+ configurable: true,
159
+ writable: true
160
+ });
161
+ delete host[BACKUP_KEY$2];
162
+ delete host[HAD_KEY$1];
163
+ }
164
+ //#endregion
165
+ //#region src/shims/geolocation.ts
166
+ /**
167
+ * `navigator.geolocation` shim.
168
+ *
169
+ * Inside Apps in Toss → routes through the SDK:
170
+ * - `getCurrentPosition` → `getCurrentLocation({ accuracy })`
171
+ * - `watchPosition` / `clearWatch` → `startUpdateLocation({ onEvent, onError, options })`
172
+ *
173
+ * Outside Apps in Toss → defers to the browser's native `navigator.geolocation`.
174
+ * If neither is available, the error callback receives a `GeolocationPositionError`.
175
+ *
176
+ * SDK/Web shape mismatch handled here:
177
+ * - SDK `Accuracy` is a numeric enum (1 = Lowest … 6 = BestForNavigation); the
178
+ * standard `PositionOptions.enableHighAccuracy` is a boolean. We map
179
+ * `true → Accuracy.High (4, "~10m")` and `false → Accuracy.Balanced (3)`.
180
+ * `Highest (5)` / `BestForNavigation (6)` are available but carry a battery
181
+ * cost that's rarely what mini-apps want; consumers who need them should
182
+ * call the SDK directly.
183
+ * - SDK coords lack `speed`; we surface `null` (per the W3C spec when unknown).
184
+ * - SDK `startUpdateLocation` returns an `unsubscribe` fn; we wrap it behind
185
+ * a numeric watch id so `clearWatch(id)` behaves like the standard.
186
+ *
187
+ * Caveat: watch ids reset whenever the shim is uninstalled and reinstalled;
188
+ * they are not stable across such cycles. Ids obtained before uninstall
189
+ * cannot be cleared after uninstall — `clearWatch(id)` on the restored native
190
+ * `navigator.geolocation` uses a different id space, so the SDK subscription
191
+ * leaks. Consumers should `clearWatch` all outstanding ids before calling
192
+ * `uninstall()`.
193
+ */
194
+ const BACKUP_KEY$1 = Symbol.for("@ait-co/polyfill/geolocation.original");
195
+ const ACCURACY_BALANCED = 3;
196
+ const ACCURACY_HIGH = 4;
197
+ function toStandardPosition(sdk) {
198
+ const coordsData = {
199
+ latitude: sdk.coords.latitude,
200
+ longitude: sdk.coords.longitude,
201
+ altitude: sdk.coords.altitude,
202
+ accuracy: sdk.coords.accuracy,
203
+ altitudeAccuracy: sdk.coords.altitudeAccuracy,
204
+ heading: sdk.coords.heading,
205
+ speed: null
206
+ };
207
+ return {
208
+ coords: {
209
+ ...coordsData,
210
+ toJSON() {
211
+ return { ...coordsData };
212
+ }
213
+ },
214
+ timestamp: sdk.timestamp,
215
+ toJSON() {
216
+ return {
217
+ coords: { ...coordsData },
218
+ timestamp: sdk.timestamp
219
+ };
220
+ }
221
+ };
222
+ }
223
+ function toPositionError(code, message) {
224
+ const Ctor = globalThis.GeolocationPositionError;
225
+ if (typeof Ctor === "function") {
226
+ const proto = Ctor.prototype;
227
+ if (proto) {
228
+ const shape = {
229
+ code,
230
+ message
231
+ };
232
+ Object.setPrototypeOf(shape, proto);
233
+ return shape;
234
+ }
235
+ }
236
+ return {
237
+ code,
238
+ message,
239
+ PERMISSION_DENIED: 1,
240
+ POSITION_UNAVAILABLE: 2,
241
+ TIMEOUT: 3
242
+ };
243
+ }
244
+ function accuracyFromOptions(options) {
245
+ return options?.enableHighAccuracy ? ACCURACY_HIGH : ACCURACY_BALANCED;
246
+ }
247
+ function createGeolocationShim(fallback) {
248
+ let nextWatchId = 1;
249
+ const sdkWatches = /* @__PURE__ */ new Map();
250
+ const nativeWatches = /* @__PURE__ */ new Map();
251
+ const pendingWatches = /* @__PURE__ */ new Map();
252
+ return {
253
+ getCurrentPosition(success, error, options) {
254
+ (async () => {
255
+ if (await isTossEnvironment()) {
256
+ const fn = (await loadTossSdk())?.getCurrentLocation;
257
+ if (typeof fn === "function") {
258
+ try {
259
+ success(toStandardPosition(await fn({ accuracy: accuracyFromOptions(options) })));
260
+ } catch (e) {
261
+ error?.(toPositionError(2, e instanceof Error ? e.message : "[@ait-co/polyfill] getCurrentLocation failed."));
262
+ }
263
+ return;
264
+ }
265
+ }
266
+ if (!fallback) {
267
+ error?.(toPositionError(2, "[@ait-co/polyfill] navigator.geolocation is not available in this environment."));
268
+ return;
269
+ }
270
+ fallback.getCurrentPosition(success, error, options);
271
+ })();
272
+ },
273
+ watchPosition(success, error, options) {
274
+ const id = nextWatchId++;
275
+ const pending = { cancelled: false };
276
+ pendingWatches.set(id, pending);
277
+ (async () => {
278
+ if (await isTossEnvironment()) {
279
+ const fn = (await loadTossSdk())?.startUpdateLocation;
280
+ if (typeof fn === "function") {
281
+ if (pending.cancelled) {
282
+ pendingWatches.delete(id);
283
+ return;
284
+ }
285
+ const unsubscribe = fn({
286
+ onEvent: (loc) => success(toStandardPosition(loc)),
287
+ onError: (err) => error?.(toPositionError(2, err instanceof Error ? err.message : "[@ait-co/polyfill] startUpdateLocation failed.")),
288
+ options: {
289
+ accuracy: accuracyFromOptions(options),
290
+ timeInterval: 1e3,
291
+ distanceInterval: 0
292
+ }
293
+ });
294
+ if (pending.cancelled) {
295
+ unsubscribe();
296
+ pendingWatches.delete(id);
297
+ return;
298
+ }
299
+ sdkWatches.set(id, unsubscribe);
300
+ pendingWatches.delete(id);
301
+ return;
302
+ }
303
+ }
304
+ if (!fallback) {
305
+ pendingWatches.delete(id);
306
+ error?.(toPositionError(2, "[@ait-co/polyfill] navigator.geolocation is not available in this environment."));
307
+ return;
308
+ }
309
+ if (pending.cancelled) {
310
+ pendingWatches.delete(id);
311
+ return;
312
+ }
313
+ const nativeId = fallback.watchPosition(success, error, options);
314
+ if (pending.cancelled) {
315
+ fallback.clearWatch(nativeId);
316
+ pendingWatches.delete(id);
317
+ return;
318
+ }
319
+ nativeWatches.set(id, nativeId);
320
+ pendingWatches.delete(id);
321
+ })();
322
+ return id;
323
+ },
324
+ clearWatch(id) {
325
+ const pending = pendingWatches.get(id);
326
+ if (pending) {
327
+ pending.cancelled = true;
328
+ pendingWatches.delete(id);
329
+ return;
330
+ }
331
+ const unsubscribe = sdkWatches.get(id);
332
+ if (unsubscribe) {
333
+ unsubscribe();
334
+ sdkWatches.delete(id);
335
+ return;
336
+ }
337
+ const nativeId = nativeWatches.get(id);
338
+ if (nativeId !== void 0 && fallback) {
339
+ fallback.clearWatch(nativeId);
340
+ nativeWatches.delete(id);
341
+ }
342
+ }
343
+ };
344
+ }
345
+ function installGeolocationShim() {
346
+ if (typeof navigator === "undefined") return () => {};
347
+ const host = navigator;
348
+ if (BACKUP_KEY$1 in host) return () => uninstallGeolocationShim();
349
+ const original = navigator.geolocation;
350
+ host[BACKUP_KEY$1] = original;
351
+ const shim = createGeolocationShim(original);
352
+ Object.defineProperty(navigator, "geolocation", {
353
+ value: shim,
354
+ configurable: true,
355
+ writable: true
356
+ });
357
+ return uninstallGeolocationShim;
358
+ }
359
+ function uninstallGeolocationShim() {
360
+ if (typeof navigator === "undefined") return;
361
+ const host = navigator;
362
+ if (!(BACKUP_KEY$1 in host)) return;
363
+ const original = host[BACKUP_KEY$1];
364
+ delete navigator.geolocation;
365
+ if (original !== void 0 && navigator.geolocation !== original) Object.defineProperty(navigator, "geolocation", {
366
+ value: original,
367
+ configurable: true,
368
+ writable: true
369
+ });
370
+ delete host[BACKUP_KEY$1];
371
+ }
372
+ //#endregion
373
+ //#region src/shims/network.ts
374
+ /**
375
+ * `navigator.onLine` + `navigator.connection` shim.
376
+ *
377
+ * Inside Apps in Toss → seeded from SDK `getNetworkStatus()` on install and
378
+ * refreshed on read (throttled):
379
+ * - `'OFFLINE'` → `onLine = false`
380
+ * - `'WIFI'` → `onLine = true`, `effectiveType = '4g'` (no web wifi value)
381
+ * - `'2G'/'3G'/'4G'/'5G'` → `onLine = true`, `effectiveType = <lowercased>`
382
+ * - `'WWAN'/'UNKNOWN'` → `onLine = true`, `effectiveType = '4g'` (best guess)
383
+ *
384
+ * Outside Apps in Toss → both `navigator.onLine` and `navigator.connection`
385
+ * read through to the native value. Install installs own-instance getters
386
+ * that consult the Toss-seeded cache first; when the cache is empty (which
387
+ * it always is in browser mode), the getter temporarily removes its own
388
+ * shadow, reads the prototype value, and reinstates the shadow.
389
+ *
390
+ * Uninstall `delete`s the instance-level override so the prototype descriptor
391
+ * (where `onLine` and `connection` actually live in real browsers) becomes
392
+ * visible again. We never mutate the prototype — doing so would throw in
393
+ * browsers where the descriptor is non-configurable.
394
+ *
395
+ * Caveat: the Web NetworkInformation API is evented (`change` fires on
396
+ * transitions). The SDK exposes only a one-shot query, so listeners attached
397
+ * to `navigator.connection` are accepted but never fire from a `change` event
398
+ * unless the shim observes a real status transition. Synthesising richer
399
+ * events via polling is tracked in TODO.md.
400
+ *
401
+ * Lifecycle: `navigator.connection` is a ShimConnection instance that lives in
402
+ * the install closure. On uninstall the instance-level override is removed,
403
+ * but listeners the consumer attached to the old instance stay bound to that
404
+ * (now-orphan) object and will not see events from a subsequent install.
405
+ * Consumers should re-attach listeners after each install.
406
+ *
407
+ * Seed-boundary race: in Toss mode, reads before the install-time SDK seed
408
+ * completes fall through to the native `navigator.connection`. After the seed
409
+ * lands, subsequent reads return the shim's ShimConnection. Consumers that
410
+ * specifically need the ShimConnection instance (e.g., to attach `change`
411
+ * listeners that fire on Toss network transitions) should wait a microtask
412
+ * after `install()` before attaching listeners, or accept that pre-seed
413
+ * reads may return the native object.
414
+ */
415
+ const INSTALLED_KEY = Symbol.for("@ait-co/polyfill/network.installed");
416
+ const REFRESH_THROTTLE_MS = 500;
417
+ function statusToOnline(status) {
418
+ return status !== "OFFLINE";
419
+ }
420
+ function statusToEffectiveType(status) {
421
+ switch (status) {
422
+ case "2G": return "2g";
423
+ case "3G": return "3g";
424
+ default: return "4g";
425
+ }
426
+ }
427
+ function statusToConnectionType(status) {
428
+ switch (status) {
429
+ case "WIFI": return "wifi";
430
+ case "2G":
431
+ case "3G":
432
+ case "4G":
433
+ case "5G":
434
+ case "WWAN": return "cellular";
435
+ case "OFFLINE": return "none";
436
+ default: return "unknown";
437
+ }
438
+ }
439
+ const SET_STATUS = Symbol("@ait-co/polyfill/network.setStatus");
440
+ var ShimConnection = class extends EventTarget {
441
+ #status = null;
442
+ onchange = null;
443
+ constructor() {
444
+ super();
445
+ this.addEventListener("change", (ev) => this.onchange?.call(this, ev));
446
+ }
447
+ [SET_STATUS](next) {
448
+ this.#status = next;
449
+ }
450
+ get effectiveType() {
451
+ return statusToEffectiveType(this.#status ?? "UNKNOWN");
452
+ }
453
+ get downlink() {
454
+ return 0;
455
+ }
456
+ get rtt() {
457
+ return 0;
458
+ }
459
+ get saveData() {
460
+ return false;
461
+ }
462
+ get type() {
463
+ return statusToConnectionType(this.#status ?? "UNKNOWN");
464
+ }
465
+ };
466
+ function installNetworkShim() {
467
+ if (typeof navigator === "undefined") return () => {};
468
+ const host = navigator;
469
+ if (host[INSTALLED_KEY]) return () => uninstallNetworkShim();
470
+ host[INSTALLED_KEY] = true;
471
+ let cachedStatus = null;
472
+ let lastRefresh = 0;
473
+ let inflight = null;
474
+ const connection = new ShimConnection();
475
+ async function refresh() {
476
+ if (inflight) return inflight;
477
+ if (Date.now() - lastRefresh < REFRESH_THROTTLE_MS) return;
478
+ inflight = (async () => {
479
+ try {
480
+ if (!await isTossEnvironment()) return;
481
+ const fn = (await loadTossSdk())?.getNetworkStatus;
482
+ if (typeof fn !== "function") return;
483
+ const next = await fn();
484
+ const prev = cachedStatus;
485
+ cachedStatus = next;
486
+ connection[SET_STATUS](next);
487
+ if (prev !== null && prev !== next) connection.dispatchEvent(new Event("change"));
488
+ } catch {} finally {
489
+ lastRefresh = Date.now();
490
+ inflight = null;
491
+ }
492
+ })();
493
+ return inflight;
494
+ }
495
+ refresh();
496
+ Object.defineProperty(navigator, "onLine", {
497
+ configurable: true,
498
+ get() {
499
+ refresh();
500
+ if (cachedStatus !== null) return statusToOnline(cachedStatus);
501
+ const desc = Object.getOwnPropertyDescriptor(navigator, "onLine");
502
+ delete navigator.onLine;
503
+ try {
504
+ return navigator.onLine;
505
+ } finally {
506
+ if (desc) Object.defineProperty(navigator, "onLine", desc);
507
+ }
508
+ }
509
+ });
510
+ Object.defineProperty(navigator, "connection", {
511
+ configurable: true,
512
+ get() {
513
+ refresh();
514
+ if (cachedStatus === null) {
515
+ const desc = Object.getOwnPropertyDescriptor(navigator, "connection");
516
+ delete navigator.connection;
517
+ try {
518
+ const native = navigator.connection;
519
+ if (native !== void 0) return native;
520
+ } finally {
521
+ if (desc) Object.defineProperty(navigator, "connection", desc);
522
+ }
523
+ }
524
+ return connection;
525
+ }
526
+ });
527
+ return uninstallNetworkShim;
528
+ }
529
+ function uninstallNetworkShim() {
530
+ if (typeof navigator === "undefined") return;
531
+ const host = navigator;
532
+ if (!host[INSTALLED_KEY]) return;
533
+ delete navigator.onLine;
534
+ delete navigator.connection;
535
+ delete host[INSTALLED_KEY];
536
+ }
537
+ //#endregion
538
+ //#region src/shims/share.ts
539
+ /**
540
+ * `navigator.share` shim.
541
+ *
542
+ * Inside Apps in Toss → routes through SDK `share({ message })`. The SDK only
543
+ * accepts a single `message` string, so we concatenate `title`, `text`, and
544
+ * `url` with newline separators (skipping missing/empty values).
545
+ *
546
+ * Outside Apps in Toss → defers to the browser's native `navigator.share`, or
547
+ * throws `NotSupportedError` if unavailable.
548
+ *
549
+ * Caveat: the SDK's share has no counterpart for `files` (Web Share Level 2).
550
+ * `canShare({ files })` returns `false` whenever the sync-accessible detection
551
+ * says Toss is active (or is being forced via the test override).
552
+ */
553
+ const SHARE_BACKUP_KEY = Symbol.for("@ait-co/polyfill/share.original");
554
+ function buildSdkMessage(data) {
555
+ const parts = [];
556
+ if (data?.title != null && data.title !== "") parts.push(data.title);
557
+ if (data?.text != null && data.text !== "") parts.push(data.text);
558
+ if (data?.url != null && data.url !== "") parts.push(data.url);
559
+ return parts.join("\n");
560
+ }
561
+ async function shareShim(data) {
562
+ if (await isTossEnvironment()) {
563
+ const fn = (await loadTossSdk())?.share;
564
+ if (typeof fn === "function") {
565
+ const message = buildSdkMessage(data);
566
+ if (!message) throw new TypeError("[@ait-co/polyfill] navigator.share requires at least one of title, text, or url.");
567
+ try {
568
+ await fn({ message });
569
+ } catch (e) {
570
+ const message_ = e instanceof Error ? e.message : String(e);
571
+ const wrapped = new DOMException(message_, "AbortError");
572
+ if (e instanceof Error) wrapped.cause = e;
573
+ throw wrapped;
574
+ }
575
+ return;
576
+ }
577
+ }
578
+ const original = navigator[SHARE_BACKUP_KEY]?.share;
579
+ if (!original) throw new DOMException("[@ait-co/polyfill] navigator.share is not available in this environment.", "NotSupportedError");
580
+ return original.call(navigator, data);
581
+ }
582
+ function canShareShim(data) {
583
+ const hasFiles = Boolean(data?.files && data.files.length > 0);
584
+ const toss = isTossEnvironmentCached();
585
+ if (hasFiles) {
586
+ if (toss === true) return false;
587
+ if (toss === void 0) return false;
588
+ }
589
+ if (toss === true) return Boolean(data?.title != null && data.title !== "" || data?.text != null && data.text !== "" || data?.url != null && data.url !== "");
590
+ const originalCanShare = navigator[SHARE_BACKUP_KEY]?.canShare;
591
+ if (originalCanShare) return originalCanShare.call(navigator, data);
592
+ return Boolean(data?.title != null && data.title !== "" || data?.text != null && data.text !== "" || data?.url != null && data.url !== "");
593
+ }
594
+ function installShareShim() {
595
+ if (typeof navigator === "undefined") return () => {};
596
+ const host = navigator;
597
+ if (SHARE_BACKUP_KEY in host) return () => uninstallShareShim();
598
+ const nav = navigator;
599
+ host[SHARE_BACKUP_KEY] = {
600
+ share: nav.share,
601
+ canShare: nav.canShare,
602
+ hadShare: "share" in nav,
603
+ hadCanShare: "canShare" in nav
604
+ };
605
+ Object.defineProperty(navigator, "share", {
606
+ value: shareShim,
607
+ configurable: true,
608
+ writable: true
609
+ });
610
+ Object.defineProperty(navigator, "canShare", {
611
+ value: canShareShim,
612
+ configurable: true,
613
+ writable: true
614
+ });
615
+ return uninstallShareShim;
616
+ }
617
+ function uninstallShareShim() {
618
+ if (typeof navigator === "undefined") return;
619
+ const host = navigator;
620
+ if (!(SHARE_BACKUP_KEY in host)) return;
621
+ const backup = host[SHARE_BACKUP_KEY];
622
+ delete navigator.share;
623
+ if (backup?.hadShare && navigator.share !== backup.share) Object.defineProperty(navigator, "share", {
624
+ value: backup.share,
625
+ configurable: true,
626
+ writable: true
627
+ });
628
+ delete navigator.canShare;
629
+ if (backup?.hadCanShare && navigator.canShare !== backup.canShare) Object.defineProperty(navigator, "canShare", {
630
+ value: backup.canShare,
631
+ configurable: true,
632
+ writable: true
633
+ });
634
+ delete host[SHARE_BACKUP_KEY];
635
+ }
636
+ //#endregion
637
+ //#region src/shims/vibrate.ts
638
+ /**
639
+ * `navigator.vibrate` shim.
640
+ *
641
+ * Inside Apps in Toss → best-effort mapping to SDK `generateHapticFeedback`:
642
+ * - `vibrate(0)` → no-op (web standard: cancels pending vibration)
643
+ * - `vibrate(number)`: short (< 40ms) → `tickWeak`, long (≥ 40ms) → `basicMedium`
644
+ * - `vibrate(number[])`: iterate "on" segments (even indices) as `tap` pulses
645
+ *
646
+ * Outside Apps in Toss → defers to the browser's native `navigator.vibrate`,
647
+ * or returns `false` when unavailable (matches the spec — browsers that don't
648
+ * support vibration simply return `false`).
649
+ *
650
+ * Caveats (documented in CLAUDE.md as the known lossy trade-off):
651
+ * - SDK haptics are qualitative ("tickWeak", "basicMedium"), not millisecond
652
+ * durations. The shim approximates intensity from duration but cannot
653
+ * reproduce exact patterns.
654
+ * - Arrays are fired sequentially via `setTimeout`; gaps between pulses are
655
+ * honoured only as "time until the next tap", not as silent-vs-vibrating.
656
+ * - `vibrate` is spec'd as **synchronous**; the SDK call is async. We return
657
+ * `true` immediately (fire-and-forget). Errors from the SDK are swallowed.
658
+ */
659
+ const BACKUP_KEY = Symbol.for("@ait-co/polyfill/vibrate.original");
660
+ const HAD_KEY = Symbol.for("@ait-co/polyfill/vibrate.hadOriginal");
661
+ const SHORT_VIBRATION_MS = 40;
662
+ async function haptic(type) {
663
+ const fn = (await loadTossSdk())?.generateHapticFeedback;
664
+ if (typeof fn === "function") try {
665
+ await fn({ type });
666
+ } catch {}
667
+ }
668
+ function durationToHaptic(duration) {
669
+ return duration < SHORT_VIBRATION_MS ? "tickWeak" : "basicMedium";
670
+ }
671
+ function vibrateShim(pattern) {
672
+ const arr = Array.isArray(pattern) ? pattern : [pattern];
673
+ if (arr.length === 0 || arr.every((n) => n === 0)) {
674
+ (async () => {
675
+ if (!await isTossEnvironment()) navigator[BACKUP_KEY]?.call(navigator, pattern);
676
+ })();
677
+ return true;
678
+ }
679
+ (async () => {
680
+ if (await isTossEnvironment()) {
681
+ if (!Array.isArray(pattern)) {
682
+ await haptic(durationToHaptic(pattern));
683
+ return;
684
+ }
685
+ for (let i = 0; i < pattern.length; i += 2) {
686
+ const on = pattern[i];
687
+ if (on === void 0) break;
688
+ if (on > 0) await haptic("tap");
689
+ const pause = pattern[i + 1];
690
+ if (typeof pause === "number" && pause > 0) await new Promise((r) => setTimeout(r, pause));
691
+ }
692
+ return;
693
+ }
694
+ navigator[BACKUP_KEY]?.call(navigator, pattern);
695
+ })();
696
+ return true;
697
+ }
698
+ function installVibrateShim() {
699
+ if (typeof navigator === "undefined") return () => {};
700
+ const host = navigator;
701
+ if (BACKUP_KEY in host) return () => uninstallVibrateShim();
702
+ const nav = navigator;
703
+ host[BACKUP_KEY] = nav.vibrate;
704
+ host[HAD_KEY] = "vibrate" in nav;
705
+ Object.defineProperty(navigator, "vibrate", {
706
+ value: vibrateShim,
707
+ configurable: true,
708
+ writable: true
709
+ });
710
+ return uninstallVibrateShim;
711
+ }
712
+ function uninstallVibrateShim() {
713
+ if (typeof navigator === "undefined") return;
714
+ const host = navigator;
715
+ if (!(BACKUP_KEY in host)) return;
716
+ const original = host[BACKUP_KEY];
717
+ const had = host[HAD_KEY];
718
+ delete navigator.vibrate;
719
+ if (had && navigator.vibrate !== original) Object.defineProperty(navigator, "vibrate", {
720
+ value: original,
721
+ configurable: true,
722
+ writable: true
723
+ });
724
+ delete host[BACKUP_KEY];
725
+ delete host[HAD_KEY];
726
+ }
727
+ //#endregion
728
+ //#region src/index.ts
729
+ const NOOP = () => {};
730
+ /**
731
+ * Install every shim this library ships, but only if we detect an Apps in
732
+ * Toss runtime. In a plain browser `install()` is a no-op — the browser's
733
+ * native APIs stay untouched.
734
+ *
735
+ * Returns a promise that resolves with an uninstall function. If the
736
+ * environment turns out not to be Toss, the uninstall function is a no-op.
737
+ *
738
+ * Install order (when active): clipboard → geolocation → share → vibrate →
739
+ * network. Not atomic on failure — if a per-shim install throws (e.g., a
740
+ * consumer pinned a target navigator property as non-configurable), earlier
741
+ * shims are already in place. Callers should catch and invoke the returned
742
+ * uninstall to roll back.
743
+ */
744
+ async function install() {
745
+ if (!await isTossEnvironment()) return NOOP;
746
+ const uninstalls = [
747
+ installClipboardShim(),
748
+ installGeolocationShim(),
749
+ installShareShim(),
750
+ installVibrateShim(),
751
+ installNetworkShim()
752
+ ];
753
+ return () => {
754
+ for (const fn of uninstalls) fn();
755
+ };
756
+ }
757
+ //#endregion
758
+ //#region src/auto.ts
759
+ /**
760
+ * Side-effect entry point: `import '@ait-co/polyfill/auto'`
761
+ *
762
+ * Kicks off detection and, if we're inside Apps in Toss, installs every shim
763
+ * this library ships. In a plain browser this is a no-op — browser native
764
+ * APIs stay untouched. No-op idempotent: importing the entry more than once
765
+ * doesn't re-install.
766
+ *
767
+ * Use this when you want the "just add the dep" experience. If you need to
768
+ * observe when the polyfill actually attached (to gate init logic) or to tear
769
+ * it down, import `install` / `uninstall` from `@ait-co/polyfill` directly.
770
+ */
771
+ install();
772
+ //#endregion
773
+ export {};
774
+
775
+ //# sourceMappingURL=auto.js.map