@the-seeker/feedback-react-native 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +67 -16
  2. package/dist/core/author-token.d.ts +16 -0
  3. package/dist/core/author-token.js +96 -0
  4. package/dist/core/client.d.ts +3 -5
  5. package/dist/core/client.js +7 -22
  6. package/dist/core/posts-schema.d.ts +306 -0
  7. package/dist/core/posts-schema.js +131 -0
  8. package/dist/core/posts.d.ts +67 -0
  9. package/dist/core/posts.js +113 -0
  10. package/dist/core/request.d.ts +1 -1
  11. package/dist/core/request.js +2 -0
  12. package/dist/core/texts.d.ts +92 -0
  13. package/dist/core/texts.js +92 -0
  14. package/dist/core/transport.d.ts +9 -0
  15. package/dist/core/transport.js +37 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +2 -0
  18. package/dist/ui/FeedbackForm.js +3 -1
  19. package/dist/ui/FeedbackPostScreen.d.ts +8 -0
  20. package/dist/ui/FeedbackPostScreen.js +74 -0
  21. package/dist/ui/FeedbackSheet.js +4 -22
  22. package/dist/ui/FollowUpSheet.d.ts +17 -0
  23. package/dist/ui/FollowUpSheet.js +50 -0
  24. package/dist/ui/Launcher.js +5 -3
  25. package/dist/ui/MyFeedbackModal.d.ts +10 -0
  26. package/dist/ui/MyFeedbackModal.js +45 -0
  27. package/dist/ui/MyFeedbackScreen.d.ts +9 -0
  28. package/dist/ui/MyFeedbackScreen.js +88 -0
  29. package/dist/ui/PostThread.d.ts +17 -0
  30. package/dist/ui/PostThread.js +57 -0
  31. package/dist/ui/Provider.d.ts +3 -0
  32. package/dist/ui/Provider.js +65 -10
  33. package/dist/ui/context.d.ts +44 -1
  34. package/dist/ui/motion.d.ts +1 -0
  35. package/dist/ui/motion.js +23 -0
  36. package/dist/ui/post-format.d.ts +19 -0
  37. package/dist/ui/post-format.js +79 -0
  38. package/dist/ui/post-pieces.d.ts +24 -0
  39. package/dist/ui/post-pieces.js +60 -0
  40. package/dist/ui/post-styles.d.ts +317 -0
  41. package/dist/ui/post-styles.js +103 -0
  42. package/dist/ui/post-view-model.d.ts +52 -0
  43. package/dist/ui/post-view-model.js +181 -0
  44. package/dist/ui/styles.d.ts +77 -0
  45. package/dist/ui/styles.js +51 -43
  46. package/dist/ui/surfaces.d.ts +13 -0
  47. package/dist/ui/surfaces.js +41 -0
  48. package/dist/ui/useMyPosts.d.ts +35 -0
  49. package/dist/ui/useMyPosts.js +124 -0
  50. package/package.json +8 -9
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @the-seeker/feedback-react-native
2
2
 
3
- TheSeeker CRM 피드백 위젯을 React Native·Expo 앱에 붙이는 SDK입니다. 순수 JS라 네이티브 모듈·prebuild 없이 Expo Go에서도 동작합니다. 웹 위젯과 같은 설정(문구·테마·표시 방식·설문)을 CRM에서 그대로 가져옵니다.
3
+ devstage 피드백을 React Native·Expo 앱에 붙이는 SDK입니다. 순수 JS라 네이티브 모듈·prebuild 없이 Expo Go에서도 동작합니다. 웹 위젯과 같은 설정(문구·테마·표시 방식·설문)을 devstage에서 그대로 가져오고, 앱 사용자가 앱 안에서 보낸 피드백과 운영팀 답변을 확인하고 추가 의견을 남기는 **내 피드백** 화면을 제공합니다(0.2.0).
4
4
 
5
5
  자세한 설치 가이드: https://docs.theseeker.io/feedback/app-install
6
6
 
@@ -12,9 +12,9 @@ npx expo install @the-seeker/feedback-react-native
12
12
 
13
13
  Expo가 아닌 React Native 앱은 `npm i @the-seeker/feedback-react-native`. 요구 버전: `react >= 18`, `react-native >= 0.74`.
14
14
 
15
- ## 1. CRM에 앱 등록 (필수)
15
+ ## 1. devstage에 앱 등록 (필수)
16
16
 
17
- CRM → 피드백 → **위젯 설정 → 허용 앱**에 앱 ID를 추가하세요. 앱 ID는 iOS bundle identifier 또는 Android applicationId입니다(예: `com.example.app`). 두 플랫폼의 ID가 다르면 둘 다 등록하고 `appId={Platform.select({ ios: "com.example.app", default: "com.example.android" })}`처럼 플랫폼별 값을 넘기세요.
17
+ devstage 대시보드 → 피드백 → **위젯 설정 → 허용 앱**에 앱 ID를 추가하세요. 앱 ID는 iOS bundle identifier 또는 Android applicationId입니다(예: `com.example.app`). 두 플랫폼의 ID가 다르면 둘 다 등록하고 `appId={Platform.select({ ios: "com.example.app", default: "com.example.android" })}`처럼 플랫폼별 값을 넘기세요.
18
18
 
19
19
  - 등록하지 않은 앱 ID로 요청하면 서버가 `403 APP_NOT_ALLOWED`를 돌려주고, 피드백 UI는 나타나지 않습니다(`onError("APP_NOT_ALLOWED")`).
20
20
  - 위젯 키(`fbw_…`)는 같은 화면의 **설치** 탭에서 복사합니다.
@@ -43,13 +43,14 @@ export default function App() {
43
43
  | --- | --- | --- | --- |
44
44
  | `widgetKey` | `string` | 필수 | 위젯 공개 키 |
45
45
  | `appId` | `string` | 필수 | 허용 앱에 등록한 앱 ID. `X-TheSeeker-App` 헤더와 `pageUrl`(`app://<appId>/<screen>`)에 쓰입니다 |
46
- | `baseUrl` | `string` | `"https://crm.theseeker.io"` | CRM 주소 |
46
+ | `baseUrl` | `string` | `"https://devstage.app"` | 서버 주소. 이전 주소를 계속 쓰려면 `"https://crm.theseeker.io"`를 넘기세요 |
47
47
  | `userId` | `string \| number \| null` | `null` | 제출에 붙는 사용자 ID(`uid`, 최대 128자) |
48
48
  | `locale` | `"ko" \| "en" \| "auto"` | `"ko"` | `auto`는 기기 언어가 `en*`이면 영어, 아니면 한국어 |
49
49
  | `screen` | `string` | `"/"` | 현재 화면 경로. 설문 경로 패턴과 `pageUrl`에 쓰입니다 |
50
50
  | `launcher` | `boolean` | `true` | `false`면 표시 방식이 launcher여도 플로팅 버튼을 숨깁니다 |
51
51
  | `pickImages` | `() => Promise<ImageAsset[]>` | 없음 | 있으면(그리고 위젯의 이미지 첨부가 켜져 있으면) 폼에 첨부 버튼이 생깁니다 |
52
- | `storage` | `{ getItem, setItem }` | 메모리 | 설문 재노출 쿨다운 저장소(동기·비동기 모두 가능) |
52
+ | `storage` | `{ getItem, setItem }` | 메모리 | 설문 재노출 쿨다운과 작성자 토큰 저장소(동기·비동기 모두 가능). 내 피드백은 이 값을 넘겨야 켜집니다 |
53
+ | `randomBytes` | `(size) => Uint8Array \| Promise<Uint8Array>` | 없음 | `globalThis.crypto.getRandomValues`가 없을 때 작성자 토큰에 쓰는 보안 난수(예: `expo-crypto`의 `getRandomBytes`) |
53
54
  | `client` | `ClientMetadata` | `Platform`에서 생성 | `{ platform, osVersion?, appVersion?, deviceModel?, deviceType? }` |
54
55
  | `onSubmitted` | `(id, kind) => void` | 없음 | 제출 성공. `kind`는 `"feedback" \| "nps" \| "csat"` |
55
56
  | `onError` | `(code) => void` | 없음 | 설정 로드 실패 또는 제출 실패 코드 |
@@ -84,7 +85,12 @@ function HelpButton() {
84
85
  | --- | --- |
85
86
  | `ready` | 위젯 설정을 불러왔으면 `true` |
86
87
  | `config` | 파싱된 위젯 설정(`WidgetConfig \| null`) |
87
- | `open()` / `close()` | 피드백 바텀 시트 열기·닫기(설정 로드 전에는 열리지 않음) |
88
+ | `open()` / `close()` | 피드백 바텀 시트 열기·닫기(설정 로드 전에는 열리지 않음). `close()`는 열려 있는 내 피드백 화면도 닫습니다 |
89
+ | `presentFeedback()` | `open()`과 같습니다 |
90
+ | `myFeedbackReady` | 이 설치에서 내 피드백 화면을 쓸 수 있으면 `true`(아래 8절 조건) |
91
+ | `openMyFeedback()` / `presentMyFeedback()` | 내 피드백 화면 열기(`myFeedbackReady`가 아니면 아무 일도 하지 않음) |
92
+ | `unreadCount` | 아직 읽지 않은 답변이 달린 글 수(내 피드백을 쓸 수 없으면 `0`) |
93
+ | `refreshUnread()` | 읽지 않은 답변 수를 다시 가져옵니다. 앱이 다시 화면에 올 때마다 자동으로도 갱신됩니다 |
88
94
  | `setScreen(path)` | 현재 화면 경로 변경. 설문 조건을 다시 평가합니다 |
89
95
  | `setUser(id)` | 사용자 ID 변경(`null`로 해제) |
90
96
  | `setContact(value)` | 연락처 미리 채우기. 폼과 `submit`의 기본값이 됩니다 |
@@ -93,11 +99,13 @@ function HelpButton() {
93
99
 
94
100
  `setScreen`·`setUser`·`setLocale`로 바꾼 값은 같은 이름의 prop이 바뀌면 prop 값으로 돌아갑니다. Provider 밖에서 훅을 부르면 `TheSeekerFeedbackContextError`를 던집니다.
95
101
 
96
- `submit` 실패 코드: `WIDGET_NOT_FOUND`(설정 로드 전·실패), `VALIDATION_ERROR`(빈 메시지 등), `IMAGES_DISABLED`, `TOO_MANY_IMAGES`, `IMAGE_TOO_LARGE`, `INVALID_IMAGE`, `RATE_LIMITED`, `APP_NOT_ALLOWED`, `NETWORK_ERROR`.
102
+ `submit` 실패 코드: `WIDGET_NOT_FOUND`(설정 로드 전·실패), `VALIDATION_ERROR`(빈 내용 등), `IMAGES_DISABLED`, `TOO_MANY_IMAGES`, `IMAGE_TOO_LARGE`, `INVALID_IMAGE`, `RATE_LIMITED`, `APP_NOT_ALLOWED`, `NETWORK_ERROR`, `ELIGIBILITY`(내 피드백이 켜진 사이트의 작성 조건 미충족).
103
+
104
+ 내 피드백을 쓸 수 있으면 폼과 `submit`은 새 글 API(`POST /api/feedback/app/posts`, 작성자 토큰 포함)로 보내 내 피드백 목록에 남깁니다. 그렇지 않으면 0.1.x와 같은 기존 위젯 API로 보냅니다. 설문 응답은 항상 기존 API를 씁니다.
97
105
 
98
106
  ## 4. 표시 방식
99
107
 
100
- CRM 위젯 설정의 **표시 방식**을 따릅니다.
108
+ devstage 위젯 설정의 **표시 방식**을 따릅니다.
101
109
 
102
110
  | 표시 방식 | 앱에서의 동작 |
103
111
  | --- | --- |
@@ -105,11 +113,11 @@ CRM 위젯 설정의 **표시 방식**을 따릅니다.
105
113
  | inline | 자동 UI 없음. `<TheSeekerFeedbackInline />`을 원하는 화면에 배치 |
106
114
  | manual | 버튼 없음. `open()`으로 바텀 시트를 엽니다 |
107
115
 
108
- `open()`과 `<TheSeekerFeedbackInline style={...} />`은 어느 방식에서든 쓸 수 있습니다. 테마(라이트·다크·자동), 강조색, 외형 색상·모서리 반경도 CRM 설정을 따르며, 자동은 기기 다크 모드를 따릅니다.
116
+ `open()`과 `<TheSeekerFeedbackInline style={...} />`은 어느 방식에서든 쓸 수 있습니다. 테마(라이트·다크·자동), 강조색, 외형 색상·모서리 반경도 devstage 설정을 따르며, 자동은 기기 다크 모드를 따릅니다.
109
117
 
110
118
  ## 5. 화면 경로와 설문
111
119
 
112
- CRM에서 만든 NPS·CSAT 설문은 웹 위젯과 같은 규칙으로 뜹니다: 경로 패턴(`/home*`)이 `screen`과 맞고, 쿨다운이 지났고, 표본 비율에 들면 `delaySeconds` 뒤 하단 카드로 표시됩니다. 화면이 바뀔 때마다 다시 평가하며, 한 Provider 수명 동안 설문당 한 번만 뜹니다.
120
+ devstage에서 만든 NPS·CSAT 설문은 웹 위젯과 같은 규칙으로 뜹니다: 경로 패턴(`/home*`)이 `screen`과 맞고, 쿨다운이 지났고, 표본 비율에 들면 `delaySeconds` 뒤 하단 카드로 표시됩니다. 화면이 바뀔 때마다 다시 평가하며, 한 Provider 수명 동안 설문당 한 번만 뜹니다.
113
121
 
114
122
  expo-router:
115
123
 
@@ -188,18 +196,60 @@ const storage = {
188
196
  };
189
197
  ```
190
198
 
199
+ ## 8. 내 피드백 (답변 확인·추가 의견)
200
+
201
+ 앱 사용자는 브라우저로 나가지 않고 앱 안에서 자기가 보낸 피드백을 다시 봅니다.
202
+
203
+ - **내 피드백**: 내가 쓴 글 목록(제목·한 줄·상태·`답변 완료`/`답변 대기`·날짜·새 답변 점).
204
+ - **피드백 글 상세**: 맨 위에 내 글, 그 아래 날짜가 붙은 **운영팀 답변** 블록, 상태 변경 줄(예: `예정으로 변경 · 11월 20일`), 내가 덧붙인 **추가 의견** 블록이 시간순으로 쌓입니다. 맨 아래 **추가 의견 남기기** 버튼이 작성 시트를 엽니다. 닫힌 글이거나 서버가 막은 글에는 버튼이 없습니다.
205
+ - **단방향 사이트**: 답변·추가 의견 없이 **접수됨 · 현재 상태** 단계만 보입니다.
206
+ - 보내기 시트 머리에 **내 피드백** 버튼(읽지 않은 답변 수 포함)이 생기고, 런처 버튼에는 읽지 않은 답변이 있을 때 점이 붙습니다.
207
+
208
+ ```tsx
209
+ import AsyncStorage from "@react-native-async-storage/async-storage";
210
+ import "react-native-get-random-values"; // 앱 진입 파일 맨 위에서 한 번
211
+
212
+ <TheSeekerFeedbackProvider widgetKey="fbw_..." appId="com.example.app" storage={AsyncStorage}>
213
+ <App />
214
+ </TheSeekerFeedbackProvider>;
215
+
216
+ function SettingsRows() {
217
+ const { presentFeedback, presentMyFeedback, myFeedbackReady, unreadCount } = useTheSeekerFeedback();
218
+ return (
219
+ <>
220
+ <Row title="피드백 보내기" onPress={presentFeedback} />
221
+ {myFeedbackReady ? <Row title="내 피드백" badge={unreadCount} onPress={presentMyFeedback} /> : null}
222
+ </>
223
+ );
224
+ }
225
+ ```
226
+
227
+ 켜지는 조건(하나라도 빠지면 내 피드백 버튼·배지가 숨고, 피드백 보내기는 0.1.x처럼 그대로 동작합니다):
228
+
229
+ 1. 서버가 새 API를 제공하고 사이트가 있음(`GET /api/feedback/app/site`가 `SITE_NOT_FOUND`가 아님) 그리고 사이트 설정의 `myPostsEnabled`가 켜져 있음.
230
+ 2. `storage`를 넘김. 작성자 토큰이 메모리에만 있으면 앱을 다시 켰을 때 내 글을 잃으므로 기본 메모리 저장소로는 켜지지 않습니다.
231
+ 3. 보안 난수가 있음. Hermes에는 `crypto.getRandomValues`가 없으니 `react-native-get-random-values`를 설치해 진입 파일 맨 위에서 import하거나, `randomBytes` prop으로 `expo-crypto`의 `getRandomBytes`를 넘기세요. 둘 다 없으면 `AuthorTokenUnavailable`로 기능을 숨기며, `Math.random`으로 대신하지 않습니다.
232
+
233
+ 작성자 토큰은 설치마다 만드는 32바이트 난수(base64url 43자)로 `tsfb:author:<widgetKey>` 키에 저장되고 `X-Devstage-Author` 헤더로만 전송됩니다. 앱을 지웠다가 다시 설치하면 이전 글은 목록에서 보이지 않습니다(이메일을 남긴 경우 답변 알림 메일은 계속 갑니다).
234
+
235
+ UI 없이 쓰려면 `createPostsClient({ publicKey, appId, authorToken })`와 `getOrCreateAuthorToken(storage, widgetKey)`를 직접 쓰세요. 메서드: `getSite()`, `createPost(input, images?)`, `listMyPosts(cursor?)`, `getPost(number)`, `addFollowUp(number, body)`, `getUnread()`. 각 메서드는 `{ ok: true, value } | { ok: false, code }`를 돌려줍니다.
236
+
237
+ ### 이미 출시한 앱
238
+
239
+ 0.1.x 앱은 `https://crm.theseeker.io`로 계속 동작합니다. 0.2.1의 기본 주소는 `https://devstage.app`이며, 새 빌드에서도 이전 주소를 쓰려면 `baseUrl="https://crm.theseeker.io"`를 넘기세요.
240
+
191
241
  ## 테스트 ID (Detox·Maestro)
192
242
 
193
- `theseeker-feedback-launcher`, `theseeker-feedback-message`, `theseeker-feedback-contact`, `theseeker-feedback-attach`, `theseeker-feedback-remove-<n>`, `theseeker-feedback-submit`, `theseeker-feedback-thanks`, `theseeker-feedback-scrim`, `theseeker-feedback-inline`, `theseeker-survey`, `theseeker-survey-score-<n>`, `theseeker-survey-follow-up`, `theseeker-survey-send`, `theseeker-survey-close`.
243
+ `theseeker-feedback-launcher`, `theseeker-feedback-message`, `theseeker-feedback-contact`, `theseeker-feedback-attach`, `theseeker-feedback-remove-<n>`, `theseeker-feedback-submit`, `theseeker-feedback-thanks`, `theseeker-feedback-scrim`, `theseeker-feedback-inline`, `theseeker-feedback-mine`, `theseeker-my-feedback-close`, `theseeker-my-feedback-write`, `theseeker-my-feedback-empty-write`, `theseeker-my-feedback-post-<number>`, `theseeker-post-back`, `theseeker-post-follow-up`, `theseeker-follow-up-body`, `theseeker-follow-up-cancel`, `theseeker-follow-up-submit`, `theseeker-survey`, `theseeker-survey-score-<n>`, `theseeker-survey-follow-up`, `theseeker-survey-send`, `theseeker-survey-close`.
194
244
 
195
245
  ---
196
246
 
197
247
  ## English
198
248
 
199
- Pure-JS React Native / Expo SDK for the TheSeeker CRM feedback widget. No native modules; works in Expo Go. Full guide: https://docs.theseeker.io/feedback/app-install
249
+ Pure-JS React Native / Expo SDK for devstage feedback. No native modules; works in Expo Go. Full guide: https://docs.theseeker.io/feedback/app-install
200
250
 
201
251
  1. **Install**: `npx expo install @the-seeker/feedback-react-native` (peer deps: `react >= 18`, `react-native >= 0.74`).
202
- 2. **Register your app ID** (iOS bundle identifier / Android applicationId) in CRM → Feedback → Widget settings → **Allowed apps**. Unregistered IDs get `403 APP_NOT_ALLOWED` and no UI renders.
252
+ 2. **Register your app ID** (iOS bundle identifier / Android applicationId) in the devstage dashboard → Feedback → Widget settings → **Allowed apps**. Unregistered IDs get `403 APP_NOT_ALLOWED` and no UI renders.
203
253
  3. **Wrap your app** near the root:
204
254
 
205
255
  ```tsx
@@ -208,9 +258,10 @@ Pure-JS React Native / Expo SDK for the TheSeeker CRM feedback widget. No native
208
258
  </TheSeekerFeedbackProvider>
209
259
  ```
210
260
 
211
- - Props: `widgetKey`, `appId` (required); `baseUrl`, `userId`, `locale` (`"ko" | "en" | "auto"`, default `"ko"`), `screen` (default `"/"`), `launcher` (default `true`), `pickImages`, `storage` (default in-memory), `client`, `onSubmitted(id, kind)`, `onError(code)`.
212
- - Hook: `useTheSeekerFeedback()` returns `{ ready, config, open, close, setScreen, setUser, setContact, setLocale, submit }`; `submit({ message, contact?, images? })` resolves to `{ ok: true, id } | { ok: false, code }`. It throws `TheSeekerFeedbackContextError` outside the provider.
213
- - Display modes follow the CRM setting: `launcher` (floating button → bottom sheet), `inline` (place `<TheSeekerFeedbackInline />` yourself), `manual` (call `open()`).
261
+ - Props: `widgetKey`, `appId` (required); `baseUrl` (default `"https://devstage.app"`; pass `"https://crm.theseeker.io"` to keep the legacy host), `userId`, `locale` (`"ko" | "en" | "auto"`, default `"ko"`), `screen` (default `"/"`), `launcher` (default `true`), `pickImages`, `storage` (default in-memory), `randomBytes`, `client`, `onSubmitted(id, kind)`, `onError(code)`.
262
+ - Hook: `useTheSeekerFeedback()` returns `{ ready, config, open, close, presentFeedback, myFeedbackReady, openMyFeedback, presentMyFeedback, unreadCount, refreshUnread, setScreen, setUser, setContact, setLocale, submit }`; `submit({ message, contact?, images? })` resolves to `{ ok: true, id } | { ok: false, code }`. It throws `TheSeekerFeedbackContextError` outside the provider.
263
+ - My feedback (0.2.1): in-app list of the user's posts, the post with dated team answers, status lines and follow-ups, and an "Add a follow-up" sheet; one-way sites show "Received · Current status" only. It turns on when the site enables it (`myPostsEnabled`), a persistent `storage` is passed and a secure RNG exists (`react-native-get-random-values` or the `randomBytes` prop). Otherwise it stays hidden and sending works exactly as in 0.1.x. The per-install author token (32 random bytes, base64url) is stored under `tsfb:author:<widgetKey>` and sent as `X-Devstage-Author`.
264
+ - Display modes follow the devstage setting: `launcher` (floating button → bottom sheet), `inline` (place `<TheSeekerFeedbackInline />` yourself), `manual` (call `open()`).
214
265
  - Surveys (NPS/CSAT) use the web widget rules: path pattern vs `screen`, cooldown read from `storage` (`tsfb:survey:<id>`), sample rate, then `delaySeconds`; at most once per provider lifetime.
215
266
  - Images: pass a `pickImages` adapter (see the expo-image-picker example above). PNG, JPEG, WebP or GIF, up to 4 images, 2 MB each.
216
267
  - Submissions are sent with `X-TheSeeker-App: <appId>` and `pageUrl = app://<appId>/<screen>`.
@@ -0,0 +1,16 @@
1
+ import type { FeedbackStorage } from "../ui/storage";
2
+ /** App-provided secure RNG (e.g. `expo-crypto`'s `getRandomBytes`), used when `globalThis.crypto` is missing. */
3
+ export type RandomBytes = (size: number) => Uint8Array | Promise<Uint8Array>;
4
+ export type AuthorTokenProblem = "no_secure_random" | "invalid_random_bytes" | "storage_failed";
5
+ /** No token can be issued: my-feedback screens stay hidden; plain feedback sending keeps working. */
6
+ export declare class AuthorTokenUnavailable extends Error {
7
+ readonly reason: AuthorTokenProblem;
8
+ constructor(reason: AuthorTokenProblem, detail?: string);
9
+ }
10
+ export declare function authorTokenStorageKey(publicKey: string): string;
11
+ /**
12
+ * The install's author token for `publicKey`: 32 secure random bytes as 43 base64url characters,
13
+ * stored under `tsfb:author:<publicKey>`. Concurrent callers share one creation, so a double-mounted
14
+ * provider never ends up holding a token that another call overwrote. Never falls back to `Math.random`.
15
+ */
16
+ export declare function getOrCreateAuthorToken(storage: FeedbackStorage, publicKey: string, randomBytes?: RandomBytes): Promise<string>;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthorTokenUnavailable = void 0;
4
+ exports.authorTokenStorageKey = authorTokenStorageKey;
5
+ exports.getOrCreateAuthorToken = getOrCreateAuthorToken;
6
+ const storage_1 = require("../ui/storage");
7
+ /** No token can be issued: my-feedback screens stay hidden; plain feedback sending keeps working. */
8
+ class AuthorTokenUnavailable extends Error {
9
+ constructor(reason, detail) {
10
+ super(`Author token unavailable: ${reason}${detail === undefined ? "" : ` (${detail})`}`);
11
+ this.reason = reason;
12
+ this.name = "AuthorTokenUnavailable";
13
+ }
14
+ }
15
+ exports.AuthorTokenUnavailable = AuthorTokenUnavailable;
16
+ const TOKEN_BYTES = 32;
17
+ const TOKEN_SHAPE = /^[A-Za-z0-9_-]{43}$/;
18
+ const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
19
+ const pending = new WeakMap();
20
+ function authorTokenStorageKey(publicKey) {
21
+ return `tsfb:author:${publicKey}`;
22
+ }
23
+ function encodeBase64Url(bytes) {
24
+ let out = "";
25
+ for (let index = 0; index < bytes.length; index += 3) {
26
+ const second = bytes[index + 1];
27
+ const third = bytes[index + 2];
28
+ const triple = ((bytes[index] ?? 0) << 16) | ((second ?? 0) << 8) | (third ?? 0);
29
+ out += BASE64URL.charAt((triple >> 18) & 63) + BASE64URL.charAt((triple >> 12) & 63);
30
+ if (second !== undefined)
31
+ out += BASE64URL.charAt((triple >> 6) & 63);
32
+ if (third !== undefined)
33
+ out += BASE64URL.charAt(triple & 63);
34
+ }
35
+ return out;
36
+ }
37
+ /** `globalThis.crypto.getRandomValues` (Hermes polyfill, Node, web) read without assuming DOM typings. */
38
+ function platformRandom() {
39
+ const crypto = Reflect.get(globalThis, "crypto");
40
+ if (typeof crypto !== "object" || crypto === null)
41
+ return null;
42
+ const fill = Reflect.get(crypto, "getRandomValues");
43
+ if (typeof fill !== "function")
44
+ return null;
45
+ return (bytes) => {
46
+ Reflect.apply(fill, crypto, [bytes]);
47
+ return bytes;
48
+ };
49
+ }
50
+ async function secureBytes(randomBytes) {
51
+ const platform = platformRandom();
52
+ if (platform !== null)
53
+ return platform(new Uint8Array(TOKEN_BYTES));
54
+ if (randomBytes === undefined)
55
+ throw new AuthorTokenUnavailable("no_secure_random");
56
+ let bytes;
57
+ try {
58
+ bytes = await randomBytes(TOKEN_BYTES);
59
+ }
60
+ catch (error) {
61
+ if (error instanceof Error)
62
+ throw new AuthorTokenUnavailable("invalid_random_bytes", error.message);
63
+ throw error;
64
+ }
65
+ if (!(bytes instanceof Uint8Array) || bytes.length !== TOKEN_BYTES)
66
+ throw new AuthorTokenUnavailable("invalid_random_bytes");
67
+ return bytes;
68
+ }
69
+ async function loadOrCreate(storage, key, randomBytes) {
70
+ const stored = await (0, storage_1.readStorage)(storage, key);
71
+ if (!stored.ok)
72
+ throw new AuthorTokenUnavailable("storage_failed", stored.error.message);
73
+ if (stored.value !== null && TOKEN_SHAPE.test(stored.value))
74
+ return stored.value;
75
+ const token = encodeBase64Url(await secureBytes(randomBytes));
76
+ const failure = await (0, storage_1.writeStorage)(storage, key, token);
77
+ if (failure !== null)
78
+ throw new AuthorTokenUnavailable("storage_failed", failure.message);
79
+ return token;
80
+ }
81
+ /**
82
+ * The install's author token for `publicKey`: 32 secure random bytes as 43 base64url characters,
83
+ * stored under `tsfb:author:<publicKey>`. Concurrent callers share one creation, so a double-mounted
84
+ * provider never ends up holding a token that another call overwrote. Never falls back to `Math.random`.
85
+ */
86
+ function getOrCreateAuthorToken(storage, publicKey, randomBytes) {
87
+ const key = authorTokenStorageKey(publicKey);
88
+ const inFlight = pending.get(storage) ?? new Map();
89
+ pending.set(storage, inFlight);
90
+ const existing = inFlight.get(key);
91
+ if (existing !== undefined)
92
+ return existing;
93
+ const created = loadOrCreate(storage, key, randomBytes).finally(() => inFlight.delete(key));
94
+ inFlight.set(key, created);
95
+ return created;
96
+ }
@@ -1,5 +1,8 @@
1
1
  import type { WidgetConfig } from "./config";
2
2
  import type { FeedbackErrorCode, FeedbackPayload, ImageAsset } from "./request";
3
+ import type { ClientResponse } from "./transport";
4
+ /** Origin used when no `baseUrl` is given. */
5
+ export declare const DEFAULT_BASE_URL = "https://devstage.app";
3
6
  export type NativeFilePart = Readonly<{
4
7
  uri: string;
5
8
  type: string;
@@ -19,10 +22,6 @@ export interface XhrLike {
19
22
  readonly responseText: string;
20
23
  timeout: number;
21
24
  }
22
- type ClientResponse = {
23
- readonly status: number;
24
- json(): Promise<unknown>;
25
- };
26
25
  export type FetchInit = Readonly<{
27
26
  method: "GET" | "POST";
28
27
  headers: Readonly<Record<string, string>>;
@@ -54,4 +53,3 @@ export interface FeedbackClient {
54
53
  submit(payload: FeedbackPayload, images?: readonly ImageAsset[]): Promise<SubmitResult>;
55
54
  }
56
55
  export declare function createFeedbackClient(options: FeedbackClientOptions): FeedbackClient;
57
- export {};
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_BASE_URL = void 0;
3
4
  exports.createFeedbackClient = createFeedbackClient;
4
5
  const zod_1 = require("zod");
5
6
  const config_1 = require("./config");
6
7
  const request_1 = require("./request");
8
+ const transport_1 = require("./transport");
9
+ /** Origin used when no `baseUrl` is given. */
10
+ exports.DEFAULT_BASE_URL = "https://devstage.app";
7
11
  const errorSchema = zod_1.z.object({
8
12
  error: zod_1.z.enum([
9
13
  "APP_NOT_ALLOWED",
@@ -42,7 +46,7 @@ async function parseSubmitResponse(response) {
42
46
  return parsed.success ? { ok: true, id: parsed.data.id } : { ok: false, code: "VALIDATION_ERROR" };
43
47
  }
44
48
  function createFeedbackClient(options) {
45
- const { widgetKey, appId, baseUrl = "https://crm.theseeker.io", fetchImpl = fetch, FormDataImpl = FormData, XMLHttpRequestImpl = globalThis.XMLHttpRequest, } = options;
49
+ const { widgetKey, appId, baseUrl = exports.DEFAULT_BASE_URL, fetchImpl = fetch, FormDataImpl = FormData, XMLHttpRequestImpl = globalThis.XMLHttpRequest, } = options;
46
50
  return {
47
51
  async fetchConfig() {
48
52
  try {
@@ -72,27 +76,8 @@ function createFeedbackClient(options) {
72
76
  form.append("payload", JSON.stringify(payload));
73
77
  for (const image of images)
74
78
  form.append("image", { uri: image.uri, type: image.mimeType, name: image.fileName });
75
- if (XMLHttpRequestImpl !== undefined) {
76
- const response = await new Promise((resolve, reject) => {
77
- const xhr = new XMLHttpRequestImpl();
78
- Object.assign(xhr, {
79
- onload: () => resolve({
80
- status: xhr.status,
81
- json: async () => {
82
- const raw = JSON.parse(xhr.responseText);
83
- return raw;
84
- },
85
- }),
86
- onerror: () => reject(new TypeError("Multipart upload failed")),
87
- ontimeout: () => reject(new TypeError("Multipart upload timed out")),
88
- });
89
- xhr.open("POST", url);
90
- xhr.timeout = 30000;
91
- xhr.setRequestHeader("X-TheSeeker-App", appId);
92
- xhr.send(form);
93
- });
94
- return await parseSubmitResponse(response);
95
- }
79
+ if (XMLHttpRequestImpl !== undefined)
80
+ return await parseSubmitResponse(await (0, transport_1.xhrPost)(XMLHttpRequestImpl, url, (0, request_1.appHeaders)(appId), form));
96
81
  body = form;
97
82
  headers = { ...(0, request_1.appHeaders)(appId) };
98
83
  }