ait-anywhere 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +98 -0
- package/README.md +124 -3
- package/dist/core.d.ts +130 -0
- package/dist/core.js +354 -0
- package/dist/core.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/server/idtoken.d.ts +47 -0
- package/dist/server/idtoken.js +134 -0
- package/dist/server/idtoken.js.map +1 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +2 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +75 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dong-Yeop Gu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.en.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# ait-anywhere
|
|
2
|
+
|
|
3
|
+
**Ship one web app as an Apps-in-Toss mini-app, a Capacitor native app (App Store / Play) and a plain website.**
|
|
4
|
+
|
|
5
|
+
[한국어](README.md)
|
|
6
|
+
|
|
7
|
+
The Apps-in-Toss SDK (`@apps-in-toss/web-framework`) only works inside the Toss app; in a browser or an iOS build its calls throw or hang. `ait-anywhere` wraps the calls apps use most so they **use Toss inside Toss and fall back quietly (or to a web equivalent) everywhere else**.
|
|
8
|
+
|
|
9
|
+
| | Inside Toss | Plain web | Native app (Capacitor) |
|
|
10
|
+
|---|---|---|---|
|
|
11
|
+
| `platform()` | `'toss'` / `'toss-sandbox'` | `'web'` | `'native'` |
|
|
12
|
+
| `getUid()` | Toss anonymous key `t:…` (retried on errors, then the last `t:` id seen on this device) | id kept in localStorage `l:…` | id kept in localStorage `l:…` |
|
|
13
|
+
| `attachBanner(el)` | Toss banner ad | AdSense, else Kakao AdFit | nothing |
|
|
14
|
+
| `showInterstitial()` | Toss full-screen ad | resolves `false` at once | resolves `false` at once |
|
|
15
|
+
| `haptic(type)` | Toss haptics | `navigator.vibrate` where supported | nothing |
|
|
16
|
+
| `onBack(fn)` | Android back button | nothing | nothing |
|
|
17
|
+
| `closeApp()` | closes the mini-app | nothing | nothing |
|
|
18
|
+
| `safeArea()` | Toss insets (px) | zeros (use CSS `env()`) | zeros (use CSS `env()`) |
|
|
19
|
+
|
|
20
|
+
Client calls never throw, and a missing or silent ad never blocks the user (safety `timeouts`).
|
|
21
|
+
|
|
22
|
+
For your server there is a **Google / Apple Sign-In ID token verifier** (`ait-anywhere/server`) that uses only Node's `crypto` and `fetch`; server-only users do not need the Toss SDK.
|
|
23
|
+
|
|
24
|
+
> Not an official Toss / Apps-in-Toss package.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
npm i ait-anywhere @apps-in-toss/web-framework
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
ESM only. The Toss SDK (`^3.10.0`) is an optional peer dependency: needed for the main entry, not for `ait-anywhere/server`.
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { configure, getUid, attachBanner, preloadInterstitial, showInterstitial, haptic, onBack, closeApp } from 'ait-anywhere';
|
|
38
|
+
|
|
39
|
+
configure({
|
|
40
|
+
ads: {
|
|
41
|
+
toss: { bannerId: 'ait-ad-...', interstitialId: 'ait-ad-...' },
|
|
42
|
+
adsense: { client: 'ca-pub-...', slot: '...' }, // plain web only
|
|
43
|
+
adfit: { unit: 'DAN-...' }, // plain web, when no AdSense unit
|
|
44
|
+
},
|
|
45
|
+
onAdStart: () => sound.mute(),
|
|
46
|
+
onAdEnd: () => sound.unmute(),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const uid = await getUid();
|
|
50
|
+
preloadInterstitial();
|
|
51
|
+
await showInterstitial(); // true if an ad was shown
|
|
52
|
+
haptic('success');
|
|
53
|
+
const off = onBack(() => (canGoBack() ? goBack() : closeApp()));
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
React banner:
|
|
57
|
+
|
|
58
|
+
```tsx
|
|
59
|
+
function Banner() {
|
|
60
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
61
|
+
useEffect(() => attachBanner(ref.current!), []);
|
|
62
|
+
return <div ref={ref} style={{ minHeight: 60 }} />;
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Server:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { createIdTokenVerifier } from 'ait-anywhere/server';
|
|
70
|
+
|
|
71
|
+
const verifyIdToken = createIdTokenVerifier({ google: GOOGLE_CLIENT_ID, apple: ['com.example.web', 'com.example.app'] });
|
|
72
|
+
let user;
|
|
73
|
+
try {
|
|
74
|
+
user = await verifyIdToken(provider, token, { nonce }); // { provider, sub, uid, claims } | null
|
|
75
|
+
} catch {
|
|
76
|
+
// keys could not be downloaded (5 s timeout) and none are cached: answer 503
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Checks the RS256 signature against the provider's JWKS, and `iss`, `aud` (plus `azp` for several audiences), `exp`, `nbf`, `iat`, `sub`, and `nonce` when you pass one. Keys are cached for an hour, refetched (at most every 10 s) for an unknown key id, and kept in use while the provider is down.
|
|
81
|
+
|
|
82
|
+
## Notes
|
|
83
|
+
|
|
84
|
+
- While `onBack` is subscribed the default back action is blocked: the handler must always go back or call `closeApp()`.
|
|
85
|
+
- App Store review: show external payment / tip links only when `isWeb()`.
|
|
86
|
+
- Native builds get no web ads; use a native ad plugin there.
|
|
87
|
+
|
|
88
|
+
## Testing your app
|
|
89
|
+
|
|
90
|
+
`createAnywhere(sdk, options)` from `ait-anywhere/core` takes any object shaped like the SDK, so your app logic can be tested with a fake. Pass `null` for "outside Toss".
|
|
91
|
+
|
|
92
|
+
## How this was made
|
|
93
|
+
|
|
94
|
+
Extracted from a shipped Apps-in-Toss game and generalized. AI coding tools (Claude Code) helped with the refactor, tests and docs; every change was reviewed by a human.
|
|
95
|
+
|
|
96
|
+
## License
|
|
97
|
+
|
|
98
|
+
MIT
|
package/README.md
CHANGED
|
@@ -1,3 +1,124 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# ait-anywhere
|
|
2
|
+
|
|
3
|
+
**웹 코드 하나로 앱인토스 미니앱, Capacitor 네이티브 앱(App Store / Play), 일반 웹을 함께 출시할 때 쓰는 작은 라이브러리예요.**
|
|
4
|
+
|
|
5
|
+
[English](README.en.md)
|
|
6
|
+
|
|
7
|
+
앱인토스 SDK(`@apps-in-toss/web-framework`)는 토스 앱 안에서만 동작해요. 같은 코드를 브라우저나 iOS 앱에서 실행하면 에러가 나거나 멈추죠. `ait-anywhere`는 자주 쓰는 SDK 기능을 감싸서 **토스 안에서는 토스 기능을 쓰고, 밖에서는 조용히 넘어가거나 웹용 대체 기능을 쓰게** 해 줘요.
|
|
8
|
+
|
|
9
|
+
| 기능 | 토스 안 | 일반 웹 | 네이티브 앱(Capacitor) |
|
|
10
|
+
|---|---|---|---|
|
|
11
|
+
| `platform()` | `'toss'` / `'toss-sandbox'` | `'web'` | `'native'` |
|
|
12
|
+
| `getUid()` | 토스 익명 키 `t:…` (일시적 오류는 재시도, 그래도 실패하면 이 기기에서 마지막으로 받은 `t:` ID) | localStorage에 저장한 ID `l:…` | localStorage에 저장한 ID `l:…` |
|
|
13
|
+
| `attachBanner(el)` | 토스 배너 광고 | AdSense → 없으면 카카오 AdFit | 아무것도 안 함 |
|
|
14
|
+
| `showInterstitial()` | 토스 전면 광고 | 즉시 `false` | 즉시 `false` |
|
|
15
|
+
| `haptic(type)` | 토스 햅틱 | `navigator.vibrate` (지원하는 브라우저만) | 아무것도 안 함 |
|
|
16
|
+
| `onBack(fn)` | 안드로이드 뒤로가기 구독 | 아무것도 안 함 | 아무것도 안 함 |
|
|
17
|
+
| `closeApp()` | 미니앱 닫기 | 아무것도 안 함 | 아무것도 안 함 |
|
|
18
|
+
| `safeArea()` | 토스 Safe Area(px) | 0 (CSS `env()` 사용) | 0 (CSS `env()` 사용) |
|
|
19
|
+
|
|
20
|
+
클라이언트 함수는 예외를 던지지 않아요. 광고를 불러오지 못하거나 SDK가 응답하지 않아도 정해진 시간(`timeouts`)이 지나면 넘어가서 사용자를 막지 않아요.
|
|
21
|
+
|
|
22
|
+
서버용으로는 **Google / Apple 로그인 ID 토큰 검증기**(`ait-anywhere/server`)가 들어 있어요. 앱인토스 밖에서 로그인을 붙일 때 쓰면 돼요. Node 내장 `crypto`와 `fetch`만 쓰고, 서버에서만 쓴다면 `@apps-in-toss/web-framework`를 설치하지 않아도 돼요.
|
|
23
|
+
|
|
24
|
+
> 토스나 앱인토스의 공식 패키지가 아니에요. 비공식 커뮤니티 라이브러리예요.
|
|
25
|
+
|
|
26
|
+
## 설치
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
npm i ait-anywhere @apps-in-toss/web-framework
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`@apps-in-toss/web-framework`(3.10 이상 3.x)는 peer dependency예요. 서버 모듈(`ait-anywhere/server`)만 쓸 때는 필요 없어요.
|
|
33
|
+
|
|
34
|
+
ESM 전용 패키지예요(Vite, Next.js, `"type": "module"` Node 프로젝트).
|
|
35
|
+
|
|
36
|
+
## 사용법
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { configure, platform, getUid, attachBanner, preloadInterstitial, showInterstitial, haptic, onBack, closeApp } from 'ait-anywhere';
|
|
40
|
+
|
|
41
|
+
// 앱 시작 시 한 번 (배너를 먼저 붙였어도 configure가 실행되면 채워져요)
|
|
42
|
+
configure({
|
|
43
|
+
ads: {
|
|
44
|
+
toss: { bannerId: import.meta.env.VITE_AIT_BANNER_ID, interstitialId: import.meta.env.VITE_AIT_INTERSTITIAL_ID },
|
|
45
|
+
adsense: { client: 'ca-pub-0000000000000000', slot: '0000000000' }, // 일반 웹에서만
|
|
46
|
+
adfit: { unit: 'DAN-xxxxxxxx' }, // AdSense가 없을 때 일반 웹에서
|
|
47
|
+
},
|
|
48
|
+
onAdStart: () => sound.mute(), // 전면 광고가 나오는 동안 효과음 끄기
|
|
49
|
+
onAdEnd: () => sound.unmute(),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const uid = await getUid(); // 토스: 't:…' 그 외: 'l:…'
|
|
53
|
+
preloadInterstitial();
|
|
54
|
+
|
|
55
|
+
// 게임 한 판이 끝났을 때
|
|
56
|
+
await showInterstitial(); // 광고가 없으면 바로 넘어감
|
|
57
|
+
haptic('success');
|
|
58
|
+
|
|
59
|
+
// 안드로이드 뒤로가기 (토스 안에서만)
|
|
60
|
+
const off = onBack(() => (canGoBack() ? goBack() : closeApp()));
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### React 배너
|
|
64
|
+
|
|
65
|
+
```tsx
|
|
66
|
+
function Banner() {
|
|
67
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
68
|
+
useEffect(() => attachBanner(ref.current!), []); // 반환값이 정리 함수
|
|
69
|
+
return <div ref={ref} style={{ minHeight: 60 }} />;
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### 서버: Google / Apple 로그인 토큰 검증
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { createIdTokenVerifier } from 'ait-anywhere/server';
|
|
77
|
+
|
|
78
|
+
const verifyIdToken = createIdTokenVerifier({
|
|
79
|
+
google: process.env.GOOGLE_CLIENT_ID, // 여러 개면 배열
|
|
80
|
+
apple: ['com.example.web', 'com.example.app'], // 웹 Services ID, iOS 번들 ID
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
let user;
|
|
84
|
+
try {
|
|
85
|
+
user = await verifyIdToken(req.body.provider, req.body.token, { nonce: session.nonce }); // nonce는 선택
|
|
86
|
+
} catch {
|
|
87
|
+
return res.status(503).end(); // Google/Apple 공개 키를 받지 못함 (5초 타임아웃)
|
|
88
|
+
}
|
|
89
|
+
if (!user) return res.status(401).end();
|
|
90
|
+
user.uid; // 'google:1234…' / 'apple:000…'
|
|
91
|
+
user.claims; // email 등 토큰에 들어 있는 값
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
검증하는 항목: RS256 서명(제공자의 공개 키), `iss`, `aud`(여러 개면 `azp`도), `exp`, `nbf`, `iat`, `sub`, 그리고 넘겨준 경우 `nonce`. 공개 키는 1시간 동안 캐시하고, 모르는 키 ID가 오면 다시 받아요(10초에 한 번까지만). 제공자 서버가 잠깐 죽어도 이미 받아 둔 키로 계속 검증해요.
|
|
95
|
+
|
|
96
|
+
## 주의할 점
|
|
97
|
+
|
|
98
|
+
- **`onBack`을 구독하는 동안에는 기본 뒤로가기가 막혀요.** 핸들러는 꼭 뭔가를 해야 해요(이전 화면으로 가거나 `closeApp()` 호출).
|
|
99
|
+
- **App Store 심사**: iOS 앱 안에서 외부 결제나 후원 링크를 보여주면 안 돼요. 그런 링크는 `isWeb()`일 때만 보여주세요.
|
|
100
|
+
- **네이티브 앱 광고**: Capacitor 빌드에서는 웹 광고를 붙이지 않아요(심사 및 정책 문제). 네이티브 광고 플러그인을 따로 쓰세요.
|
|
101
|
+
- 토스 앱이 너무 오래돼 익명 키를 못 주고 이 기기에 저장된 `t:` ID도 없으면 `l:` ID가 나와요.
|
|
102
|
+
- `getUid()`의 `l:` ID는 브라우저나 기기마다 달라요. 기기를 바꿔도 같은 사용자로 알아봐야 한다면 로그인을 붙이세요.
|
|
103
|
+
|
|
104
|
+
## 테스트용 코어
|
|
105
|
+
|
|
106
|
+
`ait-anywhere/core`의 `createAnywhere(sdk, options)`에 가짜 SDK를 넘기면 토스 앱 없이도 앱 로직을 테스트할 수 있어요. 인자로 `null`을 넘기면 "토스 밖" 상태가 돼요.
|
|
107
|
+
|
|
108
|
+
## 개발
|
|
109
|
+
|
|
110
|
+
Node 22.6 이상이 필요해요(테스트가 TypeScript를 바로 실행해요).
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
npm i
|
|
114
|
+
npm test # node:test, 브라우저 없이 실행
|
|
115
|
+
npm run build
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## 만든 과정
|
|
119
|
+
|
|
120
|
+
이 패키지는 실제로 출시한 앱인토스 게임에서 쓰던 코드를 범용으로 정리한 거예요. 정리, 테스트 작성, 문서화는 AI 코딩 도구(Claude Code)의 도움을 받았고, 모든 변경은 사람이 검토했어요.
|
|
121
|
+
|
|
122
|
+
## 라이선스
|
|
123
|
+
|
|
124
|
+
MIT
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/** Haptic types understood by the Toss app. */
|
|
2
|
+
export type HapticType = 'tickWeak' | 'tap' | 'tickMedium' | 'softMedium' | 'basicWeak' | 'basicMedium' | 'success' | 'error' | 'wiggle' | 'confetti';
|
|
3
|
+
/** Where the page is running. */
|
|
4
|
+
export type Platform = 'toss' | 'toss-sandbox' | 'native' | 'web';
|
|
5
|
+
export interface SafeAreaInsets {
|
|
6
|
+
top: number;
|
|
7
|
+
bottom: number;
|
|
8
|
+
left: number;
|
|
9
|
+
right: number;
|
|
10
|
+
}
|
|
11
|
+
type Supported = {
|
|
12
|
+
isSupported: () => boolean;
|
|
13
|
+
};
|
|
14
|
+
/** The part of `@apps-in-toss/web-framework` this library uses. */
|
|
15
|
+
export interface TossSdk {
|
|
16
|
+
getOperationalEnvironment: () => 'toss' | 'sandbox';
|
|
17
|
+
User: {
|
|
18
|
+
getAnonymousKey: (() => Promise<{
|
|
19
|
+
hash?: string;
|
|
20
|
+
} | undefined>) & Supported;
|
|
21
|
+
};
|
|
22
|
+
TossAds: {
|
|
23
|
+
initialize: ((o: {
|
|
24
|
+
callbacks?: {
|
|
25
|
+
onInitialized?: () => void;
|
|
26
|
+
onInitializationFailed?: (e: unknown) => void;
|
|
27
|
+
};
|
|
28
|
+
}) => void) & Supported;
|
|
29
|
+
attachBanner: ((id: string, el: HTMLElement, o?: object) => {
|
|
30
|
+
destroy: () => void;
|
|
31
|
+
}) & Supported;
|
|
32
|
+
};
|
|
33
|
+
loadFullScreenAd: ((p: {
|
|
34
|
+
options?: {
|
|
35
|
+
adGroupId: string;
|
|
36
|
+
};
|
|
37
|
+
onEvent: (e: {
|
|
38
|
+
type: string;
|
|
39
|
+
}) => void;
|
|
40
|
+
onError: (e: Error) => void;
|
|
41
|
+
}) => () => void) & Supported;
|
|
42
|
+
showFullScreenAd: ((p: {
|
|
43
|
+
options?: {
|
|
44
|
+
adGroupId: string;
|
|
45
|
+
};
|
|
46
|
+
onEvent: (e: {
|
|
47
|
+
type: string;
|
|
48
|
+
}) => void;
|
|
49
|
+
onError: (e: Error) => void;
|
|
50
|
+
}) => () => void) & Supported;
|
|
51
|
+
generateHapticFeedback: (o: {
|
|
52
|
+
type: HapticType;
|
|
53
|
+
}) => Promise<void>;
|
|
54
|
+
Screen: {
|
|
55
|
+
close: () => Promise<void>;
|
|
56
|
+
};
|
|
57
|
+
graniteEvent: {
|
|
58
|
+
addEventListener: (event: 'backEvent', args: {
|
|
59
|
+
onEvent: () => void;
|
|
60
|
+
onError?: (e: Error) => void;
|
|
61
|
+
}) => () => void;
|
|
62
|
+
};
|
|
63
|
+
SafeArea: {
|
|
64
|
+
get: () => SafeAreaInsets;
|
|
65
|
+
subscribe?: (args: {
|
|
66
|
+
onEvent: (d: SafeAreaInsets) => void;
|
|
67
|
+
}) => () => void;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export interface AnywhereOptions {
|
|
71
|
+
ads?: {
|
|
72
|
+
/** Apps-in-Toss ad group ids (from the Apps-in-Toss console). Used inside Toss only. */
|
|
73
|
+
toss?: {
|
|
74
|
+
bannerId?: string;
|
|
75
|
+
interstitialId?: string;
|
|
76
|
+
/** Merged over the default `{ variant: 'card', tone: 'grey' }` and passed to `TossAds.attachBanner`. */
|
|
77
|
+
banner?: {
|
|
78
|
+
theme?: 'auto' | 'light' | 'dark';
|
|
79
|
+
tone?: 'blackAndWhite' | 'grey';
|
|
80
|
+
variant?: 'card' | 'expanded';
|
|
81
|
+
callbacks?: object;
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
/** Google AdSense display unit. Used in plain browsers only (never inside Toss or a native app). */
|
|
85
|
+
adsense?: {
|
|
86
|
+
client: string;
|
|
87
|
+
slot: string;
|
|
88
|
+
height?: number;
|
|
89
|
+
};
|
|
90
|
+
/** Kakao AdFit unit. Used in plain browsers when no AdSense unit is set. */
|
|
91
|
+
adfit?: {
|
|
92
|
+
unit: string;
|
|
93
|
+
width?: number;
|
|
94
|
+
height?: number;
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
/** localStorage key for the fallback user id. Default `'ait_anywhere_uid'`. */
|
|
98
|
+
uidStorageKey?: string;
|
|
99
|
+
/** Called when a full-screen ad starts and ends, e.g. to mute your game sounds. `onAdEnd` always follows `onAdStart`. */
|
|
100
|
+
onAdStart?: () => void;
|
|
101
|
+
onAdEnd?: () => void;
|
|
102
|
+
/** Safety timeouts (ms) so a silent SDK never blocks the app. */
|
|
103
|
+
timeouts?: {
|
|
104
|
+
/** Toss Ads initialization. Default 10 000. */
|
|
105
|
+
adInit?: number;
|
|
106
|
+
/** Loading a full-screen ad. Default 30 000. */
|
|
107
|
+
adLoad?: number;
|
|
108
|
+
/** A full-screen ad with no event at all from the SDK. Default 90 000. */
|
|
109
|
+
adShow?: number;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export declare function createAnywhere(sdk: TossSdk | null, initial?: AnywhereOptions): {
|
|
113
|
+
configure: (next: AnywhereOptions) => void;
|
|
114
|
+
platform: () => Platform;
|
|
115
|
+
inToss: () => boolean;
|
|
116
|
+
isNative: () => boolean;
|
|
117
|
+
isWeb: () => boolean;
|
|
118
|
+
getUid: () => Promise<string>;
|
|
119
|
+
attachBanner: (el: HTMLElement) => () => void;
|
|
120
|
+
preloadInterstitial: () => void;
|
|
121
|
+
interstitialReady: () => boolean;
|
|
122
|
+
showInterstitial: () => Promise<boolean>;
|
|
123
|
+
haptic: (type: HapticType) => void;
|
|
124
|
+
closeApp: () => void;
|
|
125
|
+
onBack: (handler: () => void) => () => void;
|
|
126
|
+
safeArea: () => SafeAreaInsets;
|
|
127
|
+
onSafeAreaChange: (fn: (insets: SafeAreaInsets) => void) => () => void;
|
|
128
|
+
};
|
|
129
|
+
export type Anywhere = ReturnType<typeof createAnywhere>;
|
|
130
|
+
export {};
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
// Platform-neutral core. It never imports the Toss SDK itself: index.ts passes the real SDK in,
|
|
2
|
+
// and tests pass a fake. Every call degrades to a no-op (or a sensible web fallback) where the SDK is absent.
|
|
3
|
+
const safe = (f, fallback) => {
|
|
4
|
+
try {
|
|
5
|
+
return f();
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return fallback;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
const ZERO = { top: 0, bottom: 0, left: 0, right: 0 };
|
|
12
|
+
const DEFAULT_BANNER = { variant: 'card', tone: 'grey' };
|
|
13
|
+
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
14
|
+
export function createAnywhere(sdk, initial = {}) {
|
|
15
|
+
let opts = initial;
|
|
16
|
+
/** Toss Ads initialization. Only a success is cached; a failure may be retried by a later banner. */
|
|
17
|
+
let adsInit = null;
|
|
18
|
+
const banners = new Set();
|
|
19
|
+
/** Bumped by configure(): callbacks from an older configuration are ignored. */
|
|
20
|
+
let generation = 0;
|
|
21
|
+
let interstitial = { state: 'idle', id: '', generation: 0 };
|
|
22
|
+
const timeout = (k, d) => opts.timeouts?.[k] ?? d;
|
|
23
|
+
// ---------- environment ----------
|
|
24
|
+
/** True inside the Toss app (live or sandbox). */
|
|
25
|
+
const inToss = () => safe(() => !!sdk && !!sdk.getOperationalEnvironment(), false);
|
|
26
|
+
/** True in a Capacitor native build (iOS / Android app store build of the same web app). */
|
|
27
|
+
const isNative = () => safe(() => !!globalThis.Capacitor?.isNativePlatform?.(), false);
|
|
28
|
+
/** Plain browser: not Toss, not a native app. */
|
|
29
|
+
const isWeb = () => !inToss() && !isNative();
|
|
30
|
+
function platform() {
|
|
31
|
+
const env = safe(() => (sdk ? sdk.getOperationalEnvironment() : null), null);
|
|
32
|
+
if (env === 'toss')
|
|
33
|
+
return 'toss';
|
|
34
|
+
if (env === 'sandbox')
|
|
35
|
+
return 'toss-sandbox';
|
|
36
|
+
return isNative() ? 'native' : 'web';
|
|
37
|
+
}
|
|
38
|
+
// ---------- user id ----------
|
|
39
|
+
const storage = {
|
|
40
|
+
get: (k) => safe(() => globalThis.localStorage?.getItem(k) ?? null, null),
|
|
41
|
+
set: (k, v) => safe(() => globalThis.localStorage?.setItem(k, v), undefined),
|
|
42
|
+
};
|
|
43
|
+
async function tossKey() {
|
|
44
|
+
if (!sdk || !safe(() => sdk.User.getAnonymousKey.isSupported(), false))
|
|
45
|
+
return null;
|
|
46
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
47
|
+
if (attempt)
|
|
48
|
+
await delay(200 * attempt);
|
|
49
|
+
try {
|
|
50
|
+
const res = await sdk.User.getAnonymousKey();
|
|
51
|
+
if (res && typeof res.hash === 'string' && res.hash)
|
|
52
|
+
return `t:${res.hash}`;
|
|
53
|
+
return null; // answered without a key: retrying will not help
|
|
54
|
+
}
|
|
55
|
+
catch { /* transient error or unsupported app version: retry */ }
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Stable per-user id. Never throws.
|
|
61
|
+
* - Inside Toss: `t:<anonymous key hash>`, the same on every device the user signs in with. A transient SDK
|
|
62
|
+
* error is retried, then answered with the last `t:` id seen on this device.
|
|
63
|
+
* - Elsewhere, or a Toss app too old to give a key: `l:<random uuid>` kept in localStorage (per browser / install).
|
|
64
|
+
*/
|
|
65
|
+
async function getUid() {
|
|
66
|
+
const key = opts.uidStorageKey ?? 'ait_anywhere_uid';
|
|
67
|
+
const toss = inToss() ? await tossKey() : null;
|
|
68
|
+
if (toss) {
|
|
69
|
+
storage.set(`${key}:toss`, toss);
|
|
70
|
+
return toss;
|
|
71
|
+
}
|
|
72
|
+
if (inToss()) {
|
|
73
|
+
const last = storage.get(`${key}:toss`);
|
|
74
|
+
if (last)
|
|
75
|
+
return last;
|
|
76
|
+
}
|
|
77
|
+
const stored = storage.get(key);
|
|
78
|
+
if (stored)
|
|
79
|
+
return stored;
|
|
80
|
+
const id = `l:${randomId()}`;
|
|
81
|
+
storage.set(key, id);
|
|
82
|
+
return id;
|
|
83
|
+
}
|
|
84
|
+
// ---------- banner ads ----------
|
|
85
|
+
function initTossAds() {
|
|
86
|
+
if (adsInit)
|
|
87
|
+
return adsInit;
|
|
88
|
+
if (!sdk || !safe(() => sdk.TossAds.initialize.isSupported(), false))
|
|
89
|
+
return Promise.resolve(false);
|
|
90
|
+
const p = new Promise((resolve) => {
|
|
91
|
+
const timer = setTimeout(() => resolve(false), timeout('adInit', 10_000));
|
|
92
|
+
const end = (ok) => { clearTimeout(timer); resolve(ok); };
|
|
93
|
+
try {
|
|
94
|
+
sdk.TossAds.initialize({ callbacks: { onInitialized: () => end(true), onInitializationFailed: () => end(false) } });
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
end(false);
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
adsInit = p;
|
|
101
|
+
void p.then((ok) => { if (!ok && adsInit === p)
|
|
102
|
+
adsInit = null; });
|
|
103
|
+
return p;
|
|
104
|
+
}
|
|
105
|
+
function attachAdSense(el, a) {
|
|
106
|
+
const doc = el.ownerDocument;
|
|
107
|
+
if (!doc.querySelector('script[data-ait-adsense]') && !doc.querySelector('script[src*="adsbygoogle.js"]')) {
|
|
108
|
+
const s = doc.createElement('script');
|
|
109
|
+
s.async = true;
|
|
110
|
+
s.crossOrigin = 'anonymous';
|
|
111
|
+
s.dataset.aitAdsense = '';
|
|
112
|
+
s.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(a.client)}`;
|
|
113
|
+
doc.head.append(s);
|
|
114
|
+
}
|
|
115
|
+
const ins = doc.createElement('ins');
|
|
116
|
+
ins.className = 'adsbygoogle';
|
|
117
|
+
ins.style.cssText = `display:block;width:100%;height:${a.height ?? 60}px`;
|
|
118
|
+
ins.dataset.adClient = a.client;
|
|
119
|
+
ins.dataset.adSlot = a.slot;
|
|
120
|
+
el.append(ins);
|
|
121
|
+
safe(() => { (globalThis.adsbygoogle ??= []).push({}); }, undefined);
|
|
122
|
+
return () => ins.remove();
|
|
123
|
+
}
|
|
124
|
+
function attachAdFit(el, a) {
|
|
125
|
+
const doc = el.ownerDocument;
|
|
126
|
+
const ins = doc.createElement('ins');
|
|
127
|
+
ins.className = 'kakao_ad_area';
|
|
128
|
+
ins.style.display = 'none';
|
|
129
|
+
ins.dataset.adUnit = a.unit;
|
|
130
|
+
ins.dataset.adWidth = String(a.width ?? 320);
|
|
131
|
+
ins.dataset.adHeight = String(a.height ?? 50);
|
|
132
|
+
// AdFit's loader scans the page for new ad areas when it runs, so it is loaded again per banner.
|
|
133
|
+
const s = doc.createElement('script');
|
|
134
|
+
s.async = true;
|
|
135
|
+
s.src = 'https://t1.kakaocdn.net/kas/static/ba.min.js';
|
|
136
|
+
el.append(ins, s);
|
|
137
|
+
return () => { ins.remove(); s.remove(); };
|
|
138
|
+
}
|
|
139
|
+
/** (Re)fills one banner slot from the current options. */
|
|
140
|
+
function render(slot) {
|
|
141
|
+
safe(() => slot.cleanup(), undefined);
|
|
142
|
+
slot.cleanup = () => { };
|
|
143
|
+
slot.generation = generation;
|
|
144
|
+
const ads = opts.ads ?? {};
|
|
145
|
+
if (isWeb()) {
|
|
146
|
+
if (ads.adsense?.client && ads.adsense.slot)
|
|
147
|
+
slot.cleanup = safe(() => attachAdSense(slot.el, ads.adsense), () => { });
|
|
148
|
+
else if (ads.adfit?.unit)
|
|
149
|
+
slot.cleanup = safe(() => attachAdFit(slot.el, ads.adfit), () => { });
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const id = ads.toss?.bannerId;
|
|
153
|
+
if (!sdk || !id || !inToss())
|
|
154
|
+
return;
|
|
155
|
+
const gen = generation;
|
|
156
|
+
let handle = null;
|
|
157
|
+
let alive = true;
|
|
158
|
+
slot.cleanup = () => { alive = false; safe(() => handle?.destroy(), undefined); handle = null; };
|
|
159
|
+
void initTossAds().then((ok) => {
|
|
160
|
+
if (!ok || !alive || gen !== generation || !banners.has(slot))
|
|
161
|
+
return;
|
|
162
|
+
if (!safe(() => sdk.TossAds.attachBanner.isSupported(), false))
|
|
163
|
+
return;
|
|
164
|
+
handle = safe(() => sdk.TossAds.attachBanner(id, slot.el, { ...DEFAULT_BANNER, ...opts.ads?.toss?.banner }), null);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Shows a banner inside `el` and returns a cleanup function (call it on unmount).
|
|
169
|
+
* Toss: Toss Ads banner. Plain web: AdSense, else AdFit. Native app: nothing (use a native ad plugin there).
|
|
170
|
+
* A banner mounted before `configure()` is filled in when `configure()` runs.
|
|
171
|
+
*/
|
|
172
|
+
function attachBanner(el) {
|
|
173
|
+
if (!el)
|
|
174
|
+
return () => { };
|
|
175
|
+
const slot = { el, cleanup: () => { }, generation };
|
|
176
|
+
banners.add(slot);
|
|
177
|
+
render(slot);
|
|
178
|
+
return () => {
|
|
179
|
+
banners.delete(slot);
|
|
180
|
+
safe(() => slot.cleanup(), undefined);
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
// ---------- full-screen (interstitial) ads ----------
|
|
184
|
+
/** Starts loading a full-screen ad in the background. Safe to call often; Toss only. */
|
|
185
|
+
function preloadInterstitial() {
|
|
186
|
+
const id = opts.ads?.toss?.interstitialId;
|
|
187
|
+
if (!sdk || !id || interstitial.state !== 'idle' || !inToss())
|
|
188
|
+
return;
|
|
189
|
+
if (!safe(() => sdk.loadFullScreenAd.isSupported(), false))
|
|
190
|
+
return;
|
|
191
|
+
const mine = { state: 'loading', id, generation };
|
|
192
|
+
interstitial = mine;
|
|
193
|
+
let off = () => { };
|
|
194
|
+
let finished = false;
|
|
195
|
+
const timer = setTimeout(() => finish(false), timeout('adLoad', 30_000));
|
|
196
|
+
function finish(loaded) {
|
|
197
|
+
if (finished)
|
|
198
|
+
return;
|
|
199
|
+
finished = true;
|
|
200
|
+
clearTimeout(timer);
|
|
201
|
+
safe(() => off(), undefined);
|
|
202
|
+
if (interstitial === mine)
|
|
203
|
+
mine.state = loaded ? 'loaded' : 'idle';
|
|
204
|
+
}
|
|
205
|
+
try {
|
|
206
|
+
off = sdk.loadFullScreenAd({
|
|
207
|
+
options: { adGroupId: id },
|
|
208
|
+
onEvent: (e) => { if (e.type === 'loaded')
|
|
209
|
+
finish(true); },
|
|
210
|
+
onError: () => finish(false),
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
finish(false);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
// The SDK may report synchronously, before `off` was assigned.
|
|
218
|
+
if (finished)
|
|
219
|
+
safe(() => off(), undefined);
|
|
220
|
+
}
|
|
221
|
+
/** True when a preloaded full-screen ad can be shown right now. */
|
|
222
|
+
const interstitialReady = () => interstitial.state === 'loaded' && interstitial.id === opts.ads?.toss?.interstitialId;
|
|
223
|
+
/**
|
|
224
|
+
* Shows the preloaded full-screen ad and resolves when it is closed: `true` if an ad was shown.
|
|
225
|
+
* Never rejects and never blocks the user: with no ad ready it resolves `false` at once, and an SDK that
|
|
226
|
+
* goes silent is given up on after `timeouts.adShow`. Preloads the next ad afterwards.
|
|
227
|
+
*/
|
|
228
|
+
function showInterstitial() {
|
|
229
|
+
return new Promise((resolve) => {
|
|
230
|
+
const id = interstitial.id;
|
|
231
|
+
if (!sdk || !interstitialReady() || !safe(() => sdk.showFullScreenAd.isSupported(), false)) {
|
|
232
|
+
return resolve(false);
|
|
233
|
+
}
|
|
234
|
+
interstitial = { state: 'idle', id: '', generation }; // a shown ad cannot be shown again
|
|
235
|
+
safe(() => opts.onAdStart?.(), undefined);
|
|
236
|
+
let off = () => { };
|
|
237
|
+
let settled = false;
|
|
238
|
+
let shownEvent = false;
|
|
239
|
+
let timer = setTimeout(() => done(false), timeout('adShow', 90_000));
|
|
240
|
+
function done(shown) {
|
|
241
|
+
if (settled)
|
|
242
|
+
return;
|
|
243
|
+
settled = true;
|
|
244
|
+
clearTimeout(timer);
|
|
245
|
+
safe(() => off(), undefined);
|
|
246
|
+
safe(() => opts.onAdEnd?.(), undefined);
|
|
247
|
+
resolve(shown);
|
|
248
|
+
preloadInterstitial();
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
off = sdk.showFullScreenAd({
|
|
252
|
+
options: { adGroupId: id },
|
|
253
|
+
onEvent: (e) => {
|
|
254
|
+
if (e.type === 'dismissed')
|
|
255
|
+
done(true);
|
|
256
|
+
else if (e.type === 'failedToShow')
|
|
257
|
+
done(false);
|
|
258
|
+
else if (!shownEvent) {
|
|
259
|
+
// The ad is on screen: the SDK is alive, so wait for the user to close it (restart the clock).
|
|
260
|
+
shownEvent = true;
|
|
261
|
+
clearTimeout(timer);
|
|
262
|
+
timer = setTimeout(() => done(true), timeout('adShow', 90_000) * 2);
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
onError: () => done(false),
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
done(false);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (settled)
|
|
273
|
+
safe(() => off(), undefined);
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
// ---------- device ----------
|
|
277
|
+
const VIBRATE_MS = {
|
|
278
|
+
tickWeak: 5, tap: 10, tickMedium: 15, softMedium: 20, basicWeak: 10, basicMedium: 20,
|
|
279
|
+
success: [15, 60, 15], error: [40, 40, 40], wiggle: [10, 30, 10, 30, 10], confetti: [10, 20, 10, 20, 10, 20],
|
|
280
|
+
};
|
|
281
|
+
/** Haptic feedback. Toss: native haptics. Plain web: `navigator.vibrate` where the browser has it. */
|
|
282
|
+
function haptic(type) {
|
|
283
|
+
if (sdk && inToss()) {
|
|
284
|
+
safe(() => { void sdk.generateHapticFeedback({ type }).catch(() => { }); }, undefined);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (isWeb()) {
|
|
288
|
+
const ms = VIBRATE_MS[type];
|
|
289
|
+
if (ms !== undefined)
|
|
290
|
+
safe(() => globalThis.navigator?.vibrate?.(ms), undefined);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/** Closes the mini-app inside Toss. Does nothing elsewhere. */
|
|
294
|
+
function closeApp() {
|
|
295
|
+
if (!sdk || !inToss())
|
|
296
|
+
return;
|
|
297
|
+
safe(() => { void sdk.Screen.close().catch(() => { }); }, undefined);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Subscribes to the Android system back button inside Toss. Returns an unsubscribe function.
|
|
301
|
+
* While subscribed the default back action is blocked, so `handler` must always do something
|
|
302
|
+
* (go back a screen, or call closeApp()). Does nothing outside Toss.
|
|
303
|
+
*/
|
|
304
|
+
function onBack(handler) {
|
|
305
|
+
if (!sdk || !inToss())
|
|
306
|
+
return () => { };
|
|
307
|
+
return safe(() => sdk.graniteEvent.addEventListener('backEvent', { onEvent: handler, onError: () => { } }), () => { });
|
|
308
|
+
}
|
|
309
|
+
/** Safe-area insets in px inside Toss; zeros elsewhere (use CSS `env(safe-area-inset-*)` there). */
|
|
310
|
+
function safeArea() {
|
|
311
|
+
if (!sdk || !inToss())
|
|
312
|
+
return { ...ZERO };
|
|
313
|
+
const v = safe(() => sdk.SafeArea.get(), null);
|
|
314
|
+
if (!v)
|
|
315
|
+
return { ...ZERO };
|
|
316
|
+
return { top: v.top ?? 0, bottom: v.bottom ?? 0, left: v.left ?? 0, right: v.right ?? 0 };
|
|
317
|
+
}
|
|
318
|
+
/** Calls `fn` when the Toss safe area changes. Returns an unsubscribe function. */
|
|
319
|
+
function onSafeAreaChange(fn) {
|
|
320
|
+
if (!sdk || !inToss() || !sdk.SafeArea.subscribe)
|
|
321
|
+
return () => { };
|
|
322
|
+
return safe(() => sdk.SafeArea.subscribe({ onEvent: (d) => fn({ ...ZERO, ...d }) }), () => { });
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Replaces the options (ad ids etc.). Banners already on screen are refilled with the new options;
|
|
326
|
+
* a full-screen ad loaded for a different id is dropped.
|
|
327
|
+
*/
|
|
328
|
+
function configure(next) {
|
|
329
|
+
opts = next;
|
|
330
|
+
generation++;
|
|
331
|
+
if (interstitial.id !== next.ads?.toss?.interstitialId)
|
|
332
|
+
interstitial = { state: 'idle', id: '', generation };
|
|
333
|
+
for (const slot of banners)
|
|
334
|
+
render(slot);
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
configure, platform, inToss, isNative, isWeb, getUid,
|
|
338
|
+
attachBanner, preloadInterstitial, interstitialReady, showInterstitial,
|
|
339
|
+
haptic, closeApp, onBack, safeArea, onSafeAreaChange,
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function randomId() {
|
|
343
|
+
const c = globalThis.crypto;
|
|
344
|
+
if (c?.randomUUID)
|
|
345
|
+
return c.randomUUID();
|
|
346
|
+
const b = new Uint8Array(16);
|
|
347
|
+
if (c?.getRandomValues)
|
|
348
|
+
c.getRandomValues(b);
|
|
349
|
+
else
|
|
350
|
+
for (let i = 0; i < 16; i++)
|
|
351
|
+
b[i] = Math.floor(Math.random() * 256);
|
|
352
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
|
|
353
|
+
}
|
|
354
|
+
//# sourceMappingURL=core.js.map
|
package/dist/core.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,8GAA8G;AA0E9G,MAAM,IAAI,GAAG,CAAI,CAAU,EAAE,QAAW,EAAK,EAAE;IAC7C,IAAI,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;IAAC,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,QAAQ,CAAC;IAAC,CAAC;AAChD,CAAC,CAAC;AAEF,MAAM,IAAI,GAAmB,EAAE,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;AACtE,MAAM,cAAc,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAW,CAAC;AAMlE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C,MAAM,CAAC;IAC5B,IAAI,CAAC,EAAE,UAAU;QAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAC;IACzC,MAAM,CAAC,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IAC7B,IAAI,CAAC,EAAE,eAAe;QAAE,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;;QACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE;YAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,CAAC;IACzE,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACxE,CAAC","sourcesContent":["// Platform-neutral core. It never imports the Toss SDK itself: index.ts passes the real SDK in,\n// and tests pass a fake. Every call degrades to a no-op (or a sensible web fallback) where the SDK is absent.\n\n/** Haptic types understood by the Toss app. */\nexport type HapticType =\n | 'tickWeak' | 'tap' | 'tickMedium' | 'softMedium' | 'basicWeak'\n | 'basicMedium' | 'success' | 'error' | 'wiggle' | 'confetti';\n\n/** Where the page is running. */\nexport type Platform = 'toss' | 'toss-sandbox' | 'native' | 'web';\n\nexport interface SafeAreaInsets { top: number; bottom: number; left: number; right: number }\n\ntype Supported = { isSupported: () => boolean };\n\n/** The part of `@apps-in-toss/web-framework` this library uses. */\nexport interface TossSdk {\n getOperationalEnvironment: () => 'toss' | 'sandbox';\n User: { getAnonymousKey: (() => Promise<{ hash?: string } | undefined>) & Supported };\n TossAds: {\n initialize: ((o: { callbacks?: { onInitialized?: () => void; onInitializationFailed?: (e: unknown) => void } }) => void) & Supported;\n attachBanner: ((id: string, el: HTMLElement, o?: object) => { destroy: () => void }) & Supported;\n };\n loadFullScreenAd: ((p: {\n options?: { adGroupId: string };\n onEvent: (e: { type: string }) => void;\n onError: (e: Error) => void;\n }) => () => void) & Supported;\n showFullScreenAd: ((p: {\n options?: { adGroupId: string };\n onEvent: (e: { type: string }) => void;\n onError: (e: Error) => void;\n }) => () => void) & Supported;\n generateHapticFeedback: (o: { type: HapticType }) => Promise<void>;\n Screen: { close: () => Promise<void> };\n graniteEvent: {\n addEventListener: (event: 'backEvent', args: { onEvent: () => void; onError?: (e: Error) => void }) => () => void;\n };\n SafeArea: {\n get: () => SafeAreaInsets;\n subscribe?: (args: { onEvent: (d: SafeAreaInsets) => void }) => () => void;\n };\n}\n\n\nexport interface AnywhereOptions {\n ads?: {\n /** Apps-in-Toss ad group ids (from the Apps-in-Toss console). Used inside Toss only. */\n toss?: {\n bannerId?: string;\n interstitialId?: string;\n /** Merged over the default `{ variant: 'card', tone: 'grey' }` and passed to `TossAds.attachBanner`. */\n banner?: { theme?: 'auto' | 'light' | 'dark'; tone?: 'blackAndWhite' | 'grey'; variant?: 'card' | 'expanded'; callbacks?: object };\n };\n /** Google AdSense display unit. Used in plain browsers only (never inside Toss or a native app). */\n adsense?: { client: string; slot: string; height?: number };\n /** Kakao AdFit unit. Used in plain browsers when no AdSense unit is set. */\n adfit?: { unit: string; width?: number; height?: number };\n };\n /** localStorage key for the fallback user id. Default `'ait_anywhere_uid'`. */\n uidStorageKey?: string;\n /** Called when a full-screen ad starts and ends, e.g. to mute your game sounds. `onAdEnd` always follows `onAdStart`. */\n onAdStart?: () => void;\n onAdEnd?: () => void;\n /** Safety timeouts (ms) so a silent SDK never blocks the app. */\n timeouts?: {\n /** Toss Ads initialization. Default 10 000. */\n adInit?: number;\n /** Loading a full-screen ad. Default 30 000. */\n adLoad?: number;\n /** A full-screen ad with no event at all from the SDK. Default 90 000. */\n adShow?: number;\n };\n}\n\nconst safe = <T>(f: () => T, fallback: T): T => {\n try { return f(); } catch { return fallback; }\n};\n\nconst ZERO: SafeAreaInsets = { top: 0, bottom: 0, left: 0, right: 0 };\nconst DEFAULT_BANNER = { variant: 'card', tone: 'grey' } as const;\n\ntype CapacitorGlobal = { Capacitor?: { isNativePlatform?: () => boolean } };\ntype AdsByGoogle = { adsbygoogle?: unknown[] };\ntype BannerSlot = { el: HTMLElement; cleanup: () => void; generation: number };\n\nconst delay = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport function createAnywhere(sdk: TossSdk | null, initial: AnywhereOptions = {}) {\n let opts: AnywhereOptions = initial;\n /** Toss Ads initialization. Only a success is cached; a failure may be retried by a later banner. */\n let adsInit: Promise<boolean> | null = null;\n const banners = new Set<BannerSlot>();\n /** Bumped by configure(): callbacks from an older configuration are ignored. */\n let generation = 0;\n let interstitial: { state: 'idle' | 'loading' | 'loaded'; id: string; generation: number } = { state: 'idle', id: '', generation: 0 };\n\n const timeout = (k: 'adInit' | 'adLoad' | 'adShow', d: number) => opts.timeouts?.[k] ?? d;\n\n // ---------- environment ----------\n\n /** True inside the Toss app (live or sandbox). */\n const inToss = (): boolean => safe(() => !!sdk && !!sdk.getOperationalEnvironment(), false);\n\n /** True in a Capacitor native build (iOS / Android app store build of the same web app). */\n const isNative = (): boolean =>\n safe(() => !!(globalThis as CapacitorGlobal).Capacitor?.isNativePlatform?.(), false);\n\n /** Plain browser: not Toss, not a native app. */\n const isWeb = (): boolean => !inToss() && !isNative();\n\n function platform(): Platform {\n const env = safe(() => (sdk ? sdk.getOperationalEnvironment() : null), null);\n if (env === 'toss') return 'toss';\n if (env === 'sandbox') return 'toss-sandbox';\n return isNative() ? 'native' : 'web';\n }\n\n // ---------- user id ----------\n\n const storage = {\n get: (k: string) => safe(() => globalThis.localStorage?.getItem(k) ?? null, null),\n set: (k: string, v: string) => safe(() => globalThis.localStorage?.setItem(k, v), undefined),\n };\n\n async function tossKey(): Promise<string | null> {\n if (!sdk || !safe(() => sdk.User.getAnonymousKey.isSupported(), false)) return null;\n for (let attempt = 0; attempt < 3; attempt++) {\n if (attempt) await delay(200 * attempt);\n try {\n const res = await sdk.User.getAnonymousKey();\n if (res && typeof res.hash === 'string' && res.hash) return `t:${res.hash}`;\n return null; // answered without a key: retrying will not help\n } catch { /* transient error or unsupported app version: retry */ }\n }\n return null;\n }\n\n /**\n * Stable per-user id. Never throws.\n * - Inside Toss: `t:<anonymous key hash>`, the same on every device the user signs in with. A transient SDK\n * error is retried, then answered with the last `t:` id seen on this device.\n * - Elsewhere, or a Toss app too old to give a key: `l:<random uuid>` kept in localStorage (per browser / install).\n */\n async function getUid(): Promise<string> {\n const key = opts.uidStorageKey ?? 'ait_anywhere_uid';\n const toss = inToss() ? await tossKey() : null;\n if (toss) {\n storage.set(`${key}:toss`, toss);\n return toss;\n }\n if (inToss()) {\n const last = storage.get(`${key}:toss`);\n if (last) return last;\n }\n const stored = storage.get(key);\n if (stored) return stored;\n const id = `l:${randomId()}`;\n storage.set(key, id);\n return id;\n }\n\n // ---------- banner ads ----------\n\n function initTossAds(): Promise<boolean> {\n if (adsInit) return adsInit;\n if (!sdk || !safe(() => sdk.TossAds.initialize.isSupported(), false)) return Promise.resolve(false);\n const p = new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), timeout('adInit', 10_000));\n const end = (ok: boolean) => { clearTimeout(timer); resolve(ok); };\n try {\n sdk.TossAds.initialize({ callbacks: { onInitialized: () => end(true), onInitializationFailed: () => end(false) } });\n } catch { end(false); }\n });\n adsInit = p;\n void p.then((ok) => { if (!ok && adsInit === p) adsInit = null; });\n return p;\n }\n\n function attachAdSense(el: HTMLElement, a: { client: string; slot: string; height?: number }): () => void {\n const doc = el.ownerDocument;\n if (!doc.querySelector('script[data-ait-adsense]') && !doc.querySelector('script[src*=\"adsbygoogle.js\"]')) {\n const s = doc.createElement('script');\n s.async = true;\n s.crossOrigin = 'anonymous';\n s.dataset.aitAdsense = '';\n s.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(a.client)}`;\n doc.head.append(s);\n }\n const ins = doc.createElement('ins');\n ins.className = 'adsbygoogle';\n ins.style.cssText = `display:block;width:100%;height:${a.height ?? 60}px`;\n ins.dataset.adClient = a.client;\n ins.dataset.adSlot = a.slot;\n el.append(ins);\n safe(() => { ((globalThis as AdsByGoogle).adsbygoogle ??= []).push({}); }, undefined);\n return () => ins.remove();\n }\n\n function attachAdFit(el: HTMLElement, a: { unit: string; width?: number; height?: number }): () => void {\n const doc = el.ownerDocument;\n const ins = doc.createElement('ins');\n ins.className = 'kakao_ad_area';\n ins.style.display = 'none';\n ins.dataset.adUnit = a.unit;\n ins.dataset.adWidth = String(a.width ?? 320);\n ins.dataset.adHeight = String(a.height ?? 50);\n // AdFit's loader scans the page for new ad areas when it runs, so it is loaded again per banner.\n const s = doc.createElement('script');\n s.async = true;\n s.src = 'https://t1.kakaocdn.net/kas/static/ba.min.js';\n el.append(ins, s);\n return () => { ins.remove(); s.remove(); };\n }\n\n /** (Re)fills one banner slot from the current options. */\n function render(slot: BannerSlot): void {\n safe(() => slot.cleanup(), undefined);\n slot.cleanup = () => {};\n slot.generation = generation;\n const ads = opts.ads ?? {};\n if (isWeb()) {\n if (ads.adsense?.client && ads.adsense.slot) slot.cleanup = safe(() => attachAdSense(slot.el, ads.adsense!), () => {});\n else if (ads.adfit?.unit) slot.cleanup = safe(() => attachAdFit(slot.el, ads.adfit!), () => {});\n return;\n }\n const id = ads.toss?.bannerId;\n if (!sdk || !id || !inToss()) return;\n const gen = generation;\n let handle: { destroy: () => void } | null = null;\n let alive = true;\n slot.cleanup = () => { alive = false; safe(() => handle?.destroy(), undefined); handle = null; };\n void initTossAds().then((ok) => {\n if (!ok || !alive || gen !== generation || !banners.has(slot)) return;\n if (!safe(() => sdk.TossAds.attachBanner.isSupported(), false)) return;\n handle = safe(() => sdk.TossAds.attachBanner(id, slot.el, { ...DEFAULT_BANNER, ...opts.ads?.toss?.banner }), null);\n });\n }\n\n /**\n * Shows a banner inside `el` and returns a cleanup function (call it on unmount).\n * Toss: Toss Ads banner. Plain web: AdSense, else AdFit. Native app: nothing (use a native ad plugin there).\n * A banner mounted before `configure()` is filled in when `configure()` runs.\n */\n function attachBanner(el: HTMLElement): () => void {\n if (!el) return () => {};\n const slot: BannerSlot = { el, cleanup: () => {}, generation };\n banners.add(slot);\n render(slot);\n return () => {\n banners.delete(slot);\n safe(() => slot.cleanup(), undefined);\n };\n }\n\n // ---------- full-screen (interstitial) ads ----------\n\n /** Starts loading a full-screen ad in the background. Safe to call often; Toss only. */\n function preloadInterstitial(): void {\n const id = opts.ads?.toss?.interstitialId;\n if (!sdk || !id || interstitial.state !== 'idle' || !inToss()) return;\n if (!safe(() => sdk.loadFullScreenAd.isSupported(), false)) return;\n const mine = { state: 'loading' as 'idle' | 'loading' | 'loaded', id, generation };\n interstitial = mine;\n let off: () => void = () => {};\n let finished = false;\n const timer = setTimeout(() => finish(false), timeout('adLoad', 30_000));\n function finish(loaded: boolean) {\n if (finished) return;\n finished = true;\n clearTimeout(timer);\n safe(() => off(), undefined);\n if (interstitial === mine) mine.state = loaded ? 'loaded' : 'idle';\n }\n try {\n off = sdk.loadFullScreenAd({\n options: { adGroupId: id },\n onEvent: (e) => { if (e.type === 'loaded') finish(true); },\n onError: () => finish(false),\n });\n } catch {\n finish(false);\n return;\n }\n // The SDK may report synchronously, before `off` was assigned.\n if (finished) safe(() => off(), undefined);\n }\n\n /** True when a preloaded full-screen ad can be shown right now. */\n const interstitialReady = (): boolean =>\n interstitial.state === 'loaded' && interstitial.id === opts.ads?.toss?.interstitialId;\n\n /**\n * Shows the preloaded full-screen ad and resolves when it is closed: `true` if an ad was shown.\n * Never rejects and never blocks the user: with no ad ready it resolves `false` at once, and an SDK that\n * goes silent is given up on after `timeouts.adShow`. Preloads the next ad afterwards.\n */\n function showInterstitial(): Promise<boolean> {\n return new Promise((resolve) => {\n const id = interstitial.id;\n if (!sdk || !interstitialReady() || !safe(() => sdk.showFullScreenAd.isSupported(), false)) {\n return resolve(false);\n }\n interstitial = { state: 'idle', id: '', generation }; // a shown ad cannot be shown again\n safe(() => opts.onAdStart?.(), undefined);\n let off: () => void = () => {};\n let settled = false;\n let shownEvent = false;\n let timer = setTimeout(() => done(false), timeout('adShow', 90_000));\n function done(shown: boolean) {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n safe(() => off(), undefined);\n safe(() => opts.onAdEnd?.(), undefined);\n resolve(shown);\n preloadInterstitial();\n }\n try {\n off = sdk.showFullScreenAd({\n options: { adGroupId: id },\n onEvent: (e) => {\n if (e.type === 'dismissed') done(true);\n else if (e.type === 'failedToShow') done(false);\n else if (!shownEvent) {\n // The ad is on screen: the SDK is alive, so wait for the user to close it (restart the clock).\n shownEvent = true;\n clearTimeout(timer);\n timer = setTimeout(() => done(true), timeout('adShow', 90_000) * 2);\n }\n },\n onError: () => done(false),\n });\n } catch {\n done(false);\n return;\n }\n if (settled) safe(() => off(), undefined);\n });\n }\n\n // ---------- device ----------\n\n const VIBRATE_MS: Partial<Record<HapticType, number | number[]>> = {\n tickWeak: 5, tap: 10, tickMedium: 15, softMedium: 20, basicWeak: 10, basicMedium: 20,\n success: [15, 60, 15], error: [40, 40, 40], wiggle: [10, 30, 10, 30, 10], confetti: [10, 20, 10, 20, 10, 20],\n };\n\n /** Haptic feedback. Toss: native haptics. Plain web: `navigator.vibrate` where the browser has it. */\n function haptic(type: HapticType): void {\n if (sdk && inToss()) {\n safe(() => { void sdk.generateHapticFeedback({ type }).catch(() => {}); }, undefined);\n return;\n }\n if (isWeb()) {\n const ms = VIBRATE_MS[type];\n if (ms !== undefined) safe(() => globalThis.navigator?.vibrate?.(ms), undefined);\n }\n }\n\n /** Closes the mini-app inside Toss. Does nothing elsewhere. */\n function closeApp(): void {\n if (!sdk || !inToss()) return;\n safe(() => { void sdk.Screen.close().catch(() => {}); }, undefined);\n }\n\n /**\n * Subscribes to the Android system back button inside Toss. Returns an unsubscribe function.\n * While subscribed the default back action is blocked, so `handler` must always do something\n * (go back a screen, or call closeApp()). Does nothing outside Toss.\n */\n function onBack(handler: () => void): () => void {\n if (!sdk || !inToss()) return () => {};\n return safe(() => sdk.graniteEvent.addEventListener('backEvent', { onEvent: handler, onError: () => {} }), () => {});\n }\n\n /** Safe-area insets in px inside Toss; zeros elsewhere (use CSS `env(safe-area-inset-*)` there). */\n function safeArea(): SafeAreaInsets {\n if (!sdk || !inToss()) return { ...ZERO };\n const v = safe(() => sdk.SafeArea.get(), null);\n if (!v) return { ...ZERO };\n return { top: v.top ?? 0, bottom: v.bottom ?? 0, left: v.left ?? 0, right: v.right ?? 0 };\n }\n\n /** Calls `fn` when the Toss safe area changes. Returns an unsubscribe function. */\n function onSafeAreaChange(fn: (insets: SafeAreaInsets) => void): () => void {\n if (!sdk || !inToss() || !sdk.SafeArea.subscribe) return () => {};\n return safe(() => sdk.SafeArea.subscribe!({ onEvent: (d) => fn({ ...ZERO, ...d }) }), () => {});\n }\n\n /**\n * Replaces the options (ad ids etc.). Banners already on screen are refilled with the new options;\n * a full-screen ad loaded for a different id is dropped.\n */\n function configure(next: AnywhereOptions): void {\n opts = next;\n generation++;\n if (interstitial.id !== next.ads?.toss?.interstitialId) interstitial = { state: 'idle', id: '', generation };\n for (const slot of banners) render(slot);\n }\n\n return {\n configure, platform, inToss, isNative, isWeb, getUid,\n attachBanner, preloadInterstitial, interstitialReady, showInterstitial,\n haptic, closeApp, onBack, safeArea, onSafeAreaChange,\n };\n}\n\nexport type Anywhere = ReturnType<typeof createAnywhere>;\n\nfunction randomId(): string {\n const c = globalThis.crypto;\n if (c?.randomUUID) return c.randomUUID();\n const b = new Uint8Array(16);\n if (c?.getRandomValues) c.getRandomValues(b);\n else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);\n return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createAnywhere } from './core.js';
|
|
2
|
+
export declare const configure: (next: import("./core.ts").AnywhereOptions) => void, platform: () => import("./core.ts").Platform, inToss: () => boolean, isNative: () => boolean, isWeb: () => boolean, getUid: () => Promise<string>, attachBanner: (el: HTMLElement) => () => void, preloadInterstitial: () => void, interstitialReady: () => boolean, showInterstitial: () => Promise<boolean>, haptic: (type: import("./core.ts").HapticType) => void, closeApp: () => void, onBack: (handler: () => void) => () => void, safeArea: () => import("./core.ts").SafeAreaInsets, onSafeAreaChange: (fn: (insets: import("./core.ts").SafeAreaInsets) => void) => () => void;
|
|
3
|
+
export { createAnywhere };
|
|
4
|
+
export type { Anywhere, AnywhereOptions, HapticType, Platform, SafeAreaInsets, TossSdk } from './core.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Entry point for apps: wires the real Apps-in-Toss SDK into the core.
|
|
2
|
+
import * as tossSdk from '@apps-in-toss/web-framework';
|
|
3
|
+
import { createAnywhere } from "./core.js";
|
|
4
|
+
const sdk = tossSdk;
|
|
5
|
+
const anywhere = createAnywhere(sdk);
|
|
6
|
+
export const { configure, platform, inToss, isNative, isWeb, getUid, attachBanner, preloadInterstitial, interstitialReady, showInterstitial, haptic, closeApp, onBack, safeArea, onSafeAreaChange, } = anywhere;
|
|
7
|
+
export { createAnywhere };
|
|
8
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,OAAO,KAAK,OAAO,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,cAAc,EAAgB,MAAM,WAAW,CAAC;AAEzD,MAAM,GAAG,GAAY,OAAO,CAAC;AAC7B,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;AAErC,MAAM,CAAC,MAAM,EACX,SAAS,EACT,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,KAAK,EACL,MAAM,EACN,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,gBAAgB,EAChB,MAAM,EACN,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,gBAAgB,GACjB,GAAG,QAAQ,CAAC;AAEb,OAAO,EAAE,cAAc,EAAE,CAAC","sourcesContent":["// Entry point for apps: wires the real Apps-in-Toss SDK into the core.\nimport * as tossSdk from '@apps-in-toss/web-framework';\nimport { createAnywhere, type TossSdk } from './core.ts';\n\nconst sdk: TossSdk = tossSdk;\nconst anywhere = createAnywhere(sdk);\n\nexport const {\n configure,\n platform,\n inToss,\n isNative,\n isWeb,\n getUid,\n attachBanner,\n preloadInterstitial,\n interstitialReady,\n showInterstitial,\n haptic,\n closeApp,\n onBack,\n safeArea,\n onSafeAreaChange,\n} = anywhere;\n\nexport { createAnywhere };\nexport type { Anywhere, AnywhereOptions, HapticType, Platform, SafeAreaInsets, TossSdk } from './core.ts';\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export type Provider = 'google' | 'apple';
|
|
2
|
+
export interface IdTokenVerifierOptions {
|
|
3
|
+
/** Google OAuth client ids your app signs in with. Leave out to reject Google tokens. */
|
|
4
|
+
google?: string | string[];
|
|
5
|
+
/** Apple audiences: your web Services ID and/or iOS bundle id. Leave out to reject Apple tokens. */
|
|
6
|
+
apple?: string | string[];
|
|
7
|
+
/** Allowed clock difference, ms. Default 60 000. */
|
|
8
|
+
clockSkewMs?: number;
|
|
9
|
+
/** How long fetched signing keys are reused, ms. Default 1 hour (refetched at once for an unknown key id). */
|
|
10
|
+
keyCacheMs?: number;
|
|
11
|
+
/** Timeout for one key download, ms. Default 5 000. */
|
|
12
|
+
fetchTimeoutMs?: number;
|
|
13
|
+
/** Replaces global fetch (tests, proxies). */
|
|
14
|
+
fetch?: (url: string, init?: {
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}) => Promise<{
|
|
17
|
+
ok: boolean;
|
|
18
|
+
status: number;
|
|
19
|
+
json(): Promise<unknown>;
|
|
20
|
+
}>;
|
|
21
|
+
/** Overrides a provider's JWKS URL (tests). */
|
|
22
|
+
jwksUrl?: Partial<Record<Provider, string>>;
|
|
23
|
+
}
|
|
24
|
+
export interface VerifiedIdToken {
|
|
25
|
+
provider: Provider;
|
|
26
|
+
/** The provider's stable user id. */
|
|
27
|
+
sub: string;
|
|
28
|
+
/** `"<provider>:<sub>"`, convenient as a primary key. */
|
|
29
|
+
uid: string;
|
|
30
|
+
/** All token claims (email, email_verified, ... when you asked for them). */
|
|
31
|
+
claims: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Creates a verifier for the given audiences.
|
|
35
|
+
*
|
|
36
|
+
* ```ts
|
|
37
|
+
* const verifyIdToken = createIdTokenVerifier({ google: GOOGLE_CLIENT_ID, apple: ['com.example.web', 'com.example.app'] });
|
|
38
|
+
* const user = await verifyIdToken('google', token, { nonce }); // VerifiedIdToken | null
|
|
39
|
+
* ```
|
|
40
|
+
* Resolves `null` for anything that is not a valid, unexpired token for your app. Rejects only when the
|
|
41
|
+
* provider's signing keys cannot be downloaded (timeout `fetchTimeoutMs`) and none are cached: answer 503.
|
|
42
|
+
* `check.now` overrides the clock, for tests only.
|
|
43
|
+
*/
|
|
44
|
+
export declare function createIdTokenVerifier(options: IdTokenVerifierOptions): (provider: unknown, token: unknown, check?: {
|
|
45
|
+
nonce?: string;
|
|
46
|
+
now?: number;
|
|
47
|
+
}) => Promise<VerifiedIdToken | null>;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Verifies Google / Apple Sign-In ID tokens (RS256 JWTs) against the providers' published keys.
|
|
2
|
+
// No dependencies: Node's crypto and fetch only.
|
|
3
|
+
import { createPublicKey, verify } from 'node:crypto';
|
|
4
|
+
const ISSUERS = {
|
|
5
|
+
google: { jwks: 'https://www.googleapis.com/oauth2/v3/certs', iss: ['https://accounts.google.com', 'accounts.google.com'] },
|
|
6
|
+
apple: { jwks: 'https://appleid.apple.com/auth/keys', iss: ['https://appleid.apple.com'] },
|
|
7
|
+
};
|
|
8
|
+
const MAX_TOKEN = 8192;
|
|
9
|
+
const b64 = (s) => Buffer.from(s, 'base64url');
|
|
10
|
+
const json = (s) => {
|
|
11
|
+
try {
|
|
12
|
+
const v = JSON.parse(b64(s).toString('utf8'));
|
|
13
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const list = (v) => (v === undefined ? [] : Array.isArray(v) ? v : [v]);
|
|
20
|
+
/**
|
|
21
|
+
* Creates a verifier for the given audiences.
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* const verifyIdToken = createIdTokenVerifier({ google: GOOGLE_CLIENT_ID, apple: ['com.example.web', 'com.example.app'] });
|
|
25
|
+
* const user = await verifyIdToken('google', token, { nonce }); // VerifiedIdToken | null
|
|
26
|
+
* ```
|
|
27
|
+
* Resolves `null` for anything that is not a valid, unexpired token for your app. Rejects only when the
|
|
28
|
+
* provider's signing keys cannot be downloaded (timeout `fetchTimeoutMs`) and none are cached: answer 503.
|
|
29
|
+
* `check.now` overrides the clock, for tests only.
|
|
30
|
+
*/
|
|
31
|
+
export function createIdTokenVerifier(options) {
|
|
32
|
+
const audiences = { google: list(options.google), apple: list(options.apple) };
|
|
33
|
+
const skew = options.clockSkewMs ?? 60_000;
|
|
34
|
+
const cacheMs = options.keyCacheMs ?? 3_600_000;
|
|
35
|
+
const fetchTimeout = options.fetchTimeoutMs ?? 5_000;
|
|
36
|
+
const doFetch = options.fetch ?? ((url, init) => fetch(url, init));
|
|
37
|
+
/** Last good key set per URL (kept, possibly stale, when a refresh fails). */
|
|
38
|
+
const cache = new Map();
|
|
39
|
+
/** Last fetch attempt per URL, successful or not: limits fetches to one per 10 s. */
|
|
40
|
+
const tried = new Map();
|
|
41
|
+
const inflight = new Map();
|
|
42
|
+
function load(url) {
|
|
43
|
+
let p = inflight.get(url);
|
|
44
|
+
if (!p) {
|
|
45
|
+
tried.set(url, Date.now());
|
|
46
|
+
p = (async () => {
|
|
47
|
+
const r = await doFetch(url, { signal: AbortSignal.timeout(fetchTimeout) });
|
|
48
|
+
if (!r.ok)
|
|
49
|
+
throw new Error(`JWKS request failed: ${r.status}`);
|
|
50
|
+
const body = (await r.json());
|
|
51
|
+
const keys = (Array.isArray(body?.keys) ? body.keys : [])
|
|
52
|
+
.filter((k) => k && (k.use === undefined || k.use === 'sig') && (k.alg === undefined || k.alg === 'RS256'));
|
|
53
|
+
cache.set(url, { at: Date.now(), keys });
|
|
54
|
+
return keys;
|
|
55
|
+
})().finally(() => inflight.delete(url));
|
|
56
|
+
inflight.set(url, p);
|
|
57
|
+
}
|
|
58
|
+
return p;
|
|
59
|
+
}
|
|
60
|
+
async function key(url, kid) {
|
|
61
|
+
const c = cache.get(url);
|
|
62
|
+
const known = c?.keys.find((k) => k.kid === kid);
|
|
63
|
+
if (known && c && Date.now() - c.at < cacheMs)
|
|
64
|
+
return known;
|
|
65
|
+
// Expired cache or unknown key id (providers rotate keys): refetch, at most once per 10 s per URL.
|
|
66
|
+
if (Date.now() - (tried.get(url) ?? 0) < 10_000 && !inflight.has(url)) {
|
|
67
|
+
if (c || known)
|
|
68
|
+
return known;
|
|
69
|
+
throw new Error('JWKS unavailable (retrying in a few seconds)');
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return (await load(url)).find((k) => k.kid === kid);
|
|
73
|
+
}
|
|
74
|
+
catch (e) {
|
|
75
|
+
if (known)
|
|
76
|
+
return known; // provider down: keep using the key we already trust
|
|
77
|
+
throw e;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return async function verifyIdToken(provider, token, check = {}) {
|
|
81
|
+
const now = check.now ?? Date.now();
|
|
82
|
+
if (provider !== 'google' && provider !== 'apple')
|
|
83
|
+
return null;
|
|
84
|
+
const aud = audiences[provider];
|
|
85
|
+
if (aud.length === 0)
|
|
86
|
+
return null;
|
|
87
|
+
if (typeof token !== 'string' || token.length > MAX_TOKEN)
|
|
88
|
+
return null;
|
|
89
|
+
const parts = token.split('.');
|
|
90
|
+
if (parts.length !== 3)
|
|
91
|
+
return null;
|
|
92
|
+
const [h, b, sig] = parts;
|
|
93
|
+
if (!parts.every((p) => /^[A-Za-z0-9_-]+$/.test(p)))
|
|
94
|
+
return null;
|
|
95
|
+
const header = json(h);
|
|
96
|
+
if (header?.alg !== 'RS256' || typeof header.kid !== 'string')
|
|
97
|
+
return null;
|
|
98
|
+
const jwk = await key(options.jwksUrl?.[provider] ?? ISSUERS[provider].jwks, header.kid);
|
|
99
|
+
if (!jwk || (jwk.kty && jwk.kty !== 'RSA'))
|
|
100
|
+
return null;
|
|
101
|
+
let ok = false;
|
|
102
|
+
try {
|
|
103
|
+
ok = verify('RSA-SHA256', Buffer.from(`${h}.${b}`), createPublicKey({ key: jwk, format: 'jwk' }), b64(sig));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
if (!ok)
|
|
109
|
+
return null;
|
|
110
|
+
const claims = json(b);
|
|
111
|
+
if (!claims)
|
|
112
|
+
return null;
|
|
113
|
+
if (typeof claims.iss !== 'string' || !ISSUERS[provider].iss.includes(claims.iss))
|
|
114
|
+
return null;
|
|
115
|
+
const tokenAud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
116
|
+
if (!tokenAud.some((a) => typeof a === 'string' && aud.includes(a)))
|
|
117
|
+
return null;
|
|
118
|
+
// Several audiences: the authorized party must be one of yours (OpenID Connect Core 3.1.3.7).
|
|
119
|
+
if (tokenAud.length > 1 && claims.azp !== undefined && !(typeof claims.azp === 'string' && aud.includes(claims.azp)))
|
|
120
|
+
return null;
|
|
121
|
+
if (check.nonce !== undefined && claims.nonce !== check.nonce)
|
|
122
|
+
return null;
|
|
123
|
+
if (typeof claims.exp !== 'number' || claims.exp * 1000 < now - skew)
|
|
124
|
+
return null;
|
|
125
|
+
if (typeof claims.nbf === 'number' && claims.nbf * 1000 > now + skew)
|
|
126
|
+
return null;
|
|
127
|
+
if (typeof claims.iat === 'number' && claims.iat * 1000 > now + skew)
|
|
128
|
+
return null;
|
|
129
|
+
if (typeof claims.sub !== 'string' || !claims.sub)
|
|
130
|
+
return null;
|
|
131
|
+
return { provider, sub: claims.sub, uid: `${provider}:${claims.sub}`, claims };
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=idtoken.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idtoken.js","sourceRoot":"","sources":["../../src/server/idtoken.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,iDAAiD;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,EAAmB,MAAM,aAAa,CAAC;AAIvE,MAAM,OAAO,GAAsD;IACjE,MAAM,EAAE,EAAE,IAAI,EAAE,4CAA4C,EAAE,GAAG,EAAE,CAAC,6BAA6B,EAAE,qBAAqB,CAAC,EAAE;IAC3H,KAAK,EAAE,EAAE,IAAI,EAAE,qCAAqC,EAAE,GAAG,EAAE,CAAC,2BAA2B,CAAC,EAAE;CAC3F,CAAC;AA+BF,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC;AACvD,MAAM,IAAI,GAAG,CAAC,CAAS,EAAkC,EAAE;IACzD,IAAI,CAAC;QACH,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;QAC9C,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACpE,CAAC;IAA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,IAAI,CAAC;QAClF,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ,IAAI,MAAM,CAAC,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI;YAAE,OAAO,IAAI,CAAC;QAClF,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QAC/D,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,QAAQ,IAAI,MAAM,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,CAAC;IACjF,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// Verifies Google / Apple Sign-In ID tokens (RS256 JWTs) against the providers' published keys.\n// No dependencies: Node's crypto and fetch only.\nimport { createPublicKey, verify, type JsonWebKey } from 'node:crypto';\n\nexport type Provider = 'google' | 'apple';\n\nconst ISSUERS: Record<Provider, { jwks: string; iss: string[] }> = {\n google: { jwks: 'https://www.googleapis.com/oauth2/v3/certs', iss: ['https://accounts.google.com', 'accounts.google.com'] },\n apple: { jwks: 'https://appleid.apple.com/auth/keys', iss: ['https://appleid.apple.com'] },\n};\n\nexport interface IdTokenVerifierOptions {\n /** Google OAuth client ids your app signs in with. Leave out to reject Google tokens. */\n google?: string | string[];\n /** Apple audiences: your web Services ID and/or iOS bundle id. Leave out to reject Apple tokens. */\n apple?: string | string[];\n /** Allowed clock difference, ms. Default 60 000. */\n clockSkewMs?: number;\n /** How long fetched signing keys are reused, ms. Default 1 hour (refetched at once for an unknown key id). */\n keyCacheMs?: number;\n /** Timeout for one key download, ms. Default 5 000. */\n fetchTimeoutMs?: number;\n /** Replaces global fetch (tests, proxies). */\n fetch?: (url: string, init?: { signal?: AbortSignal }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;\n /** Overrides a provider's JWKS URL (tests). */\n jwksUrl?: Partial<Record<Provider, string>>;\n}\n\nexport interface VerifiedIdToken {\n provider: Provider;\n /** The provider's stable user id. */\n sub: string;\n /** `\"<provider>:<sub>\"`, convenient as a primary key. */\n uid: string;\n /** All token claims (email, email_verified, ... when you asked for them). */\n claims: Record<string, unknown>;\n}\n\ntype Jwk = JsonWebKey & { kid?: string };\n\nconst MAX_TOKEN = 8192;\nconst b64 = (s: string) => Buffer.from(s, 'base64url');\nconst json = (s: string): Record<string, unknown> | null => {\n try {\n const v = JSON.parse(b64(s).toString('utf8'));\n return v && typeof v === 'object' && !Array.isArray(v) ? v : null;\n } catch { return null; }\n};\nconst list = (v: string | string[] | undefined) => (v === undefined ? [] : Array.isArray(v) ? v : [v]);\n\n/**\n * Creates a verifier for the given audiences.\n *\n * ```ts\n * const verifyIdToken = createIdTokenVerifier({ google: GOOGLE_CLIENT_ID, apple: ['com.example.web', 'com.example.app'] });\n * const user = await verifyIdToken('google', token, { nonce }); // VerifiedIdToken | null\n * ```\n * Resolves `null` for anything that is not a valid, unexpired token for your app. Rejects only when the\n * provider's signing keys cannot be downloaded (timeout `fetchTimeoutMs`) and none are cached: answer 503.\n * `check.now` overrides the clock, for tests only.\n */\nexport function createIdTokenVerifier(options: IdTokenVerifierOptions) {\n const audiences: Record<Provider, string[]> = { google: list(options.google), apple: list(options.apple) };\n const skew = options.clockSkewMs ?? 60_000;\n const cacheMs = options.keyCacheMs ?? 3_600_000;\n const fetchTimeout = options.fetchTimeoutMs ?? 5_000;\n const doFetch = options.fetch ?? ((url: string, init?: { signal?: AbortSignal }) => fetch(url, init));\n /** Last good key set per URL (kept, possibly stale, when a refresh fails). */\n const cache = new Map<string, { at: number; keys: Jwk[] }>();\n /** Last fetch attempt per URL, successful or not: limits fetches to one per 10 s. */\n const tried = new Map<string, number>();\n const inflight = new Map<string, Promise<Jwk[]>>();\n\n function load(url: string): Promise<Jwk[]> {\n let p = inflight.get(url);\n if (!p) {\n tried.set(url, Date.now());\n p = (async () => {\n const r = await doFetch(url, { signal: AbortSignal.timeout(fetchTimeout) });\n if (!r.ok) throw new Error(`JWKS request failed: ${r.status}`);\n const body = (await r.json()) as { keys?: unknown };\n const keys = (Array.isArray(body?.keys) ? (body.keys as Jwk[]) : [])\n .filter((k) => k && (k.use === undefined || k.use === 'sig') && (k.alg === undefined || k.alg === 'RS256'));\n cache.set(url, { at: Date.now(), keys });\n return keys;\n })().finally(() => inflight.delete(url));\n inflight.set(url, p);\n }\n return p;\n }\n\n async function key(url: string, kid: string): Promise<Jwk | undefined> {\n const c = cache.get(url);\n const known = c?.keys.find((k) => k.kid === kid);\n if (known && c && Date.now() - c.at < cacheMs) return known;\n // Expired cache or unknown key id (providers rotate keys): refetch, at most once per 10 s per URL.\n if (Date.now() - (tried.get(url) ?? 0) < 10_000 && !inflight.has(url)) {\n if (c || known) return known;\n throw new Error('JWKS unavailable (retrying in a few seconds)');\n }\n try {\n return (await load(url)).find((k) => k.kid === kid);\n } catch (e) {\n if (known) return known; // provider down: keep using the key we already trust\n throw e;\n }\n }\n\n return async function verifyIdToken(\n provider: unknown,\n token: unknown,\n check: { nonce?: string; now?: number } = {},\n ): Promise<VerifiedIdToken | null> {\n const now = check.now ?? Date.now();\n if (provider !== 'google' && provider !== 'apple') return null;\n const aud = audiences[provider];\n if (aud.length === 0) return null;\n if (typeof token !== 'string' || token.length > MAX_TOKEN) return null;\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n const [h, b, sig] = parts as [string, string, string];\n if (!parts.every((p) => /^[A-Za-z0-9_-]+$/.test(p))) return null;\n const header = json(h);\n if (header?.alg !== 'RS256' || typeof header.kid !== 'string') return null;\n\n const jwk = await key(options.jwksUrl?.[provider] ?? ISSUERS[provider].jwks, header.kid);\n if (!jwk || (jwk.kty && jwk.kty !== 'RSA')) return null;\n let ok = false;\n try {\n ok = verify('RSA-SHA256', Buffer.from(`${h}.${b}`), createPublicKey({ key: jwk, format: 'jwk' }), b64(sig));\n } catch { return null; }\n if (!ok) return null;\n\n const claims = json(b);\n if (!claims) return null;\n if (typeof claims.iss !== 'string' || !ISSUERS[provider].iss.includes(claims.iss)) return null;\n const tokenAud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n if (!tokenAud.some((a) => typeof a === 'string' && aud.includes(a))) return null;\n // Several audiences: the authorized party must be one of yours (OpenID Connect Core 3.1.3.7).\n if (tokenAud.length > 1 && claims.azp !== undefined && !(typeof claims.azp === 'string' && aud.includes(claims.azp))) return null;\n if (check.nonce !== undefined && claims.nonce !== check.nonce) return null;\n if (typeof claims.exp !== 'number' || claims.exp * 1000 < now - skew) return null;\n if (typeof claims.nbf === 'number' && claims.nbf * 1000 > now + skew) return null;\n if (typeof claims.iat === 'number' && claims.iat * 1000 > now + skew) return null;\n if (typeof claims.sub !== 'string' || !claims.sub) return null;\n return { provider, sub: claims.sub, uid: `${provider}:${claims.sub}`, claims };\n };\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export { createIdTokenVerifier } from './idtoken.ts';\nexport type { IdTokenVerifierOptions, Provider, VerifiedIdToken } from './idtoken.ts';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ait-anywhere",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "One web app for Apps-in-Toss, a Capacitor native app and the plain web: Toss SDK calls that fall back safely everywhere else (user id, ads, haptics, back button, safe area), plus Google/Apple ID token verification for your server.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"apps-in-toss",
|
|
7
|
+
"toss",
|
|
8
|
+
"miniapp",
|
|
9
|
+
"capacitor",
|
|
10
|
+
"webview",
|
|
11
|
+
"ads",
|
|
12
|
+
"adsense",
|
|
13
|
+
"adfit",
|
|
14
|
+
"id-token",
|
|
15
|
+
"sign-in-with-apple"
|
|
16
|
+
],
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"author": "Gudongyeop (https://github.com/Gudongyeop)",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/Gudongyeop/ait-anywhere.git"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/Gudongyeop/ait-anywhere#readme",
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://github.com/Gudongyeop/ait-anywhere/issues"
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"main": "./dist/index.js",
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"import": "./dist/index.js",
|
|
35
|
+
"default": "./dist/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./core": {
|
|
38
|
+
"types": "./dist/core.d.ts",
|
|
39
|
+
"import": "./dist/core.js",
|
|
40
|
+
"default": "./dist/core.js"
|
|
41
|
+
},
|
|
42
|
+
"./server": {
|
|
43
|
+
"types": "./dist/server/index.d.ts",
|
|
44
|
+
"import": "./dist/server/index.js",
|
|
45
|
+
"default": "./dist/server/index.js"
|
|
46
|
+
},
|
|
47
|
+
"./package.json": "./package.json"
|
|
48
|
+
},
|
|
49
|
+
"files": [
|
|
50
|
+
"dist",
|
|
51
|
+
"README.md",
|
|
52
|
+
"README.en.md",
|
|
53
|
+
"LICENSE"
|
|
54
|
+
],
|
|
55
|
+
"engines": {
|
|
56
|
+
"node": ">=20"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "tsc -p tsconfig.build.json && node scripts/fix-dts.mjs",
|
|
60
|
+
"typecheck": "tsc --noEmit",
|
|
61
|
+
"test": "node --experimental-strip-types --no-warnings --test \"test/*.test.ts\"",
|
|
62
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"@apps-in-toss/web-framework": "^3.10.0"
|
|
66
|
+
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"@apps-in-toss/web-framework": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"devDependencies": {
|
|
73
|
+
"@apps-in-toss/web-framework": "^3.12.1",
|
|
74
|
+
"@types/node": "^22.15.0",
|
|
75
|
+
"typescript": "^5.9.0"
|
|
76
|
+
}
|
|
77
|
+
}
|