@ait-co/polyfill 0.1.1
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/README.md +83 -0
- package/dist/detect.d.ts +45 -0
- package/dist/detect.d.ts.map +1 -0
- package/dist/detect.js +65 -0
- package/dist/detect.js.map +1 -0
- package/dist/index.d.ts +197 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +754 -0
- package/dist/index.js.map +1 -0
- package/dist/shims/clipboard.d.ts +28 -0
- package/dist/shims/clipboard.d.ts.map +1 -0
- package/dist/shims/clipboard.js +137 -0
- package/dist/shims/clipboard.js.map +1 -0
- package/dist/shims/geolocation.d.ts +34 -0
- package/dist/shims/geolocation.d.ts.map +1 -0
- package/dist/shims/geolocation.js +252 -0
- package/dist/shims/geolocation.js.map +1 -0
- package/dist/shims/network.d.ts +47 -0
- package/dist/shims/network.d.ts.map +1 -0
- package/dist/shims/network.js +209 -0
- package/dist/shims/network.js.map +1 -0
- package/dist/shims/share.d.ts +20 -0
- package/dist/shims/share.d.ts.map +1 -0
- package/dist/shims/share.js +158 -0
- package/dist/shims/share.js.map +1 -0
- package/dist/shims/vibrate.d.ts +27 -0
- package/dist/shims/vibrate.d.ts.map +1 -0
- package/dist/shims/vibrate.js +135 -0
- package/dist/shims/vibrate.js.map +1 -0
- package/package.json +92 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["BACKUP_KEY","HAD_KEY","BACKUP_KEY","#status"],"sources":["../src/detect.ts","../src/shims/clipboard.ts","../src/shims/geolocation.ts","../src/shims/network.ts","../src/shims/share.ts","../src/shims/vibrate.ts","../src/index.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: feature-sniff `@apps-in-toss/web-framework`. The SDK is declared as\n * an **optional** peer dependency. If it resolves and exposes a known export,\n * we assume we can route calls through it; otherwise we fall back to the\n * browser's native implementation in each shim.\n *\n * We deliberately avoid UA sniffing (spoofable) and avoid calling any SDK\n * function during detection (could prompt permission dialogs, fire analytics,\n * etc.).\n */\n\nlet cached: boolean | undefined;\n\n/**\n * Reset the cached detection result. Primarily for tests.\n */\nexport function resetDetection(): void {\n cached = undefined;\n}\n\n/**\n * Synchronous read of the cached detection result. Returns:\n * - `true` / `false` if an override is active or the async detection has\n * already resolved\n * - `undefined` if detection hasn't run yet\n *\n * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`\n * detection.\n */\nexport function isTossEnvironmentCached(): boolean | undefined {\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n return cached;\n}\n\n/**\n * Returns `true` iff we detect we are running in an environment where the\n * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.\n *\n * Async because we use dynamic `import()` to probe the optional peer dep\n * without forcing it into the consumer's bundle.\n */\nexport async function isTossEnvironment(): Promise<boolean> {\n // Override check precedes cache so `devtools` / tests can flip the result\n // mid-session without a `resetDetection()` call.\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n\n if (cached !== undefined) return cached;\n\n const mod = await loadTossSdk();\n // Presence of a well-known export is our smoke test.\n cached = typeof mod?.getClipboardText === 'function';\n return cached;\n}\n\n/**\n * Lazy SDK accessor — returns the module if available, else `null`. Callers\n * are expected to `await` and null-check. Never throws.\n */\nexport async function loadTossSdk(): Promise<typeof import('@apps-in-toss/web-framework') | null> {\n try {\n return await import('@apps-in-toss/web-framework');\n } catch {\n return null;\n }\n}\n","/**\n * `navigator.clipboard` shim.\n *\n * Inside Apps in Toss → routes `readText` / `writeText` through the SDK\n * (`getClipboardText` / `setClipboardText`).\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.\n * If the browser doesn't implement it, the standard `TypeError` / `DOMException`\n * surfaces unchanged — we don't paper over missing support.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/clipboard.original');\nconst HAD_KEY = Symbol.for('@ait-co/polyfill/clipboard.hadOriginal');\n\ninterface BackupHost {\n [BACKUP_KEY]?: Clipboard | undefined;\n [HAD_KEY]?: boolean;\n}\n\n/**\n * Produces a Clipboard-compatible object whose `readText` / `writeText` methods\n * route to the SDK when in Toss, else fall through to the supplied `fallback`.\n */\nfunction createClipboardShim(fallback: Clipboard | undefined): Clipboard {\n const shim = {\n async readText(): Promise<string> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n if (sdk?.getClipboardText) {\n return sdk.getClipboardText();\n }\n }\n if (!fallback) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.readText is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return fallback.readText();\n },\n\n async writeText(text: string): Promise<void> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n if (sdk?.setClipboardText) {\n return sdk.setClipboardText(text);\n }\n }\n if (!fallback) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.writeText is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return fallback.writeText(text);\n },\n\n // `read` / `write` (ClipboardItem-based) are passed through to the\n // fallback when in browser mode; the SDK has no rich-content counterpart,\n // so in Toss mode they throw.\n async read(): Promise<ClipboardItems> {\n if (await isTossEnvironment()) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.read (rich content) is not supported in the Apps in Toss environment. Use readText instead.',\n 'NotSupportedError',\n );\n }\n if (!fallback?.read) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.read is not available.',\n 'NotSupportedError',\n );\n }\n return fallback.read();\n },\n\n async write(items: ClipboardItems): Promise<void> {\n if (await isTossEnvironment()) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.write (rich content) is not supported in the Apps in Toss environment. Use writeText instead.',\n 'NotSupportedError',\n );\n }\n if (!fallback?.write) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.write is not available.',\n 'NotSupportedError',\n );\n }\n return fallback.write(items);\n },\n\n // EventTarget passthrough. `navigator.clipboard` extends EventTarget in the\n // spec; mini-apps rarely use it. We forward to the fallback when one exists;\n // in Toss mode (no fallback) we silently drop subscriptions — the SDK emits\n // no clipboard events, so there is nothing to dispatch. This is lossy but\n // preserves the spec-compatible shape.\n addEventListener: (\n ...args: Parameters<EventTarget['addEventListener']>\n ): ReturnType<EventTarget['addEventListener']> => fallback?.addEventListener(...args),\n removeEventListener: (\n ...args: Parameters<EventTarget['removeEventListener']>\n ): ReturnType<EventTarget['removeEventListener']> => fallback?.removeEventListener(...args),\n // Returns `false` in Toss mode (no backing EventTarget). A caller that reads\n // this as \"default action cancelled\" should check context — there are no\n // listeners to run because the SDK doesn't surface clipboard events.\n dispatchEvent: (event: Event): boolean => fallback?.dispatchEvent(event) ?? false,\n } satisfies Clipboard;\n\n return shim;\n}\n\n/**\n * Install the `navigator.clipboard` shim.\n *\n * @returns an uninstall function that restores the original `navigator.clipboard`.\n * Calling install twice without uninstalling is a no-op on the second call\n * and returns the same uninstall function.\n */\nexport function installClipboardShim(): () => void {\n if (typeof navigator === 'undefined') {\n // No-op in non-DOM environments (pure Node).\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (BACKUP_KEY in host) {\n // Already installed. Use `in` (not `!== undefined`) because the stored\n // backup is legitimately `undefined` when the browser has no native\n // `navigator.clipboard` — without this, we'd re-wrap on each install.\n // Note: the returned uninstall is global. Any caller's uninstall fully\n // removes the shim; callers do not have independent install handles.\n return () => uninstallClipboardShim();\n }\n\n const original = navigator.clipboard as Clipboard | undefined;\n host[BACKUP_KEY] = original;\n host[HAD_KEY] = 'clipboard' in navigator;\n\n const shim = createClipboardShim(original);\n Object.defineProperty(navigator, 'clipboard', {\n value: shim,\n configurable: true,\n writable: true,\n });\n\n return uninstallClipboardShim;\n}\n\n/**\n * Remove the shim and restore the pre-install shape. Uses delete + conditional\n * redefine so a prototype-level `navigator.clipboard` (non-configurable in real\n * browsers) becomes visible again instead of being permanently shadowed.\n */\nexport function uninstallClipboardShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(BACKUP_KEY in host)) return;\n\n const original = host[BACKUP_KEY];\n const had = host[HAD_KEY];\n delete (navigator as unknown as { clipboard?: Clipboard }).clipboard;\n if (had && navigator.clipboard !== original) {\n Object.defineProperty(navigator, 'clipboard', {\n value: original,\n configurable: true,\n writable: true,\n });\n }\n delete host[BACKUP_KEY];\n delete host[HAD_KEY];\n}\n","/**\n * `navigator.geolocation` shim.\n *\n * Inside Apps in Toss → routes through the SDK:\n * - `getCurrentPosition` → `getCurrentLocation({ accuracy })`\n * - `watchPosition` / `clearWatch` → `startUpdateLocation({ onEvent, onError, options })`\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.geolocation`.\n * If neither is available, the error callback receives a `GeolocationPositionError`.\n *\n * SDK/Web shape mismatch handled here:\n * - SDK `Accuracy` is a numeric enum (1 = Lowest … 6 = BestForNavigation); the\n * standard `PositionOptions.enableHighAccuracy` is a boolean. We map\n * `true → Accuracy.High (4, \"~10m\")` and `false → Accuracy.Balanced (3)`.\n * `Highest (5)` / `BestForNavigation (6)` are available but carry a battery\n * cost that's rarely what mini-apps want; consumers who need them should\n * call the SDK directly.\n * - SDK coords lack `speed`; we surface `null` (per the W3C spec when unknown).\n * - SDK `startUpdateLocation` returns an `unsubscribe` fn; we wrap it behind\n * a numeric watch id so `clearWatch(id)` behaves like the standard.\n *\n * Caveat: watch ids reset whenever the shim is uninstalled and reinstalled;\n * they are not stable across such cycles. Ids obtained before uninstall\n * cannot be cleared after uninstall — `clearWatch(id)` on the restored native\n * `navigator.geolocation` uses a different id space, so the SDK subscription\n * leaks. Consumers should `clearWatch` all outstanding ids before calling\n * `uninstall()`.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/geolocation.original');\n\ninterface BackupHost {\n [BACKUP_KEY]?: Geolocation | undefined;\n}\n\n// SDK Accuracy enum values. We don't import the enum at runtime (peer is\n// optional), so we hard-code the numeric constants used by the SDK. Stable\n// ABI per the SDK's exported numeric enum.\nconst ACCURACY_BALANCED = 3;\nconst ACCURACY_HIGH = 4;\n\ninterface SdkLocationCoords {\n latitude: number;\n longitude: number;\n altitude: number;\n accuracy: number;\n altitudeAccuracy: number;\n heading: number;\n}\n\ninterface SdkLocation {\n timestamp: number;\n coords: SdkLocationCoords;\n}\n\nfunction toStandardPosition(sdk: SdkLocation): GeolocationPosition {\n const coordsData = {\n latitude: sdk.coords.latitude,\n longitude: sdk.coords.longitude,\n altitude: sdk.coords.altitude,\n accuracy: sdk.coords.accuracy,\n altitudeAccuracy: sdk.coords.altitudeAccuracy,\n heading: sdk.coords.heading,\n // SDK does not surface speed. Per spec, null means \"unknown\".\n speed: null,\n };\n const coords: GeolocationCoordinates = {\n ...coordsData,\n toJSON() {\n return { ...coordsData };\n },\n };\n return {\n coords,\n timestamp: sdk.timestamp,\n toJSON() {\n return { coords: { ...coordsData }, timestamp: sdk.timestamp };\n },\n };\n}\n\nfunction toPositionError(code: 1 | 2 | 3, message: string): GeolocationPositionError {\n // Prefer the real constructor when available (every real browser ships it).\n // The spec says GeolocationPositionError is not constructable, so we fall\n // through to a fabricated object whose prototype is patched via\n // `setPrototypeOf` — that keeps `instanceof` checks in consumer code working\n // and picks up the spec's PERMISSION_DENIED / POSITION_UNAVAILABLE / TIMEOUT\n // constants from the real prototype rather than hard-coding them (avoids\n // drift if the spec ever grows a new code).\n const Ctor = (globalThis as { GeolocationPositionError?: unknown }).GeolocationPositionError;\n if (typeof Ctor === 'function') {\n const proto = (Ctor as { prototype?: object }).prototype;\n if (proto) {\n const shape: { code: number; message: string } = { code, message };\n Object.setPrototypeOf(shape, proto);\n return shape as GeolocationPositionError;\n }\n }\n // jsdom / last-resort fallback: fabricate the spec shape with hard-coded\n // constants since there's no prototype to delegate to.\n return {\n code,\n message,\n PERMISSION_DENIED: 1,\n POSITION_UNAVAILABLE: 2,\n TIMEOUT: 3,\n } as GeolocationPositionError;\n}\n\nfunction accuracyFromOptions(options: PositionOptions | undefined): number {\n return options?.enableHighAccuracy ? ACCURACY_HIGH : ACCURACY_BALANCED;\n}\n\nfunction createGeolocationShim(fallback: Geolocation | undefined): Geolocation {\n // Numeric watch id → SDK unsubscribe fn. Keeps the shim's API in line with\n // the standard even though the SDK issues unsubscribe closures instead.\n // `pendingWatches` closes the race where `clearWatch` is called before the\n // async `watchPosition` installer resolves — without it we'd leak the SDK\n // subscription.\n let nextWatchId = 1;\n const sdkWatches = new Map<number, () => void>();\n const nativeWatches = new Map<number, number>();\n const pendingWatches = new Map<number, { cancelled: boolean }>();\n\n const shim: Geolocation = {\n getCurrentPosition(success, error, options) {\n void (async () => {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { getCurrentLocation?: unknown } | null)?.getCurrentLocation;\n if (typeof fn === 'function') {\n try {\n const loc = (await (fn as (o: { accuracy: number }) => Promise<SdkLocation>)({\n accuracy: accuracyFromOptions(options),\n })) as SdkLocation;\n success(toStandardPosition(loc));\n } catch (e) {\n error?.(\n toPositionError(\n 2,\n e instanceof Error ? e.message : '[@ait-co/polyfill] getCurrentLocation failed.',\n ),\n );\n }\n return;\n }\n }\n if (!fallback) {\n error?.(\n toPositionError(\n 2,\n '[@ait-co/polyfill] navigator.geolocation is not available in this environment.',\n ),\n );\n return;\n }\n fallback.getCurrentPosition(success, error, options);\n })();\n },\n\n watchPosition(success, error, options) {\n const id = nextWatchId++;\n const pending = { cancelled: false };\n pendingWatches.set(id, pending);\n\n void (async () => {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { startUpdateLocation?: unknown } | null)?.startUpdateLocation;\n if (typeof fn === 'function') {\n if (pending.cancelled) {\n pendingWatches.delete(id);\n return;\n }\n const unsubscribe = (\n fn as (p: {\n onEvent: (loc: SdkLocation) => void;\n onError: (err: unknown) => void;\n options: { accuracy: number; timeInterval: number; distanceInterval: number };\n }) => () => void\n )({\n onEvent: (loc) => success(toStandardPosition(loc)),\n onError: (err) =>\n error?.(\n toPositionError(\n 2,\n err instanceof Error\n ? err.message\n : '[@ait-co/polyfill] startUpdateLocation failed.',\n ),\n ),\n options: {\n accuracy: accuracyFromOptions(options),\n // Sensible defaults — web `watchPosition` has no analogues.\n // Consumers needing sub-second updates should use the SDK directly.\n timeInterval: 1000,\n distanceInterval: 0,\n },\n });\n if (pending.cancelled) {\n unsubscribe();\n pendingWatches.delete(id);\n return;\n }\n sdkWatches.set(id, unsubscribe);\n pendingWatches.delete(id);\n return;\n }\n }\n if (!fallback) {\n pendingWatches.delete(id);\n error?.(\n toPositionError(\n 2,\n '[@ait-co/polyfill] navigator.geolocation is not available in this environment.',\n ),\n );\n return;\n }\n if (pending.cancelled) {\n pendingWatches.delete(id);\n return;\n }\n const nativeId = fallback.watchPosition(success, error, options);\n if (pending.cancelled) {\n fallback.clearWatch(nativeId);\n pendingWatches.delete(id);\n return;\n }\n nativeWatches.set(id, nativeId);\n pendingWatches.delete(id);\n })();\n\n return id;\n },\n\n clearWatch(id) {\n const pending = pendingWatches.get(id);\n if (pending) {\n pending.cancelled = true;\n pendingWatches.delete(id);\n return;\n }\n const unsubscribe = sdkWatches.get(id);\n if (unsubscribe) {\n unsubscribe();\n sdkWatches.delete(id);\n return;\n }\n const nativeId = nativeWatches.get(id);\n if (nativeId !== undefined && fallback) {\n fallback.clearWatch(nativeId);\n nativeWatches.delete(id);\n }\n },\n };\n\n return shim;\n}\n\nexport function installGeolocationShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (BACKUP_KEY in host) {\n return () => uninstallGeolocationShim();\n }\n\n const original = navigator.geolocation as Geolocation | undefined;\n host[BACKUP_KEY] = original;\n\n const shim = createGeolocationShim(original);\n Object.defineProperty(navigator, 'geolocation', {\n value: shim,\n configurable: true,\n writable: true,\n });\n\n return uninstallGeolocationShim;\n}\n\nexport function uninstallGeolocationShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(BACKUP_KEY in host)) return;\n\n const original = host[BACKUP_KEY];\n // Delete our instance-level override so the prototype getter (on real\n // browsers) shows through again. `defineProperty` with value would leave\n // a permanent instance shadow.\n delete (navigator as unknown as { geolocation?: Geolocation }).geolocation;\n if (original !== undefined && navigator.geolocation !== original) {\n // In jsdom or test shims where the original lived on the instance, put it\n // back explicitly — the delete above would otherwise leave nothing behind.\n Object.defineProperty(navigator, 'geolocation', {\n value: original,\n configurable: true,\n writable: true,\n });\n }\n delete host[BACKUP_KEY];\n}\n","/**\n * `navigator.onLine` + `navigator.connection` shim.\n *\n * Inside Apps in Toss → seeded from SDK `getNetworkStatus()` on install and\n * refreshed on read (throttled):\n * - `'OFFLINE'` → `onLine = false`\n * - `'WIFI'` → `onLine = true`, `effectiveType = '4g'` (no web wifi value)\n * - `'2G'/'3G'/'4G'/'5G'` → `onLine = true`, `effectiveType = <lowercased>`\n * - `'WWAN'/'UNKNOWN'` → `onLine = true`, `effectiveType = '4g'` (best guess)\n *\n * Outside Apps in Toss → both `navigator.onLine` and `navigator.connection`\n * read through to the native value. Install installs own-instance getters\n * that consult the Toss-seeded cache first; when the cache is empty (which\n * it always is in browser mode), the getter temporarily removes its own\n * shadow, reads the prototype value, and reinstates the shadow.\n *\n * Uninstall `delete`s the instance-level override so the prototype descriptor\n * (where `onLine` and `connection` actually live in real browsers) becomes\n * visible again. We never mutate the prototype — doing so would throw in\n * browsers where the descriptor is non-configurable.\n *\n * Caveat: the Web NetworkInformation API is evented (`change` fires on\n * transitions). The SDK exposes only a one-shot query, so listeners attached\n * to `navigator.connection` are accepted but never fire from a `change` event\n * unless the shim observes a real status transition. Synthesising richer\n * events via polling is tracked in TODO.md.\n *\n * Lifecycle: `navigator.connection` is a ShimConnection instance that lives in\n * the install closure. On uninstall the instance-level override is removed,\n * but listeners the consumer attached to the old instance stay bound to that\n * (now-orphan) object and will not see events from a subsequent install.\n * Consumers should re-attach listeners after each install.\n *\n * Seed-boundary race: in Toss mode, reads before the install-time SDK seed\n * completes fall through to the native `navigator.connection`. After the seed\n * lands, subsequent reads return the shim's ShimConnection. Consumers that\n * specifically need the ShimConnection instance (e.g., to attach `change`\n * listeners that fire on Toss network transitions) should wait a microtask\n * after `install()` before attaching listeners, or accept that pre-seed\n * reads may return the native object.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\n\nconst INSTALLED_KEY = Symbol.for('@ait-co/polyfill/network.installed');\n\ninterface BackupHost {\n [INSTALLED_KEY]?: boolean;\n}\n\ntype SdkNetworkStatus = 'OFFLINE' | 'WIFI' | '2G' | '3G' | '4G' | '5G' | 'WWAN' | 'UNKNOWN';\ntype EffectiveType = 'slow-2g' | '2g' | '3g' | '4g';\n\nconst REFRESH_THROTTLE_MS = 500;\n\nfunction statusToOnline(status: SdkNetworkStatus): boolean {\n return status !== 'OFFLINE';\n}\n\nfunction statusToEffectiveType(status: SdkNetworkStatus): EffectiveType {\n switch (status) {\n case '2G':\n return '2g';\n case '3G':\n return '3g';\n default:\n return '4g';\n }\n}\n\nfunction statusToConnectionType(status: SdkNetworkStatus): string {\n switch (status) {\n case 'WIFI':\n return 'wifi';\n case '2G':\n case '3G':\n case '4G':\n case '5G':\n case 'WWAN':\n return 'cellular';\n case 'OFFLINE':\n return 'none';\n default:\n return 'unknown';\n }\n}\n\n// Symbol-keyed setter: the install closure can mutate status without exposing\n// a `setStatus` name on `navigator.connection` (real NetworkInformation has\n// no mutator). `Object.getOwnPropertySymbols(navigator.connection)` returns\n// nothing, so casual enumeration can't find it. A determined caller walking\n// the prototype chain (`Object.getOwnPropertySymbols(Object.getPrototypeOf(...))`)\n// can still surface the symbol — there is no trust boundary between polyfill\n// and consumer code in the same realm, so this is a discouragement, not a\n// security control.\nconst SET_STATUS = Symbol('@ait-co/polyfill/network.setStatus');\n\nclass ShimConnection extends EventTarget {\n #status: SdkNetworkStatus | null = null;\n onchange: ((this: ShimConnection, ev: Event) => unknown) | null = null;\n\n constructor() {\n super();\n // Forward `change` events to the legacy `onchange` handler for parity with\n // the NetworkInformation API.\n this.addEventListener('change', (ev) => this.onchange?.call(this, ev));\n }\n\n [SET_STATUS](next: SdkNetworkStatus | null): void {\n this.#status = next;\n }\n\n get effectiveType(): EffectiveType {\n return statusToEffectiveType(this.#status ?? 'UNKNOWN');\n }\n // `downlink` / `rtt` / `saveData` are placeholders — the SDK does not expose\n // these. We return 0/false rather than fabricate plausible numbers. Noted\n // in CLAUDE.md.\n get downlink(): number {\n return 0;\n }\n get rtt(): number {\n return 0;\n }\n get saveData(): boolean {\n return false;\n }\n get type(): string {\n return statusToConnectionType(this.#status ?? 'UNKNOWN');\n }\n}\n\nexport function installNetworkShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (host[INSTALLED_KEY]) {\n return () => uninstallNetworkShim();\n }\n host[INSTALLED_KEY] = true;\n\n // Per-install state. Kept in closure so uninstall/reinstall cycles don't\n // leak state between instances (module-scope would leak across tests).\n let cachedStatus: SdkNetworkStatus | null = null;\n let lastRefresh = 0;\n let inflight: Promise<void> | null = null;\n const connection = new ShimConnection();\n\n async function refresh(): Promise<void> {\n // Coalesce concurrent refreshes — without this, rapid reads during an\n // in-flight SDK call each set `lastRefresh` and return early, without\n // anyone actually fetching fresh data.\n if (inflight) return inflight;\n const now = Date.now();\n if (now - lastRefresh < REFRESH_THROTTLE_MS) return;\n inflight = (async () => {\n try {\n if (!(await isTossEnvironment())) return;\n const sdk = await loadTossSdk();\n const fn = (sdk as { getNetworkStatus?: unknown } | null)?.getNetworkStatus;\n if (typeof fn !== 'function') return;\n const next = (await (fn as () => Promise<SdkNetworkStatus>)()) as SdkNetworkStatus;\n const prev = cachedStatus;\n cachedStatus = next;\n connection[SET_STATUS](next);\n // Only dispatch `change` on real transitions — the null → X seed on\n // first install is learning, not a transition, and would otherwise\n // mis-trigger consumer handlers.\n if (prev !== null && prev !== next) {\n connection.dispatchEvent(new Event('change'));\n }\n } catch {\n // Advisory — refresh failures keep the prior cache. `void refresh()`\n // callers would otherwise surface unhandled rejections if\n // isTossEnvironment / loadTossSdk / getNetworkStatus ever throw.\n } finally {\n lastRefresh = Date.now();\n inflight = null;\n }\n })();\n return inflight;\n }\n\n // Seed the cache on install so the first sync read is meaningful.\n void refresh();\n\n Object.defineProperty(navigator, 'onLine', {\n configurable: true,\n get() {\n void refresh();\n if (cachedStatus !== null) {\n return statusToOnline(cachedStatus);\n }\n // Fall back to whatever the prototype would have returned. Temporarily\n // delete our shadow to read through; the try/finally guarantees the\n // shadow is restored even if the prototype getter throws.\n const desc = Object.getOwnPropertyDescriptor(navigator, 'onLine');\n delete (navigator as unknown as { onLine?: boolean }).onLine;\n try {\n return navigator.onLine;\n } finally {\n if (desc) Object.defineProperty(navigator, 'onLine', desc);\n }\n },\n });\n\n Object.defineProperty(navigator, 'connection', {\n configurable: true,\n get() {\n void refresh();\n // Symmetric with `onLine`: when the SDK hasn't seeded us (either a\n // browser-mode install or pre-seed Toss), read through to the native\n // `navigator.connection` so consumers in plain browsers don't see a\n // hardcoded `effectiveType: '4g'` default.\n if (cachedStatus === null) {\n const desc = Object.getOwnPropertyDescriptor(navigator, 'connection');\n delete (navigator as unknown as { connection?: unknown }).connection;\n try {\n const native = (navigator as Navigator & { connection?: unknown }).connection;\n if (native !== undefined) return native;\n } finally {\n if (desc) Object.defineProperty(navigator, 'connection', desc);\n }\n }\n return connection;\n },\n });\n\n return uninstallNetworkShim;\n}\n\nexport function uninstallNetworkShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!host[INSTALLED_KEY]) return;\n\n // `delete` the instance-level property so the prototype descriptor (where\n // `onLine` and `connection` actually live in real browsers) is exposed\n // again. Redefining the prototype would throw on non-configurable getters.\n delete (navigator as unknown as { onLine?: boolean }).onLine;\n delete (navigator as unknown as { connection?: unknown }).connection;\n\n delete host[INSTALLED_KEY];\n}\n","/**\n * `navigator.share` shim.\n *\n * Inside Apps in Toss → routes through SDK `share({ message })`. The SDK only\n * accepts a single `message` string, so we concatenate `title`, `text`, and\n * `url` with newline separators (skipping missing/empty values).\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.share`, or\n * throws `NotSupportedError` if unavailable.\n *\n * Caveat: the SDK's share has no counterpart for `files` (Web Share Level 2).\n * `canShare({ files })` returns `false` whenever the sync-accessible detection\n * says Toss is active (or is being forced via the test override).\n */\n\nimport { isTossEnvironment, isTossEnvironmentCached, loadTossSdk } from '../detect.js';\n\nconst SHARE_BACKUP_KEY = Symbol.for('@ait-co/polyfill/share.original');\n\ntype ShareFn = (data?: ShareData) => Promise<void>;\ntype CanShareFn = (data?: ShareData) => boolean;\n\ninterface Backup {\n share?: ShareFn | undefined;\n canShare?: CanShareFn | undefined;\n hadShare: boolean;\n hadCanShare: boolean;\n}\n\ninterface BackupHost {\n [SHARE_BACKUP_KEY]?: Backup | undefined;\n}\n\nfunction buildSdkMessage(data: ShareData | undefined): string {\n // Use presence checks rather than truthiness so an intentionally empty\n // string in one field is handled correctly alongside a non-empty sibling.\n const parts: string[] = [];\n if (data?.title != null && data.title !== '') parts.push(data.title);\n if (data?.text != null && data.text !== '') parts.push(data.text);\n if (data?.url != null && data.url !== '') parts.push(data.url);\n return parts.join('\\n');\n}\n\nasync function shareShim(data?: ShareData): Promise<void> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { share?: unknown } | null)?.share;\n if (typeof fn === 'function') {\n const message = buildSdkMessage(data);\n if (!message) {\n throw new TypeError(\n '[@ait-co/polyfill] navigator.share requires at least one of title, text, or url.',\n );\n }\n try {\n await (fn as (o: { message: string }) => Promise<void>)({ message });\n } catch (e) {\n // Spec says navigator.share rejects with a DOMException. Wrap SDK\n // errors as AbortError (the most common cause is user cancellation),\n // attaching the original as `.cause` for Sentry-style telemetry.\n const message_ = e instanceof Error ? e.message : String(e);\n const wrapped = new DOMException(message_, 'AbortError');\n if (e instanceof Error) {\n (wrapped as Error).cause = e;\n }\n throw wrapped;\n }\n return;\n }\n }\n const host = navigator as unknown as BackupHost;\n const backup = host[SHARE_BACKUP_KEY];\n const original = backup?.share;\n if (!original) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.share is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return original.call(navigator, data);\n}\n\nfunction canShareShim(data?: ShareData): boolean {\n const hasFiles = Boolean(data?.files && data.files.length > 0);\n const toss = isTossEnvironmentCached();\n\n if (hasFiles) {\n // SDK does not share files. If we know we're in Toss (or it's being\n // forced), say so honestly. If detection hasn't resolved yet, be\n // pessimistic — a false negative is safer than promising a capability\n // we'll turn around and deny.\n if (toss === true) return false;\n if (toss === undefined) return false;\n }\n\n // Toss with non-file payloads: true iff there's at least one field.\n if (toss === true) {\n return Boolean(\n (data?.title != null && data.title !== '') ||\n (data?.text != null && data.text !== '') ||\n (data?.url != null && data.url !== ''),\n );\n }\n\n // `toss === undefined` (detection not resolved) with non-file payload falls\n // through to the browser-native answer. Rationale: `canShare` is rarely\n // load-bearing — consumers care about `share()` itself, which awaits the\n // async detection correctly. A false-negative here would needlessly hide a\n // Share button while detection settles.\n // Browser path: delegate to native when present.\n const host = navigator as unknown as BackupHost;\n const backup = host[SHARE_BACKUP_KEY];\n const originalCanShare = backup?.canShare;\n if (originalCanShare) {\n return originalCanShare.call(navigator, data);\n }\n return Boolean(\n (data?.title != null && data.title !== '') ||\n (data?.text != null && data.text !== '') ||\n (data?.url != null && data.url !== ''),\n );\n}\n\nexport function installShareShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (SHARE_BACKUP_KEY in host) {\n // Already installed. Use `in` so the absence of `share` / `canShare` on\n // the pre-install navigator (legitimately stored as `undefined`) doesn't\n // re-trigger install.\n return () => uninstallShareShim();\n }\n\n const nav = navigator as Navigator & {\n share?: ShareFn;\n canShare?: CanShareFn;\n };\n host[SHARE_BACKUP_KEY] = {\n share: nav.share,\n canShare: nav.canShare,\n hadShare: 'share' in nav,\n hadCanShare: 'canShare' in nav,\n };\n\n Object.defineProperty(navigator, 'share', {\n value: shareShim,\n configurable: true,\n writable: true,\n });\n Object.defineProperty(navigator, 'canShare', {\n value: canShareShim,\n configurable: true,\n writable: true,\n });\n\n return uninstallShareShim;\n}\n\nexport function uninstallShareShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(SHARE_BACKUP_KEY in host)) return;\n\n const backup = host[SHARE_BACKUP_KEY];\n\n // Prototype-safe restore: delete the instance override first so a prototype\n // descriptor (real browsers put `share` / `canShare` on `Navigator.prototype`\n // when they exist at all) shows through. Only redefine on the instance if\n // the original was an own property that the prototype doesn't provide —\n // otherwise we'd permanently shadow the prototype getter.\n delete (navigator as unknown as { share?: ShareFn }).share;\n if (backup?.hadShare && navigator.share !== backup.share) {\n Object.defineProperty(navigator, 'share', {\n value: backup.share,\n configurable: true,\n writable: true,\n });\n }\n delete (navigator as unknown as { canShare?: CanShareFn }).canShare;\n if (backup?.hadCanShare && navigator.canShare !== backup.canShare) {\n Object.defineProperty(navigator, 'canShare', {\n value: backup.canShare,\n configurable: true,\n writable: true,\n });\n }\n\n delete host[SHARE_BACKUP_KEY];\n}\n","/**\n * `navigator.vibrate` shim.\n *\n * Inside Apps in Toss → best-effort mapping to SDK `generateHapticFeedback`:\n * - `vibrate(0)` → no-op (web standard: cancels pending vibration)\n * - `vibrate(number)`: short (< 40ms) → `tickWeak`, long (≥ 40ms) → `basicMedium`\n * - `vibrate(number[])`: iterate \"on\" segments (even indices) as `tap` pulses\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.vibrate`,\n * or returns `false` when unavailable (matches the spec — browsers that don't\n * support vibration simply return `false`).\n *\n * Caveats (documented in CLAUDE.md as the known lossy trade-off):\n * - SDK haptics are qualitative (\"tickWeak\", \"basicMedium\"), not millisecond\n * durations. The shim approximates intensity from duration but cannot\n * reproduce exact patterns.\n * - Arrays are fired sequentially via `setTimeout`; gaps between pulses are\n * honoured only as \"time until the next tap\", not as silent-vs-vibrating.\n * - `vibrate` is spec'd as **synchronous**; the SDK call is async. We return\n * `true` immediately (fire-and-forget). Errors from the SDK are swallowed.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/vibrate.original');\nconst HAD_KEY = Symbol.for('@ait-co/polyfill/vibrate.hadOriginal');\n\ninterface BackupHost {\n [BACKUP_KEY]?: ((pattern: VibratePattern) => boolean) | undefined;\n [HAD_KEY]?: boolean;\n}\n\nconst SHORT_VIBRATION_MS = 40;\n\ntype HapticType =\n | 'tickWeak'\n | 'tap'\n | 'tickMedium'\n | 'softMedium'\n | 'basicWeak'\n | 'basicMedium'\n | 'success'\n | 'error'\n | 'wiggle'\n | 'confetti';\n\nasync function haptic(type: HapticType): Promise<void> {\n const sdk = await loadTossSdk();\n const fn = (sdk as { generateHapticFeedback?: unknown } | null)?.generateHapticFeedback;\n if (typeof fn === 'function') {\n try {\n await (fn as (o: { type: HapticType }) => Promise<void>)({ type });\n } catch {\n // Best-effort; spec-level `vibrate` cannot surface errors.\n }\n }\n}\n\nfunction durationToHaptic(duration: number): HapticType {\n return duration < SHORT_VIBRATION_MS ? 'tickWeak' : 'basicMedium';\n}\n\nfunction vibrateShim(pattern: VibratePattern): boolean {\n // Matches the spec: `vibrate(0)` or `vibrate([])` cancels pending vibration.\n // We can't cancel an in-flight SDK haptic (no cancel API), but we still\n // forward the cancel to the browser fallback so native vibration stops.\n const arr = Array.isArray(pattern) ? pattern : [pattern];\n if (arr.length === 0 || arr.every((n) => n === 0)) {\n void (async () => {\n if (!(await isTossEnvironment())) {\n const host = navigator as unknown as BackupHost;\n host[BACKUP_KEY]?.call(navigator, pattern);\n }\n })();\n return true;\n }\n\n void (async () => {\n if (await isTossEnvironment()) {\n if (!Array.isArray(pattern)) {\n await haptic(durationToHaptic(pattern));\n return;\n }\n // Even indices = \"on\" durations, odd indices = pauses. `pattern[i]` is\n // `number | undefined` under `noUncheckedIndexedAccess`; the `undefined`\n // case only arises on out-of-bounds, which our length bound prevents.\n for (let i = 0; i < pattern.length; i += 2) {\n const on = pattern[i];\n if (on === undefined) break;\n if (on > 0) {\n await haptic('tap');\n }\n const pause = pattern[i + 1];\n if (typeof pause === 'number' && pause > 0) {\n await new Promise<void>((r) => setTimeout(r, pause));\n }\n }\n return;\n }\n const host = navigator as unknown as BackupHost;\n const original = host[BACKUP_KEY];\n original?.call(navigator, pattern);\n })();\n\n return true;\n}\n\nexport function installVibrateShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (BACKUP_KEY in host) {\n return () => uninstallVibrateShim();\n }\n\n const nav = navigator as Navigator & { vibrate?: (p: VibratePattern) => boolean };\n host[BACKUP_KEY] = nav.vibrate;\n host[HAD_KEY] = 'vibrate' in nav;\n\n Object.defineProperty(navigator, 'vibrate', {\n value: vibrateShim,\n configurable: true,\n writable: true,\n });\n\n return uninstallVibrateShim;\n}\n\nexport function uninstallVibrateShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(BACKUP_KEY in host)) return;\n\n const original = host[BACKUP_KEY];\n const had = host[HAD_KEY];\n // Prototype-safe restore: delete the instance override first, then only\n // redefine on the instance if the original was an own property the\n // prototype doesn't provide — prevents permanent shadowing of a prototype\n // `vibrate` getter on real browsers.\n delete (navigator as unknown as { vibrate?: (p: VibratePattern) => boolean }).vibrate;\n if (had && navigator.vibrate !== original) {\n Object.defineProperty(navigator, 'vibrate', {\n value: original,\n configurable: true,\n writable: true,\n });\n }\n delete host[BACKUP_KEY];\n delete host[HAD_KEY];\n}\n","/**\n * @ait-co/polyfill\n *\n * Write Apps in Toss mini-apps using standard Web APIs\n * (`navigator.clipboard`, `navigator.geolocation`, …). This polyfill\n * transparently routes calls through the Apps in Toss SDK at runtime when\n * detected, and falls through to the browser's native implementation\n * otherwise.\n *\n * Unofficial community project. Not affiliated with Toss.\n */\n\nexport { isTossEnvironment, isTossEnvironmentCached, loadTossSdk } from './detect.js';\nexport { installClipboardShim, uninstallClipboardShim } from './shims/clipboard.js';\nexport { installGeolocationShim, uninstallGeolocationShim } from './shims/geolocation.js';\nexport { installNetworkShim, uninstallNetworkShim } from './shims/network.js';\nexport { installShareShim, uninstallShareShim } from './shims/share.js';\nexport { installVibrateShim, uninstallVibrateShim } from './shims/vibrate.js';\n\nimport { installClipboardShim, uninstallClipboardShim } from './shims/clipboard.js';\nimport { installGeolocationShim, uninstallGeolocationShim } from './shims/geolocation.js';\nimport { installNetworkShim, uninstallNetworkShim } from './shims/network.js';\nimport { installShareShim, uninstallShareShim } from './shims/share.js';\nimport { installVibrateShim, uninstallVibrateShim } from './shims/vibrate.js';\n\nexport const VERSION: string = __VERSION__;\n\n/**\n * Install every shim this library ships. Idempotent — safe to call more than\n * once. Returns an uninstall function that restores every original API.\n *\n * Install order: clipboard → geolocation → share → vibrate → network.\n * `uninstall()` tears them down in the same order (each per-shim uninstall is\n * independent, so order doesn't affect correctness; documented for clarity).\n *\n * Not atomic on failure: if a later per-shim install throws (e.g., a consumer\n * has pinned one of the target navigator properties as non-configurable),\n * earlier shims are already installed. Callers should catch and invoke\n * `uninstall()` to roll back.\n */\nexport function install(): () => void {\n const uninstalls = [\n installClipboardShim(),\n installGeolocationShim(),\n installShareShim(),\n installVibrateShim(),\n installNetworkShim(),\n ];\n return () => {\n for (const fn of uninstalls) fn();\n };\n}\n\n/**\n * Uninstall every shim installed by `install()`. Safe to call when no shim is\n * installed — each installer's uninstall is a no-op in that case.\n */\nexport function uninstall(): void {\n uninstallClipboardShim();\n uninstallGeolocationShim();\n uninstallShareShim();\n uninstallVibrateShim();\n uninstallNetworkShim();\n}\n"],"mappings":";;;;;;;;;;;;;AAaA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
3
|
+
* `navigator.clipboard` shim.
|
|
4
|
+
*
|
|
5
|
+
* Inside Apps in Toss → routes `readText` / `writeText` through the SDK
|
|
6
|
+
* (`getClipboardText` / `setClipboardText`).
|
|
7
|
+
*
|
|
8
|
+
* Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.
|
|
9
|
+
* If the browser doesn't implement it, the standard `TypeError` / `DOMException`
|
|
10
|
+
* surfaces unchanged — we don't paper over missing support.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Install the `navigator.clipboard` shim.
|
|
14
|
+
*
|
|
15
|
+
* @returns an uninstall function that restores the original `navigator.clipboard`.
|
|
16
|
+
* Calling install twice without uninstalling is a no-op on the second call
|
|
17
|
+
* and returns the same uninstall function.
|
|
18
|
+
*/
|
|
19
|
+
declare function installClipboardShim(): () => void;
|
|
20
|
+
/**
|
|
21
|
+
* Remove the shim and restore the pre-install shape. Uses delete + conditional
|
|
22
|
+
* redefine so a prototype-level `navigator.clipboard` (non-configurable in real
|
|
23
|
+
* browsers) becomes visible again instead of being permanently shadowed.
|
|
24
|
+
*/
|
|
25
|
+
declare function uninstallClipboardShim(): void;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { installClipboardShim, uninstallClipboardShim };
|
|
28
|
+
//# sourceMappingURL=clipboard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clipboard.d.ts","names":[],"sources":["../../src/shims/clipboard.ts"],"mappings":";;AAyHA;;;;;AAmCA;;;;;;;;;;;iBAnCgB,oBAAA,CAAA;;;;;;iBAmCA,sBAAA,CAAA"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
//#region src/detect.ts
|
|
2
|
+
/**
|
|
3
|
+
* Environment detection: are we running inside Apps in Toss, or a plain browser?
|
|
4
|
+
*
|
|
5
|
+
* Strategy: feature-sniff `@apps-in-toss/web-framework`. The SDK is declared as
|
|
6
|
+
* an **optional** peer dependency. If it resolves and exposes a known export,
|
|
7
|
+
* we assume we can route calls through it; otherwise we fall back to the
|
|
8
|
+
* browser's native implementation in each shim.
|
|
9
|
+
*
|
|
10
|
+
* We deliberately avoid UA sniffing (spoofable) and avoid calling any SDK
|
|
11
|
+
* function during detection (could prompt permission dialogs, fire analytics,
|
|
12
|
+
* etc.).
|
|
13
|
+
*/
|
|
14
|
+
let cached;
|
|
15
|
+
/**
|
|
16
|
+
* Returns `true` iff we detect we are running in an environment where the
|
|
17
|
+
* Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.
|
|
18
|
+
*
|
|
19
|
+
* Async because we use dynamic `import()` to probe the optional peer dep
|
|
20
|
+
* without forcing it into the consumer's bundle.
|
|
21
|
+
*/
|
|
22
|
+
async function isTossEnvironment() {
|
|
23
|
+
const force = globalThis.__AIT_POLYFILL_FORCE__;
|
|
24
|
+
if (force === "toss") return true;
|
|
25
|
+
if (force === "browser") return false;
|
|
26
|
+
if (cached !== void 0) return cached;
|
|
27
|
+
cached = typeof (await loadTossSdk())?.getClipboardText === "function";
|
|
28
|
+
return cached;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Lazy SDK accessor — returns the module if available, else `null`. Callers
|
|
32
|
+
* are expected to `await` and null-check. Never throws.
|
|
33
|
+
*/
|
|
34
|
+
async function loadTossSdk() {
|
|
35
|
+
try {
|
|
36
|
+
return await import("@apps-in-toss/web-framework");
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/shims/clipboard.ts
|
|
43
|
+
/**
|
|
44
|
+
* `navigator.clipboard` shim.
|
|
45
|
+
*
|
|
46
|
+
* Inside Apps in Toss → routes `readText` / `writeText` through the SDK
|
|
47
|
+
* (`getClipboardText` / `setClipboardText`).
|
|
48
|
+
*
|
|
49
|
+
* Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.
|
|
50
|
+
* If the browser doesn't implement it, the standard `TypeError` / `DOMException`
|
|
51
|
+
* surfaces unchanged — we don't paper over missing support.
|
|
52
|
+
*/
|
|
53
|
+
const BACKUP_KEY = Symbol.for("@ait-co/polyfill/clipboard.original");
|
|
54
|
+
const HAD_KEY = Symbol.for("@ait-co/polyfill/clipboard.hadOriginal");
|
|
55
|
+
/**
|
|
56
|
+
* Produces a Clipboard-compatible object whose `readText` / `writeText` methods
|
|
57
|
+
* route to the SDK when in Toss, else fall through to the supplied `fallback`.
|
|
58
|
+
*/
|
|
59
|
+
function createClipboardShim(fallback) {
|
|
60
|
+
return {
|
|
61
|
+
async readText() {
|
|
62
|
+
if (await isTossEnvironment()) {
|
|
63
|
+
const sdk = await loadTossSdk();
|
|
64
|
+
if (sdk?.getClipboardText) return sdk.getClipboardText();
|
|
65
|
+
}
|
|
66
|
+
if (!fallback) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.readText is not available in this environment.", "NotSupportedError");
|
|
67
|
+
return fallback.readText();
|
|
68
|
+
},
|
|
69
|
+
async writeText(text) {
|
|
70
|
+
if (await isTossEnvironment()) {
|
|
71
|
+
const sdk = await loadTossSdk();
|
|
72
|
+
if (sdk?.setClipboardText) return sdk.setClipboardText(text);
|
|
73
|
+
}
|
|
74
|
+
if (!fallback) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.writeText is not available in this environment.", "NotSupportedError");
|
|
75
|
+
return fallback.writeText(text);
|
|
76
|
+
},
|
|
77
|
+
async read() {
|
|
78
|
+
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");
|
|
79
|
+
if (!fallback?.read) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.read is not available.", "NotSupportedError");
|
|
80
|
+
return fallback.read();
|
|
81
|
+
},
|
|
82
|
+
async write(items) {
|
|
83
|
+
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");
|
|
84
|
+
if (!fallback?.write) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.write is not available.", "NotSupportedError");
|
|
85
|
+
return fallback.write(items);
|
|
86
|
+
},
|
|
87
|
+
addEventListener: (...args) => fallback?.addEventListener(...args),
|
|
88
|
+
removeEventListener: (...args) => fallback?.removeEventListener(...args),
|
|
89
|
+
dispatchEvent: (event) => fallback?.dispatchEvent(event) ?? false
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Install the `navigator.clipboard` shim.
|
|
94
|
+
*
|
|
95
|
+
* @returns an uninstall function that restores the original `navigator.clipboard`.
|
|
96
|
+
* Calling install twice without uninstalling is a no-op on the second call
|
|
97
|
+
* and returns the same uninstall function.
|
|
98
|
+
*/
|
|
99
|
+
function installClipboardShim() {
|
|
100
|
+
if (typeof navigator === "undefined") return () => {};
|
|
101
|
+
const host = navigator;
|
|
102
|
+
if (BACKUP_KEY in host) return () => uninstallClipboardShim();
|
|
103
|
+
const original = navigator.clipboard;
|
|
104
|
+
host[BACKUP_KEY] = original;
|
|
105
|
+
host[HAD_KEY] = "clipboard" in navigator;
|
|
106
|
+
const shim = createClipboardShim(original);
|
|
107
|
+
Object.defineProperty(navigator, "clipboard", {
|
|
108
|
+
value: shim,
|
|
109
|
+
configurable: true,
|
|
110
|
+
writable: true
|
|
111
|
+
});
|
|
112
|
+
return uninstallClipboardShim;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Remove the shim and restore the pre-install shape. Uses delete + conditional
|
|
116
|
+
* redefine so a prototype-level `navigator.clipboard` (non-configurable in real
|
|
117
|
+
* browsers) becomes visible again instead of being permanently shadowed.
|
|
118
|
+
*/
|
|
119
|
+
function uninstallClipboardShim() {
|
|
120
|
+
if (typeof navigator === "undefined") return;
|
|
121
|
+
const host = navigator;
|
|
122
|
+
if (!(BACKUP_KEY in host)) return;
|
|
123
|
+
const original = host[BACKUP_KEY];
|
|
124
|
+
const had = host[HAD_KEY];
|
|
125
|
+
delete navigator.clipboard;
|
|
126
|
+
if (had && navigator.clipboard !== original) Object.defineProperty(navigator, "clipboard", {
|
|
127
|
+
value: original,
|
|
128
|
+
configurable: true,
|
|
129
|
+
writable: true
|
|
130
|
+
});
|
|
131
|
+
delete host[BACKUP_KEY];
|
|
132
|
+
delete host[HAD_KEY];
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
export { installClipboardShim, uninstallClipboardShim };
|
|
136
|
+
|
|
137
|
+
//# sourceMappingURL=clipboard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clipboard.js","names":[],"sources":["../../src/detect.ts","../../src/shims/clipboard.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: feature-sniff `@apps-in-toss/web-framework`. The SDK is declared as\n * an **optional** peer dependency. If it resolves and exposes a known export,\n * we assume we can route calls through it; otherwise we fall back to the\n * browser's native implementation in each shim.\n *\n * We deliberately avoid UA sniffing (spoofable) and avoid calling any SDK\n * function during detection (could prompt permission dialogs, fire analytics,\n * etc.).\n */\n\nlet cached: boolean | undefined;\n\n/**\n * Reset the cached detection result. Primarily for tests.\n */\nexport function resetDetection(): void {\n cached = undefined;\n}\n\n/**\n * Synchronous read of the cached detection result. Returns:\n * - `true` / `false` if an override is active or the async detection has\n * already resolved\n * - `undefined` if detection hasn't run yet\n *\n * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`\n * detection.\n */\nexport function isTossEnvironmentCached(): boolean | undefined {\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n return cached;\n}\n\n/**\n * Returns `true` iff we detect we are running in an environment where the\n * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.\n *\n * Async because we use dynamic `import()` to probe the optional peer dep\n * without forcing it into the consumer's bundle.\n */\nexport async function isTossEnvironment(): Promise<boolean> {\n // Override check precedes cache so `devtools` / tests can flip the result\n // mid-session without a `resetDetection()` call.\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n\n if (cached !== undefined) return cached;\n\n const mod = await loadTossSdk();\n // Presence of a well-known export is our smoke test.\n cached = typeof mod?.getClipboardText === 'function';\n return cached;\n}\n\n/**\n * Lazy SDK accessor — returns the module if available, else `null`. Callers\n * are expected to `await` and null-check. Never throws.\n */\nexport async function loadTossSdk(): Promise<typeof import('@apps-in-toss/web-framework') | null> {\n try {\n return await import('@apps-in-toss/web-framework');\n } catch {\n return null;\n }\n}\n","/**\n * `navigator.clipboard` shim.\n *\n * Inside Apps in Toss → routes `readText` / `writeText` through the SDK\n * (`getClipboardText` / `setClipboardText`).\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.\n * If the browser doesn't implement it, the standard `TypeError` / `DOMException`\n * surfaces unchanged — we don't paper over missing support.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/clipboard.original');\nconst HAD_KEY = Symbol.for('@ait-co/polyfill/clipboard.hadOriginal');\n\ninterface BackupHost {\n [BACKUP_KEY]?: Clipboard | undefined;\n [HAD_KEY]?: boolean;\n}\n\n/**\n * Produces a Clipboard-compatible object whose `readText` / `writeText` methods\n * route to the SDK when in Toss, else fall through to the supplied `fallback`.\n */\nfunction createClipboardShim(fallback: Clipboard | undefined): Clipboard {\n const shim = {\n async readText(): Promise<string> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n if (sdk?.getClipboardText) {\n return sdk.getClipboardText();\n }\n }\n if (!fallback) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.readText is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return fallback.readText();\n },\n\n async writeText(text: string): Promise<void> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n if (sdk?.setClipboardText) {\n return sdk.setClipboardText(text);\n }\n }\n if (!fallback) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.writeText is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return fallback.writeText(text);\n },\n\n // `read` / `write` (ClipboardItem-based) are passed through to the\n // fallback when in browser mode; the SDK has no rich-content counterpart,\n // so in Toss mode they throw.\n async read(): Promise<ClipboardItems> {\n if (await isTossEnvironment()) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.read (rich content) is not supported in the Apps in Toss environment. Use readText instead.',\n 'NotSupportedError',\n );\n }\n if (!fallback?.read) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.read is not available.',\n 'NotSupportedError',\n );\n }\n return fallback.read();\n },\n\n async write(items: ClipboardItems): Promise<void> {\n if (await isTossEnvironment()) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.write (rich content) is not supported in the Apps in Toss environment. Use writeText instead.',\n 'NotSupportedError',\n );\n }\n if (!fallback?.write) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.write is not available.',\n 'NotSupportedError',\n );\n }\n return fallback.write(items);\n },\n\n // EventTarget passthrough. `navigator.clipboard` extends EventTarget in the\n // spec; mini-apps rarely use it. We forward to the fallback when one exists;\n // in Toss mode (no fallback) we silently drop subscriptions — the SDK emits\n // no clipboard events, so there is nothing to dispatch. This is lossy but\n // preserves the spec-compatible shape.\n addEventListener: (\n ...args: Parameters<EventTarget['addEventListener']>\n ): ReturnType<EventTarget['addEventListener']> => fallback?.addEventListener(...args),\n removeEventListener: (\n ...args: Parameters<EventTarget['removeEventListener']>\n ): ReturnType<EventTarget['removeEventListener']> => fallback?.removeEventListener(...args),\n // Returns `false` in Toss mode (no backing EventTarget). A caller that reads\n // this as \"default action cancelled\" should check context — there are no\n // listeners to run because the SDK doesn't surface clipboard events.\n dispatchEvent: (event: Event): boolean => fallback?.dispatchEvent(event) ?? false,\n } satisfies Clipboard;\n\n return shim;\n}\n\n/**\n * Install the `navigator.clipboard` shim.\n *\n * @returns an uninstall function that restores the original `navigator.clipboard`.\n * Calling install twice without uninstalling is a no-op on the second call\n * and returns the same uninstall function.\n */\nexport function installClipboardShim(): () => void {\n if (typeof navigator === 'undefined') {\n // No-op in non-DOM environments (pure Node).\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (BACKUP_KEY in host) {\n // Already installed. Use `in` (not `!== undefined`) because the stored\n // backup is legitimately `undefined` when the browser has no native\n // `navigator.clipboard` — without this, we'd re-wrap on each install.\n // Note: the returned uninstall is global. Any caller's uninstall fully\n // removes the shim; callers do not have independent install handles.\n return () => uninstallClipboardShim();\n }\n\n const original = navigator.clipboard as Clipboard | undefined;\n host[BACKUP_KEY] = original;\n host[HAD_KEY] = 'clipboard' in navigator;\n\n const shim = createClipboardShim(original);\n Object.defineProperty(navigator, 'clipboard', {\n value: shim,\n configurable: true,\n writable: true,\n });\n\n return uninstallClipboardShim;\n}\n\n/**\n * Remove the shim and restore the pre-install shape. Uses delete + conditional\n * redefine so a prototype-level `navigator.clipboard` (non-configurable in real\n * browsers) becomes visible again instead of being permanently shadowed.\n */\nexport function uninstallClipboardShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(BACKUP_KEY in host)) return;\n\n const original = host[BACKUP_KEY];\n const had = host[HAD_KEY];\n delete (navigator as unknown as { clipboard?: Clipboard }).clipboard;\n if (had && navigator.clipboard !== original) {\n Object.defineProperty(navigator, 'clipboard', {\n value: original,\n configurable: true,\n writable: true,\n });\n }\n delete host[BACKUP_KEY];\n delete host[HAD_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,IAAI;;;;;;;;AAgCJ,eAAsB,oBAAsC;CAG1D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAEhC,KAAI,WAAW,KAAA,EAAW,QAAO;AAIjC,UAAS,QAFG,MAAM,aAAa,GAEV,qBAAqB;AAC1C,QAAO;;;;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AM,OAAO;AACb,KAAI,cAAc,KAMhB,cAAa,wBAAwB;CAGvC,MAAM,WAAW,UAAU;AAC3B,MAAK,cAAc;AACnB,MAAK,WAAW,eAAe;CAE/B,MAAM,OAAO,oBAAoB,SAAS;AAC1C,QAAO,eAAe,WAAW,aAAa;EAC5C,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AAEF,QAAO;;;;;;;AAQT,SAAgB,yBAA+B;AAC7C,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,EAAE,cAAc,MAAO;CAE3B,MAAM,WAAW,KAAK;CACtB,MAAM,MAAM,KAAK;AACjB,QAAQ,UAAmD;AAC3D,KAAI,OAAO,UAAU,cAAc,SACjC,QAAO,eAAe,WAAW,aAAa;EAC5C,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AAEJ,QAAO,KAAK;AACZ,QAAO,KAAK"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//#region src/shims/geolocation.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* `navigator.geolocation` shim.
|
|
4
|
+
*
|
|
5
|
+
* Inside Apps in Toss → routes through the SDK:
|
|
6
|
+
* - `getCurrentPosition` → `getCurrentLocation({ accuracy })`
|
|
7
|
+
* - `watchPosition` / `clearWatch` → `startUpdateLocation({ onEvent, onError, options })`
|
|
8
|
+
*
|
|
9
|
+
* Outside Apps in Toss → defers to the browser's native `navigator.geolocation`.
|
|
10
|
+
* If neither is available, the error callback receives a `GeolocationPositionError`.
|
|
11
|
+
*
|
|
12
|
+
* SDK/Web shape mismatch handled here:
|
|
13
|
+
* - SDK `Accuracy` is a numeric enum (1 = Lowest … 6 = BestForNavigation); the
|
|
14
|
+
* standard `PositionOptions.enableHighAccuracy` is a boolean. We map
|
|
15
|
+
* `true → Accuracy.High (4, "~10m")` and `false → Accuracy.Balanced (3)`.
|
|
16
|
+
* `Highest (5)` / `BestForNavigation (6)` are available but carry a battery
|
|
17
|
+
* cost that's rarely what mini-apps want; consumers who need them should
|
|
18
|
+
* call the SDK directly.
|
|
19
|
+
* - SDK coords lack `speed`; we surface `null` (per the W3C spec when unknown).
|
|
20
|
+
* - SDK `startUpdateLocation` returns an `unsubscribe` fn; we wrap it behind
|
|
21
|
+
* a numeric watch id so `clearWatch(id)` behaves like the standard.
|
|
22
|
+
*
|
|
23
|
+
* Caveat: watch ids reset whenever the shim is uninstalled and reinstalled;
|
|
24
|
+
* they are not stable across such cycles. Ids obtained before uninstall
|
|
25
|
+
* cannot be cleared after uninstall — `clearWatch(id)` on the restored native
|
|
26
|
+
* `navigator.geolocation` uses a different id space, so the SDK subscription
|
|
27
|
+
* leaks. Consumers should `clearWatch` all outstanding ids before calling
|
|
28
|
+
* `uninstall()`.
|
|
29
|
+
*/
|
|
30
|
+
declare function installGeolocationShim(): () => void;
|
|
31
|
+
declare function uninstallGeolocationShim(): void;
|
|
32
|
+
//#endregion
|
|
33
|
+
export { installGeolocationShim, uninstallGeolocationShim };
|
|
34
|
+
//# sourceMappingURL=geolocation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"geolocation.d.ts","names":[],"sources":["../../src/shims/geolocation.ts"],"mappings":";;AAsQA;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;iBAvBgB,sBAAA,CAAA;AAAA,iBAuBA,wBAAA,CAAA"}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
//#region src/detect.ts
|
|
2
|
+
/**
|
|
3
|
+
* Environment detection: are we running inside Apps in Toss, or a plain browser?
|
|
4
|
+
*
|
|
5
|
+
* Strategy: feature-sniff `@apps-in-toss/web-framework`. The SDK is declared as
|
|
6
|
+
* an **optional** peer dependency. If it resolves and exposes a known export,
|
|
7
|
+
* we assume we can route calls through it; otherwise we fall back to the
|
|
8
|
+
* browser's native implementation in each shim.
|
|
9
|
+
*
|
|
10
|
+
* We deliberately avoid UA sniffing (spoofable) and avoid calling any SDK
|
|
11
|
+
* function during detection (could prompt permission dialogs, fire analytics,
|
|
12
|
+
* etc.).
|
|
13
|
+
*/
|
|
14
|
+
let cached;
|
|
15
|
+
/**
|
|
16
|
+
* Returns `true` iff we detect we are running in an environment where the
|
|
17
|
+
* Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.
|
|
18
|
+
*
|
|
19
|
+
* Async because we use dynamic `import()` to probe the optional peer dep
|
|
20
|
+
* without forcing it into the consumer's bundle.
|
|
21
|
+
*/
|
|
22
|
+
async function isTossEnvironment() {
|
|
23
|
+
const force = globalThis.__AIT_POLYFILL_FORCE__;
|
|
24
|
+
if (force === "toss") return true;
|
|
25
|
+
if (force === "browser") return false;
|
|
26
|
+
if (cached !== void 0) return cached;
|
|
27
|
+
cached = typeof (await loadTossSdk())?.getClipboardText === "function";
|
|
28
|
+
return cached;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Lazy SDK accessor — returns the module if available, else `null`. Callers
|
|
32
|
+
* are expected to `await` and null-check. Never throws.
|
|
33
|
+
*/
|
|
34
|
+
async function loadTossSdk() {
|
|
35
|
+
try {
|
|
36
|
+
return await import("@apps-in-toss/web-framework");
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/shims/geolocation.ts
|
|
43
|
+
/**
|
|
44
|
+
* `navigator.geolocation` shim.
|
|
45
|
+
*
|
|
46
|
+
* Inside Apps in Toss → routes through the SDK:
|
|
47
|
+
* - `getCurrentPosition` → `getCurrentLocation({ accuracy })`
|
|
48
|
+
* - `watchPosition` / `clearWatch` → `startUpdateLocation({ onEvent, onError, options })`
|
|
49
|
+
*
|
|
50
|
+
* Outside Apps in Toss → defers to the browser's native `navigator.geolocation`.
|
|
51
|
+
* If neither is available, the error callback receives a `GeolocationPositionError`.
|
|
52
|
+
*
|
|
53
|
+
* SDK/Web shape mismatch handled here:
|
|
54
|
+
* - SDK `Accuracy` is a numeric enum (1 = Lowest … 6 = BestForNavigation); the
|
|
55
|
+
* standard `PositionOptions.enableHighAccuracy` is a boolean. We map
|
|
56
|
+
* `true → Accuracy.High (4, "~10m")` and `false → Accuracy.Balanced (3)`.
|
|
57
|
+
* `Highest (5)` / `BestForNavigation (6)` are available but carry a battery
|
|
58
|
+
* cost that's rarely what mini-apps want; consumers who need them should
|
|
59
|
+
* call the SDK directly.
|
|
60
|
+
* - SDK coords lack `speed`; we surface `null` (per the W3C spec when unknown).
|
|
61
|
+
* - SDK `startUpdateLocation` returns an `unsubscribe` fn; we wrap it behind
|
|
62
|
+
* a numeric watch id so `clearWatch(id)` behaves like the standard.
|
|
63
|
+
*
|
|
64
|
+
* Caveat: watch ids reset whenever the shim is uninstalled and reinstalled;
|
|
65
|
+
* they are not stable across such cycles. Ids obtained before uninstall
|
|
66
|
+
* cannot be cleared after uninstall — `clearWatch(id)` on the restored native
|
|
67
|
+
* `navigator.geolocation` uses a different id space, so the SDK subscription
|
|
68
|
+
* leaks. Consumers should `clearWatch` all outstanding ids before calling
|
|
69
|
+
* `uninstall()`.
|
|
70
|
+
*/
|
|
71
|
+
const BACKUP_KEY = Symbol.for("@ait-co/polyfill/geolocation.original");
|
|
72
|
+
const ACCURACY_BALANCED = 3;
|
|
73
|
+
const ACCURACY_HIGH = 4;
|
|
74
|
+
function toStandardPosition(sdk) {
|
|
75
|
+
const coordsData = {
|
|
76
|
+
latitude: sdk.coords.latitude,
|
|
77
|
+
longitude: sdk.coords.longitude,
|
|
78
|
+
altitude: sdk.coords.altitude,
|
|
79
|
+
accuracy: sdk.coords.accuracy,
|
|
80
|
+
altitudeAccuracy: sdk.coords.altitudeAccuracy,
|
|
81
|
+
heading: sdk.coords.heading,
|
|
82
|
+
speed: null
|
|
83
|
+
};
|
|
84
|
+
return {
|
|
85
|
+
coords: {
|
|
86
|
+
...coordsData,
|
|
87
|
+
toJSON() {
|
|
88
|
+
return { ...coordsData };
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
timestamp: sdk.timestamp,
|
|
92
|
+
toJSON() {
|
|
93
|
+
return {
|
|
94
|
+
coords: { ...coordsData },
|
|
95
|
+
timestamp: sdk.timestamp
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function toPositionError(code, message) {
|
|
101
|
+
const Ctor = globalThis.GeolocationPositionError;
|
|
102
|
+
if (typeof Ctor === "function") {
|
|
103
|
+
const proto = Ctor.prototype;
|
|
104
|
+
if (proto) {
|
|
105
|
+
const shape = {
|
|
106
|
+
code,
|
|
107
|
+
message
|
|
108
|
+
};
|
|
109
|
+
Object.setPrototypeOf(shape, proto);
|
|
110
|
+
return shape;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
code,
|
|
115
|
+
message,
|
|
116
|
+
PERMISSION_DENIED: 1,
|
|
117
|
+
POSITION_UNAVAILABLE: 2,
|
|
118
|
+
TIMEOUT: 3
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function accuracyFromOptions(options) {
|
|
122
|
+
return options?.enableHighAccuracy ? ACCURACY_HIGH : ACCURACY_BALANCED;
|
|
123
|
+
}
|
|
124
|
+
function createGeolocationShim(fallback) {
|
|
125
|
+
let nextWatchId = 1;
|
|
126
|
+
const sdkWatches = /* @__PURE__ */ new Map();
|
|
127
|
+
const nativeWatches = /* @__PURE__ */ new Map();
|
|
128
|
+
const pendingWatches = /* @__PURE__ */ new Map();
|
|
129
|
+
return {
|
|
130
|
+
getCurrentPosition(success, error, options) {
|
|
131
|
+
(async () => {
|
|
132
|
+
if (await isTossEnvironment()) {
|
|
133
|
+
const fn = (await loadTossSdk())?.getCurrentLocation;
|
|
134
|
+
if (typeof fn === "function") {
|
|
135
|
+
try {
|
|
136
|
+
success(toStandardPosition(await fn({ accuracy: accuracyFromOptions(options) })));
|
|
137
|
+
} catch (e) {
|
|
138
|
+
error?.(toPositionError(2, e instanceof Error ? e.message : "[@ait-co/polyfill] getCurrentLocation failed."));
|
|
139
|
+
}
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (!fallback) {
|
|
144
|
+
error?.(toPositionError(2, "[@ait-co/polyfill] navigator.geolocation is not available in this environment."));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
fallback.getCurrentPosition(success, error, options);
|
|
148
|
+
})();
|
|
149
|
+
},
|
|
150
|
+
watchPosition(success, error, options) {
|
|
151
|
+
const id = nextWatchId++;
|
|
152
|
+
const pending = { cancelled: false };
|
|
153
|
+
pendingWatches.set(id, pending);
|
|
154
|
+
(async () => {
|
|
155
|
+
if (await isTossEnvironment()) {
|
|
156
|
+
const fn = (await loadTossSdk())?.startUpdateLocation;
|
|
157
|
+
if (typeof fn === "function") {
|
|
158
|
+
if (pending.cancelled) {
|
|
159
|
+
pendingWatches.delete(id);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const unsubscribe = fn({
|
|
163
|
+
onEvent: (loc) => success(toStandardPosition(loc)),
|
|
164
|
+
onError: (err) => error?.(toPositionError(2, err instanceof Error ? err.message : "[@ait-co/polyfill] startUpdateLocation failed.")),
|
|
165
|
+
options: {
|
|
166
|
+
accuracy: accuracyFromOptions(options),
|
|
167
|
+
timeInterval: 1e3,
|
|
168
|
+
distanceInterval: 0
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
if (pending.cancelled) {
|
|
172
|
+
unsubscribe();
|
|
173
|
+
pendingWatches.delete(id);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
sdkWatches.set(id, unsubscribe);
|
|
177
|
+
pendingWatches.delete(id);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (!fallback) {
|
|
182
|
+
pendingWatches.delete(id);
|
|
183
|
+
error?.(toPositionError(2, "[@ait-co/polyfill] navigator.geolocation is not available in this environment."));
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (pending.cancelled) {
|
|
187
|
+
pendingWatches.delete(id);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const nativeId = fallback.watchPosition(success, error, options);
|
|
191
|
+
if (pending.cancelled) {
|
|
192
|
+
fallback.clearWatch(nativeId);
|
|
193
|
+
pendingWatches.delete(id);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
nativeWatches.set(id, nativeId);
|
|
197
|
+
pendingWatches.delete(id);
|
|
198
|
+
})();
|
|
199
|
+
return id;
|
|
200
|
+
},
|
|
201
|
+
clearWatch(id) {
|
|
202
|
+
const pending = pendingWatches.get(id);
|
|
203
|
+
if (pending) {
|
|
204
|
+
pending.cancelled = true;
|
|
205
|
+
pendingWatches.delete(id);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const unsubscribe = sdkWatches.get(id);
|
|
209
|
+
if (unsubscribe) {
|
|
210
|
+
unsubscribe();
|
|
211
|
+
sdkWatches.delete(id);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const nativeId = nativeWatches.get(id);
|
|
215
|
+
if (nativeId !== void 0 && fallback) {
|
|
216
|
+
fallback.clearWatch(nativeId);
|
|
217
|
+
nativeWatches.delete(id);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
function installGeolocationShim() {
|
|
223
|
+
if (typeof navigator === "undefined") return () => {};
|
|
224
|
+
const host = navigator;
|
|
225
|
+
if (BACKUP_KEY in host) return () => uninstallGeolocationShim();
|
|
226
|
+
const original = navigator.geolocation;
|
|
227
|
+
host[BACKUP_KEY] = original;
|
|
228
|
+
const shim = createGeolocationShim(original);
|
|
229
|
+
Object.defineProperty(navigator, "geolocation", {
|
|
230
|
+
value: shim,
|
|
231
|
+
configurable: true,
|
|
232
|
+
writable: true
|
|
233
|
+
});
|
|
234
|
+
return uninstallGeolocationShim;
|
|
235
|
+
}
|
|
236
|
+
function uninstallGeolocationShim() {
|
|
237
|
+
if (typeof navigator === "undefined") return;
|
|
238
|
+
const host = navigator;
|
|
239
|
+
if (!(BACKUP_KEY in host)) return;
|
|
240
|
+
const original = host[BACKUP_KEY];
|
|
241
|
+
delete navigator.geolocation;
|
|
242
|
+
if (original !== void 0 && navigator.geolocation !== original) Object.defineProperty(navigator, "geolocation", {
|
|
243
|
+
value: original,
|
|
244
|
+
configurable: true,
|
|
245
|
+
writable: true
|
|
246
|
+
});
|
|
247
|
+
delete host[BACKUP_KEY];
|
|
248
|
+
}
|
|
249
|
+
//#endregion
|
|
250
|
+
export { installGeolocationShim, uninstallGeolocationShim };
|
|
251
|
+
|
|
252
|
+
//# sourceMappingURL=geolocation.js.map
|