@mappa-ai/mappa-node 0.1.2 → 1.0.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/dist/index.d.mts CHANGED
@@ -1,67 +1,1021 @@
1
- import { z } from "zod";
2
-
3
- //#region src/presets.d.ts
4
- declare class Presets {
5
- generateReport(): Promise<string>;
1
+ //#region src/errors.d.ts
2
+ /**
3
+ * Base error type for all SDK-raised errors.
4
+ *
5
+ * When available, {@link MappaError.requestId} can be used to correlate a failure
6
+ * with server logs/support.
7
+ */
8
+ declare class MappaError extends Error {
9
+ name: string;
10
+ requestId?: string;
11
+ code?: string;
12
+ constructor(message: string, opts?: {
13
+ requestId?: string;
14
+ code?: string;
15
+ cause?: unknown;
16
+ });
17
+ }
18
+ /**
19
+ * Error returned when the API responds with a non-2xx status.
20
+ */
21
+ declare class ApiError extends MappaError {
22
+ name: string;
23
+ status: number;
24
+ details?: unknown;
25
+ constructor(message: string, opts: {
26
+ status: number;
27
+ requestId?: string;
28
+ code?: string;
29
+ details?: unknown;
30
+ });
31
+ }
32
+ /**
33
+ * Error returned for HTTP 429 responses.
34
+ *
35
+ * If provided by the server, {@link RateLimitError.retryAfterMs} indicates when
36
+ * it is safe to retry.
37
+ */
38
+ declare class RateLimitError extends ApiError {
39
+ name: string;
40
+ retryAfterMs?: number;
41
+ }
42
+ /**
43
+ * Error returned for authentication/authorization failures (typically 401/403).
44
+ */
45
+ declare class AuthError extends ApiError {
46
+ name: string;
47
+ }
48
+ /**
49
+ * Error returned when the server rejects a request as invalid (typically 422).
50
+ */
51
+ declare class ValidationError extends ApiError {
52
+ name: string;
53
+ }
54
+ /**
55
+ * Error thrown by polling helpers when a job reaches the "failed" terminal state.
56
+ */
57
+ declare class JobFailedError extends MappaError {
58
+ name: string;
59
+ jobId: string;
60
+ constructor(jobId: string, message: string, opts?: {
61
+ requestId?: string;
62
+ code?: string;
63
+ cause?: unknown;
64
+ });
65
+ }
66
+ /**
67
+ * Error thrown by polling helpers when a job reaches the "canceled" terminal state.
68
+ */
69
+ declare class JobCanceledError extends MappaError {
70
+ name: string;
71
+ jobId: string;
72
+ constructor(jobId: string, message: string, opts?: {
73
+ requestId?: string;
74
+ cause?: unknown;
75
+ });
6
76
  }
7
77
  //#endregion
8
- //#region src/mappa/model.d.ts
9
- declare namespace MappaModel {
10
- const generateReportInputSchema: z.ZodObject<{
11
- inputMedia: z.ZodDiscriminatedUnion<[z.ZodObject<{
12
- kind: z.ZodLiteral<"file">;
13
- file: z.ZodFile;
14
- }, z.core.$strip>, z.ZodObject<{
15
- kind: z.ZodLiteral<"url">;
16
- url: z.ZodURL;
17
- }, z.core.$strip>], "kind">;
18
- targetSpeaker: z.ZodDefault<z.ZodDiscriminatedUnion<[z.ZodObject<{
19
- strategy: z.ZodLiteral<"dominant">;
20
- }, z.core.$strip>, z.ZodObject<{
21
- strategy: z.ZodLiteral<"magic_hint">;
22
- hint: z.ZodString;
23
- }, z.core.$strip>], "strategy">>;
24
- template: z.ZodEnum<{
25
- base: "base";
26
- }>;
27
- }, z.core.$strip>;
28
- type GenerateReportInput = z.infer<typeof generateReportInputSchema>;
29
- const generateReportOutputSchema: z.ZodObject<{
30
- outputs: z.ZodPipe<z.ZodArray<z.ZodObject<{
31
- entity_id: z.ZodString;
32
- behavior_profile: z.ZodString;
33
- }, z.core.$strip>>, z.ZodTransform<{
34
- entity_id: string;
35
- behavior_profile: string;
36
- } | null, {
37
- entity_id: string;
38
- behavior_profile: string;
39
- }[]>>;
40
- }, z.core.$strip>;
41
- type GenerateReportOutput = z.infer<typeof generateReportOutputSchema>;
78
+ //#region src/resources/transport.d.ts
79
+ type Telemetry = {
80
+ onRequest?: (ctx: {
81
+ method: string;
82
+ url: string;
83
+ requestId?: string;
84
+ }) => void;
85
+ onResponse?: (ctx: {
86
+ status: number;
87
+ url: string;
88
+ requestId?: string;
89
+ durationMs: number;
90
+ }) => void;
91
+ onError?: (ctx: {
92
+ url: string;
93
+ requestId?: string;
94
+ error: unknown;
95
+ }) => void;
96
+ };
97
+ type TransportOptions = {
98
+ apiKey: string;
99
+ baseUrl: string;
100
+ timeoutMs: number;
101
+ maxRetries: number;
102
+ defaultHeaders?: Record<string, string>;
103
+ fetch?: typeof fetch;
104
+ telemetry?: Telemetry;
105
+ userAgent?: string;
106
+ };
107
+ type RequestOptions = {
108
+ method: "GET" | "POST" | "DELETE" | "PUT" | "PATCH";
109
+ path: string;
110
+ query?: Record<string, string | number | boolean | undefined>;
111
+ headers?: Record<string, string | undefined>;
112
+ body?: unknown;
113
+ idempotencyKey?: string;
114
+ requestId?: string;
115
+ signal?: AbortSignal;
116
+ retryable?: boolean;
117
+ };
118
+ type TransportResponse<T> = {
119
+ data: T;
120
+ status: number;
121
+ requestId?: string;
122
+ headers: Headers;
123
+ };
124
+ declare class Transport {
125
+ private readonly opts;
126
+ private readonly fetchImpl;
127
+ constructor(opts: TransportOptions);
128
+ request<T>(req: RequestOptions): Promise<TransportResponse<T>>;
42
129
  }
43
130
  //#endregion
44
- //#region src/mappa/index.d.ts
131
+ //#region src/types.d.ts
45
132
  /**
46
- * Client for the Mappa API that provides access to presets and can generate a synchronous behavior profile report
47
- * from either an uploaded media file or a remote media URL.
133
+ * JSON-serializable value.
134
+ *
135
+ * Used throughout the SDK for message payloads, webhook data, and server-provided
136
+ * metadata where the exact shape is not known at compile time.
48
137
  */
49
- declare class Mappa {
50
- private readonly apiKey;
51
- private readonly apiBaseUrl;
52
- private readonly apiVersion;
53
- readonly presets: Presets;
138
+ type JsonValue = string | number | boolean | null | {
139
+ [k: string]: JsonValue;
140
+ } | JsonValue[];
141
+ type MediaRef = {
142
+ url: string;
143
+ contentType?: string;
144
+ filename?: string;
145
+ } | {
146
+ mediaId: string;
147
+ };
148
+ /**
149
+ * A reference to an already-uploaded media object.
150
+ */
151
+ type MediaIdRef = {
152
+ mediaId: string;
153
+ };
154
+ type ReportTemplateId = "sales_playbook" | "general_report" | "hiring_report" | "profile_alignment";
155
+ type ReportTemplateParamsMap = {
156
+ sales_playbook: Record<string, never>;
157
+ general_report: Record<string, never>;
158
+ hiring_report: {
159
+ roleTitle: string;
160
+ roleDescription: string;
161
+ companyCulture: string;
162
+ };
163
+ profile_alignment: {
164
+ idealProfile: string;
165
+ };
166
+ };
167
+ type ReportOutputType = "markdown" | "json" | "pdf" | "url";
168
+ type ReportOutputEntry<OutputType extends ReportOutputType, Template extends ReportTemplateId> = ReportTemplateParamsMap[Template] extends Record<string, never> ? {
169
+ type: OutputType;
170
+ template: Template;
171
+ templateParams?: ReportTemplateParamsMap[Template];
172
+ } : {
173
+ type: OutputType;
174
+ template: Template;
175
+ templateParams: ReportTemplateParamsMap[Template];
176
+ };
177
+ type ReportOutputForType<OutputType extends ReportOutputType> = ReportOutputEntry<OutputType, "sales_playbook"> | ReportOutputEntry<OutputType, "general_report"> | ReportOutputEntry<OutputType, "hiring_report"> | ReportOutputEntry<OutputType, "profile_alignment">;
178
+ type ReportOutput = ReportOutputForType<"markdown"> | ReportOutputForType<"json"> | ReportOutputForType<"pdf"> | ReportOutputForType<"url">;
179
+ type TargetStrategy = "dominant" | "timerange" | "entity_id" | "magic_hint";
180
+ type TargetOnMiss = "fallback_dominant" | "error";
181
+ type TargetTimeRange = {
182
+ /**
183
+ * Start time in seconds.
184
+ * When omitted, starts from the beginning.
185
+ */
186
+ startSeconds?: number;
187
+ /**
188
+ * End time in seconds.
189
+ * When omitted, goes until the end.
190
+ */
191
+ endSeconds?: number;
192
+ };
193
+ type TargetBase = {
194
+ /**
195
+ * Behavior when the entity is not found.
196
+ */
197
+ onMiss?: TargetOnMiss;
198
+ };
199
+ type TargetDominant = TargetBase & {
200
+ strategy: "dominant";
201
+ };
202
+ type TargetTimeRangeStrategy = TargetBase & {
203
+ strategy: "timerange";
204
+ timeRange: TargetTimeRange;
205
+ };
206
+ type TargetEntityId = TargetBase & {
207
+ strategy: "entity_id";
208
+ entityId: string;
209
+ };
210
+ type TargetMagicHint = TargetBase & {
211
+ strategy: "magic_hint";
212
+ hint: string;
213
+ };
214
+ type TargetSelector = TargetDominant | TargetTimeRangeStrategy | TargetEntityId | TargetMagicHint;
215
+ type TargetStrategyMap = {
216
+ dominant: TargetDominant;
217
+ timerange: TargetTimeRangeStrategy;
218
+ entity_id: TargetEntityId;
219
+ magic_hint: TargetMagicHint;
220
+ };
221
+ type TargetFor<Strategy extends TargetStrategy> = TargetStrategyMap[Strategy];
222
+ type Usage = {
223
+ creditsUsed: number;
224
+ creditsDiscounted?: number;
225
+ creditsNetUsed: number;
226
+ durationMs?: number;
227
+ modelVersion?: string;
228
+ };
229
+ type JobStage = "uploaded" | "queued" | "transcoding" | "extracting" | "scoring" | "rendering" | "finalizing";
230
+ type JobStatus = "queued" | "running" | "succeeded" | "failed" | "canceled";
231
+ type JobCreditReservation = {
232
+ reservedCredits: number | null;
233
+ reservationStatus: "active" | "released" | "applied" | null;
234
+ };
235
+ type Job = {
236
+ id: string;
237
+ type: "report.generate";
238
+ status: JobStatus;
239
+ stage?: JobStage;
240
+ progress?: number;
241
+ createdAt: string;
242
+ updatedAt: string;
243
+ reportId?: string;
244
+ usage?: Usage;
245
+ credits?: JobCreditReservation;
246
+ releasedCredits?: number | null;
247
+ error?: {
248
+ code: string;
249
+ message: string;
250
+ details?: JsonValue;
251
+ retryable?: boolean;
252
+ };
253
+ requestId?: string;
254
+ };
255
+ type JobEvent = {
256
+ type: "status";
257
+ job: Job;
258
+ } | {
259
+ type: "stage";
260
+ stage: JobStage;
261
+ progress?: number;
262
+ job: Job;
263
+ } | {
264
+ type: "log";
265
+ message: string;
266
+ ts: string;
267
+ } | {
268
+ type: "terminal";
269
+ job: Job;
270
+ };
271
+ type Subject = {
272
+ id?: string;
273
+ externalRef?: string;
274
+ metadata?: Record<string, JsonValue>;
275
+ };
276
+ type WebhookConfig = {
277
+ url: string;
278
+ headers?: Record<string, string>;
279
+ };
280
+ type ReportCreateJobRequest = {
281
+ subject?: Subject;
282
+ /**
283
+ * Reference to already-uploaded media.
284
+ *
285
+ * Note: Report job creation requires a `mediaId`. To start from a remote URL or local bytes,
286
+ * use helper methods like `reports.createJobFromUrl()` / `reports.createJobFromFile()`.
287
+ */
288
+ media: MediaIdRef;
289
+ output: ReportOutput;
290
+ /**
291
+ * Select the target entity for analysis.
292
+ *
293
+ * When omitted, the API defaults to the dominant speaker.
294
+ */
295
+ target?: TargetSelector;
296
+ options?: {
297
+ language?: string;
298
+ timezone?: string;
299
+ includeMetrics?: boolean;
300
+ includeRawModelOutput?: boolean;
301
+ };
302
+ /**
303
+ * Webhook to call when the job completes or fails.
304
+ *
305
+ * @example
306
+ * webhook: {
307
+ * url: "https://example.com/webhooks/mappa",
308
+ * headers: { "X-Custom-Header": "value" }
309
+ * }
310
+ */
311
+ webhook?: WebhookConfig;
312
+ idempotencyKey?: string;
313
+ requestId?: string;
314
+ };
315
+ type ReportBase = {
316
+ id: string;
317
+ createdAt: string;
318
+ subject?: Subject;
319
+ media: {
320
+ url?: string;
321
+ mediaId?: string;
322
+ };
323
+ usage?: Usage;
324
+ metrics?: Record<string, JsonValue>;
325
+ raw?: JsonValue;
326
+ };
327
+ type MarkdownReport = ReportBase & {
328
+ output: {
329
+ type: "markdown";
330
+ };
331
+ markdown: string;
332
+ };
333
+ type JsonReport = ReportBase & {
334
+ output: {
335
+ type: "json";
336
+ };
337
+ sections: Array<{
338
+ section_title: string;
339
+ section_content: JsonValue;
340
+ }>;
341
+ };
342
+ type PdfReport = ReportBase & {
343
+ output: {
344
+ type: "pdf";
345
+ template: string;
346
+ };
347
+ markdown: string;
348
+ pdfUrl: string;
349
+ };
350
+ type UrlReport = ReportBase & {
351
+ output: {
352
+ type: "url";
353
+ template: string;
354
+ };
355
+ markdown?: string;
356
+ sections?: Array<{
357
+ section_title: string;
358
+ section_content: JsonValue;
359
+ }>;
360
+ reportUrl: string;
361
+ };
362
+ type Report = MarkdownReport | JsonReport | PdfReport | UrlReport;
363
+ type ReportJobReceipt = {
364
+ jobId: string;
365
+ status: "queued" | "running";
366
+ stage?: JobStage;
367
+ estimatedWaitSec?: number;
368
+ requestId?: string;
369
+ handle?: ReportRunHandle;
370
+ };
371
+ type FeedbackReceipt = {
372
+ id: string;
373
+ createdAt: string;
374
+ target: {
375
+ reportId?: string;
376
+ jobId?: string;
377
+ };
378
+ rating: "thumbs_up" | "thumbs_down" | "1" | "2" | "3" | "4" | "5";
379
+ tags?: string[];
380
+ comment?: string;
381
+ credits: {
382
+ eligible: boolean;
383
+ reason?: string;
384
+ discountApplied: number;
385
+ netUsed: number;
386
+ };
387
+ };
388
+ type MediaObject = {
389
+ mediaId: string;
390
+ createdAt: string;
391
+ contentType: string;
392
+ filename?: string;
393
+ sizeBytes?: number;
394
+ };
395
+ type MediaProcessingStatus = "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED";
396
+ type MediaRetention = {
397
+ expiresAt: string | null;
398
+ daysRemaining: number | null;
399
+ locked: boolean;
400
+ };
401
+ type MediaFile = {
402
+ mediaId: string;
403
+ createdAt: string;
404
+ contentType: string;
405
+ filename: string | null;
406
+ sizeBytes: number | null;
407
+ durationSeconds: number | null;
408
+ processingStatus: MediaProcessingStatus;
409
+ lastUsedAt: string | null;
410
+ retention: MediaRetention;
411
+ };
412
+ type FileDeleteReceipt = {
413
+ mediaId: string;
414
+ deleted: true;
415
+ };
416
+ type RetentionLockResult = {
417
+ mediaId: string;
418
+ retentionLock: boolean;
419
+ message: string;
420
+ };
421
+ type CursorPaginationParams = {
422
+ limit?: number;
423
+ cursor?: string;
424
+ };
425
+ type OffsetPaginationParams = {
426
+ limit?: number;
427
+ offset?: number;
428
+ };
429
+ type CursorPage<T> = {
430
+ data: T[];
431
+ cursor?: string;
432
+ hasMore: boolean;
433
+ };
434
+ type OffsetPage<T> = {
435
+ data: T[];
436
+ pagination: {
437
+ limit: number;
438
+ offset: number;
439
+ total: number;
440
+ };
441
+ };
442
+ type CreditBalance = {
443
+ balance: number;
444
+ reserved: number;
445
+ available: number;
446
+ };
447
+ type CreditTransactionType = "PURCHASE" | "SUBSCRIPTION_GRANT" | "PROMO_GRANT" | "USAGE" | "REFUND" | "FEEDBACK_DISCOUNT" | "ADJUSTMENT" | "EXPIRATION";
448
+ type CreditTransaction = {
449
+ id: string;
450
+ type: CreditTransactionType;
451
+ amount: number;
452
+ createdAt: string;
453
+ effectiveAt: string;
454
+ expiresAt: string | null;
455
+ jobId: string | null;
456
+ job?: {
457
+ id: string;
458
+ status: string;
459
+ createdAt: string;
460
+ };
461
+ };
462
+ type CreditUsage = {
463
+ jobId: string;
464
+ creditsUsed: number;
465
+ creditsDiscounted?: number;
466
+ creditsNetUsed: number;
467
+ durationMs?: number;
468
+ modelVersion?: string;
469
+ };
470
+ /**
471
+ * Options for long-polling job completion.
472
+ */
473
+ type WaitOptions = {
474
+ /**
475
+ * Maximum time to wait before failing.
476
+ *
477
+ * @defaultValue 300000
478
+ */
479
+ timeoutMs?: number;
480
+ /**
481
+ * Initial polling interval.
482
+ *
483
+ * @defaultValue 1000
484
+ */
485
+ pollIntervalMs?: number;
486
+ /**
487
+ * Maximum polling interval used with exponential backoff.
488
+ *
489
+ * @defaultValue 10000
490
+ */
491
+ maxPollIntervalMs?: number;
492
+ /**
493
+ * Optional callback invoked on meaningful job state transitions.
494
+ */
495
+ onEvent?: (event: JobEvent) => void;
496
+ /**
497
+ * Abort signal used to cancel waiting.
498
+ */
499
+ signal?: AbortSignal;
500
+ };
501
+ type ReportRunHandle = {
502
+ jobId: string;
503
+ stream(opts?: {
504
+ signal?: AbortSignal;
505
+ onEvent?: (e: JobEvent) => void;
506
+ }): AsyncIterable<JobEvent>;
507
+ wait(opts?: WaitOptions): Promise<Report>;
508
+ cancel(): Promise<Job>;
509
+ job(): Promise<Job>;
510
+ report(): Promise<Report | null>;
511
+ };
512
+ /**
513
+ * Type guard for MarkdownReport.
514
+ */
515
+ declare function isMarkdownReport(report: Report): report is MarkdownReport;
516
+ /**
517
+ * Type guard for JsonReport.
518
+ */
519
+ declare function isJsonReport(report: Report): report is JsonReport;
520
+ /**
521
+ * Type guard for PdfReport.
522
+ */
523
+ declare function isPdfReport(report: Report): report is PdfReport;
524
+ /**
525
+ * Type guard for UrlReport.
526
+ */
527
+ declare function isUrlReport(report: Report): report is UrlReport;
528
+ //#endregion
529
+ //#region src/resources/credits.d.ts
530
+ type ListTransactionsOptions = {
531
+ /** Max transactions per page (1-100, default 50) */
532
+ limit?: number;
533
+ /** Offset for pagination (default 0) */
534
+ offset?: number;
535
+ requestId?: string;
536
+ signal?: AbortSignal;
537
+ };
538
+ type ListTransactionsResponse = {
539
+ transactions: CreditTransaction[];
540
+ pagination: {
541
+ limit: number;
542
+ offset: number;
543
+ total: number;
544
+ };
545
+ };
546
+ /**
547
+ * Credits API resource.
548
+ *
549
+ * Provides methods to manage and query credit balances, transaction history,
550
+ * and job-specific credit usage.
551
+ */
552
+ declare class CreditsResource {
553
+ private readonly transport;
554
+ constructor(transport: Transport);
555
+ /**
556
+ * Get the current credit balance for your team.
557
+ *
558
+ * @example
559
+ * const balance = await mappa.credits.getBalance();
560
+ * console.log(`Available: ${balance.available} credits`);
561
+ */
562
+ getBalance(opts?: {
563
+ requestId?: string;
564
+ signal?: AbortSignal;
565
+ }): Promise<CreditBalance>;
566
+ /**
567
+ * List credit transactions with offset pagination.
568
+ *
569
+ * @example
570
+ * const { transactions, pagination } = await mappa.credits.listTransactions({ limit: 25 });
571
+ * console.log(`Showing ${transactions.length} of ${pagination.total}`);
572
+ */
573
+ listTransactions(opts?: ListTransactionsOptions): Promise<ListTransactionsResponse>;
574
+ /**
575
+ * Iterate over all transactions, automatically handling pagination.
576
+ *
577
+ * @example
578
+ * for await (const tx of mappa.credits.listAllTransactions()) {
579
+ * console.log(`${tx.type}: ${tx.amount}`);
580
+ * }
581
+ */
582
+ listAllTransactions(opts?: Omit<ListTransactionsOptions, "offset">): AsyncIterable<CreditTransaction>;
583
+ /**
584
+ * Get credit usage details for a completed job.
585
+ *
586
+ * @example
587
+ * const usage = await mappa.credits.getJobUsage("job_xyz");
588
+ * console.log(`Net credits used: ${usage.creditsNetUsed}`);
589
+ */
590
+ getJobUsage(jobId: string, opts?: {
591
+ requestId?: string;
592
+ signal?: AbortSignal;
593
+ }): Promise<CreditUsage>;
594
+ /**
595
+ * Check if the team has enough available credits for an operation.
596
+ *
597
+ * @example
598
+ * if (await mappa.credits.hasEnough(100)) {
599
+ * await mappa.reports.createJob(...);
600
+ * }
601
+ */
602
+ hasEnough(credits: number, opts?: {
603
+ requestId?: string;
604
+ signal?: AbortSignal;
605
+ }): Promise<boolean>;
606
+ /**
607
+ * Get the number of available credits (balance - reserved).
608
+ *
609
+ * @example
610
+ * const available = await mappa.credits.getAvailable();
611
+ * console.log(`You can spend ${available} credits`);
612
+ */
613
+ getAvailable(opts?: {
614
+ requestId?: string;
615
+ signal?: AbortSignal;
616
+ }): Promise<number>;
617
+ }
618
+ //#endregion
619
+ //#region src/resources/feedback.d.ts
620
+ type FeedbackCreateRequest = {
621
+ reportId?: string;
622
+ jobId?: string;
623
+ rating: "thumbs_up" | "thumbs_down" | "1" | "2" | "3" | "4" | "5";
624
+ tags?: string[];
625
+ comment?: string;
626
+ corrections?: Array<{
627
+ path: string;
628
+ expected?: unknown;
629
+ observed?: unknown;
630
+ }>;
631
+ idempotencyKey?: string;
632
+ requestId?: string;
633
+ signal?: AbortSignal;
634
+ };
635
+ declare class FeedbackResource {
636
+ private readonly transport;
637
+ constructor(transport: Transport);
54
638
  /**
55
- * Initializes the client with an API key sourced from arguments or the environment.
639
+ * Create feedback for a report or job. Provide exactly one of `reportId` or `jobId`.
56
640
  */
57
- constructor(apiKey?: string);
641
+ create(req: FeedbackCreateRequest): Promise<FeedbackReceipt>;
642
+ }
643
+ //#endregion
644
+ //#region src/resources/files.d.ts
645
+ type UploadRequest = {
646
+ file: Blob | ArrayBuffer | Uint8Array | ReadableStream<Uint8Array>;
647
+ /**
648
+ * Optional override.
649
+ * If omitted, the SDK will try to infer it from `file.type` (Blob) and then from `filename`.
650
+ */
651
+ contentType?: string;
652
+ filename?: string;
653
+ idempotencyKey?: string;
654
+ requestId?: string;
655
+ signal?: AbortSignal;
656
+ };
657
+ type ListFilesOptions = {
658
+ /** Max files per page (1-100, default 20) */
659
+ limit?: number;
660
+ /** Pagination cursor from previous response */
661
+ cursor?: string;
662
+ /** Include soft-deleted files (default false) */
663
+ includeDeleted?: boolean;
664
+ requestId?: string;
665
+ signal?: AbortSignal;
666
+ };
667
+ type ListFilesResponse = {
668
+ files: MediaFile[];
669
+ cursor?: string;
670
+ hasMore: boolean;
671
+ };
672
+ /**
673
+ * Uses multipart/form-data for uploads.
674
+ *
675
+ * If you need resumable uploads, add a dedicated resumable protocol.
676
+ */
677
+ declare class FilesResource {
678
+ private readonly transport;
679
+ constructor(transport: Transport);
680
+ upload(req: UploadRequest): Promise<MediaObject>;
681
+ /**
682
+ * Retrieve metadata for a single uploaded file.
683
+ *
684
+ * @example
685
+ * const file = await mappa.files.get("media_abc123");
686
+ * console.log(file.processingStatus); // "COMPLETED"
687
+ */
688
+ get(mediaId: string, opts?: {
689
+ requestId?: string;
690
+ signal?: AbortSignal;
691
+ }): Promise<MediaFile>;
692
+ /**
693
+ * List uploaded files with cursor pagination.
694
+ *
695
+ * @example
696
+ * const page1 = await mappa.files.list({ limit: 10 });
697
+ * if (page1.hasMore) {
698
+ * const page2 = await mappa.files.list({ limit: 10, cursor: page1.cursor });
699
+ * }
700
+ */
701
+ list(opts?: ListFilesOptions): Promise<ListFilesResponse>;
58
702
  /**
59
- * Generates a synchronous behavior profile report from either an uploaded media file or a remote media URL.
703
+ * Iterate over all files, automatically handling pagination.
704
+ *
705
+ * @example
706
+ * for await (const file of mappa.files.listAll()) {
707
+ * console.log(file.mediaId);
708
+ * }
709
+ *
710
+ * // Or collect all
711
+ * const allFiles = [];
712
+ * for await (const file of mappa.files.listAll({ limit: 50 })) {
713
+ * allFiles.push(file);
714
+ * }
60
715
  */
61
- generateTextReport(body: MappaModel.GenerateReportInput): Promise<{
62
- behaviorProfile: string;
63
- entityId: string;
716
+ listAll(opts?: Omit<ListFilesOptions, "cursor">): AsyncIterable<MediaFile>;
717
+ /**
718
+ * Lock or unlock a file's retention to prevent/allow automatic deletion.
719
+ *
720
+ * @example
721
+ * // Prevent automatic deletion
722
+ * await mappa.files.setRetentionLock("media_abc", true);
723
+ *
724
+ * // Allow automatic deletion
725
+ * await mappa.files.setRetentionLock("media_abc", false);
726
+ */
727
+ setRetentionLock(mediaId: string, locked: boolean, opts?: {
728
+ requestId?: string;
729
+ signal?: AbortSignal;
730
+ }): Promise<RetentionLockResult>;
731
+ delete(mediaId: string, opts?: {
732
+ idempotencyKey?: string;
733
+ requestId?: string;
734
+ signal?: AbortSignal;
735
+ }): Promise<FileDeleteReceipt>;
736
+ }
737
+ //#endregion
738
+ //#region src/resources/health.d.ts
739
+ declare class HealthResource {
740
+ private readonly transport;
741
+ constructor(transport: Transport);
742
+ ping(): Promise<{
743
+ ok: true;
744
+ time: string;
64
745
  }>;
65
746
  }
66
747
  //#endregion
67
- export { Mappa };
748
+ //#region src/resources/jobs.d.ts
749
+ declare class JobsResource {
750
+ private readonly transport;
751
+ constructor(transport: Transport);
752
+ get(jobId: string, opts?: {
753
+ requestId?: string;
754
+ signal?: AbortSignal;
755
+ }): Promise<Job>;
756
+ cancel(jobId: string, opts?: {
757
+ idempotencyKey?: string;
758
+ requestId?: string;
759
+ signal?: AbortSignal;
760
+ }): Promise<Job>;
761
+ wait(jobId: string, opts?: WaitOptions): Promise<Job>;
762
+ /**
763
+ * Public stream API.
764
+ * If you add SSE later, keep this signature and switch implementation internally.
765
+ * For now, it yields events based on polling. Use `AbortSignal` to cancel streaming.
766
+ */
767
+ stream(jobId: string, opts?: {
768
+ signal?: AbortSignal;
769
+ onEvent?: (e: JobEvent) => void;
770
+ }): AsyncIterable<JobEvent>;
771
+ }
772
+ //#endregion
773
+ //#region src/resources/reports.d.ts
774
+ /**
775
+ * Request shape for {@link ReportsResource.createJobFromFile}.
776
+ *
777
+ * This helper performs two API calls as one logical operation:
778
+ * 1) Upload bytes via `files.upload()` (multipart)
779
+ * 2) Create a report job via {@link ReportsResource.createJob} using the returned `{ mediaId }`
780
+ *
781
+ * Differences vs {@link ReportCreateJobRequest}:
782
+ * - `media` is derived from the upload result and therefore omitted.
783
+ * - `idempotencyKey` applies to the *whole* upload + create-job sequence.
784
+ * - `requestId` is forwarded to both requests for end-to-end correlation.
785
+ *
786
+ * Abort behavior:
787
+ * - `signal` (from {@link UploadRequest}) is applied to the upload request.
788
+ * Job creation only runs after a successful upload.
789
+ */
790
+ type ReportCreateJobFromFileRequest = Omit<ReportCreateJobRequest, "media" | "idempotencyKey" | "requestId"> & Omit<UploadRequest, "filename"> & {
791
+ /**
792
+ * Optional filename to attach to the upload.
793
+ *
794
+ * When omitted, the upload layer may infer it (e.g. from a `File` object).
795
+ */
796
+ filename?: string;
797
+ /**
798
+ * Idempotency for the upload + job creation sequence.
799
+ */
800
+ idempotencyKey?: string;
801
+ /**
802
+ * Optional request correlation ID forwarded to both the upload and the job creation call.
803
+ */
804
+ requestId?: string;
805
+ };
806
+ /**
807
+ * Request shape for {@link ReportsResource.createJobFromUrl}.
808
+ *
809
+ * This helper performs two API calls as one logical operation:
810
+ * 1) Download bytes from a remote URL using `fetch()`
811
+ * 2) Upload bytes via `files.upload()` and then create a report job via {@link ReportsResource.createJob}
812
+ *
813
+ * Differences vs {@link ReportCreateJobRequest}:
814
+ * - `media` is derived from the upload result and therefore omitted.
815
+ * - `idempotencyKey` applies to the *whole* download + upload + create-job sequence.
816
+ * - `requestId` is forwarded to both upload and job creation calls.
817
+ */
818
+ type ReportCreateJobFromUrlRequest = Omit<ReportCreateJobRequest, "media" | "idempotencyKey" | "requestId"> & {
819
+ url: string;
820
+ contentType?: string;
821
+ filename?: string;
822
+ idempotencyKey?: string;
823
+ requestId?: string;
824
+ signal?: AbortSignal;
825
+ };
826
+ /**
827
+ * Reports API resource.
828
+ *
829
+ * Responsibilities:
830
+ * - Create report jobs (`POST /v1/reports/jobs`).
831
+ * - Fetch reports by report ID (`GET /v1/reports/:reportId`).
832
+ * - Fetch reports by job ID (`GET /v1/reports/by-job/:jobId`).
833
+ *
834
+ * Convenience helpers:
835
+ * - {@link ReportsResource.createJobFromFile} orchestrates `files.upload()` + {@link ReportsResource.createJob}.
836
+ * - {@link ReportsResource.createJobFromUrl} downloads a remote URL, uploads it, then calls {@link ReportsResource.createJob}.
837
+ * - {@link ReportsResource.generate} / {@link ReportsResource.generateFromFile} are script-friendly wrappers that
838
+ * create a job, wait for completion, and then fetch the final report.
839
+ *
840
+ * For production systems, prefer `createJob*()` plus webhooks or streaming job events rather than blocking waits.
841
+ */
842
+ declare class ReportsResource {
843
+ private readonly transport;
844
+ private readonly jobs;
845
+ private readonly files;
846
+ private readonly fetchImpl;
847
+ constructor(transport: Transport, jobs: JobsResource, files: {
848
+ upload: (req: UploadRequest) => Promise<MediaObject>;
849
+ }, fetchImpl: typeof fetch);
850
+ /**
851
+ * Create a new report job.
852
+ *
853
+ * Behavior:
854
+ * - Validates {@link MediaIdRef} at runtime (must provide `{ mediaId }`).
855
+ * - Applies an idempotency key: uses `req.idempotencyKey` when provided; otherwise generates a best-effort default.
856
+ * - Forwards `req.requestId` to the transport for end-to-end correlation.
857
+ *
858
+ * The returned receipt includes a {@link ReportRunHandle} (`receipt.handle`) which can be used to:
859
+ * - stream job events
860
+ * - wait for completion and fetch the final report
861
+ * - cancel the job, or fetch job/report metadata
862
+ */
863
+ createJob(req: ReportCreateJobRequest): Promise<ReportJobReceipt>;
864
+ /**
865
+ * Upload a file and create a report job in one call.
866
+ *
867
+ * Keeps `createJob()` strict about `media: { mediaId }` while offering a
868
+ * convenient helper when you start from raw bytes.
869
+ */
870
+ createJobFromFile(req: ReportCreateJobFromFileRequest): Promise<ReportJobReceipt>;
871
+ /**
872
+ * Download a file from a URL, upload it, and create a report job.
873
+ *
874
+ * Recommended when starting from a remote URL because report job creation
875
+ * only accepts `media: { mediaId }`.
876
+ *
877
+ * Workflow:
878
+ * 1) `fetch(url)`
879
+ * 2) Validate the response (2xx) and derive `contentType`
880
+ * 3) `files.upload({ file: Blob, ... })`
881
+ * 4) `createJob({ media: { mediaId }, ... })`
882
+ *
883
+ * Verification / safety:
884
+ * - Only allows `http:` and `https:` URLs.
885
+ * - Requires a resolvable `contentType` (from `req.contentType` or response header).
886
+ */
887
+ createJobFromUrl(req: ReportCreateJobFromUrlRequest): Promise<ReportJobReceipt>;
888
+ get(reportId: string, opts?: {
889
+ requestId?: string;
890
+ signal?: AbortSignal;
891
+ }): Promise<Report>;
892
+ getByJob(jobId: string, opts?: {
893
+ requestId?: string;
894
+ signal?: AbortSignal;
895
+ }): Promise<Report | null>;
896
+ /**
897
+ * Convenience wrapper: createJob + wait + get
898
+ * Use for scripts; for production prefer createJob + webhooks/stream.
899
+ */
900
+ generate(req: ReportCreateJobRequest, opts?: {
901
+ wait?: WaitOptions;
902
+ }): Promise<Report>;
903
+ /**
904
+ * Convenience wrapper: createJobFromFile + wait + get.
905
+ * Use for scripts; for production prefer createJobFromFile + webhooks/stream.
906
+ */
907
+ generateFromFile(req: ReportCreateJobFromFileRequest, opts?: {
908
+ wait?: WaitOptions;
909
+ }): Promise<Report>;
910
+ /**
911
+ * Convenience wrapper: createJobFromUrl + wait + get.
912
+ * Use for scripts; for production prefer createJobFromUrl + webhooks/stream.
913
+ */
914
+ generateFromUrl(req: ReportCreateJobFromUrlRequest, opts?: {
915
+ wait?: WaitOptions;
916
+ }): Promise<Report>;
917
+ makeHandle(jobId: string): ReportRunHandle;
918
+ private defaultIdempotencyKey;
919
+ private normalizeJobRequest;
920
+ }
921
+ //#endregion
922
+ //#region src/resources/webhooks.d.ts
923
+ /**
924
+ * Async signature verification using WebCrypto (works in modern Node and browsers).
925
+ * Signature scheme placeholder:
926
+ * headers["mappa-signature"] = "t=1700000000,v1=<hex_hmac_sha256>"
927
+ * Signed payload: `${t}.${rawBody}`
928
+ */
929
+ declare class WebhooksResource {
930
+ verifySignature(params: {
931
+ payload: string;
932
+ headers: Record<string, string | string[] | undefined>;
933
+ secret: string;
934
+ toleranceSec?: number;
935
+ }): Promise<{
936
+ ok: true;
937
+ }>;
938
+ parseEvent<T = unknown>(payload: string): {
939
+ id: string;
940
+ type: string;
941
+ createdAt: string;
942
+ data: T;
943
+ };
944
+ }
945
+ //#endregion
946
+ //#region src/Mappa.d.ts
947
+ /**
948
+ * Options for constructing a {@link Mappa} client.
949
+ */
950
+ type MappaClientOptions = {
951
+ /**
952
+ * API key used for authenticating requests.
953
+ */
954
+ apiKey: string;
955
+ /**
956
+ * Base URL for the Mappa API.
957
+ *
958
+ * @defaultValue "https://api.mappa.ai"
959
+ */
960
+ baseUrl?: string;
961
+ /**
962
+ * Per-request timeout, in milliseconds.
963
+ *
964
+ * Note: this timeout applies to individual HTTP attempts (including retries).
965
+ * Long-running workflows should use {@link JobsResource.wait} through
966
+ * {@link ReportsResource.makeHandle} instead.
967
+ *
968
+ * @defaultValue 30000
969
+ */
970
+ timeoutMs?: number;
971
+ /**
972
+ * Maximum number of retries performed by the transport for retryable requests.
973
+ *
974
+ * @defaultValue 2
975
+ */
976
+ maxRetries?: number;
977
+ /**
978
+ * Headers that will be sent with every request.
979
+ */
980
+ defaultHeaders?: Record<string, string>;
981
+ /**
982
+ * Custom fetch implementation (useful for polyfills, instrumentation, or tests).
983
+ */
984
+ fetch?: typeof fetch;
985
+ /**
986
+ * Overrides the User-Agent header.
987
+ */
988
+ userAgent?: string;
989
+ /**
990
+ * Telemetry hooks called on request/response/error.
991
+ */
992
+ telemetry?: Telemetry;
993
+ };
994
+ /**
995
+ * Main SDK client.
996
+ *
997
+ * Exposes resource namespaces ({@link Mappa.files}, {@link Mappa.reports}, etc.)
998
+ * and configures a shared HTTP transport.
999
+ */
1000
+ declare class Mappa {
1001
+ readonly files: FilesResource;
1002
+ readonly jobs: JobsResource;
1003
+ readonly reports: ReportsResource;
1004
+ readonly feedback: FeedbackResource;
1005
+ readonly credits: CreditsResource;
1006
+ readonly webhooks: WebhooksResource;
1007
+ readonly health: HealthResource;
1008
+ private readonly transport;
1009
+ private readonly opts;
1010
+ constructor(options: MappaClientOptions);
1011
+ withOptions(overrides: Partial<MappaClientOptions>): Mappa;
1012
+ close(): void;
1013
+ }
1014
+ //#endregion
1015
+ //#region src/index.d.ts
1016
+ /**
1017
+ * Type guard for catching SDK errors.
1018
+ */
1019
+ declare function isMappaError(err: unknown): err is MappaError;
1020
+ //#endregion
1021
+ export { ApiError, AuthError, CreditBalance, CreditTransaction, CreditTransactionType, CreditUsage, CursorPage, CursorPaginationParams, FeedbackReceipt, FileDeleteReceipt, Job, JobCanceledError, JobCreditReservation, JobEvent, JobFailedError, JobStage, JobStatus, JsonReport, JsonValue, Mappa, MappaError, MarkdownReport, MediaFile, MediaIdRef, MediaObject, MediaProcessingStatus, MediaRef, MediaRetention, OffsetPage, OffsetPaginationParams, PdfReport, RateLimitError, Report, ReportBase, ReportCreateJobRequest, ReportJobReceipt, ReportOutput, ReportOutputType, ReportRunHandle, ReportTemplateId, ReportTemplateParamsMap, RetentionLockResult, Subject, TargetDominant, TargetEntityId, TargetFor, TargetMagicHint, TargetOnMiss, TargetSelector, TargetStrategy, TargetStrategyMap, TargetTimeRange, TargetTimeRangeStrategy, UrlReport, Usage, ValidationError, WaitOptions, WebhookConfig, isJsonReport, isMappaError, isMarkdownReport, isPdfReport, isUrlReport };