@the-seeker/changes-react 0.1.1 → 0.3.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  제품 문서: https://docs.theseeker.io/changes/react
4
4
 
5
- TheSeeker CRM 체인지로그(Changes)를 웹 React 앱에 붙이는 SDK입니다. 새 버전 소식을 한 번만 띄우는
5
+ devstage 체인지로그(Changes)를 웹 React 앱에 붙이는 SDK입니다. 새 버전 소식을 한 번만 띄우는
6
6
  What's New 시트, 읽지 않은 수 배지가 달린 체인지로그 버튼, 릴리스 목록, 추천·비추천, 스토어 평가
7
7
  유도, 댓글(답글 1단계·신고·커뮤니티 이용 안내 동의)을 제공합니다.
8
8
 
@@ -28,7 +28,7 @@ export function App() {
28
28
  }
29
29
  ```
30
30
 
31
- 공개 키(`chg_…`)는 CRM의 **체인지로그 → 설치** 탭에 있습니다. 브라우저에서 호출하므로 CRM 설정의
31
+ 공개 키(`chg_…`)는 devstage 대시보드의 **체인지로그 → 설치** 탭에 있습니다. 브라우저에서 호출하므로 체인지로그 설정의
32
32
  **허용 도메인**(`allowedDomains`)에 앱의 origin을 등록해야 합니다. 등록되지 않은 origin은
33
33
  `ORIGIN_NOT_ALLOWED`로 거절되고 SDK는 아무것도 그리지 않습니다(`onError`로 코드를 받습니다).
34
34
 
@@ -38,9 +38,9 @@ export function App() {
38
38
  |---|---|---|
39
39
  | `changesKey` | 필수 | 공개 키 |
40
40
  | `appVersion` | 없음 | 앱 버전을 알면 "네이티브 모드"(아래 표시 규칙)로 동작합니다 |
41
- | `user` | 없음 | `{ userId?, name? }`. `userId`가 있으면 투표·댓글이 기기 대신 사용자에 묶입니다. `name`은 프로젝트가 작성자 이름을 허용할 때만 쓰입니다 |
41
+ | `user` | 없음 | `{ userId?, name?, ssoToken? }` 또는 `null`. SSO는 아래 절을 참고하세요. `userId`는 기존 사용자 식별 방식이며 `name`은 작성자 이름 허용 시에만 쓰입니다 |
42
42
  | `locale` | `"auto"` | `"auto"`는 브라우저 언어(ko/en) → 프로젝트 기본 언어 순서로 고릅니다 |
43
- | `baseUrl` | `https://crm.theseeker.io` | 자체 도메인을 쓸 때만 바꿉니다 |
43
+ | `baseUrl` | `https://devstage.app` | 서버 주소. 0.1.x처럼 이전 주소를 계속 쓰려면 `"https://crm.theseeker.io"`를 넘기세요(두 주소 모두 같은 API를 제공합니다) |
44
44
  | `storage` | `localStorage` | `{ getItem, setItem }`(동기·비동기 모두 가능). SSR에서 안전하며 접근이 막히면 메모리로 대체합니다 |
45
45
  | `showOnFirstLaunch` | `false` | 첫 방문에도 최신 소식을 띄웁니다 |
46
46
  | `forceShow` | `false` | 디버그용: 상태와 무관하게 최신 소식을 띄웁니다 |
@@ -49,13 +49,37 @@ export function App() {
49
49
  | `onError` | 없음 | 설정·목록 로딩 실패 코드(`ORIGIN_NOT_ALLOWED`, `CHANGES_NOT_FOUND`, `NETWORK_ERROR` 등) |
50
50
  | `fetchImpl` | 전역 `fetch` | 테스트나 특수 런타임용 전송 계층 |
51
51
 
52
+ ## SSO 방문자 식별 (0.3.0)
53
+
54
+ 연결된 사이트에서 SSO를 켠 뒤, **고객 서버에서 서명한** 짧은 수명의 JWS를 전달합니다. 서명 비밀키를 브라우저에 넣지 마세요.
55
+
56
+ ```tsx
57
+ <ChangesProvider changesKey="chg_…" user={session ? { ssoToken: session.changesJws } : null}>
58
+ <ChangelogButton />
59
+ </ChangesProvider>
60
+ ```
61
+
62
+ 첫 방문자 식별 요청(릴리스·댓글·로드맵 읽기, 투표·이벤트 등) 전에 `POST /api/changes/sso`로
63
+ `{ key, token }`을 교환하고 이후 요청에는 `X-Devstage-Visitor`를 보냅니다. JWS는 일반 요청 본문에 포함하지 않습니다.
64
+ 같은 Provider 안에서 같은 토큰 값은 교환을 공유하며, 값이 바뀌면 다시 교환합니다. 로그아웃은 `user={null}`
65
+ 또는 `ssoToken` 생략으로 토큰을 비웁니다. Provider를 새로 마운트하면 새 교환이 필요합니다.
66
+
67
+ 방문자 bearer는 **메모리에만** 보관하며 `localStorage`나 주입한 `storage`에 저장하지 않습니다.
68
+ 기존 설치 ID·표시 상태 저장은 유지됩니다. `401 VISITOR_INVALID`는 저장된 방문자 토큰을 버리고 한 번만
69
+ 재교환·재시도합니다. `SSO_DISABLED`·`SSO_REJECTED`는 익명 쓰기로 우회하지 않고 기존 오류 결과로 반환합니다.
70
+ 기존 익명 투표는 SSO 사용자에게 병합하지 않습니다.
71
+
72
+ 저수준 `createChangesClient`에도 `user`와 `visitorStore?: VisitorTokenStore`를 넘길 수 있습니다.
73
+ `VisitorTokenStore`는 `get(key)`와 `set(key, string | null)`을 제공하며 동기·비동기 구현을 지원합니다.
74
+ 웹에서는 `createMemoryVisitorStore()`를 사용하세요.
75
+
52
76
  ## 컴포넌트
53
77
 
54
- - `ChangelogButton` — 체인지로그 대화상자를 엽니다. 배지는 마지막으로 목록을 연 뒤 게시된 릴리스 수입니다.
78
+ - `ChangelogButton` — 체인지로그 모달을 엽니다. 배지는 마지막으로 목록을 연 뒤 게시된 릴리스 수입니다.
55
79
  - `WhatsNewModal` — 표시 규칙이 고른 릴리스 하나를 시트로 보여 줍니다. 제목·버전·날짜, 노트, 추천 캡슐
56
80
  `↑ n | ↓`, 그 아래 평가 버튼, 댓글 수와 "댓글 보기", 계속 버튼 순서입니다.
57
81
  - `ChangelogList` — 릴리스 카드 목록. 페이지 안에 직접 넣을 수 있습니다.
58
- - `ChangelogDialog` — `openChangelog()`로 여는 전체 목록 대화상자(Provider가 렌더합니다).
82
+ - `ChangelogDialog` — `openChangelog()`로 여는 전체 목록 모달(Provider가 렌더합니다).
59
83
  - `ReleaseCard`, `CommentsThread`, `Blocks` — 직접 화면을 짤 때 쓰는 조각입니다.
60
84
 
61
85
  설정 화면의 행처럼 자체 UI에서 목록을 열려면 `useChanges().openChangelog()`를 호출합니다.
@@ -71,6 +95,26 @@ report }, guidelinesAccepted, acceptGuidelines, banned, reload }`를 돌려줍
71
95
  첫 주소를 새 탭에 열고 `rating_click` 이벤트를 남깁니다. 평가 버튼은 프로젝트 설정 `ratingMode`가
72
96
  `always`이거나, `after_upvote`일 때 사용자가 해당 릴리스를 추천한 뒤에만 보입니다.
73
97
 
98
+ ## 로드맵과 반영된 요청 (0.2.1, 클라이언트)
99
+
100
+ 웹 UI는 아직 없고, `createChangesClient()`가 돌려주는 클라이언트에 읽기·투표 함수가 있습니다. 결과는 다른 함수처럼
101
+ `{ ok: true, body } | { ok: false, code }`입니다.
102
+
103
+ ```ts
104
+ import { createChangesClient } from "@the-seeker/changes-react";
105
+
106
+ const client = createChangesClient({ key: "chg_…", platform: "web", fetchImpl: fetch });
107
+ const roadmap = await client.listRoadmap({ installId }); // 예정·진행 중 항목
108
+ await client.voteRoadmap(itemId, 1, { installId }); // 1 = 공감, 0 = 공감 취소
109
+ const requests = await client.listReleaseRequests(releaseId); // 이 업데이트에 반영된 공개 요청
110
+ ```
111
+
112
+ - `listRoadmap({ stages?, installId? })` → `GET /api/changes/roadmap`. 기본 단계는 `planned,in_progress`입니다.
113
+ 응답은 `{ enabled, votesEnabled, stageLabels, items }`이며, 이 SDK가 모르는 단계의 항목은 버립니다.
114
+ - `voteRoadmap(itemId, value, voter)` → `POST /api/changes/roadmap/vote`, 응답 `{ voteCount, voted }`.
115
+ - `listReleaseRequests(releaseId)` → `GET /api/changes/requests`, 응답은 `{ kind: "roadmap" | "feedback", title }` 배열입니다.
116
+ - 이 엔드포인트가 없는 이전 서버(404)에서는 로드맵이 꺼진 것(`ROADMAP_DISABLED`)으로, 요청 목록은 빈 배열로 읽습니다.
117
+
74
118
  ## 표시 규칙 (show-once)
75
119
 
76
120
  - **첫 방문**: 현재 상태(최신 릴리스, `appVersion`)만 기록하고 아무것도 띄우지 않습니다.
@@ -87,7 +131,7 @@ report }, guidelinesAccepted, acceptGuidelines, banned, reload }`를 돌려줍
87
131
 
88
132
  ## 접근성과 테마
89
133
 
90
- - 대화상자는 `role="dialog"`·`aria-modal`이며, 열리면 포커스가 안으로 들어가고 Tab이 안에서 순환하며
134
+ - 모달은 `role="dialog"`·`aria-modal`이며, 열리면 포커스가 안으로 들어가고 Tab이 안에서 순환하며
91
135
  Escape·닫기 버튼·바깥 클릭으로 닫히고 닫힌 뒤 원래 포커스로 돌아갑니다. 520px 이하에서는 아래 시트로 열립니다.
92
136
  - 터치 대상은 44px 이상, 입력은 16px(iOS 확대 방지)이며 `prefers-reduced-motion`이면 전환·진입 애니메이션을 끕니다.
93
137
  - 강조색은 프로젝트 `accentColor`(CSS 변수 `--tsc-accent`)이고 나머지 색은 라이트/다크 중립 팔레트입니다.
@@ -1,4 +1,5 @@
1
- import type { Platform, User, Voter, ClientInfo, Failure, Result, Releases } from "./types";
1
+ import type { VisitorTokenStore } from "./types";
2
+ import type { Platform, User, Voter, ClientInfo, Failure, Result, Releases, RoadmapStage } from "./types";
2
3
  export type FetchInit = Readonly<{
3
4
  method: "GET" | "POST";
4
5
  headers: Readonly<Record<string, string>>;
@@ -21,7 +22,8 @@ export type ChangesClientOptions = Readonly<{
21
22
  locale?: string;
22
23
  appId?: string;
23
24
  appHeader?: string;
24
- user?: User;
25
+ user?: User | null;
26
+ visitorStore?: VisitorTokenStore;
25
27
  fetchImpl: FetchImpl;
26
28
  }>;
27
29
  export type ListOptions = Readonly<{
@@ -30,6 +32,10 @@ export type ListOptions = Readonly<{
30
32
  voter?: string;
31
33
  etag?: string;
32
34
  }>;
35
+ export type RoadmapListOptions = Readonly<{
36
+ stages?: readonly RoadmapStage[];
37
+ installId?: string;
38
+ }>;
33
39
  export type ReleasesResult = Readonly<{
34
40
  ok: true;
35
41
  status: 200;
@@ -65,6 +71,7 @@ export type ReportInput = CommentWrite & Readonly<{
65
71
  reason: "spam" | "abuse" | "off_topic" | "other";
66
72
  note?: string;
67
73
  }>;
74
+ export declare const DEFAULT_BASE_URL = "https://devstage.app";
68
75
  export declare function createChangesClient(options: ChangesClientOptions): {
69
76
  getConfig: () => Promise<Result<Readonly<{
70
77
  enabled: boolean;
@@ -158,6 +165,32 @@ export declare function createChangesClient(options: ChangesClientOptions): {
158
165
  myVote: 0 | 1 | -1;
159
166
  }>>>;
160
167
  reportComment: (input: ReportInput) => Promise<Result<Readonly<Record<string, never>>>>;
168
+ listRoadmap: ({ stages, installId }?: RoadmapListOptions) => Promise<Result<Readonly<{
169
+ enabled: boolean;
170
+ votesEnabled: boolean;
171
+ stageLabels: Readonly<{
172
+ planned?: string | undefined;
173
+ in_progress?: string | undefined;
174
+ }>;
175
+ items: readonly Readonly<{
176
+ id: string;
177
+ number: number | null;
178
+ title: string;
179
+ excerpt: string | null;
180
+ stage: "planned" | "in_progress";
181
+ targetLabel: string | null;
182
+ voteCount: number;
183
+ voted: boolean;
184
+ }>[];
185
+ }>>>;
186
+ voteRoadmap: (itemId: string, value: 0 | 1, voter: Voter) => Promise<Result<Readonly<{
187
+ voteCount: number;
188
+ voted: boolean;
189
+ }>>>;
190
+ listReleaseRequests: (releaseId: string) => Promise<Result<readonly Readonly<{
191
+ kind: "roadmap" | "feedback";
192
+ title: string;
193
+ }>[]>>;
161
194
  };
162
195
  export type ChangesClient = ReturnType<typeof createChangesClient>;
163
196
  export {};
@@ -1,8 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_BASE_URL = void 0;
3
4
  exports.createChangesClient = createChangesClient;
4
5
  const zod_1 = require("zod");
6
+ const sso_1 = require("./sso");
5
7
  const types_1 = require("./types");
8
+ const types_2 = require("./types");
9
+ exports.DEFAULT_BASE_URL = "https://devstage.app";
6
10
  const emptySchema = zod_1.z.object({}).readonly();
7
11
  const errorSchema = zod_1.z.object({ error: types_1.errorCodeSchema });
8
12
  function httpFailure(status, raw) {
@@ -22,16 +26,37 @@ function httpFailure(status, raw) {
22
26
  }
23
27
  function createChangesClient(options) {
24
28
  const { key, platform, fetchImpl, user } = options;
25
- const baseUrl = (options.baseUrl ?? "https://crm.theseeker.io").replace(/\/+$/, "");
29
+ const baseUrl = (options.baseUrl ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, "");
26
30
  const appHeaders = options.appId && platform !== "web" ? { "X-TheSeeker-App": options.appHeader ?? options.appId } : {};
27
- const identity = (voter) => ({ ...voter, ...user });
31
+ const identity = (voter) => ({
32
+ ...voter,
33
+ ...(user?.userId === undefined ? {} : { userId: user.userId }),
34
+ ...(user?.name === undefined ? {} : { name: user.name }),
35
+ });
36
+ const visitor = (0, sso_1.createVisitorSession)({
37
+ scope: `${baseUrl}:${key}`,
38
+ key,
39
+ token: user?.ssoToken ?? null,
40
+ store: options.visitorStore ?? (0, sso_1.createMemoryVisitorStore)(),
41
+ exchange: async () => {
42
+ const result = await transport(`${baseUrl}/api/changes/sso`, {
43
+ method: "POST",
44
+ headers: { ...appHeaders, "Content-Type": "application/json" },
45
+ body: JSON.stringify({ key, token: user?.ssoToken }),
46
+ });
47
+ if (!result.ok)
48
+ return result;
49
+ const parsed = await parse(result.response, sso_1.visitorSessionSchema);
50
+ return parsed.ok ? { ok: true, body: parsed.body.visitorToken } : parsed;
51
+ },
52
+ });
28
53
  const url = (path, query = {}) => {
29
54
  const values = { key, ...query };
30
55
  const pairs = Object.entries(values).filter((entry) => entry[1] !== undefined);
31
56
  return `${baseUrl}/api/changes/${path}?${pairs.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("&")}`;
32
57
  };
33
58
  // Transport boundary: arbitrary rejected values must become a result, not escape to host apps.
34
- async function request(path, init) {
59
+ async function transport(path, init) {
35
60
  try {
36
61
  return { ok: true, response: await fetchImpl(path, init) };
37
62
  }
@@ -39,6 +64,35 @@ function createChangesClient(options) {
39
64
  return { ok: false, code: "NETWORK_ERROR" };
40
65
  }
41
66
  }
67
+ async function request(path, init) {
68
+ if (user?.ssoToken === undefined || /\/api\/changes\/(config|requests)(\?|$)/.test(path))
69
+ return transport(path, init);
70
+ try {
71
+ for (let attempt = 0; attempt < 2; attempt += 1) {
72
+ const token = await visitor.get();
73
+ if (!token.ok)
74
+ return token;
75
+ const result = await transport(path, {
76
+ ...init,
77
+ headers: { ...init.headers, ...(token.body === null ? {} : { "X-Devstage-Visitor": token.body }) },
78
+ });
79
+ if (!result.ok || result.response.status !== 401 || token.body === null)
80
+ return result;
81
+ const raw = await result.response.json();
82
+ const error = errorSchema.safeParse(raw);
83
+ const response = { status: result.response.status, headers: result.response.headers, json: async () => raw };
84
+ if (!error.success || error.data.error !== "VISITOR_INVALID")
85
+ return { ok: true, response };
86
+ await visitor.invalidate(token.body);
87
+ if (attempt === 1)
88
+ return { ok: false, code: "VISITOR_INVALID" };
89
+ }
90
+ }
91
+ catch {
92
+ return { ok: false, code: "NETWORK_ERROR" };
93
+ }
94
+ return { ok: false, code: "VISITOR_INVALID" };
95
+ }
42
96
  async function parse(response, schema) {
43
97
  let raw;
44
98
  try {
@@ -58,6 +112,13 @@ function createChangesClient(options) {
58
112
  const result = await request(url(path, query), { method: "GET", headers: appHeaders });
59
113
  return result.ok ? parse(result.response, schema) : result;
60
114
  }
115
+ // Endpoints newer than the server the app talks to answer 404; that reads as `missing`, not as an error.
116
+ async function getOptional(path, schema, query, missing) {
117
+ const result = await request(url(path, query), { method: "GET", headers: appHeaders });
118
+ if (!result.ok)
119
+ return result;
120
+ return result.response.status === 404 ? { ok: true, body: missing } : parse(result.response, schema);
121
+ }
61
122
  async function post(path, schema, body) {
62
123
  const result = await request(`${baseUrl}/api/changes/${path}`, {
63
124
  method: "POST",
@@ -94,5 +155,8 @@ function createChangesClient(options) {
94
155
  postComment: (input) => post("comments", zod_1.z.object({ comment: types_1.commentSchema }).readonly(), input),
95
156
  voteComment: (input) => post("comments/vote", types_1.voteSchema, input),
96
157
  reportComment: (input) => post("comments/report", emptySchema, input),
158
+ listRoadmap: ({ stages = [], installId } = {}) => getOptional("roadmap", types_2.roadmapSchema, { stages: (stages.length > 0 ? stages : types_2.ROADMAP_STAGES).join(","), installId, userId: user?.userId }, types_2.ROADMAP_DISABLED),
159
+ voteRoadmap: (itemId, value, voter) => post("roadmap/vote", types_2.roadmapVoteSchema, { itemId, value, voter }),
160
+ listReleaseRequests: (releaseId) => getOptional("requests", types_2.releaseRequestsSchema, { releaseId }, []),
97
161
  };
98
162
  }
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ import type { Result, VisitorTokenStore } from "./types";
3
+ export declare const visitorSessionSchema: z.ZodObject<{
4
+ visitorToken: z.ZodString;
5
+ expiresAt: z.ZodString;
6
+ visitor: z.ZodObject<{
7
+ name: z.ZodNullable<z.ZodString>;
8
+ emailMasked: z.ZodNullable<z.ZodString>;
9
+ }, z.core.$strip>;
10
+ }, z.core.$strip>;
11
+ type Exchange = () => Promise<Result<string>>;
12
+ export declare function createMemoryVisitorStore(): VisitorTokenStore;
13
+ export declare function createVisitorSession(options: Readonly<{
14
+ scope: string;
15
+ key: string;
16
+ token: string | null;
17
+ store: VisitorTokenStore;
18
+ exchange: Exchange;
19
+ }>): {
20
+ get(): Promise<Result<string | null>>;
21
+ invalidate(rejected: string): Promise<void>;
22
+ };
23
+ export {};
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.visitorSessionSchema = void 0;
4
+ exports.createMemoryVisitorStore = createMemoryVisitorStore;
5
+ exports.createVisitorSession = createVisitorSession;
6
+ const zod_1 = require("zod");
7
+ exports.visitorSessionSchema = zod_1.z.object({
8
+ visitorToken: zod_1.z.string().min(1),
9
+ expiresAt: zod_1.z.string().datetime(),
10
+ visitor: zod_1.z.object({ name: zod_1.z.string().nullable(), emailMasked: zod_1.z.string().nullable() }),
11
+ });
12
+ const stores = new WeakMap();
13
+ function createMemoryVisitorStore() {
14
+ const values = new Map();
15
+ return {
16
+ get: (key) => values.get(key) ?? null,
17
+ set: (key, value) => {
18
+ if (value === null)
19
+ values.delete(key);
20
+ else
21
+ values.set(key, value);
22
+ },
23
+ };
24
+ }
25
+ function createVisitorSession(options) {
26
+ const { store, token, exchange } = options;
27
+ const storageKey = `tsch:visitor:${options.key}`;
28
+ let scopes = stores.get(store);
29
+ if (scopes === undefined) {
30
+ scopes = new Map();
31
+ stores.set(store, scopes);
32
+ }
33
+ const previous = scopes.get(options.scope);
34
+ const entry = previous?.entry.token === token ? previous.entry : { token, pending: null, clear: Promise.resolve(true) };
35
+ const changed = previous?.entry !== entry;
36
+ const state = previous ?? { entry, writes: Promise.resolve(true) };
37
+ const write = (value) => {
38
+ // Serialize adapter writes so a late exchange cannot restore a logged-out bearer.
39
+ state.writes = state.writes
40
+ .then(async () => {
41
+ if (state.entry !== entry)
42
+ return true;
43
+ await store.set(storageKey, value);
44
+ return true;
45
+ })
46
+ .catch(() => false);
47
+ return state.writes;
48
+ };
49
+ state.entry = entry;
50
+ scopes.set(options.scope, state);
51
+ if (changed)
52
+ entry.clear = write(null);
53
+ async function acquire() {
54
+ if (!(await entry.clear))
55
+ return { ok: false, code: "NETWORK_ERROR" };
56
+ if (state.entry !== entry)
57
+ return { ok: false, code: "SSO_REJECTED" };
58
+ if (token === null)
59
+ return { ok: true, body: null };
60
+ const result = await exchange();
61
+ if (!result.ok)
62
+ return result;
63
+ if (state.entry !== entry)
64
+ return { ok: false, code: "SSO_REJECTED" };
65
+ return (await write(result.body)) ? result : { ok: false, code: "NETWORK_ERROR" };
66
+ }
67
+ return {
68
+ get() {
69
+ if (state.entry !== entry)
70
+ return Promise.resolve({ ok: false, code: "SSO_REJECTED" });
71
+ entry.pending ?? (entry.pending = acquire().then((result) => {
72
+ if (!result.ok)
73
+ entry.pending = null;
74
+ return result;
75
+ }));
76
+ return entry.pending;
77
+ },
78
+ async invalidate(rejected) {
79
+ if (state.entry !== entry)
80
+ return;
81
+ if ((await store.get(storageKey)) !== rejected)
82
+ return;
83
+ entry.pending = null;
84
+ entry.clear = write(null);
85
+ await entry.clear;
86
+ },
87
+ };
88
+ }
@@ -277,6 +277,112 @@ export declare const commentsSchema: z.ZodReadonly<z.ZodObject<{
277
277
  }, z.core.$strip>>;
278
278
  export type Comment = z.infer<typeof threadSchema>;
279
279
  export type CommentReply = z.infer<typeof commentSchema>;
280
+ export declare const ROADMAP_STAGES: readonly ["planned", "in_progress"];
281
+ export declare const roadmapStageSchema: z.ZodEnum<{
282
+ planned: "planned";
283
+ in_progress: "in_progress";
284
+ }>;
285
+ export type RoadmapStage = z.infer<typeof roadmapStageSchema>;
286
+ export declare const roadmapItemSchema: z.ZodReadonly<z.ZodObject<{
287
+ id: z.ZodString;
288
+ number: z.ZodCatch<z.ZodNullable<z.ZodNumber>>;
289
+ title: z.ZodString;
290
+ excerpt: z.ZodCatch<z.ZodNullable<z.ZodString>>;
291
+ stage: z.ZodEnum<{
292
+ planned: "planned";
293
+ in_progress: "in_progress";
294
+ }>;
295
+ targetLabel: z.ZodCatch<z.ZodNullable<z.ZodString>>;
296
+ voteCount: z.ZodNumber;
297
+ voted: z.ZodBoolean;
298
+ }, z.core.$strip>>;
299
+ export declare const roadmapSchema: z.ZodPipe<z.ZodObject<{
300
+ roadmap: z.ZodReadonly<z.ZodObject<{
301
+ enabled: z.ZodBoolean;
302
+ votesEnabled: z.ZodBoolean;
303
+ stageLabels: z.ZodCatch<z.ZodReadonly<z.ZodObject<{
304
+ planned: z.ZodOptional<z.ZodString>;
305
+ in_progress: z.ZodOptional<z.ZodString>;
306
+ }, z.core.$strip>>>;
307
+ items: z.ZodPipe<z.ZodArray<z.ZodUnknown>, z.ZodTransform<readonly Readonly<{
308
+ id: string;
309
+ number: number | null;
310
+ title: string;
311
+ excerpt: string | null;
312
+ stage: "planned" | "in_progress";
313
+ targetLabel: string | null;
314
+ voteCount: number;
315
+ voted: boolean;
316
+ }>[], unknown[]>>;
317
+ }, z.core.$strip>>;
318
+ }, z.core.$strip>, z.ZodTransform<Readonly<{
319
+ enabled: boolean;
320
+ votesEnabled: boolean;
321
+ stageLabels: Readonly<{
322
+ planned?: string | undefined;
323
+ in_progress?: string | undefined;
324
+ }>;
325
+ items: readonly Readonly<{
326
+ id: string;
327
+ number: number | null;
328
+ title: string;
329
+ excerpt: string | null;
330
+ stage: "planned" | "in_progress";
331
+ targetLabel: string | null;
332
+ voteCount: number;
333
+ voted: boolean;
334
+ }>[];
335
+ }>, {
336
+ roadmap: Readonly<{
337
+ enabled: boolean;
338
+ votesEnabled: boolean;
339
+ stageLabels: Readonly<{
340
+ planned?: string | undefined;
341
+ in_progress?: string | undefined;
342
+ }>;
343
+ items: readonly Readonly<{
344
+ id: string;
345
+ number: number | null;
346
+ title: string;
347
+ excerpt: string | null;
348
+ stage: "planned" | "in_progress";
349
+ targetLabel: string | null;
350
+ voteCount: number;
351
+ voted: boolean;
352
+ }>[];
353
+ }>;
354
+ }>>;
355
+ export type RoadmapItem = z.infer<typeof roadmapItemSchema>;
356
+ export type Roadmap = z.infer<typeof roadmapSchema>;
357
+ /** What an older server without `/api/changes/roadmap` (HTTP 404) reads as. */
358
+ export declare const ROADMAP_DISABLED: Roadmap;
359
+ export declare const roadmapVoteSchema: z.ZodReadonly<z.ZodObject<{
360
+ voteCount: z.ZodNumber;
361
+ voted: z.ZodBoolean;
362
+ }, z.core.$strip>>;
363
+ export type RoadmapVote = z.infer<typeof roadmapVoteSchema>;
364
+ export declare const releaseRequestSchema: z.ZodReadonly<z.ZodObject<{
365
+ kind: z.ZodEnum<{
366
+ roadmap: "roadmap";
367
+ feedback: "feedback";
368
+ }>;
369
+ title: z.ZodString;
370
+ }, z.core.$strip>>;
371
+ export declare const releaseRequestsSchema: z.ZodPipe<z.ZodObject<{
372
+ requests: z.ZodPipe<z.ZodArray<z.ZodUnknown>, z.ZodTransform<readonly Readonly<{
373
+ kind: "roadmap" | "feedback";
374
+ title: string;
375
+ }>[], unknown[]>>;
376
+ }, z.core.$strip>, z.ZodTransform<readonly Readonly<{
377
+ kind: "roadmap" | "feedback";
378
+ title: string;
379
+ }>[], {
380
+ requests: readonly Readonly<{
381
+ kind: "roadmap" | "feedback";
382
+ title: string;
383
+ }>[];
384
+ }>>;
385
+ export type ReleaseRequest = z.infer<typeof releaseRequestSchema>;
280
386
  export declare const errorCodeSchema: z.ZodEnum<{
281
387
  BAD_REQUEST: "BAD_REQUEST";
282
388
  VALIDATION_ERROR: "VALIDATION_ERROR";
@@ -295,6 +401,9 @@ export declare const errorCodeSchema: z.ZodEnum<{
295
401
  NETWORK_ERROR: "NETWORK_ERROR";
296
402
  HTTP_ERROR: "HTTP_ERROR";
297
403
  INVALID_RESPONSE: "INVALID_RESPONSE";
404
+ SSO_DISABLED: "SSO_DISABLED";
405
+ SSO_REJECTED: "SSO_REJECTED";
406
+ VISITOR_INVALID: "VISITOR_INVALID";
298
407
  }>;
299
408
  export type ErrorCode = z.infer<typeof errorCodeSchema>;
300
409
  export type Failure = Readonly<{
@@ -313,6 +422,11 @@ export type Voter = Readonly<{
313
422
  export type User = Readonly<{
314
423
  userId?: string;
315
424
  name?: string;
425
+ ssoToken?: string;
426
+ }>;
427
+ export type VisitorTokenStore = Readonly<{
428
+ get: (key: string) => Promise<string | null> | string | null;
429
+ set: (key: string, value: string | null) => Promise<void> | void;
316
430
  }>;
317
431
  export type ClientInfo = Readonly<{
318
432
  platform: Platform;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.stateSchema = exports.errorCodeSchema = exports.commentsSchema = exports.threadSchema = exports.commentSchema = exports.configSchema = exports.releasesSchema = exports.releaseSchema = exports.voteSchema = exports.blockSchema = exports.inlineSchema = exports.platformSchema = void 0;
3
+ exports.stateSchema = exports.errorCodeSchema = exports.releaseRequestsSchema = exports.releaseRequestSchema = exports.roadmapVoteSchema = exports.ROADMAP_DISABLED = exports.roadmapSchema = exports.roadmapItemSchema = exports.roadmapStageSchema = exports.ROADMAP_STAGES = exports.commentsSchema = exports.threadSchema = exports.commentSchema = exports.configSchema = exports.releasesSchema = exports.releaseSchema = exports.voteSchema = exports.blockSchema = exports.inlineSchema = exports.platformSchema = void 0;
4
4
  const zod_1 = require("zod");
5
5
  exports.platformSchema = zod_1.z.enum(["web", "ios", "android"]);
6
6
  exports.inlineSchema = zod_1.z.union([
@@ -95,6 +95,52 @@ exports.commentsSchema = zod_1.z
95
95
  total: zod_1.z.number().int().nonnegative(),
96
96
  })
97
97
  .readonly();
98
+ // Newer endpoints are read leniently: an entry this SDK version cannot render is dropped, not fatal.
99
+ function tolerantList(item) {
100
+ return zod_1.z.array(zod_1.z.unknown()).transform((values) => values.flatMap((value) => {
101
+ const parsed = item.safeParse(value);
102
+ return parsed.success ? [parsed.data] : [];
103
+ }));
104
+ }
105
+ const optionalText = zod_1.z.string().nullable().catch(null);
106
+ exports.ROADMAP_STAGES = ["planned", "in_progress"];
107
+ exports.roadmapStageSchema = zod_1.z.enum(exports.ROADMAP_STAGES);
108
+ exports.roadmapItemSchema = zod_1.z
109
+ .object({
110
+ id: zod_1.z.string(),
111
+ number: zod_1.z.number().int().nullable().catch(null),
112
+ title: zod_1.z.string(),
113
+ excerpt: optionalText,
114
+ stage: exports.roadmapStageSchema,
115
+ targetLabel: optionalText,
116
+ voteCount: zod_1.z.number().int().nonnegative(),
117
+ voted: zod_1.z.boolean(),
118
+ })
119
+ .readonly();
120
+ exports.roadmapSchema = zod_1.z
121
+ .object({
122
+ roadmap: zod_1.z
123
+ .object({
124
+ enabled: zod_1.z.boolean(),
125
+ votesEnabled: zod_1.z.boolean(),
126
+ stageLabels: zod_1.z
127
+ .object({ planned: zod_1.z.string().min(1).optional(), in_progress: zod_1.z.string().min(1).optional() })
128
+ .readonly()
129
+ .catch({}),
130
+ items: tolerantList(exports.roadmapItemSchema),
131
+ })
132
+ .readonly(),
133
+ })
134
+ .transform((body) => body.roadmap);
135
+ /** What an older server without `/api/changes/roadmap` (HTTP 404) reads as. */
136
+ exports.ROADMAP_DISABLED = { enabled: false, votesEnabled: false, stageLabels: {}, items: [] };
137
+ exports.roadmapVoteSchema = zod_1.z.object({ voteCount: zod_1.z.number().int().nonnegative(), voted: zod_1.z.boolean() }).readonly();
138
+ exports.releaseRequestSchema = zod_1.z
139
+ .object({ kind: zod_1.z.enum(["roadmap", "feedback"]), title: zod_1.z.string().min(1) })
140
+ .readonly();
141
+ exports.releaseRequestsSchema = zod_1.z
142
+ .object({ requests: tolerantList(exports.releaseRequestSchema) })
143
+ .transform((body) => body.requests);
98
144
  exports.errorCodeSchema = zod_1.z.enum([
99
145
  "BAD_REQUEST",
100
146
  "VALIDATION_ERROR",
@@ -113,6 +159,9 @@ exports.errorCodeSchema = zod_1.z.enum([
113
159
  "NETWORK_ERROR",
114
160
  "HTTP_ERROR",
115
161
  "INVALID_RESPONSE",
162
+ "SSO_DISABLED",
163
+ "SSO_REJECTED",
164
+ "VISITOR_INVALID",
116
165
  ]);
117
166
  exports.stateSchema = zod_1.z
118
167
  .object({
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export * from "./core/decide";
5
5
  export * from "./core/cache";
6
6
  export * from "./core/versions";
7
7
  export * from "./core/rating";
8
+ export { createMemoryVisitorStore } from "./core/sso";
8
9
  export { ChangesProvider } from "./web/Provider";
9
10
  export type { ChangesProviderProps } from "./web/Provider";
10
11
  export { useChanges, ChangesProviderMissingError } from "./web/useChanges";
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.DEFAULT_TEXTS = exports.localStorageAdapter = exports.Blocks = exports.CommentsThread = exports.ReleaseCard = exports.ChangelogDialog = exports.ChangelogList = exports.ChangelogButton = exports.WhatsNewModal = exports.ChangesProviderMissingError = exports.useChanges = exports.ChangesProvider = void 0;
17
+ exports.DEFAULT_TEXTS = exports.localStorageAdapter = exports.Blocks = exports.CommentsThread = exports.ReleaseCard = exports.ChangelogDialog = exports.ChangelogList = exports.ChangelogButton = exports.WhatsNewModal = exports.ChangesProviderMissingError = exports.useChanges = exports.ChangesProvider = exports.createMemoryVisitorStore = void 0;
18
18
  __exportStar(require("./core/types"), exports);
19
19
  __exportStar(require("./core/client"), exports);
20
20
  __exportStar(require("./core/storage"), exports);
@@ -22,6 +22,8 @@ __exportStar(require("./core/decide"), exports);
22
22
  __exportStar(require("./core/cache"), exports);
23
23
  __exportStar(require("./core/versions"), exports);
24
24
  __exportStar(require("./core/rating"), exports);
25
+ var sso_1 = require("./core/sso");
26
+ Object.defineProperty(exports, "createMemoryVisitorStore", { enumerable: true, get: function () { return sso_1.createMemoryVisitorStore; } });
25
27
  var Provider_1 = require("./web/Provider");
26
28
  Object.defineProperty(exports, "ChangesProvider", { enumerable: true, get: function () { return Provider_1.ChangesProvider; } });
27
29
  var useChanges_1 = require("./web/useChanges");
@@ -7,7 +7,7 @@ import type { ColorScheme } from "./theme";
7
7
  export type ChangesProviderProps = Readonly<{
8
8
  changesKey: string;
9
9
  appVersion?: string;
10
- user?: User;
10
+ user?: User | null;
11
11
  locale?: LocalePreference;
12
12
  baseUrl?: string;
13
13
  storage?: ChangesStorage;
@@ -6,6 +6,7 @@ const react_1 = require("react");
6
6
  const client_1 = require("../core/client");
7
7
  const decide_1 = require("../core/decide");
8
8
  const storage_1 = require("../core/storage");
9
+ const sso_1 = require("../core/sso");
9
10
  const ChangelogDialog_1 = require("./ChangelogDialog");
10
11
  const context_1 = require("./context");
11
12
  const controls_css_1 = require("./controls-css");
@@ -34,6 +35,8 @@ function ChangesProvider(props) {
34
35
  const { autoPresent = true, colorScheme = "auto", children } = props;
35
36
  const userId = props.user?.userId;
36
37
  const userName = props.user?.name;
38
+ const ssoToken = props.user?.ssoToken;
39
+ const [visitorStore] = (0, react_1.useState)(sso_1.createMemoryVisitorStore);
37
40
  const [model, setModel] = (0, react_1.useState)(() => (0, model_1.initialModel)(locale === "auto" ? "ko" : locale));
38
41
  const injected = (0, react_1.useRef)({ storage: props.storage, fetchImpl: props.fetchImpl, onError: props.onError });
39
42
  (0, react_1.useEffect)(() => {
@@ -42,12 +45,17 @@ function ChangesProvider(props) {
42
45
  const start = (0, react_1.useCallback)(async (guard) => {
43
46
  const { storage: given, fetchImpl, onError } = injected.current;
44
47
  const storage = given ?? (0, storage_2.localStorageAdapter)();
45
- const user = { ...(userId ? { userId } : {}), ...(userName ? { name: userName } : {}) };
48
+ const user = {
49
+ ...(userId ? { userId } : {}),
50
+ ...(userName ? { name: userName } : {}),
51
+ ...(ssoToken === undefined ? {} : { ssoToken }),
52
+ };
46
53
  const client = (0, client_1.createChangesClient)({
47
54
  key: changesKey,
48
55
  platform: "web",
49
56
  fetchImpl: fetchImpl ?? browserFetch,
50
57
  user,
58
+ visitorStore,
51
59
  ...(baseUrl ? { baseUrl } : {}),
52
60
  ...(appVersion ? { appVersion } : {}),
53
61
  });
@@ -69,7 +77,7 @@ function ChangesProvider(props) {
69
77
  setModel((current) => ({ ...current, ...loaded, overrides: {}, runtime }));
70
78
  if (loaded.error !== null)
71
79
  onError?.(loaded.error);
72
- }, [changesKey, baseUrl, appVersion, userId, userName, locale, showOnFirstLaunch, forceShow]);
80
+ }, [changesKey, baseUrl, appVersion, userId, userName, ssoToken, visitorStore, locale, showOnFirstLaunch, forceShow]);
73
81
  (0, react_1.useEffect)(() => {
74
82
  const guard = { active: true };
75
83
  void start(guard);
@@ -35,7 +35,7 @@ export declare const DEFAULT_TEXTS: {
35
35
  readonly empty: "아직 업데이트가 없습니다";
36
36
  readonly loadError: "소식을 불러오지 못했습니다";
37
37
  readonly offline: "오프라인입니다. 저장된 소식을 표시합니다";
38
- readonly contactDeveloper: "개발자에게 문의";
38
+ readonly contactDeveloper: "개발자에게 연락하기";
39
39
  readonly tag_new: "새 기능";
40
40
  readonly tag_improved: "개선";
41
41
  readonly tag_fixed: "수정";
@@ -40,7 +40,7 @@ exports.DEFAULT_TEXTS = {
40
40
  empty: "아직 업데이트가 없습니다",
41
41
  loadError: "소식을 불러오지 못했습니다",
42
42
  offline: "오프라인입니다. 저장된 소식을 표시합니다",
43
- contactDeveloper: "개발자에게 문의",
43
+ contactDeveloper: "개발자에게 연락하기",
44
44
  tag_new: "새 기능",
45
45
  tag_improved: "개선",
46
46
  tag_fixed: "수정",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@the-seeker/changes-react",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "files": [
@@ -12,12 +12,6 @@
12
12
  },
13
13
  "sideEffects": false,
14
14
  "license": "MIT",
15
- "scripts": {
16
- "build": "tsc -p tsconfig.build.json",
17
- "typecheck": "tsc --noEmit",
18
- "test": "vitest run",
19
- "prepublishOnly": "pnpm run typecheck && pnpm test && pnpm run build"
20
- },
21
15
  "peerDependencies": {
22
16
  "react": ">=18",
23
17
  "react-dom": ">=18"
@@ -26,13 +20,18 @@
26
20
  "zod": "^4"
27
21
  },
28
22
  "devDependencies": {
29
- "typescript": "^5",
30
- "vitest": "^4.1.11",
23
+ "@types/node": "^24.19.4",
31
24
  "@types/react": "^19",
32
25
  "@types/react-dom": "^19",
26
+ "jsdom": "^29",
33
27
  "react": "19.2.3",
34
28
  "react-dom": "19.2.3",
35
- "jsdom": "^29"
29
+ "typescript": "^5",
30
+ "vitest": "^5.1.1"
36
31
  },
37
- "packageManager": "pnpm@12.1.0"
38
- }
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.build.json",
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "vitest run"
36
+ }
37
+ }