@ait-co/polyfill 0.1.4 → 0.1.6

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 (47) hide show
  1. package/README.md +53 -3
  2. package/dist/auto.cjs +919 -0
  3. package/dist/auto.cjs.map +1 -0
  4. package/dist/auto.d.cts +1 -0
  5. package/dist/auto.js +18 -6
  6. package/dist/auto.js.map +1 -1
  7. package/dist/detect.cjs +84 -0
  8. package/dist/detect.cjs.map +1 -0
  9. package/dist/detect.d.cts +50 -0
  10. package/dist/detect.d.cts.map +1 -0
  11. package/dist/index.cjs +982 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +222 -0
  14. package/dist/index.d.cts.map +1 -0
  15. package/dist/index.d.ts +26 -27
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +68 -8
  18. package/dist/index.js.map +1 -1
  19. package/dist/shims/clipboard.cjs +192 -0
  20. package/dist/shims/clipboard.cjs.map +1 -0
  21. package/dist/shims/clipboard.d.cts +26 -0
  22. package/dist/shims/clipboard.d.cts.map +1 -0
  23. package/dist/shims/geolocation.cjs +356 -0
  24. package/dist/shims/geolocation.cjs.map +1 -0
  25. package/dist/shims/geolocation.d.cts +41 -0
  26. package/dist/shims/geolocation.d.cts.map +1 -0
  27. package/dist/shims/network.cjs +290 -0
  28. package/dist/shims/network.cjs.map +1 -0
  29. package/dist/shims/network.d.cts +56 -0
  30. package/dist/shims/network.d.cts.map +1 -0
  31. package/dist/shims/share.cjs +239 -0
  32. package/dist/shims/share.cjs.map +1 -0
  33. package/dist/shims/share.d.cts +26 -0
  34. package/dist/shims/share.d.cts.map +1 -0
  35. package/dist/shims/vibrate-semantic.d.ts +27 -0
  36. package/dist/shims/vibrate-semantic.d.ts.map +1 -0
  37. package/dist/shims/vibrate-semantic.js +150 -0
  38. package/dist/shims/vibrate-semantic.js.map +1 -0
  39. package/dist/shims/vibrate.cjs +235 -0
  40. package/dist/shims/vibrate.cjs.map +1 -0
  41. package/dist/shims/vibrate.d.cts +43 -0
  42. package/dist/shims/vibrate.d.cts.map +1 -0
  43. package/dist/shims/vibrate.d.ts +16 -5
  44. package/dist/shims/vibrate.d.ts.map +1 -1
  45. package/dist/shims/vibrate.js +19 -7
  46. package/dist/shims/vibrate.js.map +1 -1
  47. package/package.json +83 -30
package/dist/auto.cjs ADDED
@@ -0,0 +1,919 @@
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/_install-helpers.ts
73
+ /**
74
+ * Install `descriptor` at `navigator[prop]`. Prefer instance-level; if the
75
+ * browser refuses (property is non-configurable on the instance), install on
76
+ * `Navigator.prototype` instead.
77
+ *
78
+ * Returns a snapshot describing where the original value was, which
79
+ * `restoreNavigatorProperty` uses to undo the install.
80
+ */
81
+ function installNavigatorProperty(prop, descriptor) {
82
+ const nav = navigator;
83
+ const instanceDesc = Object.getOwnPropertyDescriptor(nav, prop);
84
+ const instanceHadOwn = instanceDesc !== void 0;
85
+ if (!instanceDesc || instanceDesc.configurable) try {
86
+ Object.defineProperty(nav, prop, descriptor);
87
+ return {
88
+ location: "instance",
89
+ originalDescriptor: instanceDesc,
90
+ instanceHadOwn
91
+ };
92
+ } catch {}
93
+ const proto = Object.getPrototypeOf(nav);
94
+ const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);
95
+ if (instanceHadOwn) try {
96
+ delete nav[prop];
97
+ } catch {}
98
+ Object.defineProperty(proto, prop, descriptor);
99
+ return {
100
+ location: "prototype",
101
+ originalDescriptor: protoDesc,
102
+ instanceHadOwn
103
+ };
104
+ }
105
+ /**
106
+ * Reverse the install recorded in `snapshot`. If the original descriptor was
107
+ * `undefined` (property didn't exist before), delete the property instead of
108
+ * re-defining it.
109
+ */
110
+ function restoreNavigatorProperty(prop, snapshot) {
111
+ const target = snapshot.location === "instance" ? navigator : Object.getPrototypeOf(navigator);
112
+ if (snapshot.originalDescriptor) try {
113
+ Object.defineProperty(target, prop, snapshot.originalDescriptor);
114
+ } catch {}
115
+ else try {
116
+ delete target[prop];
117
+ } catch {}
118
+ }
119
+ /**
120
+ * Mutate methods on an existing object rather than replacing the object
121
+ * itself. This is the path we take for `navigator.geolocation`, `navigator.share`,
122
+ * and `navigator.vibrate` in Chromium, where the slot on `navigator` is a
123
+ * non-configurable own property that we cannot replace — but the methods
124
+ * themselves (or the methods on the referenced object) are still
125
+ * `configurable: true, writable: true`.
126
+ *
127
+ * Each replacement is installed via plain assignment. If any slot is not
128
+ * writable (e.g. frozen object), install is aborted and previously-applied
129
+ * replacements are rolled back, so the caller observes an atomic "all or
130
+ * nothing" failure as `null`. The caller is expected to degrade gracefully
131
+ * (e.g. log a one-time `console.warn`) when that happens.
132
+ */
133
+ function installObjectMethods(target, replacements) {
134
+ const methods = {};
135
+ const applied = [];
136
+ const bag = target;
137
+ for (const key of Object.keys(replacements)) {
138
+ const hadOwn = Object.hasOwn(target, key);
139
+ const original = bag[key];
140
+ try {
141
+ bag[key] = replacements[key];
142
+ } catch {
143
+ for (const applieKey of applied) {
144
+ const prev = methods[applieKey];
145
+ if (!prev) continue;
146
+ if (prev.hadOwn) bag[applieKey] = prev.original;
147
+ else delete bag[applieKey];
148
+ }
149
+ return null;
150
+ }
151
+ if (bag[key] !== replacements[key]) {
152
+ for (const applieKey of applied) {
153
+ const prev = methods[applieKey];
154
+ if (!prev) continue;
155
+ if (prev.hadOwn) bag[applieKey] = prev.original;
156
+ else delete bag[applieKey];
157
+ }
158
+ return null;
159
+ }
160
+ methods[key] = {
161
+ hadOwn,
162
+ original
163
+ };
164
+ applied.push(key);
165
+ }
166
+ return {
167
+ target,
168
+ methods
169
+ };
170
+ }
171
+ /**
172
+ * Reverse an `installObjectMethods` snapshot. Reassigns originals for slots
173
+ * that were own properties before install; deletes the override for slots
174
+ * that were inherited (so the prototype method surfaces again).
175
+ */
176
+ function restoreObjectMethods(snapshot) {
177
+ const bag = snapshot.target;
178
+ for (const key of Object.keys(snapshot.methods)) {
179
+ const entry = snapshot.methods[key];
180
+ if (!entry) continue;
181
+ try {
182
+ if (entry.hadOwn) bag[key] = entry.original;
183
+ else delete bag[key];
184
+ } catch {}
185
+ }
186
+ }
187
+ //#endregion
188
+ //#region src/shims/clipboard.ts
189
+ /**
190
+ * `navigator.clipboard` shim.
191
+ *
192
+ * Inside Apps in Toss → routes `readText` / `writeText` through the SDK
193
+ * (`getClipboardText` / `setClipboardText`).
194
+ *
195
+ * Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.
196
+ * If the browser doesn't implement it, the standard `TypeError` / `DOMException`
197
+ * surfaces unchanged — we don't paper over missing support.
198
+ */
199
+ const BACKUP_KEY$2 = Symbol.for("@ait-co/polyfill/clipboard.original");
200
+ const SNAPSHOT_KEY$2 = Symbol.for("@ait-co/polyfill/clipboard.snapshot");
201
+ /**
202
+ * Produces a Clipboard-compatible object whose `readText` / `writeText` methods
203
+ * route to the SDK when in Toss, else fall through to the supplied `fallback`.
204
+ */
205
+ function createClipboardShim(fallback) {
206
+ return {
207
+ async readText() {
208
+ if (await isTossEnvironment()) {
209
+ const sdk = await loadTossSdk();
210
+ if (sdk?.getClipboardText) return sdk.getClipboardText();
211
+ }
212
+ if (!fallback) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.readText is not available in this environment.", "NotSupportedError");
213
+ return fallback.readText();
214
+ },
215
+ async writeText(text) {
216
+ if (await isTossEnvironment()) {
217
+ const sdk = await loadTossSdk();
218
+ if (sdk?.setClipboardText) return sdk.setClipboardText(text);
219
+ }
220
+ if (!fallback) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.writeText is not available in this environment.", "NotSupportedError");
221
+ return fallback.writeText(text);
222
+ },
223
+ async read() {
224
+ 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");
225
+ if (!fallback?.read) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.read is not available.", "NotSupportedError");
226
+ return fallback.read();
227
+ },
228
+ async write(items) {
229
+ 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");
230
+ if (!fallback?.write) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.write is not available.", "NotSupportedError");
231
+ return fallback.write(items);
232
+ },
233
+ addEventListener: (...args) => fallback?.addEventListener(...args),
234
+ removeEventListener: (...args) => fallback?.removeEventListener(...args),
235
+ dispatchEvent: (event) => fallback?.dispatchEvent(event) ?? false
236
+ };
237
+ }
238
+ /**
239
+ * Install the `navigator.clipboard` shim.
240
+ *
241
+ * @returns an uninstall function that restores the original `navigator.clipboard`.
242
+ * Calling install twice without uninstalling is a no-op on the second call
243
+ * and returns the same uninstall function.
244
+ */
245
+ function installClipboardShim() {
246
+ if (typeof navigator === "undefined") return () => {};
247
+ const host = navigator;
248
+ if (BACKUP_KEY$2 in host) return () => uninstallClipboardShim();
249
+ const original = navigator.clipboard;
250
+ host[BACKUP_KEY$2] = original;
251
+ host[SNAPSHOT_KEY$2] = installNavigatorProperty("clipboard", {
252
+ value: createClipboardShim(original),
253
+ configurable: true,
254
+ writable: true
255
+ });
256
+ return uninstallClipboardShim;
257
+ }
258
+ /**
259
+ * Remove the shim and restore the pre-install shape.
260
+ */
261
+ function uninstallClipboardShim() {
262
+ if (typeof navigator === "undefined") return;
263
+ const host = navigator;
264
+ if (!(BACKUP_KEY$2 in host)) return;
265
+ const snapshot = host[SNAPSHOT_KEY$2];
266
+ if (snapshot) restoreNavigatorProperty("clipboard", snapshot);
267
+ delete host[BACKUP_KEY$2];
268
+ delete host[SNAPSHOT_KEY$2];
269
+ }
270
+ //#endregion
271
+ //#region src/shims/geolocation.ts
272
+ /**
273
+ * `navigator.geolocation` shim.
274
+ *
275
+ * Inside Apps in Toss → routes through the SDK:
276
+ * - `getCurrentPosition` → `getCurrentLocation({ accuracy })`
277
+ * - `watchPosition` / `clearWatch` → `startUpdateLocation({ onEvent, onError, options })`
278
+ *
279
+ * Outside Apps in Toss → defers to the browser's native `navigator.geolocation`.
280
+ * If neither is available, the error callback receives a `GeolocationPositionError`.
281
+ *
282
+ * Install strategy: **method-level**. We do **not** replace `navigator.geolocation`
283
+ * itself — Chromium marks that slot as a non-configurable own property, which
284
+ * both `defineProperty(navigator, 'geolocation', …)` and the prototype-level
285
+ * fallback cannot override (the instance shadow blocks prototype reads). We
286
+ * instead mutate the methods on the existing `Geolocation` object, whose own
287
+ * method descriptors are configurable+writable in every browser we've seen.
288
+ *
289
+ * SDK/Web shape mismatch handled here:
290
+ * - SDK `Accuracy` is a numeric enum (1 = Lowest … 6 = BestForNavigation); the
291
+ * standard `PositionOptions.enableHighAccuracy` is a boolean. We map
292
+ * `true → Accuracy.High (4, "~10m")` and `false → Accuracy.Balanced (3)`.
293
+ * `Highest (5)` / `BestForNavigation (6)` are available but carry a battery
294
+ * cost that's rarely what mini-apps want; consumers who need them should
295
+ * call the SDK directly.
296
+ * - SDK coords lack `speed`; we surface `null` (per the W3C spec when unknown).
297
+ * - SDK `startUpdateLocation` returns an `unsubscribe` fn; we wrap it behind
298
+ * a numeric watch id so `clearWatch(id)` behaves like the standard.
299
+ *
300
+ * Caveat: watch ids reset whenever the shim is uninstalled and reinstalled;
301
+ * they are not stable across such cycles. Ids obtained before uninstall
302
+ * cannot be cleared after uninstall — `clearWatch(id)` on the restored native
303
+ * `navigator.geolocation` uses a different id space, so the SDK subscription
304
+ * leaks. Consumers should `clearWatch` all outstanding ids before calling
305
+ * `uninstall()`.
306
+ */
307
+ const BACKUP_KEY$1 = Symbol.for("@ait-co/polyfill/geolocation.original");
308
+ const SNAPSHOT_KEY$1 = Symbol.for("@ait-co/polyfill/geolocation.snapshot");
309
+ const ACCURACY_BALANCED = 3;
310
+ const ACCURACY_HIGH = 4;
311
+ function toStandardPosition(sdk) {
312
+ const coordsData = {
313
+ latitude: sdk.coords.latitude,
314
+ longitude: sdk.coords.longitude,
315
+ altitude: sdk.coords.altitude,
316
+ accuracy: sdk.coords.accuracy,
317
+ altitudeAccuracy: sdk.coords.altitudeAccuracy,
318
+ heading: sdk.coords.heading,
319
+ speed: null
320
+ };
321
+ return {
322
+ coords: {
323
+ ...coordsData,
324
+ toJSON() {
325
+ return { ...coordsData };
326
+ }
327
+ },
328
+ timestamp: sdk.timestamp,
329
+ toJSON() {
330
+ return {
331
+ coords: { ...coordsData },
332
+ timestamp: sdk.timestamp
333
+ };
334
+ }
335
+ };
336
+ }
337
+ function toPositionError(code, message) {
338
+ const Ctor = globalThis.GeolocationPositionError;
339
+ if (typeof Ctor === "function") {
340
+ const proto = Ctor.prototype;
341
+ if (proto) {
342
+ const shape = {
343
+ code,
344
+ message
345
+ };
346
+ Object.setPrototypeOf(shape, proto);
347
+ return shape;
348
+ }
349
+ }
350
+ return {
351
+ code,
352
+ message,
353
+ PERMISSION_DENIED: 1,
354
+ POSITION_UNAVAILABLE: 2,
355
+ TIMEOUT: 3
356
+ };
357
+ }
358
+ function accuracyFromOptions(options) {
359
+ return options?.enableHighAccuracy ? ACCURACY_HIGH : ACCURACY_BALANCED;
360
+ }
361
+ function createGeolocationShim(fallback) {
362
+ let nextWatchId = 1;
363
+ const sdkWatches = /* @__PURE__ */ new Map();
364
+ const nativeWatches = /* @__PURE__ */ new Map();
365
+ const pendingWatches = /* @__PURE__ */ new Map();
366
+ return {
367
+ getCurrentPosition(success, error, options) {
368
+ (async () => {
369
+ if (await isTossEnvironment()) {
370
+ const fn = (await loadTossSdk())?.getCurrentLocation;
371
+ if (typeof fn === "function") {
372
+ try {
373
+ success(toStandardPosition(await fn({ accuracy: accuracyFromOptions(options) })));
374
+ } catch (e) {
375
+ error?.(toPositionError(2, e instanceof Error ? e.message : "[@ait-co/polyfill] getCurrentLocation failed."));
376
+ }
377
+ return;
378
+ }
379
+ }
380
+ if (!fallback.getCurrentPosition) {
381
+ error?.(toPositionError(2, "[@ait-co/polyfill] navigator.geolocation is not available in this environment."));
382
+ return;
383
+ }
384
+ fallback.getCurrentPosition(success, error, options);
385
+ })();
386
+ },
387
+ watchPosition(success, error, options) {
388
+ const id = nextWatchId++;
389
+ const pending = { cancelled: false };
390
+ pendingWatches.set(id, pending);
391
+ (async () => {
392
+ if (await isTossEnvironment()) {
393
+ const fn = (await loadTossSdk())?.startUpdateLocation;
394
+ if (typeof fn === "function") {
395
+ if (pending.cancelled) {
396
+ pendingWatches.delete(id);
397
+ return;
398
+ }
399
+ const unsubscribe = fn({
400
+ onEvent: (loc) => success(toStandardPosition(loc)),
401
+ onError: (err) => error?.(toPositionError(2, err instanceof Error ? err.message : "[@ait-co/polyfill] startUpdateLocation failed.")),
402
+ options: {
403
+ accuracy: accuracyFromOptions(options),
404
+ timeInterval: 1e3,
405
+ distanceInterval: 0
406
+ }
407
+ });
408
+ if (pending.cancelled) {
409
+ unsubscribe();
410
+ pendingWatches.delete(id);
411
+ return;
412
+ }
413
+ sdkWatches.set(id, unsubscribe);
414
+ pendingWatches.delete(id);
415
+ return;
416
+ }
417
+ }
418
+ if (!fallback.watchPosition) {
419
+ pendingWatches.delete(id);
420
+ error?.(toPositionError(2, "[@ait-co/polyfill] navigator.geolocation is not available in this environment."));
421
+ return;
422
+ }
423
+ if (pending.cancelled) {
424
+ pendingWatches.delete(id);
425
+ return;
426
+ }
427
+ const nativeId = fallback.watchPosition(success, error, options);
428
+ if (pending.cancelled) {
429
+ fallback.clearWatch?.(nativeId);
430
+ pendingWatches.delete(id);
431
+ return;
432
+ }
433
+ nativeWatches.set(id, nativeId);
434
+ pendingWatches.delete(id);
435
+ })();
436
+ return id;
437
+ },
438
+ clearWatch(id) {
439
+ const pending = pendingWatches.get(id);
440
+ if (pending) {
441
+ pending.cancelled = true;
442
+ pendingWatches.delete(id);
443
+ return;
444
+ }
445
+ const unsubscribe = sdkWatches.get(id);
446
+ if (unsubscribe) {
447
+ unsubscribe();
448
+ sdkWatches.delete(id);
449
+ return;
450
+ }
451
+ const nativeId = nativeWatches.get(id);
452
+ if (nativeId !== void 0 && fallback.clearWatch) {
453
+ fallback.clearWatch(nativeId);
454
+ nativeWatches.delete(id);
455
+ }
456
+ }
457
+ };
458
+ }
459
+ function installGeolocationShim() {
460
+ if (typeof navigator === "undefined") return () => {};
461
+ const host = navigator;
462
+ if (BACKUP_KEY$1 in host) return () => uninstallGeolocationShim();
463
+ const target = navigator.geolocation;
464
+ if (!target) {
465
+ host[BACKUP_KEY$1] = void 0;
466
+ return () => uninstallGeolocationShim();
467
+ }
468
+ const shim = createGeolocationShim({
469
+ getCurrentPosition: target.getCurrentPosition?.bind(target),
470
+ watchPosition: target.watchPosition?.bind(target),
471
+ clearWatch: target.clearWatch?.bind(target)
472
+ });
473
+ const snapshot = installObjectMethods(target, {
474
+ getCurrentPosition: shim.getCurrentPosition,
475
+ watchPosition: shim.watchPosition,
476
+ clearWatch: shim.clearWatch
477
+ });
478
+ if (!snapshot) {
479
+ host[BACKUP_KEY$1] = void 0;
480
+ return () => uninstallGeolocationShim();
481
+ }
482
+ host[BACKUP_KEY$1] = { target };
483
+ host[SNAPSHOT_KEY$1] = snapshot;
484
+ return uninstallGeolocationShim;
485
+ }
486
+ function uninstallGeolocationShim() {
487
+ if (typeof navigator === "undefined") return;
488
+ const host = navigator;
489
+ if (!(BACKUP_KEY$1 in host)) return;
490
+ const snapshot = host[SNAPSHOT_KEY$1];
491
+ if (snapshot) restoreObjectMethods(snapshot);
492
+ delete host[BACKUP_KEY$1];
493
+ delete host[SNAPSHOT_KEY$1];
494
+ }
495
+ //#endregion
496
+ //#region src/shims/network.ts
497
+ /**
498
+ * `navigator.onLine` + `navigator.connection` shim.
499
+ *
500
+ * Inside Apps in Toss → seeded from SDK `getNetworkStatus()` on install and
501
+ * refreshed on read (throttled):
502
+ * - `'OFFLINE'` → `onLine = false`
503
+ * - `'WIFI'` → `onLine = true`, `effectiveType = '4g'` (no web wifi value)
504
+ * - `'2G'/'3G'/'4G'/'5G'` → `onLine = true`, `effectiveType = <lowercased>`
505
+ * - `'WWAN'/'UNKNOWN'` → `onLine = true`, `effectiveType = '4g'` (best guess)
506
+ *
507
+ * Outside Apps in Toss → both `navigator.onLine` and `navigator.connection`
508
+ * read through to the native value. Install installs own-instance getters
509
+ * that consult the Toss-seeded cache first; when the cache is empty (which
510
+ * it always is in browser mode), the getter temporarily removes its own
511
+ * shadow, reads the prototype value, and reinstates the shadow.
512
+ *
513
+ * Uninstall `delete`s the instance-level override so the prototype descriptor
514
+ * (where `onLine` and `connection` actually live in real browsers) becomes
515
+ * visible again. We never mutate the prototype — doing so would throw in
516
+ * browsers where the descriptor is non-configurable.
517
+ *
518
+ * Browser-compat caveat (Chromium): `navigator.onLine` and `navigator.connection`
519
+ * are value slots, not methods, so the method-level install trick we use for
520
+ * `geolocation`/`share`/`vibrate` does not apply here. When Chromium marks the
521
+ * instance descriptor as non-configurable AND the prototype descriptor is also
522
+ * non-configurable, we cannot install. In that case the shim logs a one-time
523
+ * `console.warn` and leaves the native values in place — consumers keep the
524
+ * browser's own `onLine`/`connection` values; the SDK-synced state is simply
525
+ * disabled for that session.
526
+ *
527
+ * Caveat: the Web NetworkInformation API is evented (`change` fires on
528
+ * transitions). The SDK exposes only a one-shot query, so listeners attached
529
+ * to `navigator.connection` are accepted but never fire from a `change` event
530
+ * unless the shim observes a real status transition. Synthesising richer
531
+ * events via polling is tracked in TODO.md.
532
+ *
533
+ * Lifecycle: `navigator.connection` is a ShimConnection instance that lives in
534
+ * the install closure. On uninstall the instance-level override is removed,
535
+ * but listeners the consumer attached to the old instance stay bound to that
536
+ * (now-orphan) object and will not see events from a subsequent install.
537
+ * Consumers should re-attach listeners after each install.
538
+ *
539
+ * Seed-boundary race: in Toss mode, reads before the install-time SDK seed
540
+ * completes fall through to the native `navigator.connection`. After the seed
541
+ * lands, subsequent reads return the shim's ShimConnection. Consumers that
542
+ * specifically need the ShimConnection instance (e.g., to attach `change`
543
+ * listeners that fire on Toss network transitions) should wait a microtask
544
+ * after `install()` before attaching listeners, or accept that pre-seed
545
+ * reads may return the native object.
546
+ */
547
+ const INSTALLED_KEY = Symbol.for("@ait-co/polyfill/network.installed");
548
+ const ON_LINE_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/network.onLine.snapshot");
549
+ const CONNECTION_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/network.connection.snapshot");
550
+ const REFRESH_THROTTLE_MS = 500;
551
+ function statusToOnline(status) {
552
+ return status !== "OFFLINE";
553
+ }
554
+ function statusToEffectiveType(status) {
555
+ switch (status) {
556
+ case "2G": return "2g";
557
+ case "3G": return "3g";
558
+ default: return "4g";
559
+ }
560
+ }
561
+ function statusToConnectionType(status) {
562
+ switch (status) {
563
+ case "WIFI": return "wifi";
564
+ case "2G":
565
+ case "3G":
566
+ case "4G":
567
+ case "5G":
568
+ case "WWAN": return "cellular";
569
+ case "OFFLINE": return "none";
570
+ default: return "unknown";
571
+ }
572
+ }
573
+ const SET_STATUS = Symbol("@ait-co/polyfill/network.setStatus");
574
+ var ShimConnection = class extends EventTarget {
575
+ #status = null;
576
+ onchange = null;
577
+ constructor() {
578
+ super();
579
+ this.addEventListener("change", (ev) => this.onchange?.call(this, ev));
580
+ }
581
+ [SET_STATUS](next) {
582
+ this.#status = next;
583
+ }
584
+ get effectiveType() {
585
+ return statusToEffectiveType(this.#status ?? "UNKNOWN");
586
+ }
587
+ get downlink() {
588
+ return 0;
589
+ }
590
+ get rtt() {
591
+ return 0;
592
+ }
593
+ get saveData() {
594
+ return false;
595
+ }
596
+ get type() {
597
+ return statusToConnectionType(this.#status ?? "UNKNOWN");
598
+ }
599
+ };
600
+ function installNetworkShim() {
601
+ if (typeof navigator === "undefined") return () => {};
602
+ const host = navigator;
603
+ if (host[INSTALLED_KEY]) return () => uninstallNetworkShim();
604
+ host[INSTALLED_KEY] = true;
605
+ let cachedStatus = null;
606
+ let lastRefresh = 0;
607
+ let inflight = null;
608
+ const connection = new ShimConnection();
609
+ async function refresh() {
610
+ if (inflight) return inflight;
611
+ if (Date.now() - lastRefresh < REFRESH_THROTTLE_MS) return;
612
+ inflight = (async () => {
613
+ try {
614
+ if (!await isTossEnvironment()) return;
615
+ const fn = (await loadTossSdk())?.getNetworkStatus;
616
+ if (typeof fn !== "function") return;
617
+ const next = await fn();
618
+ const prev = cachedStatus;
619
+ cachedStatus = next;
620
+ connection[SET_STATUS](next);
621
+ if (prev !== null && prev !== next) connection.dispatchEvent(new Event("change"));
622
+ } catch {} finally {
623
+ lastRefresh = Date.now();
624
+ inflight = null;
625
+ }
626
+ })();
627
+ return inflight;
628
+ }
629
+ const nativeOnLine = navigator.onLine;
630
+ const nativeConnection = navigator.connection;
631
+ refresh();
632
+ let installWarned = false;
633
+ const warnNonConfigurable = (e) => {
634
+ if (installWarned) return;
635
+ installWarned = true;
636
+ console.warn("[@ait-co/polyfill] navigator.onLine/connection is non-configurable in this browser; Toss network status sync disabled.", e);
637
+ };
638
+ try {
639
+ host[ON_LINE_SNAPSHOT_KEY] = installNavigatorProperty("onLine", {
640
+ configurable: true,
641
+ get() {
642
+ refresh();
643
+ if (cachedStatus !== null) return statusToOnline(cachedStatus);
644
+ return nativeOnLine ?? true;
645
+ }
646
+ });
647
+ } catch (e) {
648
+ warnNonConfigurable(e);
649
+ }
650
+ try {
651
+ host[CONNECTION_SNAPSHOT_KEY] = installNavigatorProperty("connection", {
652
+ configurable: true,
653
+ get() {
654
+ refresh();
655
+ if (cachedStatus === null && nativeConnection !== void 0) return nativeConnection;
656
+ return connection;
657
+ }
658
+ });
659
+ } catch (e) {
660
+ warnNonConfigurable(e);
661
+ }
662
+ return uninstallNetworkShim;
663
+ }
664
+ function uninstallNetworkShim() {
665
+ if (typeof navigator === "undefined") return;
666
+ const host = navigator;
667
+ if (!host[INSTALLED_KEY]) return;
668
+ const onLineSnap = host[ON_LINE_SNAPSHOT_KEY];
669
+ if (onLineSnap) restoreNavigatorProperty("onLine", onLineSnap);
670
+ const connSnap = host[CONNECTION_SNAPSHOT_KEY];
671
+ if (connSnap) restoreNavigatorProperty("connection", connSnap);
672
+ delete host[INSTALLED_KEY];
673
+ delete host[ON_LINE_SNAPSHOT_KEY];
674
+ delete host[CONNECTION_SNAPSHOT_KEY];
675
+ }
676
+ //#endregion
677
+ //#region src/shims/share.ts
678
+ /**
679
+ * `navigator.share` shim.
680
+ *
681
+ * Inside Apps in Toss → routes through SDK `share({ message })`. The SDK only
682
+ * accepts a single `message` string, so we concatenate `title`, `text`, and
683
+ * `url` with newline separators (skipping missing/empty values).
684
+ *
685
+ * Outside Apps in Toss → defers to the browser's native `navigator.share`, or
686
+ * throws `NotSupportedError` if unavailable.
687
+ *
688
+ * Install strategy: **method-level** on `navigator`. Assigning
689
+ * `navigator.share = fn` creates an own property that shadows the prototype
690
+ * method. Uninstall deletes the own shadow so the prototype method surfaces
691
+ * again. We do not mutate `Navigator.prototype` — in real browsers its
692
+ * descriptor may be non-configurable, which would throw on reassignment.
693
+ *
694
+ * Caveat: the SDK's share has no counterpart for `files` (Web Share Level 2).
695
+ * `canShare({ files })` returns `false` whenever the sync-accessible detection
696
+ * says Toss is active (or is being forced via the test override).
697
+ */
698
+ const SHARE_BACKUP_KEY = Symbol.for("@ait-co/polyfill/share.original");
699
+ const SHARE_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/share.snapshot");
700
+ function buildSdkMessage(data) {
701
+ const parts = [];
702
+ if (data?.title != null && data.title !== "") parts.push(data.title);
703
+ if (data?.text != null && data.text !== "") parts.push(data.text);
704
+ if (data?.url != null && data.url !== "") parts.push(data.url);
705
+ return parts.join("\n");
706
+ }
707
+ async function shareShim(data) {
708
+ if (await isTossEnvironment()) {
709
+ const fn = (await loadTossSdk())?.share;
710
+ if (typeof fn === "function") {
711
+ const message = buildSdkMessage(data);
712
+ if (!message) throw new TypeError("[@ait-co/polyfill] navigator.share requires at least one of title, text, or url.");
713
+ try {
714
+ await fn({ message });
715
+ } catch (e) {
716
+ const message_ = e instanceof Error ? e.message : String(e);
717
+ const wrapped = new DOMException(message_, "AbortError");
718
+ if (e instanceof Error) wrapped.cause = e;
719
+ throw wrapped;
720
+ }
721
+ return;
722
+ }
723
+ }
724
+ const original = navigator[SHARE_BACKUP_KEY]?.share;
725
+ if (!original) throw new DOMException("[@ait-co/polyfill] navigator.share is not available in this environment.", "NotSupportedError");
726
+ return original(data);
727
+ }
728
+ function canShareShim(data) {
729
+ const hasFiles = Boolean(data?.files && data.files.length > 0);
730
+ const toss = isTossEnvironmentCached();
731
+ if (hasFiles) {
732
+ if (toss === true) return false;
733
+ if (toss === void 0) return false;
734
+ }
735
+ if (toss === true) return Boolean(data?.title != null && data.title !== "" || data?.text != null && data.text !== "" || data?.url != null && data.url !== "");
736
+ const originalCanShare = navigator[SHARE_BACKUP_KEY]?.canShare;
737
+ if (originalCanShare) return originalCanShare(data);
738
+ return Boolean(data?.title != null && data.title !== "" || data?.text != null && data.text !== "" || data?.url != null && data.url !== "");
739
+ }
740
+ function installShareShim() {
741
+ if (typeof navigator === "undefined") return () => {};
742
+ const host = navigator;
743
+ if (SHARE_BACKUP_KEY in host) return () => uninstallShareShim();
744
+ const nav = navigator;
745
+ host[SHARE_BACKUP_KEY] = {
746
+ share: nav.share ? nav.share.bind(navigator) : void 0,
747
+ canShare: nav.canShare ? nav.canShare.bind(navigator) : void 0
748
+ };
749
+ const snapshot = installObjectMethods(navigator, {
750
+ share: shareShim,
751
+ canShare: canShareShim
752
+ });
753
+ if (!snapshot) {
754
+ delete host[SHARE_BACKUP_KEY];
755
+ return () => uninstallShareShim();
756
+ }
757
+ host[SHARE_SNAPSHOT_KEY] = snapshot;
758
+ return uninstallShareShim;
759
+ }
760
+ function uninstallShareShim() {
761
+ if (typeof navigator === "undefined") return;
762
+ const host = navigator;
763
+ if (!(SHARE_BACKUP_KEY in host)) return;
764
+ const snapshot = host[SHARE_SNAPSHOT_KEY];
765
+ if (snapshot) restoreObjectMethods(snapshot);
766
+ delete host[SHARE_BACKUP_KEY];
767
+ delete host[SHARE_SNAPSHOT_KEY];
768
+ }
769
+ //#endregion
770
+ //#region src/shims/vibrate.ts
771
+ /**
772
+ * `navigator.vibrate` shim.
773
+ *
774
+ * Inside Apps in Toss → best-effort mapping to SDK `generateHapticFeedback`.
775
+ * Single-duration calls land in three buckets so the qualitative SDK haptic
776
+ * tracks intensity a little more closely than the original two-bucket split:
777
+ * - `vibrate(0)` → no-op (web standard: cancels pending vibration)
778
+ * - `vibrate(1..20ms)` → `tickWeak`
779
+ * - `vibrate(21..45ms)` → `tickMedium`
780
+ * - `vibrate(>=46ms)` → `basicMedium`
781
+ * - `vibrate(number[])` → iterates "on" segments (even indices) as `tap`
782
+ * pulses with `setTimeout` gaps. Per-element ms mapping is intentionally
783
+ * skipped: arrays in the wild are mostly rhythmic patterns, and the SDK
784
+ * has no "stronger heavy" variant to reach for, so per-pulse precision
785
+ * buys little. Callers needing intent should use `vibrateSemantic`.
786
+ *
787
+ * Outside Apps in Toss → defers to the browser's native `navigator.vibrate`,
788
+ * or returns `false` when unavailable (matches the spec — browsers that don't
789
+ * support vibration simply return `false`).
790
+ *
791
+ * Install strategy: **method-level** on `navigator`. We assign our wrapper to
792
+ * `navigator.vibrate` (creating an own shadow over the prototype method) and
793
+ * delete it on uninstall so the prototype re-surfaces. We do not mutate
794
+ * `Navigator.prototype` itself — browsers may mark it non-configurable.
795
+ *
796
+ * Caveats (documented in CLAUDE.md as the known lossy trade-off):
797
+ * - SDK haptics are qualitative ("tickWeak", "basicMedium"), not millisecond
798
+ * durations. The shim approximates intensity from duration but cannot
799
+ * reproduce exact patterns. Length-only mapping cannot recover semantic
800
+ * intent (success vs. error vs. warning); use `vibrateSemantic` for that.
801
+ * - Arrays are fired sequentially via `setTimeout`; gaps between pulses are
802
+ * honoured only as "time until the next tap", not as silent-vs-vibrating.
803
+ * - `vibrate` is spec'd as **synchronous**; the SDK call is async. We return
804
+ * `true` immediately (fire-and-forget). Errors from the SDK are swallowed.
805
+ */
806
+ const BACKUP_KEY = Symbol.for("@ait-co/polyfill/vibrate.original");
807
+ const SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/vibrate.snapshot");
808
+ const TICK_WEAK_MAX_MS = 20;
809
+ const TICK_MEDIUM_MAX_MS = 45;
810
+ async function haptic(type) {
811
+ const fn = (await loadTossSdk())?.generateHapticFeedback;
812
+ if (typeof fn === "function") try {
813
+ await fn({ type });
814
+ } catch {}
815
+ }
816
+ function durationToHaptic(duration) {
817
+ if (duration <= TICK_WEAK_MAX_MS) return "tickWeak";
818
+ if (duration <= TICK_MEDIUM_MAX_MS) return "tickMedium";
819
+ return "basicMedium";
820
+ }
821
+ function vibrateShim(pattern) {
822
+ const arr = Array.isArray(pattern) ? pattern : [pattern];
823
+ if (arr.length === 0 || arr.every((n) => n === 0)) {
824
+ (async () => {
825
+ if (!await isTossEnvironment()) navigator[BACKUP_KEY]?.(pattern);
826
+ })();
827
+ return true;
828
+ }
829
+ (async () => {
830
+ if (await isTossEnvironment()) {
831
+ if (!Array.isArray(pattern)) {
832
+ await haptic(durationToHaptic(pattern));
833
+ return;
834
+ }
835
+ for (let i = 0; i < pattern.length; i += 2) {
836
+ const on = pattern[i];
837
+ if (on === void 0) break;
838
+ if (on > 0) await haptic("tap");
839
+ const pause = pattern[i + 1];
840
+ if (typeof pause === "number" && pause > 0) await new Promise((r) => setTimeout(r, pause));
841
+ }
842
+ return;
843
+ }
844
+ const original = navigator[BACKUP_KEY];
845
+ original?.(pattern);
846
+ })();
847
+ return true;
848
+ }
849
+ function installVibrateShim() {
850
+ if (typeof navigator === "undefined") return () => {};
851
+ const host = navigator;
852
+ if (BACKUP_KEY in host) return () => uninstallVibrateShim();
853
+ const nav = navigator;
854
+ host[BACKUP_KEY] = nav.vibrate ? nav.vibrate.bind(navigator) : void 0;
855
+ const snapshot = installObjectMethods(navigator, { vibrate: vibrateShim });
856
+ if (!snapshot) {
857
+ delete host[BACKUP_KEY];
858
+ return () => uninstallVibrateShim();
859
+ }
860
+ host[SNAPSHOT_KEY] = snapshot;
861
+ return uninstallVibrateShim;
862
+ }
863
+ function uninstallVibrateShim() {
864
+ if (typeof navigator === "undefined") return;
865
+ const host = navigator;
866
+ if (!(BACKUP_KEY in host)) return;
867
+ const snapshot = host[SNAPSHOT_KEY];
868
+ if (snapshot) restoreObjectMethods(snapshot);
869
+ delete host[BACKUP_KEY];
870
+ delete host[SNAPSHOT_KEY];
871
+ }
872
+ //#endregion
873
+ //#region src/index.ts
874
+ const NOOP = () => {};
875
+ /**
876
+ * Install every shim this library ships, but only if we detect an Apps in
877
+ * Toss runtime. In a plain browser `install()` is a no-op — the browser's
878
+ * native APIs stay untouched.
879
+ *
880
+ * Returns a promise that resolves with an uninstall function. If the
881
+ * environment turns out not to be Toss, the uninstall function is a no-op.
882
+ *
883
+ * Install order (when active): clipboard → geolocation → share → vibrate →
884
+ * network. Not atomic on failure — if a per-shim install throws (e.g., a
885
+ * consumer pinned a target navigator property as non-configurable), earlier
886
+ * shims are already in place. Callers should catch and invoke the returned
887
+ * uninstall to roll back.
888
+ */
889
+ async function install() {
890
+ if (!await isTossEnvironment()) return NOOP;
891
+ const uninstalls = [
892
+ installClipboardShim(),
893
+ installGeolocationShim(),
894
+ installShareShim(),
895
+ installVibrateShim(),
896
+ installNetworkShim()
897
+ ];
898
+ return () => {
899
+ for (const fn of uninstalls) fn();
900
+ };
901
+ }
902
+ //#endregion
903
+ //#region src/auto.ts
904
+ /**
905
+ * Side-effect entry point: `import '@ait-co/polyfill/auto'`
906
+ *
907
+ * Kicks off detection and, if we're inside Apps in Toss, installs every shim
908
+ * this library ships. In a plain browser this is a no-op — browser native
909
+ * APIs stay untouched. No-op idempotent: importing the entry more than once
910
+ * doesn't re-install.
911
+ *
912
+ * Use this when you want the "just add the dep" experience. If you need to
913
+ * observe when the polyfill actually attached (to gate init logic) or to tear
914
+ * it down, import `install` / `uninstall` from `@ait-co/polyfill` directly.
915
+ */
916
+ install();
917
+ //#endregion
918
+
919
+ //# sourceMappingURL=auto.cjs.map