@ait-co/polyfill 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto.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","../src/auto.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export\n * that returns the runtime's Toss globals (deploymentId, brand name, …)\n * inside the Apps in Toss runtime and throws (RN bridge unavailable)\n * anywhere else. The SDK itself is an **optional** peer dependency; if its\n * module can't be imported we are definitely not inside Toss.\n *\n * Just having the SDK module resolvable is not enough — apps can bundle it\n * and still run in a plain browser. We need the bridge probe to confirm.\n *\n * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but\n * that's a constant read from the bridge — no permission dialogs, no\n * analytics fire. In a plain browser the bridge lookup fails fast (sync\n * throw, microsecond-scale), so the startup cost is negligible.\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 if (typeof mod?.getAppsInTossGlobals !== 'function') {\n cached = false;\n return cached;\n }\n // Inside Toss the bridge returns a populated globals object. In a plain\n // browser the RN bridge isn't attached and the call throws — that's our\n // signal. Any non-throwing call with an object return is treated as Toss.\n try {\n const globals = mod.getAppsInTossGlobals();\n cached = Boolean(globals) && typeof globals === 'object';\n } catch {\n cached = false;\n }\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 routes\n * calls through the Apps in Toss SDK **only when we detect we are actually\n * running inside the Toss app** — in every other environment (a plain browser,\n * local dev, tests) the shims are not installed and the browser's native\n * implementations are used as-is.\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 { isTossEnvironment } from './detect.js';\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\nconst NOOP = (): void => {};\n\n/**\n * Install every shim this library ships, but only if we detect an Apps in\n * Toss runtime. In a plain browser `install()` is a no-op — the browser's\n * native APIs stay untouched.\n *\n * Returns a promise that resolves with an uninstall function. If the\n * environment turns out not to be Toss, the uninstall function is a no-op.\n *\n * Install order (when active): clipboard → geolocation → share → vibrate →\n * network. Not atomic on failure — if a per-shim install throws (e.g., a\n * consumer pinned a target navigator property as non-configurable), earlier\n * shims are already in place. Callers should catch and invoke the returned\n * uninstall to roll back.\n */\nexport async function install(): Promise<() => void> {\n if (!(await isTossEnvironment())) return NOOP;\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","/**\n * Side-effect entry point: `import '@ait-co/polyfill/auto'`\n *\n * Kicks off detection and, if we're inside Apps in Toss, installs every shim\n * this library ships. In a plain browser this is a no-op — browser native\n * APIs stay untouched. No-op idempotent: importing the entry more than once\n * doesn't re-install.\n *\n * Use this when you want the \"just add the dep\" experience. If you need to\n * observe when the polyfill actually attached (to gate init logic) or to tear\n * it down, import `install` / `uninstall` from `@ait-co/polyfill` directly.\n */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BAAkB;EAClB,oBAAoB;EACpB,oBAAoB;EACrB;AACD,cAAa;AACX,OAAK,MAAM,MAAM,WAAY,KAAI;;;;;;;;;;;;;;;;;ACxChC,SAAS"}
package/dist/detect.d.ts CHANGED
@@ -4,14 +4,19 @@ import * as _$_apps_in_toss_web_framework0 from "@apps-in-toss/web-framework";
4
4
  /**
5
5
  * Environment detection: are we running inside Apps in Toss, or a plain browser?
6
6
  *
7
- * Strategy: feature-sniff `@apps-in-toss/web-framework`. The SDK is declared as
8
- * an **optional** peer dependency. If it resolves and exposes a known export,
9
- * we assume we can route calls through it; otherwise we fall back to the
10
- * browser's native implementation in each shim.
7
+ * Strategy: call the SDK's `getAppsInTossGlobals()` a synchronous export
8
+ * that returns the runtime's Toss globals (deploymentId, brand name, …)
9
+ * inside the Apps in Toss runtime and throws (RN bridge unavailable)
10
+ * anywhere else. The SDK itself is an **optional** peer dependency; if its
11
+ * module can't be imported we are definitely not inside Toss.
11
12
  *
12
- * We deliberately avoid UA sniffing (spoofable) and avoid calling any SDK
13
- * function during detection (could prompt permission dialogs, fire analytics,
14
- * etc.).
13
+ * Just having the SDK module resolvable is not enough apps can bundle it
14
+ * and still run in a plain browser. We need the bridge probe to confirm.
15
+ *
16
+ * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but
17
+ * that's a constant read from the bridge — no permission dialogs, no
18
+ * analytics fire. In a plain browser the bridge lookup fails fast (sync
19
+ * throw, microsecond-scale), so the startup cost is negligible.
15
20
  */
16
21
  /**
17
22
  * Reset the cached detection result. Primarily for tests.
@@ -1 +1 @@
1
- {"version":3,"file":"detect.d.ts","names":[],"sources":["../src/detect.ts"],"mappings":";;;;;;AAkBA;;;;;AAaA;;;;;AAcA;;iBA3BgB,cAAA,CAAA;;;AA8ChB;;;;;;;iBAjCgB,uBAAA,CAAA;;;;;;;;iBAcM,iBAAA,CAAA,GAAqB,OAAA;;;;;iBAmBrB,WAAA,CAAA,GAAe,OAAA,QAAJ,8BAAA"}
1
+ {"version":3,"file":"detect.d.ts","names":[],"sources":["../src/detect.ts"],"mappings":";;;;;;AAuBA;;;;;AAaA;;;;;AAcA;;;;;AA8BA;;iBAzDgB,cAAA,CAAA;;;;;;;;;;iBAaA,uBAAA,CAAA;;;;;;;;iBAcM,iBAAA,CAAA,GAAqB,OAAA;;;;;iBA8BrB,WAAA,CAAA,GAAe,OAAA,QAAJ,8BAAA"}
package/dist/detect.js CHANGED
@@ -2,14 +2,19 @@
2
2
  /**
3
3
  * Environment detection: are we running inside Apps in Toss, or a plain browser?
4
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.
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.
9
10
  *
10
- * We deliberately avoid UA sniffing (spoofable) and avoid calling any SDK
11
- * function during detection (could prompt permission dialogs, fire analytics,
12
- * etc.).
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.
13
18
  */
14
19
  let cached;
15
20
  /**
@@ -45,7 +50,17 @@ async function isTossEnvironment() {
45
50
  if (force === "toss") return true;
46
51
  if (force === "browser") return false;
47
52
  if (cached !== void 0) return cached;
48
- cached = typeof (await loadTossSdk())?.getClipboardText === "function";
53
+ const mod = await loadTossSdk();
54
+ if (typeof mod?.getAppsInTossGlobals !== "function") {
55
+ cached = false;
56
+ return cached;
57
+ }
58
+ try {
59
+ const globals = mod.getAppsInTossGlobals();
60
+ cached = Boolean(globals) && typeof globals === "object";
61
+ } catch {
62
+ cached = false;
63
+ }
49
64
  return cached;
50
65
  }
51
66
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"detect.js","names":[],"sources":["../src/detect.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"],"mappings":";;;;;;;;;;;;;AAaA,IAAI;;;;AAKJ,SAAgB,iBAAuB;AACrC,UAAS,KAAA;;;;;;;;;;;AAYX,SAAgB,0BAA+C;CAC7D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAChC,QAAO;;;;;;;;;AAUT,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;;;;;;AAOT,eAAsB,cAA4E;AAChG,KAAI;AACF,SAAO,MAAM,OAAO;SACd;AACN,SAAO"}
1
+ {"version":3,"file":"detect.js","names":[],"sources":["../src/detect.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export\n * that returns the runtime's Toss globals (deploymentId, brand name, …)\n * inside the Apps in Toss runtime and throws (RN bridge unavailable)\n * anywhere else. The SDK itself is an **optional** peer dependency; if its\n * module can't be imported we are definitely not inside Toss.\n *\n * Just having the SDK module resolvable is not enough apps can bundle it\n * and still run in a plain browser. We need the bridge probe to confirm.\n *\n * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but\n * that's a constant read from the bridge — no permission dialogs, no\n * analytics fire. In a plain browser the bridge lookup fails fast (sync\n * throw, microsecond-scale), so the startup cost is negligible.\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 if (typeof mod?.getAppsInTossGlobals !== 'function') {\n cached = false;\n return cached;\n }\n // Inside Toss the bridge returns a populated globals object. In a plain\n // browser the RN bridge isn't attached and the call throws — that's our\n // signal. Any non-throwing call with an object return is treated as Toss.\n try {\n const globals = mod.getAppsInTossGlobals();\n cached = Boolean(globals) && typeof globals === 'object';\n } catch {\n cached = false;\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;AAKJ,SAAgB,iBAAuB;AACrC,UAAS,KAAA;;;;;;;;;;;AAYX,SAAgB,0BAA+C;CAC7D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAChC,QAAO;;;;;;;;;AAUT,eAAsB,oBAAsC;CAG1D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAEhC,KAAI,WAAW,KAAA,EAAW,QAAO;CAEjC,MAAM,MAAM,MAAM,aAAa;AAC/B,KAAI,OAAO,KAAK,yBAAyB,YAAY;AACnD,WAAS;AACT,SAAO;;AAKT,KAAI;EACF,MAAM,UAAU,IAAI,sBAAsB;AAC1C,WAAS,QAAQ,QAAQ,IAAI,OAAO,YAAY;SAC1C;AACN,WAAS;;AAEX,QAAO;;;;;;AAOT,eAAsB,cAA4E;AAChG,KAAI;AACF,SAAO,MAAM,OAAO;SACd;AACN,SAAO"}
package/dist/index.d.ts CHANGED
@@ -174,19 +174,20 @@ declare function uninstallVibrateShim(): void;
174
174
  //#region src/index.d.ts
175
175
  declare const VERSION: string;
176
176
  /**
177
- * Install every shim this library ships. Idempotent safe to call more than
178
- * once. Returns an uninstall function that restores every original API.
179
- *
180
- * Install order: clipboard → geolocation → share → vibrate → network.
181
- * `uninstall()` tears them down in the same order (each per-shim uninstall is
182
- * independent, so order doesn't affect correctness; documented for clarity).
183
- *
184
- * Not atomic on failure: if a later per-shim install throws (e.g., a consumer
185
- * has pinned one of the target navigator properties as non-configurable),
186
- * earlier shims are already installed. Callers should catch and invoke
187
- * `uninstall()` to roll back.
177
+ * Install every shim this library ships, but only if we detect an Apps in
178
+ * Toss runtime. In a plain browser `install()` is a no-op — the browser's
179
+ * native APIs stay untouched.
180
+ *
181
+ * Returns a promise that resolves with an uninstall function. If the
182
+ * environment turns out not to be Toss, the uninstall function is a no-op.
183
+ *
184
+ * Install order (when active): clipboard geolocation share vibrate
185
+ * network. Not atomic on failure if a per-shim install throws (e.g., a
186
+ * consumer pinned a target navigator property as non-configurable), earlier
187
+ * shims are already in place. Callers should catch and invoke the returned
188
+ * uninstall to roll back.
188
189
  */
189
- declare function install(): () => void;
190
+ declare function install(): Promise<() => void>;
190
191
  /**
191
192
  * Uninstall every shim installed by `install()`. Safe to call when no shim is
192
193
  * installed — each installer's uninstall is a no-op in that case.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"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"],"mappings":";;;;;;;;ACyHA;;;;iBD1FgB,uBAAA,CAAA;AC6HhB;;;;;;;AAAA,iBD/GsB,iBAAA,CAAA,GAAqB,OAAA;AEyN3C;;;;AAAA,iBFtMsB,WAAA,CAAA,GAAe,OAAA,QAAJ,8BAAA;;;;;;AAjCjC;;;;;AAcA;;;;;AAmBA;;;;iBCyDgB,oBAAA,CAAA;;;;AAAhB;;iBAmCgB,sBAAA,CAAA;;;;;;AD7HhB;;;;;AAcA;;;;;AAmBA;;;;;;;;ACyDA;;;;;AAmCA;;iBC0GgB,sBAAA,CAAA;AAAA,iBAuBA,wBAAA,CAAA;;;;;;AF9PhB;;;;;AAcA;;;;;AAmBA;;;;;;;;ACyDA;;;;;AAmCA;;;;;;;;AC0GA;;;;;AAuBA;;iBCzJgB,kBAAA,CAAA;AAAA,iBAqGA,oBAAA,CAAA;;;;;;AH1MhB;;;;;AAcA;;;;;AAmBA;iBI2DgB,gBAAA,CAAA;AAAA,iBAsCA,kBAAA,CAAA;;;;;;AJlIhB;;;;;AAcA;;;;;AAmBA;;;;;;;;iBK2CgB,kBAAA,CAAA;AAAA,iBAuBA,oBAAA,CAAA;;;cCzGH,OAAA;;;;ALgGb;;;;;AAmCA;;;;;iBKpHgB,OAAA,CAAA;;;AJ8NhB;;iBI7MgB,SAAA,CAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"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"],"mappings":";;;ACyHA;;;;;AAmCA;;;;AAnCA,iBDrFgB,uBAAA,CAAA;;;;AEkOhB;;;;iBFpNsB,iBAAA,CAAA,GAAqB,OAAA;AE2O3C;;;;AAAA,iBF7MsB,WAAA,CAAA,GAAe,OAAA,QAAJ,8BAAA;;;;;;AA5CjC;;;;;AAcA;;;;;AA8BA;;;;iBCyCgB,oBAAA,CAAA;;;;AAAhB;;iBAmCgB,sBAAA,CAAA;;;;;;ADxHhB;;;;;AAcA;;;;;AA8BA;;;;;;;;ACyCA;;;;;AAmCA;;iBC0GgB,sBAAA,CAAA;AAAA,iBAuBA,wBAAA,CAAA;;;;;;AFzPhB;;;;;AAcA;;;;;AA8BA;;;;;;;;ACyCA;;;;;AAmCA;;;;;;;;AC0GA;;;;;AAuBA;;iBCzJgB,kBAAA,CAAA;AAAA,iBAqGA,oBAAA,CAAA;;;;;;AHrMhB;;;;;AAcA;;;;;AA8BA;iBI2CgB,gBAAA,CAAA;AAAA,iBAsCA,kBAAA,CAAA;;;;;;AJ7HhB;;;;;AAcA;;;;;AA8BA;;;;;;;;iBK2BgB,kBAAA,CAAA;AAAA,iBAuBA,oBAAA,CAAA;;;cCvGH,OAAA;;;AL8Fb;;;;;AAmCA;;;;;;;iBK/GsB,OAAA,CAAA,GAAW,OAAA;AJyNjC;;;;AAAA,iBIvMgB,SAAA,CAAA"}
package/dist/index.js CHANGED
@@ -2,14 +2,19 @@
2
2
  /**
3
3
  * Environment detection: are we running inside Apps in Toss, or a plain browser?
4
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.
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.
9
10
  *
10
- * We deliberately avoid UA sniffing (spoofable) and avoid calling any SDK
11
- * function during detection (could prompt permission dialogs, fire analytics,
12
- * etc.).
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.
13
18
  */
14
19
  let cached;
15
20
  /**
@@ -39,7 +44,17 @@ async function isTossEnvironment() {
39
44
  if (force === "toss") return true;
40
45
  if (force === "browser") return false;
41
46
  if (cached !== void 0) return cached;
42
- cached = typeof (await loadTossSdk())?.getClipboardText === "function";
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
+ }
43
58
  return cached;
44
59
  }
45
60
  /**
@@ -711,21 +726,24 @@ function uninstallVibrateShim() {
711
726
  }
712
727
  //#endregion
713
728
  //#region src/index.ts
714
- const VERSION = "0.1.1";
729
+ const VERSION = "0.1.2";
730
+ const NOOP = () => {};
715
731
  /**
716
- * Install every shim this library ships. Idempotent safe to call more than
717
- * once. Returns an uninstall function that restores every original API.
732
+ * Install every shim this library ships, but only if we detect an Apps in
733
+ * Toss runtime. In a plain browser `install()` is a no-op — the browser's
734
+ * native APIs stay untouched.
718
735
  *
719
- * Install order: clipboard geolocation share vibrate network.
720
- * `uninstall()` tears them down in the same order (each per-shim uninstall is
721
- * independent, so order doesn't affect correctness; documented for clarity).
736
+ * Returns a promise that resolves with an uninstall function. If the
737
+ * environment turns out not to be Toss, the uninstall function is a no-op.
722
738
  *
723
- * Not atomic on failure: if a later per-shim install throws (e.g., a consumer
724
- * has pinned one of the target navigator properties as non-configurable),
725
- * earlier shims are already installed. Callers should catch and invoke
726
- * `uninstall()` to roll back.
739
+ * Install order (when active): clipboard geolocation share vibrate
740
+ * network. Not atomic on failure if a per-shim install throws (e.g., a
741
+ * consumer pinned a target navigator property as non-configurable), earlier
742
+ * shims are already in place. Callers should catch and invoke the returned
743
+ * uninstall to roll back.
727
744
  */
728
- function install() {
745
+ async function install() {
746
+ if (!await isTossEnvironment()) return NOOP;
729
747
  const uninstalls = [
730
748
  installClipboardShim(),
731
749
  installGeolocationShim(),