@supersdk/jssdk 1.0.0 → 3.0.3-SNAPSHOT

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/dist/index.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export type AnalyticsConsent = 'denied' | 'granted';
2
2
 
3
+ import type { BridgeEventMap, BridgeMethodMap, BridgeState, PushMessagePayload, PushOpenedPayload, PushPermission, PushStatusWire } from './protocol.js';
4
+ import type { MonitoringConsent, MonitoringEnvelopeV1 } from './monitoring-contract.js';
5
+ export * from './monitoring-contract.js';
6
+
3
7
  export interface SettingsOptions {
4
8
  cacheTtlMs?: number;
5
9
  maxCacheEntries?: number;
@@ -39,14 +43,39 @@ export interface InitConfig {
39
43
  export type SuperSDKErrorCode =
40
44
  | 'INVALID_ARGUMENT' | 'NOT_INITIALIZED' | 'CONSENT_DENIED' | 'QUEUE_FULL'
41
45
  | 'PAYLOAD_TOO_LARGE' | 'RATE_LIMITED' | 'UNAVAILABLE' | 'TIMEOUT'
42
- | 'NETWORK_ERROR' | 'PROTOCOL_MISMATCH' | 'UNSUPPORTED';
46
+ | 'NETWORK_ERROR' | 'PROTOCOL_MISMATCH' | 'UNSUPPORTED' | 'BRIDGE_ABSENT'
47
+ | 'BRIDGE_INCOMPATIBLE' | 'BRIDGE_DEGRADED' | 'BRIDGE_ERROR' | 'CANCELLED' | 'DISPOSED'
48
+ | 'MONITORING_START_FAILED' | 'MONITORING_TRANSPORT_NOT_CONFIGURED';
43
49
 
44
50
  export class SuperSDKError extends Error {
45
51
  readonly code: SuperSDKErrorCode;
46
52
  readonly retryable: boolean;
53
+ readonly nativeCode?: string;
54
+ readonly reasonCode?: string;
55
+ readonly details?: Readonly<Record<string, string | number | boolean | null>>;
47
56
  readonly cause?: unknown;
48
57
  }
49
58
 
59
+ export interface FeedbackParams {
60
+ /** 反馈场景(必填 · ≤64 字符),如 'settings' / 'chat' */
61
+ scene: string;
62
+ /** 子场景(可选 · ≤64 字符) */
63
+ subScene?: string;
64
+ /** 标题(必填 · ≤200 字符) */
65
+ title: string;
66
+ /** 反馈内容(必填 · ≤5000 字符) */
67
+ content: string;
68
+ /** 业务用户 ID(可选 · ≤128 字符 · 由调用方提供) */
69
+ userId?: string;
70
+ /** 附加信息(可选 · JSON object · 序列化后 ≤4KB) */
71
+ extra?: Record<string, unknown>;
72
+ }
73
+
74
+ export interface FeedbackReceipt {
75
+ /** 服务端反馈记录 ID */
76
+ feedbackId: number;
77
+ }
78
+
50
79
  export interface QueuedEvent {
51
80
  readonly eventId: string;
52
81
  readonly queued: true;
@@ -59,6 +88,43 @@ export interface FlushSummary {
59
88
  readonly retrying: number;
60
89
  readonly pending: number;
61
90
  readonly reason?: string;
91
+ readonly sessionId?: string;
92
+ readonly pageId?: string;
93
+ readonly requestId?: string;
94
+ readonly api?: string;
95
+ readonly event?: string;
96
+ readonly state?: string;
97
+ readonly outcome?: string;
98
+ readonly latencyBucket?: string;
99
+ readonly protocol?: string;
100
+ readonly container?: string;
101
+ readonly errorClass?: string;
102
+ }
103
+
104
+ export interface BridgeOperationOptions {
105
+ timeoutMs?: number;
106
+ signal?: AbortSignal;
107
+ }
108
+
109
+ type MethodIdsOfKind<K extends BridgeMethodMap[keyof BridgeMethodMap]['kind']> = {
110
+ [P in keyof BridgeMethodMap]: BridgeMethodMap[P]['kind'] extends K ? P : never
111
+ }[keyof BridgeMethodMap];
112
+
113
+ export interface BridgeStream<TProgress = unknown, TResult = unknown> {
114
+ readonly completion: Promise<TResult>;
115
+ onProgress(listener: (value: TProgress) => void): () => void;
116
+ cancel(): void;
117
+ }
118
+
119
+ export interface BridgeClient {
120
+ ready(options?: { force?: boolean }): Promise<BridgeState>;
121
+ getBridgeState(): BridgeState;
122
+ supports(id: keyof BridgeMethodMap | keyof BridgeEventMap): boolean;
123
+ request<M extends MethodIdsOfKind<'request'>>(methodId: M, args: BridgeMethodMap[M]['args'], options?: BridgeOperationOptions): Promise<BridgeMethodMap[M]['result']>;
124
+ command<M extends MethodIdsOfKind<'command'>>(methodId: M, args: BridgeMethodMap[M]['args'], options?: BridgeOperationOptions): Promise<void>;
125
+ openStream<M extends MethodIdsOfKind<'stream'>>(methodId: M, args: BridgeMethodMap[M]['args'], options?: BridgeOperationOptions): BridgeStream<BridgeMethodMap[M]['progress'], BridgeMethodMap[M]['result']>;
126
+ subscribe<E extends keyof BridgeEventMap>(eventId: E, listener: (event: BridgeEventMap[E]) => void): () => void;
127
+ dispose(): void;
62
128
  }
63
129
 
64
130
  export interface DeliveryState {
@@ -81,13 +147,173 @@ export interface Diagnostic {
81
147
  readonly reason?: string;
82
148
  }
83
149
 
150
+ export interface SuEncCapabilities {
151
+ readonly supported: boolean;
152
+ readonly codecs: readonly string[];
153
+ }
154
+
155
+ export interface SubscriptionPricingPhase {
156
+ readonly formattedPrice: string;
157
+ readonly currencyCode: string;
158
+ readonly priceAmountMicros: number;
159
+ readonly billingPeriod: string;
160
+ readonly billingCycleCount: number;
161
+ readonly recurrenceMode: number;
162
+ }
163
+
164
+ export interface SubscriptionOffer {
165
+ readonly productId: string;
166
+ readonly basePlanId: string;
167
+ readonly offerId: string | null;
168
+ readonly offerTags: readonly string[];
169
+ readonly title: string;
170
+ readonly description: string;
171
+ readonly pricingPhases: readonly SubscriptionPricingPhase[];
172
+ }
173
+
174
+ export interface PayResult3State {
175
+ readonly status: 'finished' | 'cancelled' | 'error';
176
+ readonly phase?: 'create' | 'pay';
177
+ readonly code?: string;
178
+ readonly message?: string;
179
+ readonly orderToken?: string;
180
+ }
181
+
182
+ export interface PayConfig {
183
+ provider?: string;
184
+ payParams: Record<string, unknown>;
185
+ createOrder?: (payParams: Record<string, unknown>) => unknown | Promise<unknown>;
186
+ pay?: (json: unknown) => PayResult3State | Promise<PayResult3State>;
187
+ }
188
+
189
+ export interface PayProviderRegistration {
190
+ createOrder?: (payParams: Record<string, unknown>) => unknown | Promise<unknown>;
191
+ pay?: (json: unknown) => PayResult3State | Promise<PayResult3State>;
192
+ }
193
+
194
+ export interface PayNamespace {
195
+ getProviders(): Promise<string[]>;
196
+ querySubscriptionOffers(options: {
197
+ provider?: string;
198
+ productIds: readonly string[];
199
+ }): Promise<SubscriptionOffer[]>;
200
+ purchase(config: PayConfig): Promise<PayResult3State>;
201
+ registerProvider(name: string, provider: PayProviderRegistration): void;
202
+ restorePurchases(options?: { provider?: string }): Promise<Record<string, unknown>[]>;
203
+ }
204
+
205
+ export type PushStatus = PushStatusWire;
206
+ export type PushOpenedInfo = PushOpenedPayload;
207
+ export type PushMessage = PushMessagePayload;
208
+
209
+ /**
210
+ * 推送命名空间(SDK-F261008030551 · Android `supersdk-push-firebase`)。
211
+ * 浏览器(无 appbridge):getStatus resolve `{supported:false}`,其余 reject `Error('NOT_SUPPORTED')`;
212
+ * 宿主未接线:getStatus `{supported:false}`,其余 reject `UNSUPPORTED`;iOS 当前 reject `UNSUPPORTED`(stub)。
213
+ * 端内错误为 `Error`,带 `code`(注册表归一后)/ `nativeCode` / `retryable` / `detail`。
214
+ */
215
+ export interface PushNamespace {
216
+ /** 状态快照;`lastOpened` 一次性字段,由首个读到它的 getStatus() 消费,不要在轮询里调用。 */
217
+ getStatus(): Promise<PushStatus>;
218
+ /** 申请通知权限(交互类 · 超时 120000ms);无前台 Activity → `UNAVAILABLE`(retryable)。 */
219
+ requestPermission(): Promise<{ permission: PushPermission }>;
220
+ /** 设置标签;null / [] = 清空。边界(≤10 项 · 每项 ≤32 码点)由 Native 判定 → `INVALID_ARGUMENT`。 */
221
+ setTags(tags: readonly string[] | null): Promise<void>;
222
+ /** 设置业务用户 ID;null / '' = 清除。仅用于推送定向,不是身份认证凭据。≤128 码点由 Native 判定。 */
223
+ setUserId(userId: string | null): Promise<void>;
224
+ /** 前台收到推送(BROADCAST `push.message`);只投递给事件发生时已存活且已订阅的 WebView。 */
225
+ onMessage(callback: (message: PushMessage) => void): () => void;
226
+ /** 推送点击(BROADCAST `push.opened`);与 `getStatus().lastOpened` 按 messageId 去重兜底。 */
227
+ onOpened(callback: (opened: PushOpenedInfo) => void): () => void;
228
+ }
229
+
230
+ /** 实验结果来源:参与(alloc/override/rollout)或未参与的原因。 */
231
+ export type ExperimentReason =
232
+ | 'alloc' | 'override' | 'rollout'
233
+ | 'unknown' | 'paused' | 'no_subject' | 'audience' | 'traffic' | 'not_loaded' | 'no_result'
234
+ | (string & {});
235
+
236
+ export interface ExperimentResult<P extends Record<string, unknown> = Record<string, unknown>> {
237
+ /** 参与实验(含 `rollout` 全量)时为 true。 */
238
+ readonly inExperiment: boolean;
239
+ /** 分组 key;未参与为 ''。 */
240
+ readonly variant: string;
241
+ /** 变体 ID(实验 × 轮次 × 分组);未参与为 null。 */
242
+ readonly vid: number | null;
243
+ /** 分组参数;未参与时为 `options.default ?? {}`。 */
244
+ readonly payload: P;
245
+ readonly reason: ExperimentReason;
246
+ }
247
+
248
+ /** `getAll()` 的条目:`client` 用 `get(key)` 读取;`server` 由后端经请求头读取(`get` 对它返回未参与)。 */
249
+ export interface ExperimentListItem extends ExperimentResult {
250
+ readonly type: 'client' | 'server';
251
+ }
252
+
253
+ export interface ExperimentGetOptions<P extends Record<string, unknown> = Record<string, unknown>> {
254
+ /** false:只读取并冻结,不上报曝光;稍后用 `expose(key)` 补报。默认 true。 */
255
+ expose?: boolean;
256
+ /** 未参与时返回的 payload。 */
257
+ default?: P;
258
+ }
259
+
260
+ export interface ExperimentReadyOptions {
261
+ /** 最长等待毫秒数,到时也 resolve。默认 2000。 */
262
+ timeoutMs?: number;
263
+ /** 追加要加载的命名空间(`^[a-z][a-z0-9_]{1,31}$`,含 default 合计 ≤ 10)。 */
264
+ namespaces?: readonly string[];
265
+ }
266
+
267
+ /**
268
+ * A/B 实验(WS-12)。纯网页端自行调用 assign;首次读取即冻结到页面卸载;默认读取即曝光(每会话、每自然日各去重一次)。
269
+ * 端内(2.6.0 起):容器声明了实验 JSB 时委托原生——拉取、冻结(与原生代码及其他 WebView 共享)、曝光(source `h5`)
270
+ * 与 `exp_vids` 均由原生完成;`get` 同步读取 `ready()`/`refresh()` 建立的镜像,`ready()` 之前读取返回 `no_result` 并冻结。
271
+ * 旧容器(未声明这些方法)保持网页路径(设备 ID 取自端内环境)。
272
+ */
273
+ export interface ExperimentNamespace {
274
+ /** 等待本会话首个可用结果(拉取完成或失败);超时也 resolve。未同意分析时立即 resolve。 */
275
+ ready(options?: ExperimentReadyOptions): Promise<void>;
276
+ /** 同步读取并冻结;默认同时上报 `$exp_exposure`。 */
277
+ get<P extends Record<string, unknown> = Record<string, unknown>>(key: string, options?: ExperimentGetOptions<P>): ExperimentResult<P>;
278
+ /** 为此前以 `expose:false` 读取的实验补报曝光;未参与或未读取过为无操作。 */
279
+ expose(key: string): void;
280
+ /** 诊断用:不冻结、不曝光;已冻结的 key 返回冻结值。每项带 `type`(2.7.0 起,含服务端实验)。 */
281
+ getAll(): Record<string, ExperimentListItem>;
282
+ /** 主动拉取;网络失败 reject(本地结果照常可用)。端内委托模式下为重新读取原生当前结果(原生自行调度拉取)。 */
283
+ refresh(): Promise<void>;
284
+ /** 设置自定义受众属性 `attr.*`(键可带或不带 `attr.` 前缀;null 删除),去抖后重拉。 */
285
+ setAttributes(attributes: Record<string, string | number | boolean | null | undefined>): void;
286
+ /**
287
+ * 服务端实验(2.7.0 起):返回 `{ 'X-Super-AB-Vids': '<已曝光 vid 升序逗号分隔>' }`,集合为空时返回 `{}`。
288
+ * 副作用:已加载命名空间里本设备命中的服务端实验视为已读取(冻结到会话结束、曝光一次、加入已曝光集合)。
289
+ * 端内委托时同步读镜像,`ready()` 之前返回 `{}`。
290
+ */
291
+ getRequestHeaders(): Partial<Record<'X-Super-AB-Vids', string>>;
292
+ /** 返回加上 `super_ab_vids=<vids>` 的 URL(覆盖同名参数,保留其他参数与 hash;集合为空时原样返回)。副作用同 `getRequestHeaders`。 */
293
+ appendVidsToUrl(url: string | URL): string;
294
+ /** 全局 `fetch` 的薄封装:合并 `X-Super-AB-Vids` 后调用(同名头以 SDK 为准,不改 URL)。副作用同 `getRequestHeaders`。 */
295
+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
296
+ }
297
+
84
298
  export interface SuperSDKInstance {
85
299
  readonly sdkVersion: string;
300
+ readonly experiment: ExperimentNamespace;
301
+ readonly bridge: BridgeClient;
302
+ readonly monitoring: MonitoringController;
303
+ readonly pay: PayNamespace;
304
+ readonly push: PushNamespace;
86
305
  init(config: InitConfig): void;
87
306
  initFallback(config: InitConfig): void;
88
307
  isFallbackMode(): boolean;
89
308
  isInApp(): boolean;
90
309
  getEnv(): Promise<Record<string, unknown> & { deviceId?: string }>;
310
+ /**
311
+ * 设置项目环境(web 降级模式生效;端内 reject UNSUPPORTED,环境由原生宿主控制)。
312
+ * 非法值 reject INVALID_ARGUMENT;未初始化 reject NOT_INITIALIZED。
313
+ */
314
+ setAPIEnvironment(environment: string): Promise<void>;
315
+ /** 获取当前项目环境;端内透传原生值,web 未初始化时返回 "prod"。 */
316
+ getAPIEnvironment(): Promise<string>;
91
317
  getAppName(): Promise<string>;
92
318
  getAppIcon(): Promise<string>;
93
319
  getHostSettings<T = Record<string, unknown>>(configName?: string, params?: Record<string, unknown>): Promise<T>;
@@ -98,17 +324,31 @@ export interface SuperSDKInstance {
98
324
  addEventCommonParam(key: string, value: unknown): void;
99
325
  addEventCommonParams(values: Record<string, unknown>): void;
100
326
  reportEvent(name: string, params?: Record<string, unknown>): Promise<QueuedEvent | unknown>;
327
+ /**
328
+ * 提交用户反馈(CA-F260916-user-feedback)。端内经 JSB 由 Native 补齐 spid/env/设备/版本后上报;
329
+ * web 需先 `init()` 提供 baseUrls + spid。`userId` 由调用方按次传入(SDK 不维护用户身份)。
330
+ * 校验失败抛 INVALID_ARGUMENT(web)/ INVALID_PARAMS(端内)。
331
+ */
332
+ submitFeedback(params: FeedbackParams): Promise<FeedbackReceipt>;
101
333
  flush(options?: { keepalive?: boolean }): Promise<FlushSummary>;
102
334
  getDeliveryState(): DeliveryState;
103
335
  onDiagnostic(listener: (diagnostic: Diagnostic) => void): () => void;
336
+ /** 查询本运行时支持的 suenc 响应编码能力;据此决定是否发送 `suenc=1`。 */
337
+ getSuEncCapabilities(): SuEncCapabilities;
338
+ /**
339
+ * 解码 suenc 响应体。`codec` 必须直接使用响应 `X-Su-Enc` header 的原始值,
340
+ * 不接受自定义 table。未知 codec 抛 UNSUPPORTED_SUENC_CODEC,
341
+ * 数据非法抛 SUENC_DECODE_FAILED,解码结果非合法 UTF-8 抛 SUENC_INVALID_UTF8。
342
+ */
343
+ decodeSuEnc(encodedData: string, codec: string): string;
104
344
  installGlobal(): SuperSDKInstance;
105
345
 
106
346
  callHostMethod(methodName: string, params?: Record<string, unknown>): Promise<unknown>;
107
347
  getAuthProviders(): Promise<string[]>;
108
- requestLogin(provider: string, params?: Record<string, unknown>): Promise<unknown>;
348
+ requestLogin(options: { provider: string }): Promise<unknown>;
109
349
  getAttribution(): Promise<unknown>;
110
350
  share(content: string): void;
111
- openPage(url: string, title?: string): void;
351
+ openPage(url: string, options?: { showTitleBar?: boolean }): void;
112
352
  openBrowser(url: string, title?: string): void;
113
353
  openExternal(url: string): void;
114
354
  openWithBrowser(url: string): void;
@@ -124,18 +364,26 @@ export interface SuperSDKInstance {
124
364
  onBackground(callback: (data?: unknown) => void): void;
125
365
  subscribe(event: string, callback: (data: unknown) => void): () => void;
126
366
 
127
- fileExists(path: string): Promise<boolean>;
128
- readFile(path: string): Promise<string>;
367
+ fileExists(path: string): Promise<{ exists: boolean; isFile: boolean; isDirectory: boolean }>;
368
+ readFile(path: string): Promise<{ content: string }>;
129
369
  writeFile(path: string, content: string): Promise<unknown>;
130
370
  deleteFile(path: string): Promise<unknown>;
131
371
  createDir(path: string): Promise<unknown>;
132
- listDir(path: string): Promise<unknown[]>;
372
+ listDir(path: string): Promise<{ files: Array<{ name: string; isFile: boolean; isDirectory: boolean; size: number; lastModified: number }> }>;
133
373
  moveFile(source: string, destination: string): Promise<unknown>;
134
374
  unzipFile(source: string, destination: string): Promise<unknown>;
135
375
  zipDir(source: string, destination: string): Promise<unknown>;
136
- getFileMd5(path: string): Promise<string>;
137
- downloadFile(url: string, destination?: string): Promise<unknown>;
138
- downloadWithCache(url: string, options?: Record<string, unknown>): Promise<unknown>;
376
+ getFileMd5(path: string): Promise<{ md5: string }>;
377
+ downloadFile(options: {
378
+ url: string;
379
+ savePath: string;
380
+ headers?: Record<string, string>;
381
+ onStart?: () => void;
382
+ onProgress?: (progress: { progress: number; downloadedBytes: number; totalBytes: number }) => void;
383
+ onSuccess?: (result: { filePath: string; downloadedBytes: number; totalBytes: number }) => void;
384
+ onFail?: (result: { error: unknown }) => void;
385
+ }): () => void;
386
+ downloadWithCache(fileUrl: string, fileMd5?: string, cacheTts?: number, fileCacheKey?: string): Promise<{ filePath: string; cacheHit: boolean; cacheKey: string }>;
139
387
 
140
388
  showBannerAd(...args: unknown[]): Promise<unknown> | unknown;
141
389
  hideBannerAd(...args: unknown[]): Promise<unknown> | unknown;
@@ -155,7 +403,26 @@ export interface CreateSuperSDKOptions {
155
403
  crypto?: Crypto;
156
404
  now?: () => number;
157
405
  random?: () => number;
406
+ diagnosticSink?: (diagnostic: Diagnostic) => void;
407
+ bridgeClock?: () => number;
408
+ bridgeSetTimeout?: (handler: () => void, timeoutMs: number) => unknown;
409
+ bridgeClearTimeout?: (timer: unknown) => void;
410
+ monitoringSetTimeout?: (handler: () => void, timeoutMs: number) => unknown;
411
+ monitoringClearTimeout?: (timer: unknown) => void;
412
+ }
413
+
414
+ export interface MonitoringBudgets { pageEnvelopes: number; sessionEnvelopes: number; bytesPerMinute: number; envelopeBytes: number; aggregationKeys: number; errorFingerprintsPerPage: number }
415
+ export interface MonitoringRemoteAdapter { deliver(envelope: MonitoringEnvelopeV1, context: { signal: AbortSignal }): void | Promise<void> }
416
+ export interface MonitoringStartOptions {
417
+ budgets?: Partial<MonitoringBudgets>;
418
+ sampleRates?: Partial<{ errors: number; performance: number }>;
419
+ beforeSend?: (envelope: MonitoringEnvelopeV1) => MonitoringEnvelopeV1 | null;
420
+ routeAdapter?: { subscribe(onRoute: () => void): () => void };
421
+ remoteAdapter?: MonitoringRemoteAdapter | { kind: 'reportEventV2' };
158
422
  }
423
+ export interface MonitoringState { readonly status: 'stopped'|'dormant'|'active'; readonly generation: number; readonly consent: MonitoringConsent; readonly runtimeSessionId: string|null; readonly activeCollectors: readonly string[]; readonly remoteStatus: 'disabled'|'ready'|'in_flight'|'blocked'|'degraded' }
424
+ export interface MonitoringSnapshot { readonly state: MonitoringState; readonly context: Readonly<Record<string, unknown>>|null; readonly aggregates: readonly Readonly<Record<string, unknown>>[]; readonly measurements: readonly Readonly<Record<string, unknown>>[]; readonly drops: Readonly<Record<string, number>>; readonly recent: readonly MonitoringEnvelopeV1[] }
425
+ export interface MonitoringController { start(options?: MonitoringStartOptions): MonitoringState; stop(): MonitoringState; getState(): MonitoringState; getSnapshot(): MonitoringSnapshot; onEnvelope(listener: (envelope: MonitoringEnvelopeV1) => void): () => void; setConsent(next: Partial<MonitoringConsent>): MonitoringConsent; getConsent(): MonitoringConsent }
159
426
 
160
427
  export function createSuperSDK(options?: CreateSuperSDKOptions): SuperSDKInstance;
161
428
  export function installGlobal(target?: typeof globalThis | Record<string, unknown>): SuperSDKInstance;