docs/.vitepress/theme/internal/api.ts
287 lines · 6310 bytes
1interface ApiConfig {
2 baseUrl: string
3 defaultHeaders?: Record<string, string | Promise<string | null>>
4 maxRetries?: number
5 initialRetryDelay?: number
6}
7
8interface FetchOptions extends RequestInit {
9 retries?: number
10}
11
12class Api {
13 private baseUrl: string
14 private headers: Record<string, string | Promise<string | null>>
15 private maxRetries: number
16 private initialRetryDelay: number
17
18 constructor(config: ApiConfig) {
19 this.baseUrl = config.baseUrl
20 this.headers = {
21 'Content-Type': 'application/json',
22 ...config.defaultHeaders
23 }
24 this.maxRetries = config.maxRetries ?? 3
25 this.initialRetryDelay = config.initialRetryDelay ?? 500
26 }
27
28 private async resolveHeaders(): Promise<Record<string, string>> {
29 const resolvedHeaders: Record<string, string> = {}
30 for (const [key, value] of Object.entries(this.headers)) {
31 const resolvedValue = await value
32 if (resolvedValue !== null) {
33 resolvedHeaders[key] = resolvedValue
34 }
35 }
36 return resolvedHeaders
37 }
38
39 public addHeader(key: string, value: string | Promise<string | null>) {
40 this.headers[key] = value
41 }
42
43 private async post<ReqBody, ResBody>(
44 url: string,
45 data: ReqBody,
46 options: FetchOptions,
47 attempt: number
48 ): Promise<ResBody | null> {
49 try {
50 const response = await fetch(url, {
51 method: 'POST',
52 headers: await this.resolveHeaders(),
53 body: JSON.stringify(data ?? {}),
54 keepalive: true,
55 ...options
56 })
57
58 if (response.status === 401) return null
59
60 if (response.status !== 200 && response.status !== 202) {
61 throw new Error(`HTTP error! status: ${response.status}`)
62 }
63
64 const responseText = await response.text()
65 return responseText ? JSON.parse(responseText) : null
66 } catch (error) {
67 if (attempt < this.maxRetries) {
68 const delay = this.initialRetryDelay * 2 ** attempt
69 await new Promise((resolve) => setTimeout(resolve, delay))
70 return this.post<ReqBody, ResBody>(url, data, options, attempt + 1)
71 }
72 console.error('Max retries reached:', error)
73 return null
74 }
75 }
76
77 async fetch<ReqBody, ResBody>(
78 path: string,
79 data: ReqBody,
80 options: FetchOptions = {}
81 ): Promise<ResBody | null> {
82 const url = `${this.baseUrl}${path}`
83 return this.post<ReqBody, ResBody>(url, data, options, 0)
84 }
85}
86
87export type TrackHandlerPayload =
88 | {
89 type: 'track'
90 payload: TrackPayload
91 }
92 | {
93 type: 'increment'
94 payload: IncrementPayload
95 }
96 | {
97 type: 'decrement'
98 payload: DecrementPayload
99 }
100 | {
101 type: 'alias'
102 payload: AliasPayload
103 }
104 | {
105 type: 'identify'
106 payload: IdentifyPayload
107 }
108
109export type TrackPayload = {
110 name: string
111 properties?: Record<string, unknown>
112 profileId?: string
113}
114
115export type TrackProperties = {
116 [key: string]: unknown
117 profileId?: string
118}
119
120export type IdentifyPayload = {
121 profileId: string
122 firstName?: string
123 lastName?: string
124 email?: string
125 avatar?: string
126 properties?: Record<string, unknown>
127}
128
129export type AliasPayload = {
130 profileId: string
131 alias: string
132}
133
134export type IncrementPayload = {
135 profileId: string
136 property: string
137 value?: number
138}
139
140export type DecrementPayload = {
141 profileId: string
142 property: string
143 value?: number
144}
145
146export type InternalOptions = {
147 clientId: string
148 clientSecret?: string
149 apiUrl?: string
150 sdk?: string
151 sdkVersion?: string
152 waitForProfile?: boolean
153 filter?: (payload: TrackHandlerPayload) => boolean
154 disabled?: boolean
155}
156
157export class InternalAPI {
158 api: Api
159 profileId?: string
160 global?: Record<string, unknown>
161 queue: TrackHandlerPayload[] = []
162
163 constructor(public options: InternalOptions) {
164 const defaultHeaders: Record<string, string> = {
165 'openpanel-client-id': options.clientId
166 }
167
168 if (options.clientSecret) {
169 defaultHeaders['openpanel-client-secret'] = options.clientSecret
170 }
171
172 defaultHeaders['openpanel-sdk-name'] = options.sdk || 'node'
173 defaultHeaders['openpanel-sdk-version'] =
174 options.sdkVersion || process.env.SDK_VERSION!
175
176 this.api = new Api({
177 baseUrl: 'https://wotaku.wiki',
178 defaultHeaders
179 })
180 }
181
182 // placeholder for future use
183 init() {
184 // empty
185 }
186
187 ready() {
188 this.options.waitForProfile = false
189 this.flush()
190 }
191
192 async send(payload: TrackHandlerPayload) {
193 if (this.options.disabled) {
194 return Promise.resolve()
195 }
196
197 if (this.options.filter && !this.options.filter(payload)) {
198 return Promise.resolve()
199 }
200
201 if (this.options.waitForProfile && !this.profileId) {
202 this.queue.push(payload)
203 return Promise.resolve()
204 }
205 return this.api.fetch('/icons', payload)
206 }
207
208 setGlobalProperties(properties: Record<string, unknown>) {
209 this.global = {
210 ...this.global,
211 ...properties
212 }
213 }
214
215 async track(name: string, properties?: TrackProperties) {
216 return this.send({
217 type: 'track',
218 payload: {
219 name,
220 profileId: properties?.profileId ?? this.profileId,
221 properties: {
222 ...(this.global ?? {}),
223 ...(properties ?? {})
224 }
225 }
226 })
227 }
228
229 async identify(payload: IdentifyPayload) {
230 if (payload.profileId) {
231 this.profileId = payload.profileId
232 this.flush()
233 }
234
235 if (Object.keys(payload).length > 1) {
236 return this.send({
237 type: 'identify',
238 payload: {
239 ...payload,
240 properties: {
241 ...this.global,
242 ...payload.properties
243 }
244 }
245 })
246 }
247 }
248
249 async alias(payload: AliasPayload) {
250 return this.send({
251 type: 'alias',
252 payload
253 })
254 }
255
256 async increment(payload: IncrementPayload) {
257 return this.send({
258 type: 'increment',
259 payload
260 })
261 }
262
263 async decrement(payload: DecrementPayload) {
264 return this.send({
265 type: 'decrement',
266 payload
267 })
268 }
269
270 clear() {
271 this.profileId = undefined
272 }
273
274 flush() {
275 this.queue.forEach((item) => {
276 this.send({
277 ...item,
278 // @ts-expect-error
279 payload: {
280 ...item.payload,
281 profileId: item.payload.profileId ?? this.profileId
282 }
283 })
284 })
285 this.queue = []
286 }
287}