pcific 0.0.0-stage → 0.2.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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/SKILL.md +127 -0
  4. package/dist/api/catalog.js +637 -0
  5. package/dist/api/run.js +960 -0
  6. package/dist/api/search.js +171 -0
  7. package/dist/api/shortcuts.js +799 -0
  8. package/dist/bin.js +648 -0
  9. package/dist/commands/auth.js +513 -0
  10. package/dist/commands/doctor.js +410 -0
  11. package/dist/commands/init.js +306 -0
  12. package/dist/commands/sync.js +214 -0
  13. package/dist/detect.js +214 -0
  14. package/dist/env.js +339 -0
  15. package/dist/goLive.js +629 -0
  16. package/dist/keyLink.js +305 -0
  17. package/dist/mcp/server.js +206 -0
  18. package/dist/mcp/tools.js +689 -0
  19. package/dist/python/template.js +793 -0
  20. package/dist/schema/discover.js +324 -0
  21. package/dist/schema/helpers.js +396 -0
  22. package/dist/schema/prismaToJsonSchema.js +197 -0
  23. package/dist/schema/push.js +570 -0
  24. package/dist/schema/tsToJsonSchema.js +405 -0
  25. package/dist/schema/zodToJsonSchema.js +442 -0
  26. package/dist/templates/openapi.json +1 -0
  27. package/dist/templates/sdk/auth.ts +139 -0
  28. package/dist/templates/sdk/client.ts +1059 -0
  29. package/dist/templates/sdk/errors.ts +76 -0
  30. package/dist/templates/sdk/generated-types.ts +5746 -0
  31. package/dist/templates/sdk/http.ts +359 -0
  32. package/dist/templates/sdk/index.ts +84 -0
  33. package/dist/templates/sdk/json.ts +24 -0
  34. package/dist/templates/sdk/kit.ts +516 -0
  35. package/dist/templates/sdk/multipart.ts +99 -0
  36. package/dist/templates/sdk/sse.ts +131 -0
  37. package/dist/templates/sdk/verify.ts +766 -0
  38. package/dist/templates/sdk-js/auth.d.ts +20 -0
  39. package/dist/templates/sdk-js/auth.js +85 -0
  40. package/dist/templates/sdk-js/client.d.ts +324 -0
  41. package/dist/templates/sdk-js/client.js +607 -0
  42. package/dist/templates/sdk-js/errors.d.ts +51 -0
  43. package/dist/templates/sdk-js/errors.js +48 -0
  44. package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
  45. package/dist/templates/sdk-js/generated-types.js +5 -0
  46. package/dist/templates/sdk-js/http.d.ts +50 -0
  47. package/dist/templates/sdk-js/http.js +263 -0
  48. package/dist/templates/sdk-js/index.d.ts +9 -0
  49. package/dist/templates/sdk-js/index.js +7 -0
  50. package/dist/templates/sdk-js/json.d.ts +11 -0
  51. package/dist/templates/sdk-js/json.js +16 -0
  52. package/dist/templates/sdk-js/kit.d.ts +220 -0
  53. package/dist/templates/sdk-js/kit.js +208 -0
  54. package/dist/templates/sdk-js/multipart.d.ts +23 -0
  55. package/dist/templates/sdk-js/multipart.js +61 -0
  56. package/dist/templates/sdk-js/sse.d.ts +12 -0
  57. package/dist/templates/sdk-js/sse.js +99 -0
  58. package/dist/templates/sdk-js/verify.d.ts +114 -0
  59. package/dist/templates/sdk-js/verify.js +506 -0
  60. package/dist/templates.js +925 -0
  61. package/dist/ui.js +399 -0
  62. package/dist/webhooks/events.js +171 -0
  63. package/dist/webhooks/listen.js +772 -0
  64. package/package.json +32 -4
@@ -0,0 +1,1059 @@
1
+ import { resolvePcificAuth, type PcificMode, type ResolvePcificAuthOptions } from "./auth.js";
2
+ import { PcificStreamError } from "./errors.js";
3
+ import { PcificHttpClient, type RequestOptions } from "./http.js";
4
+ import { isJsonObject, isString, type JsonObject } from "./json.js";
5
+ import { normalizeUpload, type UploadInput } from "./multipart.js";
6
+ import { parseSseStream, type SseFrame } from "./sse.js";
7
+ import {
8
+ verifyMessageCheckReceipt,
9
+ verifyPixelTraceManifest,
10
+ type JsonWebKeySet,
11
+ type VerifyMessageCheckReceiptOptions,
12
+ type VerifyMessageCheckReceiptResult,
13
+ type VerifyPixelTraceManifestOptions,
14
+ type VerifyPixelTraceManifestResult,
15
+ } from "./verify.js";
16
+
17
+ export interface PcificClientOptions extends ResolvePcificAuthOptions {
18
+ baseUrl?: string;
19
+ signingSecret?: string;
20
+ marketplaceId?: string;
21
+ testAiStub?: boolean;
22
+ fetch?: typeof globalThis.fetch;
23
+ maxRetries?: number;
24
+ baseDelayMs?: number;
25
+ maxDelayMs?: number;
26
+ sleep?: (ms: number) => Promise<void>;
27
+ now?: () => number;
28
+ random?: () => number;
29
+ aiNoticeTtlMs?: number;
30
+ }
31
+
32
+ export interface MoneyMinorUnits {
33
+ amount: number;
34
+ currency: string;
35
+ }
36
+
37
+ export interface WaitOptions extends RequestOptions {
38
+ mode?: "sse" | "poll";
39
+ pollIntervalMs?: number;
40
+ timeoutMs?: number;
41
+ onStatus?: (snapshot: JsonObject) => void;
42
+ }
43
+
44
+ export interface GetAiNoticeOptions extends RequestOptions {
45
+ ttlMs?: number;
46
+ forceRefresh?: boolean;
47
+ }
48
+
49
+ export interface CreateListingInput {
50
+ notes?: string | null;
51
+ details?: JsonObject | null;
52
+ images?: string[] | null;
53
+ category?: string | null;
54
+ price?: boolean | null;
55
+ safeguard?: boolean | null;
56
+ faq?: boolean | null;
57
+ modelTier?: "standard" | "ultra-fast" | null;
58
+ listingRef?: string | null;
59
+ editChat?: boolean | null;
60
+ }
61
+
62
+ export interface CreateReviewInput {
63
+ category?: string | null;
64
+ listing?: JsonObject | null;
65
+ images?: string[] | null;
66
+ requirePhotos?: boolean | null;
67
+ sellerNotes?: string | null;
68
+ orbitRunId?: string | null;
69
+ review?: boolean | null;
70
+ faq?: boolean | null;
71
+ rewrite?: boolean | string[] | null;
72
+ modelTier?: "standard" | "ultra-fast" | null;
73
+ listingRef?: string | null;
74
+ }
75
+
76
+ export interface AskPcificInput {
77
+ question: string;
78
+ quotes?: boolean;
79
+ modelTier?: "standard" | "ultra-fast" | null;
80
+ conversationId?: string | null;
81
+ buyer?: { accountId?: string | null } | null;
82
+ item?: {
83
+ id?: string | number | null;
84
+ type?: string | null;
85
+ title?: string | null;
86
+ url?: string | null;
87
+ reservedForAccountId?: string | null;
88
+ price?: MoneyMinorUnits;
89
+ details?: Record<string, string | number | boolean | null> | null;
90
+ } | null;
91
+ }
92
+
93
+ export interface MessageCheckSender {
94
+ id?: string;
95
+ accountCreatedAt?: string;
96
+ accountAgeDays?: number;
97
+ completedOrders?: number;
98
+ }
99
+
100
+ export interface MessageCheckInput {
101
+ text: string;
102
+ conversationId?: string;
103
+ sender?: MessageCheckSender;
104
+ context?: {
105
+ orderPlaced?: boolean;
106
+ recentMessages?: Array<{ text: string; fromSender: boolean }>;
107
+ };
108
+ confirmToken?: string;
109
+ metadata?: JsonObject;
110
+ }
111
+
112
+ export interface MessageCheckPresentInput {
113
+ conversationId?: string;
114
+ messages: Array<{
115
+ id: string;
116
+ text: string;
117
+ sender?: MessageCheckSender;
118
+ context?: { orderPlaced?: boolean };
119
+ }>;
120
+ }
121
+
122
+ export interface MessageCheckVerifyOnlineInput {
123
+ receipt: string;
124
+ text: string;
125
+ maskedText?: string;
126
+ conversationId?: string;
127
+ senderId?: string;
128
+ }
129
+
130
+ export interface DisputePackPushListingInput {
131
+ listingRef: string;
132
+ listing: JsonObject | string;
133
+ occurredAt?: string;
134
+ photos?: UploadInput[];
135
+ }
136
+
137
+ export interface DisputePackRecordSaleInput {
138
+ listingRef: string;
139
+ buyerId: string;
140
+ orderId: string;
141
+ soldAt: string;
142
+ price: MoneyMinorUnits;
143
+ }
144
+
145
+ export interface DisputePackRecordMessageInput {
146
+ listingRef: string;
147
+ buyerId: string;
148
+ role: "buyer" | "seller";
149
+ messageId: string;
150
+ sentAt: string;
151
+ text: string;
152
+ attachments?: Array<{ name?: string; contentType?: string }>;
153
+ }
154
+
155
+ export interface DisputePackRecordTrackingInput {
156
+ listingRef?: string;
157
+ orderId: string;
158
+ carrier: string;
159
+ trackingNumber: string;
160
+ events?: Array<{ at?: string; status?: string; location?: string }>;
161
+ deliveredAt?: string | null;
162
+ }
163
+
164
+ export interface DisputePackCreateDisputeInput {
165
+ listingRef: string;
166
+ buyerId: string;
167
+ orderId: string;
168
+ disputeId: string;
169
+ reason: string;
170
+ note?: string;
171
+ sellerEmail?: string;
172
+ }
173
+
174
+ export interface EmbedSessionInput {
175
+ origin: string;
176
+ tools: Array<"orbit" | "safeguard" | "ask-pcific" | "pixel-trace" | "message-check">;
177
+ minutes?: number;
178
+ chat?: {
179
+ conversationId?: string;
180
+ sender: MessageCheckSender & { id: string };
181
+ orderPlaced?: boolean;
182
+ };
183
+ }
184
+
185
+ const DEFAULT_AI_NOTICE_TTL_MS = 5 * 60 * 1000;
186
+
187
+ const ORBIT_TERMINAL_STATUSES = new Set(["listing", "questions", "failed", "cancelled"]);
188
+
189
+ const SAFEGUARD_TERMINAL_STATUSES = new Set(["done", "questions", "failed"]);
190
+
191
+ function encodePathSegment(segment: string): string {
192
+ return encodeURIComponent(segment);
193
+ }
194
+
195
+ function isStringId(value: string | CreateListingInput | CreateReviewInput): value is string {
196
+ return typeof value === "string";
197
+ }
198
+
199
+ function isRawListingJson(value: JsonObject | string): value is string {
200
+ return typeof value === "string";
201
+ }
202
+
203
+ export class PcificClient {
204
+ readonly mode: PcificMode;
205
+ readonly http: PcificHttpClient;
206
+
207
+ private readonly aiNoticeCache = new Map<string, { value: string; expiresAt: number }>();
208
+ private readonly defaultAiNoticeTtlMs: number;
209
+
210
+ constructor(options: PcificClientOptions = {}) {
211
+ const auth = resolvePcificAuth(options);
212
+ this.mode = auth.mode;
213
+ this.defaultAiNoticeTtlMs = options.aiNoticeTtlMs ?? DEFAULT_AI_NOTICE_TTL_MS;
214
+ this.http = new PcificHttpClient({
215
+ apiKey: auth.apiKey,
216
+ baseUrl: options.baseUrl,
217
+ signingSecret: options.signingSecret,
218
+ marketplaceId: options.marketplaceId,
219
+ testAiStub: options.testAiStub,
220
+ fetch: options.fetch,
221
+ maxRetries: options.maxRetries,
222
+ baseDelayMs: options.baseDelayMs,
223
+ maxDelayMs: options.maxDelayMs,
224
+ sleep: options.sleep,
225
+ now: options.now,
226
+ random: options.random,
227
+ });
228
+ }
229
+
230
+ /**
231
+ * Reads and caches the shop's aiNotice from GET /api/v1/marketplace/settings.
232
+ * Explicitly preserves "" (empty string) as a cached valid value (never treating "" as a cache miss).
233
+ */
234
+ async getAiNotice(options: GetAiNoticeOptions = {}): Promise<string> {
235
+ const cacheKey = options.marketplaceId ?? this.http.config.marketplaceId ?? "__default__";
236
+ const nowMs = this.http.config.now();
237
+ const ttlMs = options.ttlMs ?? this.defaultAiNoticeTtlMs;
238
+
239
+ if (!options.forceRefresh && this.aiNoticeCache.has(cacheKey)) {
240
+ const entry = this.aiNoticeCache.get(cacheKey)!;
241
+
242
+ if (entry.expiresAt > nowMs) {
243
+ return entry.value;
244
+ }
245
+ }
246
+
247
+ const settings = await this.account.getSettings(options);
248
+ const notice = isString(settings.aiNotice) ? settings.aiNotice : "";
249
+ this.aiNoticeCache.set(cacheKey, { value: notice, expiresAt: nowMs + ttlMs });
250
+
251
+ return notice;
252
+ }
253
+
254
+ invalidateAiNoticeCache(marketplaceId?: string): void {
255
+ if (marketplaceId === undefined) {
256
+ this.aiNoticeCache.clear();
257
+
258
+ return;
259
+ }
260
+
261
+ this.aiNoticeCache.delete(marketplaceId);
262
+ }
263
+
264
+ // --- Images ----------------------------------------------------------------
265
+
266
+ readonly images = {
267
+ upload: async (
268
+ files: UploadInput[],
269
+ options?: RequestOptions,
270
+ ): Promise<{ images: JsonObject[]; problems?: JsonObject[] }> => {
271
+ const formData = new FormData();
272
+ files.forEach((file, index) => {
273
+ const normalized = normalizeUpload(file, `photo-${index + 1}.jpg`, "image/jpeg");
274
+ formData.append("photos", normalized.blob, normalized.filename);
275
+ });
276
+
277
+ return this.http.requestJson({
278
+ ...options,
279
+ method: "POST",
280
+ path: "/api/v1/images",
281
+ formData,
282
+ });
283
+ },
284
+
285
+ get: (id: string, options?: RequestOptions): Promise<JsonObject> =>
286
+ this.http.requestJson({
287
+ ...options,
288
+ method: "GET",
289
+ path: `/api/v1/images/${encodePathSegment(id)}`,
290
+ }),
291
+
292
+ delete: (id: string, options?: RequestOptions): Promise<void> =>
293
+ this.http.requestVoid({
294
+ ...options,
295
+ method: "DELETE",
296
+ path: `/api/v1/images/${encodePathSegment(id)}`,
297
+ }),
298
+ };
299
+
300
+ // --- Orbit -----------------------------------------------------------------
301
+
302
+ readonly orbit = {
303
+ createListing: (input: CreateListingInput, options?: RequestOptions): Promise<JsonObject> =>
304
+ this.http.requestJson({
305
+ ...options,
306
+ method: "POST",
307
+ path: "/api/v1/listings",
308
+ jsonBody: input,
309
+ }),
310
+
311
+ getListing: (id: string, options?: RequestOptions): Promise<JsonObject> =>
312
+ this.http.requestJson({
313
+ ...options,
314
+ method: "GET",
315
+ path: `/api/v1/listings/${encodePathSegment(id)}`,
316
+ }),
317
+
318
+ streamListing: async function* (
319
+ this: PcificClient,
320
+ idOrInput: string | CreateListingInput,
321
+ options?: RequestOptions,
322
+ ): AsyncGenerator<SseFrame<JsonObject>, void, undefined> {
323
+ const stream = isStringId(idOrInput)
324
+ ? await this.http.requestStream({
325
+ ...options,
326
+ method: "GET",
327
+ path: `/api/v1/listings/${encodePathSegment(idOrInput)}`,
328
+ })
329
+ : await this.http.requestStream({
330
+ ...options,
331
+ method: "POST",
332
+ path: "/api/v1/listings",
333
+ jsonBody: idOrInput,
334
+ });
335
+
336
+ yield* parseSseStream<JsonObject>(stream);
337
+ }.bind(this),
338
+
339
+ waitForListing: async (
340
+ idOrInput: string | CreateListingInput,
341
+ options: WaitOptions = {},
342
+ ): Promise<JsonObject> => {
343
+ if (options.mode !== "poll") {
344
+ let lastSnapshot: JsonObject | undefined;
345
+
346
+ for await (const frame of this.orbit.streamListing(idOrInput, options)) {
347
+ if (frame.event === "status" && isJsonObject(frame.data)) {
348
+ lastSnapshot = frame.data;
349
+ options.onStatus?.(frame.data);
350
+ } else if (frame.event === "done") {
351
+ return frame.data;
352
+ } else if (frame.event === "error") {
353
+ if (isJsonObject(frame.data) && "status" in frame.data) {
354
+ return frame.data;
355
+ }
356
+
357
+ throw new PcificStreamError(
358
+ isJsonObject(frame.data) && isString(frame.data.error)
359
+ ? frame.data.error
360
+ : "Orbit stream failed.",
361
+ {
362
+ code: isJsonObject(frame.data) && isString(frame.data.code) ? frame.data.code : undefined,
363
+ tryThis: isJsonObject(frame.data) && isString(frame.data.tryThis) ? frame.data.tryThis : undefined,
364
+ payload: frame.data,
365
+ },
366
+ );
367
+ }
368
+ }
369
+
370
+ if (lastSnapshot) return lastSnapshot;
371
+ throw new PcificStreamError("Orbit event stream closed before reaching a terminal state.");
372
+ }
373
+
374
+ const id = isStringId(idOrInput)
375
+ ? idOrInput
376
+ : String((await this.orbit.createListing(idOrInput, options)).runId ?? "");
377
+
378
+ const pollIntervalMs = options.pollIntervalMs ?? 1000;
379
+ const timeoutMs = options.timeoutMs ?? 180_000;
380
+ const deadline = this.http.config.now() + timeoutMs;
381
+
382
+ while (true) {
383
+ const snapshot = await this.orbit.getListing(id, options);
384
+ options.onStatus?.(snapshot);
385
+ const status = isString(snapshot.status) ? snapshot.status : "";
386
+
387
+ if (ORBIT_TERMINAL_STATUSES.has(status) && snapshot.processing !== true) {
388
+ return snapshot;
389
+ }
390
+
391
+ if (this.http.config.now() >= deadline) {
392
+ return snapshot;
393
+ }
394
+
395
+ await this.http.config.sleep(pollIntervalMs);
396
+ }
397
+ },
398
+
399
+ answerQuestions: (
400
+ id: string,
401
+ answers: Array<{ id: string; answer: string }>,
402
+ options?: RequestOptions,
403
+ ): Promise<JsonObject> =>
404
+ this.http.requestJson({
405
+ ...options,
406
+ method: "POST",
407
+ path: `/api/v1/listings/${encodePathSegment(id)}/answers`,
408
+ jsonBody: { answers },
409
+ }),
410
+
411
+ retry: (id: string, options?: RequestOptions): Promise<JsonObject> =>
412
+ this.http.requestJson({
413
+ ...options,
414
+ method: "POST",
415
+ path: `/api/v1/listings/${encodePathSegment(id)}/retry`,
416
+ }),
417
+
418
+ cancel: (id: string, options?: RequestOptions): Promise<JsonObject> =>
419
+ this.http.requestJson({
420
+ ...options,
421
+ method: "POST",
422
+ path: `/api/v1/listings/${encodePathSegment(id)}/cancel`,
423
+ }),
424
+
425
+ publish: (id: string, options?: RequestOptions): Promise<JsonObject> =>
426
+ this.http.requestJson({
427
+ ...options,
428
+ method: "POST",
429
+ path: `/api/v1/listings/${encodePathSegment(id)}/publish`,
430
+ }),
431
+
432
+ check: (id: string, options?: RequestOptions): Promise<JsonObject> =>
433
+ this.http.requestJson({
434
+ ...options,
435
+ method: "POST",
436
+ path: `/api/v1/listings/${encodePathSegment(id)}/check`,
437
+ }),
438
+
439
+ submitEdits: (id: string, item: JsonObject, options?: RequestOptions): Promise<JsonObject> =>
440
+ this.http.requestJson({
441
+ ...options,
442
+ method: "POST",
443
+ path: `/api/v1/listings/${encodePathSegment(id)}/edits`,
444
+ jsonBody: { item },
445
+ }),
446
+
447
+ chat: (
448
+ id: string,
449
+ input: { message: string } | { accept: true },
450
+ options?: RequestOptions,
451
+ ): Promise<JsonObject> =>
452
+ this.http.requestJson({
453
+ ...options,
454
+ method: "POST",
455
+ path: `/api/v1/listings/${encodePathSegment(id)}/chat`,
456
+ jsonBody: input,
457
+ }),
458
+
459
+ reportOutcome: (
460
+ id: string,
461
+ input: {
462
+ event: "published" | "abandoned";
463
+ changes?: Array<{ field: string; percentChanged: number }>;
464
+ finalListing?: JsonObject | null;
465
+ },
466
+ options?: RequestOptions,
467
+ ): Promise<JsonObject> =>
468
+ this.http.requestJson({
469
+ ...options,
470
+ method: "POST",
471
+ path: `/api/v1/listings/${encodePathSegment(id)}/outcome`,
472
+ jsonBody: input,
473
+ }),
474
+
475
+ getSettings: (options?: RequestOptions): Promise<JsonObject> =>
476
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/orbit/settings" }),
477
+
478
+ updateSettings: (settings: JsonObject, options?: RequestOptions): Promise<JsonObject> =>
479
+ this.http.requestJson({
480
+ ...options,
481
+ method: "PUT",
482
+ path: "/api/v1/orbit/settings",
483
+ jsonBody: settings,
484
+ }),
485
+ };
486
+
487
+ // --- Safeguard -------------------------------------------------------------
488
+
489
+ readonly safeguard = {
490
+ createReview: (input: CreateReviewInput, options?: RequestOptions): Promise<JsonObject> =>
491
+ this.http.requestJson({
492
+ ...options,
493
+ method: "POST",
494
+ path: "/api/v1/safeguard/reviews",
495
+ jsonBody: input,
496
+ }),
497
+
498
+ getReview: (id: string, options?: RequestOptions): Promise<JsonObject> =>
499
+ this.http.requestJson({
500
+ ...options,
501
+ method: "GET",
502
+ path: `/api/v1/safeguard/reviews/${encodePathSegment(id)}`,
503
+ }),
504
+
505
+ streamReview: async function* (
506
+ this: PcificClient,
507
+ idOrInput: string | CreateReviewInput,
508
+ options?: RequestOptions,
509
+ ): AsyncGenerator<SseFrame<JsonObject>, void, undefined> {
510
+ const stream = isStringId(idOrInput)
511
+ ? await this.http.requestStream({
512
+ ...options,
513
+ method: "GET",
514
+ path: `/api/v1/safeguard/reviews/${encodePathSegment(idOrInput)}`,
515
+ })
516
+ : await this.http.requestStream({
517
+ ...options,
518
+ method: "POST",
519
+ path: "/api/v1/safeguard/reviews",
520
+ jsonBody: idOrInput,
521
+ });
522
+
523
+ yield* parseSseStream<JsonObject>(stream);
524
+ }.bind(this),
525
+
526
+ waitForReview: async (
527
+ idOrInput: string | CreateReviewInput,
528
+ options: WaitOptions = {},
529
+ ): Promise<JsonObject> => {
530
+ if (options.mode !== "poll") {
531
+ let lastSnapshot: JsonObject | undefined;
532
+
533
+ for await (const frame of this.safeguard.streamReview(idOrInput, options)) {
534
+ if (frame.event === "status" && isJsonObject(frame.data)) {
535
+ lastSnapshot = frame.data;
536
+ options.onStatus?.(frame.data);
537
+ } else if (frame.event === "done") {
538
+ return frame.data;
539
+ } else if (frame.event === "error") {
540
+ if (isJsonObject(frame.data) && "status" in frame.data) {
541
+ return frame.data;
542
+ }
543
+
544
+ throw new PcificStreamError(
545
+ isJsonObject(frame.data) && isString(frame.data.error)
546
+ ? frame.data.error
547
+ : "Safeguard stream failed.",
548
+ {
549
+ code: isJsonObject(frame.data) && isString(frame.data.code) ? frame.data.code : undefined,
550
+ tryThis: isJsonObject(frame.data) && isString(frame.data.tryThis) ? frame.data.tryThis : undefined,
551
+ payload: frame.data,
552
+ },
553
+ );
554
+ }
555
+ }
556
+
557
+ if (lastSnapshot) return lastSnapshot;
558
+ throw new PcificStreamError("Safeguard event stream closed before reaching a terminal state.");
559
+ }
560
+
561
+ const id = isStringId(idOrInput)
562
+ ? idOrInput
563
+ : String((await this.safeguard.createReview(idOrInput, options)).reviewId ?? "");
564
+
565
+ const pollIntervalMs = options.pollIntervalMs ?? 1000;
566
+ const timeoutMs = options.timeoutMs ?? 180_000;
567
+ const deadline = this.http.config.now() + timeoutMs;
568
+
569
+ while (true) {
570
+ const snapshot = await this.safeguard.getReview(id, options);
571
+ options.onStatus?.(snapshot);
572
+ const status = isString(snapshot.status) ? snapshot.status : "";
573
+
574
+ if (SAFEGUARD_TERMINAL_STATUSES.has(status)) {
575
+ return snapshot;
576
+ }
577
+
578
+ if (this.http.config.now() >= deadline) {
579
+ return snapshot;
580
+ }
581
+
582
+ await this.http.config.sleep(pollIntervalMs);
583
+ }
584
+ },
585
+
586
+ answerQuestions: (
587
+ id: string,
588
+ answers: Array<{ id: string; answer: string }>,
589
+ options?: RequestOptions,
590
+ ): Promise<JsonObject> =>
591
+ this.http.requestJson({
592
+ ...options,
593
+ method: "POST",
594
+ path: `/api/v1/safeguard/reviews/${encodePathSegment(id)}/answers`,
595
+ jsonBody: { answers },
596
+ }),
597
+
598
+ retry: (id: string, options?: RequestOptions): Promise<JsonObject> =>
599
+ this.http.requestJson({
600
+ ...options,
601
+ method: "POST",
602
+ path: `/api/v1/safeguard/reviews/${encodePathSegment(id)}/retry`,
603
+ }),
604
+
605
+ getSettings: (options?: RequestOptions): Promise<JsonObject> =>
606
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/safeguard/settings" }),
607
+
608
+ updateSettings: (settings: JsonObject, options?: RequestOptions): Promise<JsonObject> =>
609
+ this.http.requestJson({
610
+ ...options,
611
+ method: "PUT",
612
+ path: "/api/v1/safeguard/settings",
613
+ jsonBody: settings,
614
+ }),
615
+ };
616
+
617
+ // --- Ask PCIFIC ------------------------------------------------------------
618
+
619
+ readonly askPcific = {
620
+ ask: (input: AskPcificInput, options?: RequestOptions): Promise<JsonObject> =>
621
+ this.http.requestJson({
622
+ ...options,
623
+ method: "POST",
624
+ path: "/api/v1/ask-pcific",
625
+ jsonBody: input,
626
+ }),
627
+
628
+ askStream: async function* (
629
+ this: PcificClient,
630
+ input: AskPcificInput,
631
+ options?: RequestOptions,
632
+ ): AsyncGenerator<SseFrame<JsonObject>, void, undefined> {
633
+ const stream = await this.http.requestStream({
634
+ ...options,
635
+ method: "POST",
636
+ path: "/api/v1/ask-pcific",
637
+ jsonBody: input,
638
+ });
639
+
640
+ yield* parseSseStream<JsonObject>(stream);
641
+ }.bind(this),
642
+
643
+ getSettings: (options?: RequestOptions): Promise<JsonObject> =>
644
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/ask-pcific/settings" }),
645
+
646
+ updateSettings: (settings: JsonObject, options?: RequestOptions): Promise<JsonObject> =>
647
+ this.http.requestJson({
648
+ ...options,
649
+ method: "PUT",
650
+ path: "/api/v1/ask-pcific/settings",
651
+ jsonBody: settings,
652
+ }),
653
+ };
654
+
655
+ // --- PixelTrace ------------------------------------------------------------
656
+
657
+ readonly pixelTrace = {
658
+ createCapture: (
659
+ input: { listingId: string; listingTitle?: string; listingRef?: string | null },
660
+ options?: RequestOptions,
661
+ ): Promise<JsonObject> =>
662
+ this.http.requestJson({
663
+ ...options,
664
+ method: "POST",
665
+ path: "/api/v1/pixel-trace/captures",
666
+ jsonBody: input,
667
+ }),
668
+
669
+ getCapture: (captureId: string, options?: RequestOptions): Promise<JsonObject> =>
670
+ this.http.requestJson({
671
+ ...options,
672
+ method: "GET",
673
+ path: `/api/v1/pixel-trace/captures/${encodePathSegment(captureId)}`,
674
+ }),
675
+
676
+ completeCapture: (
677
+ captureId: string,
678
+ input: { marketplaceName?: string; listingUrl?: string } = {},
679
+ options?: RequestOptions,
680
+ ): Promise<JsonObject> =>
681
+ this.http.requestJson({
682
+ ...options,
683
+ method: "POST",
684
+ path: `/api/v1/pixel-trace/captures/${encodePathSegment(captureId)}/complete`,
685
+ jsonBody: input,
686
+ }),
687
+
688
+ publishCapture: (
689
+ captureId: string,
690
+ input: { marketplaceName?: string; listingUrl?: string } = {},
691
+ options?: RequestOptions,
692
+ ): Promise<JsonObject> => this.pixelTrace.completeCapture(captureId, input, options),
693
+
694
+ retractCapture: (captureId: string, options?: RequestOptions): Promise<JsonObject> =>
695
+ this.http.requestJson({
696
+ ...options,
697
+ method: "POST",
698
+ path: `/api/v1/pixel-trace/captures/${encodePathSegment(captureId)}/retract`,
699
+ }),
700
+
701
+ checkPhoto: async (photo: UploadInput, options?: RequestOptions): Promise<JsonObject> => {
702
+ const normalized = normalizeUpload(photo, "photo.jpg", "image/jpeg");
703
+ const bytes = new Uint8Array(await normalized.blob.arrayBuffer());
704
+
705
+ return this.http.requestJson({
706
+ ...options,
707
+ method: "POST",
708
+ path: "/api/v1/pixel-trace/check",
709
+ binaryBody: { bytes, contentType: normalized.contentType },
710
+ });
711
+ },
712
+
713
+ getCertificate: (code: string, options?: RequestOptions): Promise<JsonObject> =>
714
+ this.http.requestJson({
715
+ ...options,
716
+ method: "GET",
717
+ path: `/api/v1/pixel-trace/certificates/${encodePathSegment(code)}`,
718
+ auth: false,
719
+ }),
720
+
721
+ getJwks: (options?: RequestOptions): Promise<JsonWebKeySet> =>
722
+ this.http.requestJson({
723
+ ...options,
724
+ method: "GET",
725
+ path: "/api/v1/pixel-trace/jwks.json",
726
+ auth: false,
727
+ }),
728
+
729
+ verifyManifest: (
730
+ input: Omit<VerifyPixelTraceManifestOptions, "fetch" | "jwksUrl"> & { jwksUrl?: string },
731
+ ): Promise<VerifyPixelTraceManifestResult> =>
732
+ verifyPixelTraceManifest({
733
+ ...input,
734
+ jwksUrl: input.jwksUrl ?? `${this.http.config.baseUrl}/api/v1/pixel-trace/jwks.json`,
735
+ fetch: this.http.config.fetch,
736
+ }),
737
+
738
+ uploadTestPhoto: async (
739
+ captureId: string,
740
+ photo: UploadInput,
741
+ options?: RequestOptions,
742
+ ): Promise<JsonObject> => {
743
+ const normalized = normalizeUpload(photo, "photo.jpg", "image/jpeg");
744
+ const bytes = new Uint8Array(await normalized.blob.arrayBuffer());
745
+
746
+ return this.http.requestJson({
747
+ ...options,
748
+ method: "POST",
749
+ path: `/api/v1/pixel-trace/captures/${encodePathSegment(captureId)}/test-photos`,
750
+ binaryBody: { bytes, contentType: normalized.contentType },
751
+ });
752
+ },
753
+
754
+ confirmTestCapture: (
755
+ captureId: string,
756
+ input: { photoIds?: string[] } = {},
757
+ options?: RequestOptions,
758
+ ): Promise<JsonObject> =>
759
+ this.http.requestJson({
760
+ ...options,
761
+ method: "POST",
762
+ path: `/api/v1/pixel-trace/captures/${encodePathSegment(captureId)}/test-confirm`,
763
+ jsonBody: input,
764
+ }),
765
+ };
766
+
767
+ // --- Message Check ---------------------------------------------------------
768
+
769
+ readonly messageCheck = {
770
+ check: (input: MessageCheckInput, options?: RequestOptions): Promise<JsonObject> => {
771
+ const body: MessageCheckInput = { text: input.text };
772
+
773
+ if (input.conversationId !== undefined) body.conversationId = input.conversationId;
774
+
775
+ if (input.sender !== undefined) body.sender = input.sender;
776
+
777
+ if (input.context !== undefined) body.context = input.context;
778
+
779
+ if (input.confirmToken !== undefined) body.confirmToken = input.confirmToken;
780
+
781
+ if (input.metadata !== undefined) body.metadata = input.metadata;
782
+
783
+ return this.http.requestJson({
784
+ ...options,
785
+ method: "POST",
786
+ path: "/api/v1/message-check",
787
+ jsonBody: body,
788
+ });
789
+ },
790
+
791
+ present: (input: MessageCheckPresentInput, options?: RequestOptions): Promise<JsonObject> =>
792
+ this.http.requestJson({
793
+ ...options,
794
+ method: "POST",
795
+ path: "/api/v1/message-check/present",
796
+ jsonBody: input,
797
+ }),
798
+
799
+ verifyReceiptOnline: (
800
+ input: MessageCheckVerifyOnlineInput,
801
+ options?: RequestOptions,
802
+ ): Promise<JsonObject> => {
803
+ const body: MessageCheckVerifyOnlineInput = {
804
+ receipt: input.receipt,
805
+ text: input.text,
806
+ };
807
+
808
+ if (input.maskedText !== undefined) body.maskedText = input.maskedText;
809
+
810
+ if (input.conversationId !== undefined) body.conversationId = input.conversationId;
811
+
812
+ if (input.senderId !== undefined) body.senderId = input.senderId;
813
+
814
+ return this.http.requestJson({
815
+ ...options,
816
+ method: "POST",
817
+ path: "/api/v1/message-check/receipts/verify",
818
+ jsonBody: body,
819
+ });
820
+ },
821
+
822
+ verifyReceiptOffline: (
823
+ input: Omit<VerifyMessageCheckReceiptOptions, "fetch" | "jwksUrl"> & { jwksUrl?: string },
824
+ ): Promise<VerifyMessageCheckReceiptResult> =>
825
+ verifyMessageCheckReceipt({
826
+ ...input,
827
+ jwksUrl: input.jwksUrl ?? `${this.http.config.baseUrl}/.well-known/jwks.json`,
828
+ fetch: this.http.config.fetch,
829
+ }),
830
+
831
+ getPolicy: (options?: RequestOptions): Promise<JsonObject> =>
832
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/message-check/policy" }),
833
+
834
+ updatePolicy: (policy: JsonObject, options?: RequestOptions): Promise<JsonObject> =>
835
+ this.http.requestJson({
836
+ ...options,
837
+ method: "PUT",
838
+ path: "/api/v1/message-check/policy",
839
+ jsonBody: policy,
840
+ }),
841
+
842
+ listFlags: (
843
+ query?: { verdict?: string; review?: string; limit?: number; before?: string },
844
+ options?: RequestOptions,
845
+ ): Promise<JsonObject> =>
846
+ this.http.requestJson({
847
+ ...options,
848
+ method: "GET",
849
+ path: "/api/v1/message-check/flags",
850
+ query,
851
+ }),
852
+
853
+ reviewFlag: (
854
+ id: string,
855
+ review: "correct" | "wrong" | null,
856
+ options?: RequestOptions,
857
+ ): Promise<JsonObject> =>
858
+ this.http.requestJson({
859
+ ...options,
860
+ method: "PUT",
861
+ path: `/api/v1/message-check/flags/${encodePathSegment(id)}/review`,
862
+ jsonBody: { review },
863
+ }),
864
+ };
865
+
866
+ // --- Dispute Pack ----------------------------------------------------------
867
+
868
+ readonly disputePack = {
869
+ pushListing: (input: DisputePackPushListingInput, options?: RequestOptions): Promise<JsonObject> => {
870
+ const formData = new FormData();
871
+ formData.append("listingRef", input.listingRef);
872
+ formData.append(
873
+ "listing",
874
+ isRawListingJson(input.listing) ? input.listing : JSON.stringify(input.listing),
875
+ );
876
+
877
+ if (input.occurredAt !== undefined) {
878
+ formData.append("occurredAt", input.occurredAt);
879
+ }
880
+
881
+ if (input.photos) {
882
+ input.photos.forEach((photo, index) => {
883
+ const normalized = normalizeUpload(photo, `photo-${index + 1}.jpg`, "image/jpeg");
884
+ formData.append("photos", normalized.blob, normalized.filename);
885
+ });
886
+ }
887
+
888
+ return this.http.requestJson({
889
+ ...options,
890
+ method: "POST",
891
+ path: "/api/v1/dispute-pack/listings",
892
+ formData,
893
+ });
894
+ },
895
+
896
+ captureListing: (
897
+ input: { listingRef: string; url: string; occurredAt?: string },
898
+ options?: RequestOptions,
899
+ ): Promise<JsonObject> =>
900
+ this.http.requestJson({
901
+ ...options,
902
+ method: "POST",
903
+ path: "/api/v1/dispute-pack/listings/capture",
904
+ jsonBody: input,
905
+ }),
906
+
907
+ recordSale: (input: DisputePackRecordSaleInput, options?: RequestOptions): Promise<JsonObject> =>
908
+ this.http.requestJson({
909
+ ...options,
910
+ method: "POST",
911
+ path: "/api/v1/dispute-pack/sales",
912
+ jsonBody: {
913
+ listingRef: input.listingRef,
914
+ buyerId: input.buyerId,
915
+ orderId: input.orderId,
916
+ soldAt: input.soldAt,
917
+ price: {
918
+ amount: input.price.amount,
919
+ currency: input.price.currency,
920
+ },
921
+ },
922
+ }),
923
+
924
+ recordMessage: (
925
+ input: DisputePackRecordMessageInput,
926
+ options?: RequestOptions,
927
+ ): Promise<JsonObject> => {
928
+ const body: DisputePackRecordMessageInput = {
929
+ listingRef: input.listingRef,
930
+ buyerId: input.buyerId,
931
+ role: input.role,
932
+ messageId: input.messageId,
933
+ sentAt: input.sentAt,
934
+ text: input.text,
935
+ };
936
+
937
+ if (input.attachments !== undefined) body.attachments = input.attachments;
938
+
939
+ return this.http.requestJson({
940
+ ...options,
941
+ method: "POST",
942
+ path: "/api/v1/dispute-pack/messages",
943
+ jsonBody: body,
944
+ });
945
+ },
946
+
947
+ recordTracking: (
948
+ input: DisputePackRecordTrackingInput,
949
+ options?: RequestOptions,
950
+ ): Promise<JsonObject> =>
951
+ this.http.requestJson({
952
+ ...options,
953
+ method: "POST",
954
+ path: "/api/v1/dispute-pack/tracking",
955
+ jsonBody: input,
956
+ }),
957
+
958
+ createDispute: (
959
+ input: DisputePackCreateDisputeInput,
960
+ options?: RequestOptions,
961
+ ): Promise<JsonObject> =>
962
+ this.http.requestJson({
963
+ ...options,
964
+ method: "POST",
965
+ path: "/api/v1/dispute-pack/disputes",
966
+ jsonBody: input,
967
+ }),
968
+
969
+ getDispute: (
970
+ id: string,
971
+ query?: { version?: number },
972
+ options?: RequestOptions,
973
+ ): Promise<JsonObject> =>
974
+ this.http.requestJson({
975
+ ...options,
976
+ method: "GET",
977
+ path: `/api/v1/dispute-pack/disputes/${encodePathSegment(id)}`,
978
+ query,
979
+ }),
980
+
981
+ getDisputePdf: (
982
+ id: string,
983
+ query?: { version?: number },
984
+ options?: RequestOptions,
985
+ ): Promise<Uint8Array> =>
986
+ this.http.requestBinary({
987
+ ...options,
988
+ method: "GET",
989
+ path: `/api/v1/dispute-pack/disputes/${encodePathSegment(id)}/pdf`,
990
+ query,
991
+ accept: "application/pdf",
992
+ }),
993
+
994
+ releaseDispute: (id: string, input: JsonObject, options?: RequestOptions): Promise<JsonObject> =>
995
+ this.http.requestJson({
996
+ ...options,
997
+ method: "POST",
998
+ path: `/api/v1/dispute-pack/disputes/${encodePathSegment(id)}/release`,
999
+ jsonBody: input,
1000
+ }),
1001
+ };
1002
+
1003
+ // --- Embed -----------------------------------------------------------------
1004
+
1005
+ readonly embed = {
1006
+ createSession: (input: EmbedSessionInput, options?: RequestOptions): Promise<JsonObject> =>
1007
+ this.http.requestJson({
1008
+ ...options,
1009
+ method: "POST",
1010
+ path: "/api/v1/embed-sessions",
1011
+ jsonBody: input,
1012
+ }),
1013
+
1014
+ getBranding: (options?: RequestOptions): Promise<JsonObject> =>
1015
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/embed/branding" }),
1016
+
1017
+ updateBranding: (branding: JsonObject, options?: RequestOptions): Promise<JsonObject> =>
1018
+ this.http.requestJson({
1019
+ ...options,
1020
+ method: "PUT",
1021
+ path: "/api/v1/embed/branding",
1022
+ jsonBody: branding,
1023
+ }),
1024
+ };
1025
+
1026
+ // --- Account ---------------------------------------------------------------
1027
+
1028
+ readonly account = {
1029
+ getKey: (options?: RequestOptions): Promise<JsonObject> =>
1030
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/key" }),
1031
+
1032
+ getMe: (options?: RequestOptions): Promise<JsonObject> =>
1033
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/me" }),
1034
+
1035
+ getUsage: (
1036
+ query?: { keyKind?: "live" | "test"; from?: string; to?: string },
1037
+ options?: RequestOptions,
1038
+ ): Promise<JsonObject> =>
1039
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/usage", query }),
1040
+
1041
+ listMarketplaces: (options?: RequestOptions): Promise<JsonObject> =>
1042
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/marketplaces" }),
1043
+
1044
+ getSettings: (options?: RequestOptions): Promise<JsonObject> =>
1045
+ this.http.requestJson({ ...options, method: "GET", path: "/api/v1/marketplace/settings" }),
1046
+
1047
+ updateSettings: (settings: JsonObject, options?: RequestOptions): Promise<JsonObject> =>
1048
+ this.http.requestJson({
1049
+ ...options,
1050
+ method: "PUT",
1051
+ path: "/api/v1/marketplace/settings",
1052
+ jsonBody: settings,
1053
+ }),
1054
+ };
1055
+ }
1056
+
1057
+ export function createPcificClient(options: PcificClientOptions = {}): PcificClient {
1058
+ return new PcificClient(options);
1059
+ }