docs/.vitepress/theme/internal/api.ts

d7294a32af86e6123e470dd3bfbcbde8510ff5fc
wotaku/docs/.vitepress/theme/internal/api.ts history · blame · raw

294 lines · 6570 bytes

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