@zweer/mage-space-client 0.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.
@@ -0,0 +1,800 @@
1
+ //#region lib/types.d.ts
2
+ /**
3
+ * Shared type definitions for the mage.space client.
4
+ *
5
+ * @remarks
6
+ * mage.space is not a REST API: it uses Next.js Server Actions. These types model
7
+ * the request/response shapes reverse-engineered in `docs/api/*.md`.
8
+ */
9
+ /** Minimal `fetch` signature the client depends on (injectable for tests). */
10
+ type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
11
+ /** In-memory representation of the Firebase token chain. */
12
+ interface AuthTokens {
13
+ /** Firebase ID token (JWT), ~1h lifetime — used as `authToken` in bodies. */
14
+ idToken: string;
15
+ /** Long-lived refresh token (rotated on each refresh). */
16
+ refreshToken: string;
17
+ /** Firebase user id (uid). */
18
+ userId: string;
19
+ /** Epoch ms at which `idToken` expires. */
20
+ expiresAt: number;
21
+ }
22
+ /** Firebase session cookie state (`__session`). */
23
+ interface SessionState {
24
+ /** The raw `__session` cookie value (a Firebase session JWT). */
25
+ cookie: string;
26
+ /** Epoch ms at which the session cookie expires (~24h). */
27
+ expiresAt: number;
28
+ }
29
+ /** Server Action function names the client relies on for the MVP surface. */
30
+ type ActionName = 'createUserSession' | 'deleteUserSession' | 'getUserHydrationData' | 'runArchitecture' | 'getHistoryById' | 'cancelArchitectureJob' | 'getHistoryPaginated' | 'getMentionSuggestionsParallel' | 'createCharacter' | 'updateCharacter' | 'deleteCharacter' | 'getCharacter' | 'getCharacters' | 'publishCharacter' | 'unpublishCharacter' | 'uploadCharacterImage' | 'uploadReferenceImage' | 'createReference' | 'updateReference' | 'deleteReference' | 'getReferences' | 'getReferencesPaginated' | 'getCharactersPaginated' | 'getCreationsPaginatedParallel' | 'deleteHistory' | 'deleteManyHistories' | 'deleteCreation' | 'deleteManyCreations' | 'saveCreation' | 'generateCharacterVoice' | 'followCharacter' | 'unfollowCharacter';
31
+ /** Map of Server Action function name → hex action hash. */
32
+ type ActionHashes = Record<string, string>;
33
+ /** A discovered (or seeded) set of action hashes for a single Vercel deploy. */
34
+ interface ActionSnapshot {
35
+ /** Vercel deployment id these hashes belong to (from `x-deployment-id`). */
36
+ deploymentId: string;
37
+ /** function name → hash. */
38
+ hashes: ActionHashes;
39
+ /** Epoch ms when this snapshot was produced. */
40
+ discoveredAt: number;
41
+ }
42
+ /**
43
+ * Pluggable persistence for the action snapshot.
44
+ *
45
+ * @remarks
46
+ * The default is in-memory (per-process). In a Lambda/serverless deployment,
47
+ * supply your own implementation backed by S3/DynamoDB/Redis/`/tmp` so discovery
48
+ * runs once and is shared across warm invocations and instances.
49
+ */
50
+ interface ActionCache {
51
+ load(): Promise<ActionSnapshot | null>;
52
+ save(snapshot: ActionSnapshot): Promise<void>;
53
+ }
54
+ type AspectRatio = 'portrait' | 'landscape' | 'square';
55
+ type Resolution = '1K' | '2K' | '4K';
56
+ /** `unlimited` = Pro Plus/Max, `play` = free tier, `gems` = gem-based. */
57
+ type GenerationMode = 'unlimited' | 'play' | 'gems';
58
+ /** Job lifecycle status returned by `getHistoryById`. */
59
+ type JobStatus = 'running' | 'success' | 'error';
60
+ /** A trained character referenced inside a generation prompt. */
61
+ interface CharacterRef {
62
+ id: string;
63
+ name: string;
64
+ username: string;
65
+ image_url: string;
66
+ /** Optional; serialized as the `$undefined` sentinel when absent. */
67
+ audio_url?: string;
68
+ }
69
+ /** The `architectureConfig` payload sent to `runArchitecture`. */
70
+ interface ArchitectureConfig {
71
+ seed: number | null;
72
+ prompt: string;
73
+ model_id: string;
74
+ fast_mode: boolean;
75
+ resolution: string;
76
+ architecture: string;
77
+ aspect_ratio?: AspectRatio;
78
+ /** Reference image URL, or the `$undefined` sentinel. */
79
+ image: string;
80
+ additional_images: string[];
81
+ characters: CharacterRef[];
82
+ references: unknown[];
83
+ audio_references: unknown[];
84
+ /** Moodboard id, or the `$undefined` sentinel. */
85
+ moodboard?: string;
86
+ }
87
+ /** The `result` object of a completed generation. */
88
+ interface GenerationResult {
89
+ data: {
90
+ image?: string;
91
+ video?: string;
92
+ seed?: number;
93
+ width?: number;
94
+ height?: number;
95
+ moderation?: {
96
+ is_nsfw: boolean;
97
+ is_forbidden: boolean;
98
+ };
99
+ };
100
+ type?: string;
101
+ duration?: number;
102
+ }
103
+ /** A single history/generation record returned by the API. */
104
+ interface HistoryItem {
105
+ id: string;
106
+ uid?: string;
107
+ status: JobStatus;
108
+ created_at?: string;
109
+ updated_at?: string;
110
+ error?: unknown;
111
+ result: GenerationResult | null;
112
+ concept_id?: string;
113
+ architecture_config?: ArchitectureConfig;
114
+ architecture?: string;
115
+ model_id?: string;
116
+ membership_tier?: string;
117
+ [key: string]: unknown;
118
+ }
119
+ /** A page of history records from `getHistoryPaginated`. */
120
+ interface HistoryPage {
121
+ histories: HistoryItem[];
122
+ hasMore: boolean;
123
+ }
124
+ interface MageSpaceClientOptions {
125
+ /** Firebase refresh token extracted from a logged-in browser session. */
126
+ refreshToken: string;
127
+ /** Persistence for discovered action hashes (default: in-memory). */
128
+ cache?: ActionCache;
129
+ /** Custom `fetch` implementation (default: global `fetch`). */
130
+ fetch?: FetchLike;
131
+ /** Override the default browser-like `user-agent`. */
132
+ userAgent?: string;
133
+ /** Override the bundled action-hash seed snapshot. */
134
+ seed?: ActionSnapshot;
135
+ /** Base URL (default `https://www.mage.space`). */
136
+ baseUrl?: string;
137
+ /** Override the Firebase Web API key. */
138
+ firebaseApiKey?: string;
139
+ }
140
+ interface GenerateOptions {
141
+ /** Prompt text; supports `@character-username` mentions. */
142
+ prompt: string;
143
+ /** Model/concept id. Defaults to the bundled mango-v3-pro concept id. */
144
+ conceptId?: string;
145
+ /** Model id (default `mango-v3-pro`). */
146
+ model?: string;
147
+ /** Architecture name (default `mango`). */
148
+ architecture?: string;
149
+ aspectRatio?: AspectRatio;
150
+ resolution?: Resolution;
151
+ /** Random seed (null = random). */
152
+ seed?: number | null;
153
+ /** Fast mode (may cost gems). */
154
+ fastMode?: boolean;
155
+ /** Characters to inject into the generation. */
156
+ characters?: CharacterRef[];
157
+ /**
158
+ * Reference assets to influence style/composition. Same object shape as
159
+ * characters; unlike characters they are NOT `@username`-mentioned in the
160
+ * prompt (see `docs/api/generation.md`).
161
+ */
162
+ references?: CharacterRef[];
163
+ /** First reference image URL. */
164
+ image?: string;
165
+ /** Additional reference image URLs. */
166
+ additionalImages?: string[];
167
+ /** Override the generation mode (default `unlimited`). */
168
+ generationMode?: GenerationMode;
169
+ }
170
+ /** Aspect ratios accepted by video architectures (`berry_aspect_ratio`). */
171
+ type VideoAspectRatio = '16:9' | '9:16' | '1:1' | '4:3' | '3:4';
172
+ /** Video output resolutions (`480p` unlimited on Pro Plus; `720p` costs gems). */
173
+ type VideoResolution = '480p' | '720p';
174
+ /**
175
+ * The `architectureConfig` payload for video architectures.
176
+ *
177
+ * @remarks
178
+ * Differs from the image {@link ArchitectureConfig}: `duration` is a string,
179
+ * aspect ratio is `berry_aspect_ratio`, and there is no `moodboard` field.
180
+ */
181
+ interface VideoArchitectureConfig {
182
+ seed: number | null;
183
+ prompt: string;
184
+ model_id: string;
185
+ fast_mode: boolean;
186
+ /** `480p` or `720p`. */
187
+ resolution: string;
188
+ architecture: string;
189
+ berry_aspect_ratio?: VideoAspectRatio;
190
+ /** Clip length in seconds — a string (e.g. `"3"`, `"5"`, `"7"`). */
191
+ duration: string;
192
+ /** First-frame image URL, or the `$undefined` sentinel. */
193
+ image: string;
194
+ additional_images: string[];
195
+ characters: CharacterRef[];
196
+ references: unknown[];
197
+ audio_references: unknown[];
198
+ }
199
+ interface GenerateVideoOptions {
200
+ /** Prompt text; supports `@character-username` mentions. */
201
+ prompt: string;
202
+ /** Model/concept id. Defaults to the bundled berry-2 concept id. */
203
+ conceptId?: string;
204
+ /** Model id (default `berry-2`). */
205
+ model?: string;
206
+ /** Architecture name (default `berry`). */
207
+ architecture?: string;
208
+ /** Video aspect ratio (default `9:16`). */
209
+ aspectRatio?: VideoAspectRatio;
210
+ /** Output resolution (default `480p`). */
211
+ resolution?: VideoResolution;
212
+ /** Clip length in seconds as a string (default `"3"`). */
213
+ duration?: string;
214
+ /** Random seed (null = random). */
215
+ seed?: number | null;
216
+ /** Fast mode (may cost gems). */
217
+ fastMode?: boolean;
218
+ /** Characters to inject into the video. */
219
+ characters?: CharacterRef[];
220
+ /** Reference assets (same shape as characters; not `@`-mentioned). */
221
+ references?: CharacterRef[];
222
+ /** First-frame image URL (text-to-video when omitted). */
223
+ image?: string;
224
+ /** Additional reference image URLs. */
225
+ additionalImages?: string[];
226
+ /** Override the generation mode (default `unlimited`). */
227
+ generationMode?: GenerationMode;
228
+ }
229
+ /**
230
+ * Required confirmation for irreversible, destructive operations.
231
+ *
232
+ * @remarks
233
+ * A safety flag so a mass/permanent delete cannot fire by accident. Pass
234
+ * `{ confirm: true }` to actually execute.
235
+ */
236
+ interface ConfirmOptions {
237
+ confirm: boolean;
238
+ }
239
+ interface WaitOptions {
240
+ /** Poll interval in ms (default 4000). */
241
+ intervalMs?: number;
242
+ /** Overall timeout in ms (default 300000). */
243
+ timeoutMs?: number;
244
+ /** Abort signal to cancel waiting. */
245
+ signal?: AbortSignal;
246
+ }
247
+ interface ListHistoryOptions {
248
+ /** Max results (default 10). */
249
+ limit?: number;
250
+ /** Pagination offset (default 0). */
251
+ offset?: number;
252
+ /** Filter by status; `all` disables the status filter (default `success`). */
253
+ status?: JobStatus | 'all';
254
+ }
255
+ /** Whether an asset is driven by an image or an audio reference. */
256
+ type Modality = 'image' | 'audio';
257
+ /** Asset visibility. */
258
+ type Visibility = 'private' | 'public';
259
+ /**
260
+ * A trained character (or reference asset) as returned by the API.
261
+ *
262
+ * @remarks
263
+ * References share this shape with `variant: "reference"`; characters use
264
+ * `variant: "character"`.
265
+ */
266
+ interface Character {
267
+ id: string;
268
+ uid?: string;
269
+ name: string;
270
+ username: string;
271
+ image_url: string;
272
+ audio_url: string | null;
273
+ modality?: Modality;
274
+ description?: string | null;
275
+ tags?: string[];
276
+ visibility?: Visibility;
277
+ moderation?: string[];
278
+ num_plays_all_time?: number;
279
+ num_plays_monthly?: number;
280
+ num_plays_daily?: number;
281
+ created_at?: string;
282
+ is_deleted?: boolean;
283
+ is_featured?: boolean;
284
+ variant?: string;
285
+ [key: string]: unknown;
286
+ }
287
+ /** A reference asset — structurally identical to {@link Character}. */
288
+ type Reference = Character;
289
+ /** Parsed result of `getMentionSuggestionsParallel`. */
290
+ interface CharacterSearchResult {
291
+ characters: Character[];
292
+ references: Reference[];
293
+ moodboards: unknown[];
294
+ }
295
+ interface SearchCharactersOptions {
296
+ /** Search text (matches character name). */
297
+ query: string;
298
+ /** Max results (default 10). */
299
+ limit?: number;
300
+ /** Include public references in the results (default false). */
301
+ includePublicReferences?: boolean;
302
+ /** Reference modalities to include (default `['image', 'audio']`). */
303
+ referenceModalities?: Modality[];
304
+ }
305
+ interface CreateCharacterInput {
306
+ /** Display name. */
307
+ name: string;
308
+ /** Unique @-mention handle (name + short suffix). */
309
+ username: string;
310
+ /** CDN URL from {@link uploadCharacterImage} or an existing character. */
311
+ image_url: string;
312
+ /** Voice audio URL (default null). */
313
+ audio_url?: string | null;
314
+ /** Optional description (default null). */
315
+ description?: string | null;
316
+ /** Category tags (default `[]`). */
317
+ tags?: string[];
318
+ /** Visibility (default `private`). */
319
+ visibility?: Visibility;
320
+ /** Moderation flags — always `[]` for new characters. */
321
+ moderation?: string[];
322
+ }
323
+ interface UpdateCharacterInput {
324
+ name?: string;
325
+ description?: string | null;
326
+ tags?: string[];
327
+ visibility?: Visibility;
328
+ audio_url?: string | null;
329
+ }
330
+ interface CreateReferenceInput {
331
+ /** Display name. */
332
+ name: string;
333
+ /** Unique handle (name + short suffix). */
334
+ username: string;
335
+ /** CDN URL from {@link uploadReferenceImage} (required for image refs). */
336
+ image_url?: string;
337
+ /** Audio URL (required for audio refs). */
338
+ audio_url?: string | null;
339
+ /** Reference modality (default `image`). */
340
+ modality?: Modality;
341
+ /** `reference` for image refs, `audio` for audio refs (default `reference`). */
342
+ variant?: string;
343
+ description?: string | null;
344
+ tags?: string[];
345
+ visibility?: Visibility;
346
+ moderation?: string[];
347
+ }
348
+ /** Reference asset variants. */
349
+ type ReferenceVariant = 'reference' | 'object' | 'outfit' | 'pose';
350
+ interface UpdateReferenceInput {
351
+ name?: string;
352
+ description?: string | null;
353
+ tags?: string[];
354
+ visibility?: Visibility;
355
+ }
356
+ /** Ordering for the paginated reference feed. */
357
+ type ReferenceOrder = 'trending' | 'top' | 'newest' | 'oldest';
358
+ interface ListReferencesOptions {
359
+ /** Max results per page (default 20). */
360
+ limit?: number;
361
+ /** Pagination offset (default 0). */
362
+ offset?: number;
363
+ /** Filter by owner uid (omit for the public feed). */
364
+ uid?: string;
365
+ /** Filter by visibility. */
366
+ visibility?: Visibility;
367
+ /** Sort order (default `top`). */
368
+ orderBy?: ReferenceOrder;
369
+ /** Only featured references. */
370
+ featuredOnly?: boolean;
371
+ /** Filter by modality (default `image`). */
372
+ modality?: Modality;
373
+ }
374
+ /** A page of references from `getReferencesPaginated`. */
375
+ interface ReferencePage {
376
+ references: Reference[];
377
+ hasMore: boolean;
378
+ }
379
+ interface ListCharactersOptions {
380
+ /** Max results per page (default 100). */
381
+ limit?: number;
382
+ /** Pagination offset (default 0). */
383
+ offset?: number;
384
+ /** Filter by owner uid (omit for the public feed). */
385
+ uid?: string;
386
+ /** Filter by visibility. */
387
+ visibility?: Visibility;
388
+ /** Filter by modality. */
389
+ modality?: Modality;
390
+ /** Only featured characters. */
391
+ featured?: boolean;
392
+ }
393
+ /** A page of characters from `getCharactersPaginated`. */
394
+ interface CharacterPage {
395
+ characters: Character[];
396
+ hasMore: boolean;
397
+ }
398
+ /** A permanently saved creation (as opposed to transient history). */
399
+ interface Creation {
400
+ id: string;
401
+ uid?: string;
402
+ /** Permanent CDN URL (not `/temp/30d/`). */
403
+ url: string;
404
+ hash?: string;
405
+ type?: 'image' | 'video';
406
+ visibility?: Visibility;
407
+ concept_id?: string;
408
+ architecture_config?: ArchitectureConfig;
409
+ metadata?: {
410
+ seed?: number;
411
+ width?: number;
412
+ height?: number;
413
+ duration?: number;
414
+ moderation?: {
415
+ is_nsfw: boolean;
416
+ is_forbidden: boolean;
417
+ };
418
+ };
419
+ created_at?: string;
420
+ updated_at?: string;
421
+ tags?: string[];
422
+ [key: string]: unknown;
423
+ }
424
+ /** A page of creations from `getCreationsPaginatedParallel`. */
425
+ interface CreationPage {
426
+ creations: Creation[];
427
+ hasMore: boolean;
428
+ }
429
+ interface ListCreationsOptions {
430
+ /** Max results (default 10). */
431
+ limit?: number;
432
+ /** Pagination offset (default 0). */
433
+ offset?: number;
434
+ }
435
+ interface GenerateVoiceOptions {
436
+ /** CDN URL of the character's reference image. */
437
+ imageUrl: string;
438
+ /** Text describing the desired voice (default empty). */
439
+ guidancePrompt?: string;
440
+ }
441
+ /** Result of `generateCharacterVoice`. */
442
+ interface VoiceResult {
443
+ ok: boolean;
444
+ data?: {
445
+ /** CDN URL of the generated MP3 voice. */
446
+ audioUrl: string;
447
+ /** Gems charged for the generation. */
448
+ gemsCharged?: number;
449
+ };
450
+ error?: {
451
+ code: string;
452
+ required_gems?: number;
453
+ balance_gems?: number;
454
+ };
455
+ }
456
+ //#endregion
457
+ //#region lib/actions.d.ts
458
+ /** Default in-process snapshot cache. */
459
+ declare class InMemoryActionCache implements ActionCache {
460
+ private snapshot;
461
+ load(): Promise<ActionSnapshot | null>;
462
+ save(snapshot: ActionSnapshot): Promise<void>;
463
+ }
464
+ interface DiscoveryOptions {
465
+ fetch: FetchLike;
466
+ baseUrl: string;
467
+ /** Single page to scrape for chunk references (overrides {@link discoveryPaths}). */
468
+ discoveryPath?: string;
469
+ /** Pages to scrape and union (default: the main app routes). */
470
+ discoveryPaths?: string[];
471
+ }
472
+ /**
473
+ * Discover the current Server Action hashes by scraping the page HTML for JS
474
+ * chunk URLs and extracting `createServerReference(...)` calls from each chunk.
475
+ *
476
+ * @throws {DiscoveryError} on network failure or when nothing is discovered.
477
+ */
478
+ declare function discoverActions(opts: DiscoveryOptions): Promise<ActionSnapshot>;
479
+ interface ActionRegistryOptions {
480
+ fetch: FetchLike;
481
+ baseUrl: string;
482
+ cache?: ActionCache;
483
+ seed?: ActionSnapshot;
484
+ discoveryPath?: string;
485
+ discoveryPaths?: string[];
486
+ /** Re-discover when the snapshot is older than this (ms). 0 = never by age. */
487
+ maxAgeMs?: number;
488
+ }
489
+ /**
490
+ * Serves action hashes from a warm seed / pluggable cache, discovering lazily and
491
+ * refreshing on staleness. Concurrent refreshes are de-duplicated (single-flight).
492
+ */
493
+ declare class ActionRegistry {
494
+ private readonly fetch;
495
+ private readonly baseUrl;
496
+ private readonly cache;
497
+ private readonly seed;
498
+ private readonly discoveryPath;
499
+ private readonly discoveryPaths;
500
+ private readonly maxAgeMs;
501
+ private snapshot;
502
+ private inflight;
503
+ constructor(opts: ActionRegistryOptions);
504
+ private isStale;
505
+ /** Return the current snapshot, loading from cache/seed or discovering as needed. */
506
+ getSnapshot(): Promise<ActionSnapshot>;
507
+ /** Force re-discovery. Concurrent callers share one in-flight discovery. */
508
+ refresh(): Promise<ActionSnapshot>;
509
+ /** Resolve a function name to its current hash + deployment id. */
510
+ getHash(action: ActionName | string): Promise<{
511
+ hash: string;
512
+ deploymentId: string;
513
+ }>;
514
+ /** Drop the cached snapshot and re-discover (called on a stale 404). */
515
+ invalidate(): Promise<ActionSnapshot>;
516
+ }
517
+ //#endregion
518
+ //#region lib/http.d.ts
519
+ interface CallActionParams {
520
+ /** Server Action function name (resolved to a hash via the registry). */
521
+ action: string;
522
+ /** Page path to POST to (e.g. `/explore`, `/creations`). */
523
+ path: string;
524
+ /** Request body — always a JSON array of arguments. */
525
+ args: unknown[];
526
+ /** `__session` cookie value for authenticated actions. */
527
+ session?: string;
528
+ }
529
+ interface CallActionResult<T> {
530
+ data: T;
531
+ headers: Headers;
532
+ deploymentId: string;
533
+ }
534
+ declare class HttpClient {
535
+ private readonly registry;
536
+ private readonly fetchImpl;
537
+ private readonly baseUrl;
538
+ private readonly userAgent;
539
+ constructor(registry: ActionRegistry, fetchImpl: FetchLike, baseUrl: string, userAgent?: string);
540
+ callAction<T = unknown>(params: CallActionParams, retried?: boolean): Promise<CallActionResult<T>>;
541
+ }
542
+ //#endregion
543
+ //#region lib/auth.d.ts
544
+ interface AuthManagerOptions {
545
+ refreshToken: string;
546
+ http: HttpClient;
547
+ fetch: FetchLike;
548
+ firebaseApiKey?: string;
549
+ /** Page path for the `createUserSession` action (default `/creations`). */
550
+ sessionPath?: string;
551
+ }
552
+ declare class AuthManager {
553
+ private refreshToken;
554
+ private readonly http;
555
+ private readonly fetchImpl;
556
+ private readonly apiKey;
557
+ private readonly sessionPath;
558
+ private tokens;
559
+ private session;
560
+ constructor(opts: AuthManagerOptions);
561
+ /** Return a valid Firebase ID token, refreshing via the refresh token if needed. */
562
+ getIdToken(): Promise<string>;
563
+ /** Return the Firebase uid (fetching an ID token first if necessary). */
564
+ getUserId(): Promise<string>;
565
+ /** Return a valid `__session` cookie, creating one via `createUserSession` if needed. */
566
+ getSession(): Promise<string>;
567
+ private refreshTokens;
568
+ }
569
+ //#endregion
570
+ //#region lib/characters.d.ts
571
+ declare class CharactersService {
572
+ private readonly http;
573
+ private readonly auth;
574
+ constructor(http: HttpClient, auth: AuthManager);
575
+ /** Search the caller's characters (and optionally public references) by name. */
576
+ search(opts: SearchCharactersOptions): Promise<CharacterSearchResult>;
577
+ /** Create a new character from an already-uploaded image URL. */
578
+ create(input: CreateCharacterInput): Promise<Character>;
579
+ /** Update a character's mutable fields (name, description, tags, visibility, voice). */
580
+ update(id: string, patch: UpdateCharacterInput): Promise<Character>;
581
+ /** Soft-delete a character. */
582
+ delete(id: string): Promise<void>;
583
+ /** Fetch a single character by id; resolves to `null` when it does not exist. */
584
+ get(id: string): Promise<Character | null>;
585
+ /** Fetch multiple characters by id in a single call. */
586
+ getMany(ids: string[]): Promise<Character[]>;
587
+ /** Make a character public. */
588
+ publish(id: string): Promise<void>;
589
+ /** Make a character private. */
590
+ unpublish(id: string): Promise<void>;
591
+ /**
592
+ * Upload a character reference image (base64 data URL) and return its CDN URL.
593
+ *
594
+ * @param dataUrl - `data:image/jpeg;base64,...` (JPEG preferred; PNG/WebP ok).
595
+ */
596
+ uploadImage(dataUrl: string): Promise<string>;
597
+ /**
598
+ * Browse characters with pagination.
599
+ *
600
+ * @remarks
601
+ * Omit `uid` to browse the public/featured feed; pass it to page through a
602
+ * single user's characters.
603
+ */
604
+ listPaginated(opts?: ListCharactersOptions): Promise<CharacterPage>;
605
+ /**
606
+ * Generate a voice for a character from its reference image.
607
+ *
608
+ * @remarks Costs gems (not covered by the unlimited tier).
609
+ * @experimental Request body inferred from JS bundle; not yet verified live.
610
+ */
611
+ generateVoice(opts: GenerateVoiceOptions): Promise<VoiceResult>;
612
+ /**
613
+ * Follow a (public) character.
614
+ *
615
+ * @experimental Request body inferred from JS bundle; not yet verified live.
616
+ */
617
+ follow(id: string): Promise<void>;
618
+ /**
619
+ * Unfollow a character.
620
+ *
621
+ * @experimental Request body inferred from JS bundle; not yet verified live.
622
+ */
623
+ unfollow(id: string): Promise<void>;
624
+ }
625
+ //#endregion
626
+ //#region lib/references.d.ts
627
+ declare class ReferencesService {
628
+ private readonly http;
629
+ private readonly auth;
630
+ constructor(http: HttpClient, auth: AuthManager);
631
+ /**
632
+ * Upload a reference image (base64 data URL) and return its CDN URL.
633
+ *
634
+ * @param dataUrl - `data:image/jpeg;base64,...` (JPEG preferred; PNG/WebP ok).
635
+ */
636
+ uploadImage(dataUrl: string): Promise<string>;
637
+ /** Create a reusable reference from an uploaded image/audio URL. */
638
+ create(input: CreateReferenceInput): Promise<Reference>;
639
+ /** Update a reference's mutable fields (name, description, tags, visibility). */
640
+ update(id: string, patch: UpdateReferenceInput): Promise<Reference>;
641
+ /**
642
+ * Permanently delete a reference (soft-delete). Irreversible — requires
643
+ * `{ confirm: true }`.
644
+ */
645
+ delete(id: string, opts?: ConfirmOptions): Promise<void>;
646
+ /** List the caller's own references for a given modality (default `image`). */
647
+ list(modality?: Modality): Promise<Reference[]>;
648
+ /**
649
+ * Browse references with pagination.
650
+ *
651
+ * @remarks
652
+ * Omit `uid` to browse the public/featured feed; pass it to page through a
653
+ * single user's references.
654
+ */
655
+ listPaginated(opts?: ListReferencesOptions): Promise<ReferencePage>;
656
+ }
657
+ //#endregion
658
+ //#region lib/client.d.ts
659
+ declare class MageSpaceClient {
660
+ private readonly registry;
661
+ private readonly auth;
662
+ private readonly generationService;
663
+ private readonly historyService;
664
+ /** Character management (search, CRUD, pagination, uploads). */
665
+ readonly characters: CharactersService;
666
+ /** Reference asset management (upload, create, update, list, feed). */
667
+ readonly references: ReferencesService;
668
+ constructor(options: MageSpaceClientOptions);
669
+ /** Submit a generation job; returns its `historyId`. */
670
+ generate(options: GenerateOptions): Promise<{
671
+ historyId: string;
672
+ }>;
673
+ /** Submit a video generation job (Berry-2 family); returns its `historyId`. */
674
+ generateVideo(options: GenerateVideoOptions): Promise<{
675
+ historyId: string;
676
+ }>;
677
+ /** Fetch the current state of a generation by id. */
678
+ getResult(historyId: string): Promise<HistoryItem>;
679
+ /** Poll until a generation finishes (or fails / times out). */
680
+ waitForResult(historyId: string, options?: WaitOptions): Promise<HistoryItem>;
681
+ /** Cancel a running generation job. */
682
+ cancelJob(historyId: string): Promise<void>;
683
+ /** List past generations for the authenticated user. */
684
+ listHistory(options?: ListHistoryOptions): Promise<HistoryPage>;
685
+ /** List the user's permanently saved creations. */
686
+ listCreations(options?: ListCreationsOptions): Promise<CreationPage>;
687
+ /** Save a completed generation result as a permanent creation. */
688
+ saveCreation(result: GenerationResult): Promise<void>;
689
+ /** Permanently delete a history item. Irreversible — requires `{ confirm: true }`. */
690
+ deleteHistory(historyId: string, options?: ConfirmOptions): Promise<void>;
691
+ /** Permanently delete many history items. Irreversible — requires `{ confirm: true }`. */
692
+ deleteManyHistories(historyIds: string[], options?: ConfirmOptions): Promise<void>;
693
+ /** Permanently delete a saved creation. Irreversible — requires `{ confirm: true }`. */
694
+ deleteCreation(creationId: string, options?: ConfirmOptions): Promise<void>;
695
+ /** Permanently delete many creations. Irreversible — requires `{ confirm: true }`. */
696
+ deleteManyCreations(creationIds: string[], options?: ConfirmOptions): Promise<void>;
697
+ /** Force re-discovery of the Server Action hashes. */
698
+ refreshActions(): Promise<ActionSnapshot>;
699
+ }
700
+ //#endregion
701
+ //#region lib/errors.d.ts
702
+ /** Typed error hierarchy for the mage.space client. */
703
+ /** Base class for every error thrown by this library. */
704
+ declare class MageSpaceError extends Error {
705
+ constructor(message: string, options?: {
706
+ cause?: unknown;
707
+ });
708
+ }
709
+ /** Authentication failures (token refresh, session creation). */
710
+ declare class AuthError extends MageSpaceError {
711
+ constructor(message: string, options?: {
712
+ cause?: unknown;
713
+ });
714
+ }
715
+ /** Action-hash discovery failures (page/chunk fetch, empty registry). */
716
+ declare class DiscoveryError extends MageSpaceError {
717
+ constructor(message: string, options?: {
718
+ cause?: unknown;
719
+ });
720
+ }
721
+ /** A Server Action returned 404, indicating a stale (post-deploy) hash. */
722
+ declare class StaleActionError extends MageSpaceError {
723
+ readonly action: string;
724
+ constructor(action: string, options?: {
725
+ cause?: unknown;
726
+ });
727
+ }
728
+ /** Failures while submitting or polling a generation job. */
729
+ declare class GenerationError extends MageSpaceError {
730
+ readonly code?: number | undefined;
731
+ constructor(message: string, code?: number | undefined, options?: {
732
+ cause?: unknown;
733
+ });
734
+ }
735
+ /** Failure to parse a React Server Component (RSC) wire response. */
736
+ declare class RscParseError extends MageSpaceError {
737
+ constructor(message: string, options?: {
738
+ cause?: unknown;
739
+ });
740
+ }
741
+ /** A wait/poll operation exceeded its deadline or was aborted. */
742
+ declare class TimeoutError extends MageSpaceError {
743
+ constructor(message: string, options?: {
744
+ cause?: unknown;
745
+ });
746
+ }
747
+ //#endregion
748
+ //#region lib/rsc.d.ts
749
+ /**
750
+ * Parse the raw Flight text into a map of `rowId → value`.
751
+ *
752
+ * @remarks
753
+ * Most rows are `id:<json>\n`, but text rows are length-delimited:
754
+ * `id:T<hexlen>,<hexlen UTF-8 bytes>` and are NOT newline-terminated — the next
755
+ * row begins immediately after the counted bytes. A naive line split therefore
756
+ * glues the following data row onto a multi-line prompt (which is exactly why
757
+ * large `getHistoryPaginated` responses failed to parse). This parser is
758
+ * position/length aware so length-delimited rows are consumed exactly and every
759
+ * subsequent row stays isolated.
760
+ */
761
+ declare function parseFlightRows(text: string): Map<string, unknown>;
762
+ /** Recursively resolve Flight sentinels/references within a parsed value. */
763
+ declare function resolveFlightValue(value: unknown, rows: Map<string, unknown>, seen?: Set<string>): unknown;
764
+ /**
765
+ * Parse a Server Action response and return the action's resolved return value.
766
+ *
767
+ * @throws {RscParseError} when the response contains no parseable rows.
768
+ */
769
+ declare function parseServerActionResponse<T = unknown>(text: string): T;
770
+ /**
771
+ * Unwrap a single-object result that some Server Actions (notably the
772
+ * `*Parallel` family) wrap in a one-element array.
773
+ *
774
+ * @remarks
775
+ * `getCreationsPaginatedParallel` and `getMentionSuggestionsParallel` return their
776
+ * payload as `[value]` on the RSC wire (`1:["$@2"]`), whereas most actions return
777
+ * the value directly. This normalizes object-returning actions to the value; it is
778
+ * a no-op when the response is already the object. Do NOT use it for actions whose
779
+ * genuine return type is an array (e.g. `getReferences`).
780
+ */
781
+ declare function unwrapResult<T>(value: unknown): T;
782
+ //#endregion
783
+ //#region lib/seed.d.ts
784
+ /**
785
+ * Bundled action-hash snapshot from the mage.space Vercel deploy discovered on
786
+ * 2026-08-06 (`docs/api/actions.md`).
787
+ *
788
+ * @remarks
789
+ * Used as a warm seed so the very first call does not pay the discovery cost.
790
+ * Hashes change on every deploy; when one goes stale the client re-discovers
791
+ * automatically (404 → invalidate → refresh).
792
+ */
793
+ declare const SEED_SNAPSHOT: ActionSnapshot;
794
+ //#endregion
795
+ //#region lib/index.d.ts
796
+ /** Public entry point for `@zweer/mage-space-client`. */
797
+ declare const VERSION = "0.0.0";
798
+ //#endregion
799
+ export { type ActionCache, type ActionHashes, type ActionName, ActionRegistry, type ActionSnapshot, type ArchitectureConfig, type AspectRatio, AuthError, type AuthTokens, type Character, type CharacterPage, type CharacterRef, type CharacterSearchResult, CharactersService, type ConfirmOptions, type CreateCharacterInput, type CreateReferenceInput, type Creation, type CreationPage, DiscoveryError, type FetchLike, type GenerateOptions, type GenerateVideoOptions, type GenerateVoiceOptions, GenerationError, type GenerationMode, type GenerationResult, type HistoryItem, type HistoryPage, InMemoryActionCache, type JobStatus, type ListCharactersOptions, type ListCreationsOptions, type ListHistoryOptions, type ListReferencesOptions, MageSpaceClient, type MageSpaceClientOptions, MageSpaceError, type Modality, type Reference, type ReferenceOrder, type ReferencePage, type ReferenceVariant, ReferencesService, type Resolution, RscParseError, SEED_SNAPSHOT, type SearchCharactersOptions, type SessionState, StaleActionError, TimeoutError, type UpdateCharacterInput, type UpdateReferenceInput, VERSION, type VideoArchitectureConfig, type VideoAspectRatio, type VideoResolution, type Visibility, type VoiceResult, type WaitOptions, discoverActions, parseFlightRows, parseServerActionResponse, resolveFlightValue, unwrapResult };
800
+ //# sourceMappingURL=index.d.cts.map