@snowcone-app/sdk 0.1.14 → 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.
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { createDevFetcher } from './dev-fetcher.cjs';
2
2
  import { PublicDesign, PublicFill, PublicOptions } from '@snowcone-app/mockup-url';
3
- import { O as OptionAttribute, a as OptionSelection, C as Combination, F as FrameworkAdapter, b as ComponentProps, c as ComponentDescriptor, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, g as FrameworkUtilities } from './websocket-Dum3OooZ.cjs';
4
- export { A as AdapterRegistry, M as MockupResult, P as ProductComponentContext, R as RealtimeMockupCallbacks, h as RealtimeMockupService, i as RealtimeMockupState, j as RenderResult, W as WebSocketConfig, k as WebSocketMessage, l as adapterRegistry, m as computeDisabledChoices, n as createComponent, o as defineComponent, p as deriveDefaultSelection, q as findBestCombination, r as getPricePreview, s as isOptionAvailable, t as resolveBestCombination } from './websocket-Dum3OooZ.cjs';
3
+ import { O as OptionAttribute, a as OptionSelection, C as Combination, F as FrameworkAdapter, b as ComponentProps, c as ComponentDescriptor, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, g as FrameworkUtilities, P as PlacementSettings, M as MockupResult, R as RealtimeMockupService } from './websocket-Poy8LZNA.cjs';
4
+ export { A as AdapterRegistry, h as ProductComponentContext, i as RealtimeMockupCallbacks, j as RealtimeMockupState, k as RenderResult, W as WebSocketConfig, l as WebSocketMessage, m as adapterRegistry, n as computeDisabledChoices, o as createComponent, p as defineComponent, q as deriveDefaultSelection, r as findBestCombination, s as getPricePreview, t as isOptionAvailable, u as resolveBestCombination } from './websocket-Poy8LZNA.cjs';
5
5
 
6
6
  interface CatalogProduct$2 {
7
7
  id: string;
@@ -16,7 +16,6 @@ interface CatalogProduct$2 {
16
16
  highestPrice?: number;
17
17
  mockups?: {
18
18
  id: string;
19
- ar: number;
20
19
  gvids: string[];
21
20
  }[];
22
21
  options?: {
@@ -2481,6 +2480,236 @@ declare class SvelteAdapter implements FrameworkAdapter<ComponentProps> {
2481
2480
  */
2482
2481
  declare function createSvelteComponent(descriptor: ComponentDescriptor, svelte: any): any;
2483
2482
 
2483
+ /**
2484
+ * Production realtime render WebSocket endpoint (the rendercenter edge).
2485
+ *
2486
+ * This is the value to connect to for server-side canvas rendering — open
2487
+ * `${REALTIME_WS_URL}?token=<grant>`. Replaces the old un-discoverable
2488
+ * `wss://WS_URL_NOT_CONFIGURED.invalid/realtime` placeholder so a 3rd party
2489
+ * can find the endpoint from the package alone (ADR-0079, Phase 2).
2490
+ */
2491
+ declare const REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
2492
+
2493
+ /**
2494
+ * Realtime grant helpers (ADR-0079, Phase 2).
2495
+ *
2496
+ * A realtime render session is authorized by a short-lived (60s) grant token.
2497
+ * There are two ways to obtain one, mirroring Stripe's pk_/sk_ split:
2498
+ *
2499
+ * - {@link mintRealtimeGrant} — SERVER-SIDE, with a secret API key (sk_).
2500
+ * - {@link fetchRealtimeGrant} — BROWSER, from your own proxy endpoint.
2501
+ *
2502
+ * The browser then opens `${REALTIME_WS_URL}?token=<token>` (RenderSession does
2503
+ * this for you).
2504
+ */
2505
+ /** A short-lived realtime session grant. */
2506
+ interface RealtimeGrant {
2507
+ /** Opaque session token to put on the WS URL as `?token=`. */
2508
+ token: string;
2509
+ /** Expiry, epoch seconds. Renew before this (RenderSession auto-renews). */
2510
+ expiresAt: number;
2511
+ }
2512
+ /** Default backend base URL hosting `POST /realtime/grant`. */
2513
+ declare const DEFAULT_GRANT_BASE = "https://api.snowcone.app";
2514
+ /**
2515
+ * SERVER-SIDE: mint a realtime grant with a secret API key (sk_). Call this
2516
+ * from YOUR backend — never the browser; the API key must stay secret. The key
2517
+ * needs the `mockups:realtime` (or `mockups`) scope and its organization must
2518
+ * own the target `shop`. Returns a 60s grant your browser code opens the WS
2519
+ * with (hand it down via your own endpoint + {@link fetchRealtimeGrant}).
2520
+ *
2521
+ * @example
2522
+ * // your backend route: POST /api/realtime/grant
2523
+ * const grant = await mintRealtimeGrant({ apiKey: process.env.SNOWCONE_API_KEY!, shop });
2524
+ * return Response.json(grant);
2525
+ */
2526
+ declare function mintRealtimeGrant(opts: {
2527
+ /** Secret API key (sk_) with the `mockups:realtime` or `mockups` scope. */
2528
+ apiKey: string;
2529
+ /** Target shop id (= shop.id). Must belong to the key's organization. */
2530
+ shop: string;
2531
+ /** Backend base URL. Defaults to {@link DEFAULT_GRANT_BASE}. */
2532
+ base?: string;
2533
+ /** Override fetch (e.g. in tests / non-global-fetch runtimes). */
2534
+ fetch?: typeof fetch;
2535
+ }): Promise<RealtimeGrant>;
2536
+ /**
2537
+ * BROWSER: fetch a grant from your own proxy endpoint, which calls
2538
+ * {@link mintRealtimeGrant} server-side (so the secret key never reaches the
2539
+ * browser). The proxy receives `POST { shop }` and returns `{ token, expiresAt }`.
2540
+ * This is the default token provider {@link RenderSession} uses when given a
2541
+ * `grantUrl`.
2542
+ */
2543
+ declare function fetchRealtimeGrant(grantUrl: string, shop: string, fetchImpl?: typeof fetch): Promise<RealtimeGrant>;
2544
+
2545
+ /**
2546
+ * RenderSession — a high-level facade over {@link RealtimeMockupService} for the
2547
+ * server-side canvas render flow (ADR-0079, Phase 2).
2548
+ *
2549
+ * It hides the connect → grant → config → renew → canvas_state choreography so a
2550
+ * 3rd party can do what the www PDP does in a few calls, without holding the
2551
+ * artwork bytes or rendering each placement client-side:
2552
+ *
2553
+ * @example
2554
+ * const session = new RenderSession({
2555
+ * shop: 'YOUR_SHOP_ID',
2556
+ * grantUrl: '/api/realtime/grant', // your proxy → mintRealtimeGrant (server)
2557
+ * product: { productId: 'BEEB77', mockupIds: ['front'] },
2558
+ * });
2559
+ * session.onMockups((results) => { img.src = results[0].imageUrl; });
2560
+ * await session.connect();
2561
+ * session.renderState('Front', serializeStateForServer(canvasState));
2562
+ *
2563
+ * For the low-level escape hatch, use {@link RealtimeMockupService} directly.
2564
+ */
2565
+
2566
+ /**
2567
+ * The server-render canvas state — the JSON produced by `serializeStateForServer()`
2568
+ * in `@snowcone-app/canvas` (its `ServerRenderRequest`). Typed structurally here
2569
+ * so the SDK stays dependency-free; if you have `@snowcone-app/canvas`, its
2570
+ * `ServerRenderRequest` is assignable to this. `schemaVersion` is the wire
2571
+ * contract version (`CANVAS_STATE_SCHEMA_VERSION`); a missing value is treated
2572
+ * as `1` by the renderer.
2573
+ */
2574
+ interface RenderState {
2575
+ schemaVersion?: number;
2576
+ artboards?: Array<Record<string, unknown>>;
2577
+ elements?: Array<Record<string, unknown>>;
2578
+ [key: string]: unknown;
2579
+ }
2580
+ /** Product the session renders against (Snowcone catalog ids). */
2581
+ interface RenderProduct {
2582
+ productId: string;
2583
+ /**
2584
+ * The mockup scenes to render — opaque catalog codes (the product's
2585
+ * `mockups[].id`, e.g. `'FV1qjO'`). These are a DIFFERENT namespace from the
2586
+ * `placement` you pass to {@link RenderSession.renderState} (a print-area name
2587
+ * like `'Front'`). Don't pass a placement name here.
2588
+ */
2589
+ mockupIds: string[];
2590
+ /**
2591
+ * Optional variant (gvid). Omit if the product has no variant axis. Required
2592
+ * for products with a color option — it auto-fills the color placement; without
2593
+ * it the render waits for a color blob that never comes.
2594
+ */
2595
+ variantId?: string;
2596
+ /** Render width in px (default 1000). */
2597
+ width?: number;
2598
+ /** Per-placement settings (tiling, scale mode). */
2599
+ placementSettings?: Record<string, PlacementSettings>;
2600
+ }
2601
+ interface RenderSessionOptions {
2602
+ /** Publishable shop id (= shop.id, like Stripe pk_). */
2603
+ shop: string;
2604
+ /** Product config. Can also be set later via {@link RenderSession.setProduct}. */
2605
+ product?: RenderProduct;
2606
+ /** Realtime WS endpoint. Defaults to {@link REALTIME_WS_URL}. */
2607
+ wsUrl?: string;
2608
+ /**
2609
+ * How to authorize the session. Provide exactly one:
2610
+ * - `grantUrl`: your endpoint that returns `{ token, expiresAt }` for
2611
+ * `POST { shop }` (recommended — a same-origin proxy to `mintRealtimeGrant`).
2612
+ * - `getToken`: full control over fetching the grant.
2613
+ */
2614
+ grantUrl?: string;
2615
+ getToken?: () => Promise<RealtimeGrant>;
2616
+ /** Override fetch (used with `grantUrl`). */
2617
+ fetch?: typeof fetch;
2618
+ }
2619
+ declare class RenderSession {
2620
+ private readonly svc;
2621
+ private readonly opts;
2622
+ private product;
2623
+ private mockupCb;
2624
+ private errorCb;
2625
+ private ready;
2626
+ constructor(opts: RenderSessionOptions);
2627
+ /** Register a callback fired whenever rendered mockup URLs update. */
2628
+ onMockups(cb: (results: MockupResult[]) => void): this;
2629
+ /** Register an error callback (server/transport errors). */
2630
+ onError(cb: (error: string) => void): this;
2631
+ /** Set or update the product. Sends config immediately if already connected. */
2632
+ setProduct(product: RenderProduct): void;
2633
+ /**
2634
+ * Connect, authorize, and configure. Resolves once the session is ready to
2635
+ * accept {@link RenderSession.renderState}. Idempotent.
2636
+ */
2637
+ connect(): Promise<void>;
2638
+ /**
2639
+ * Render a canvas state for a placement. The server rasterizes it and fetches
2640
+ * the assets referenced inside — no pixels are uploaded. Results arrive via
2641
+ * {@link RenderSession.onMockups}. Safe to call repeatedly (e.g. on every
2642
+ * canvas edit); pass `throttleMs` to debounce during live dragging.
2643
+ *
2644
+ * `placement` is the print-area NAME (e.g. `'Front'`, the product's
2645
+ * `placements[].label`) — a different id from the product's `mockupIds`, and it
2646
+ * must match an artboard in `state`. The server renders only once it has a state
2647
+ * for EVERY required placement, so on a multi-placement product call this once
2648
+ * per placement; a missing one surfaces as an `incomplete_canvas_placements`
2649
+ * error on {@link RenderSession.onError}.
2650
+ *
2651
+ * `state` is the flattened `serializeStateForServer()` shape — NOT the
2652
+ * un-flattened shape `createDesignState` takes.
2653
+ */
2654
+ renderState(placement: string, state: RenderState, throttleMs?: number): Promise<void>;
2655
+ /**
2656
+ * Render a SAVED canvas by reference (ADR-0079 Phase 4). The server resolves
2657
+ * the `stateId`, fetches the referenced assets, and renders — no pixels are
2658
+ * uploaded and you don't need to hold the canvas JSON. Ideal for re-rendering
2659
+ * a stored design (fulfillment, agents, server-to-server). Results arrive via
2660
+ * {@link RenderSession.onMockups}.
2661
+ */
2662
+ renderSavedState(placement: string, stateId: string): Promise<void>;
2663
+ /** Update only the mockup ids to render (reuses the current state). */
2664
+ updateMockupIds(mockupIds: string[]): void;
2665
+ /** Current rendered results. */
2666
+ getMockups(): MockupResult[];
2667
+ /** Close the WebSocket and stop auto-renew. */
2668
+ close(): void;
2669
+ /** Escape hatch: the underlying low-level service. */
2670
+ get service(): RealtimeMockupService;
2671
+ private toConfig;
2672
+ }
2673
+
2674
+ interface CreateDesignStateInput {
2675
+ /** Catalog product code the design targets. */
2676
+ productId: string;
2677
+ /**
2678
+ * The canvas state to persist — the **raw, un-flattened** stored shape:
2679
+ * top-level `elements` with `transformType` + nested `transformData`, plus
2680
+ * bare `artboards` metadata. The server flattens this at render time
2681
+ * (`normalizeCanvasState`).
2682
+ *
2683
+ * ⚠️ This is NOT the `serializeStateForServer()` output you pass to
2684
+ * `RenderSession.renderState` — that shape is already flattened and will
2685
+ * mis-render if stored here. Persist the raw canvas state (e.g. `toJSON()`
2686
+ * from the editor), not the server-render payload.
2687
+ */
2688
+ state: RenderState | Record<string, unknown>;
2689
+ /**
2690
+ * Preview thumbnail as a base64 PNG/JPEG (no data: prefix). Optional —
2691
+ * defaults to a 1×1 transparent PNG, which is fine for render-only use.
2692
+ */
2693
+ previewBase64?: string;
2694
+ /** Backend base URL. Defaults to {@link DEFAULT_GRANT_BASE}. */
2695
+ base?: string;
2696
+ /** Override fetch (tests / non-global-fetch runtimes). */
2697
+ fetch?: typeof fetch;
2698
+ }
2699
+ interface CreatedDesignState {
2700
+ /** The id to pass to `renderSavedState(placement, stateId)`. */
2701
+ stateId: string;
2702
+ /** Content-addressed URL of the persisted state JSON. */
2703
+ stateUrl: string;
2704
+ /** Content-addressed URL of the preview image. */
2705
+ previewUrl: string;
2706
+ }
2707
+ /**
2708
+ * Persist a canvas state and return its `stateId` (+ URLs). Pair with
2709
+ * `RenderSession.renderSavedState(placement, stateId)`.
2710
+ */
2711
+ declare function createDesignState(input: CreateDesignStateInput): Promise<CreatedDesignState>;
2712
+
2484
2713
  interface ProductPlacement {
2485
2714
  label: string;
2486
2715
  x: number;
@@ -2535,4 +2764,4 @@ declare function getProduct(idOrSlug: string, config?: Partial<SdkConfig>): Prom
2535
2764
  */
2536
2765
  declare function createClient(config: SdkConfig): SnowconeClient;
2537
2766
 
2538
- export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogListResponse, type CatalogProduct$2 as CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_COLOR, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, type RateLimitState, type RegularArtwork, type SdkConfig, type SeamlessPattern, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, autoRegister, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, withContext, withErrorHandling, withSyncErrorHandling };
2767
+ export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogListResponse, type CatalogProduct$2 as CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, autoRegister, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, withContext, withErrorHandling, withSyncErrorHandling };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { createDevFetcher } from './dev-fetcher.js';
2
2
  import { PublicDesign, PublicFill, PublicOptions } from '@snowcone-app/mockup-url';
3
- import { O as OptionAttribute, a as OptionSelection, C as Combination, F as FrameworkAdapter, b as ComponentProps, c as ComponentDescriptor, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, g as FrameworkUtilities } from './websocket-Dum3OooZ.js';
4
- export { A as AdapterRegistry, M as MockupResult, P as ProductComponentContext, R as RealtimeMockupCallbacks, h as RealtimeMockupService, i as RealtimeMockupState, j as RenderResult, W as WebSocketConfig, k as WebSocketMessage, l as adapterRegistry, m as computeDisabledChoices, n as createComponent, o as defineComponent, p as deriveDefaultSelection, q as findBestCombination, r as getPricePreview, s as isOptionAvailable, t as resolveBestCombination } from './websocket-Dum3OooZ.js';
3
+ import { O as OptionAttribute, a as OptionSelection, C as Combination, F as FrameworkAdapter, b as ComponentProps, c as ComponentDescriptor, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, g as FrameworkUtilities, P as PlacementSettings, M as MockupResult, R as RealtimeMockupService } from './websocket-Poy8LZNA.js';
4
+ export { A as AdapterRegistry, h as ProductComponentContext, i as RealtimeMockupCallbacks, j as RealtimeMockupState, k as RenderResult, W as WebSocketConfig, l as WebSocketMessage, m as adapterRegistry, n as computeDisabledChoices, o as createComponent, p as defineComponent, q as deriveDefaultSelection, r as findBestCombination, s as getPricePreview, t as isOptionAvailable, u as resolveBestCombination } from './websocket-Poy8LZNA.js';
5
5
 
6
6
  interface CatalogProduct$2 {
7
7
  id: string;
@@ -16,7 +16,6 @@ interface CatalogProduct$2 {
16
16
  highestPrice?: number;
17
17
  mockups?: {
18
18
  id: string;
19
- ar: number;
20
19
  gvids: string[];
21
20
  }[];
22
21
  options?: {
@@ -2481,6 +2480,236 @@ declare class SvelteAdapter implements FrameworkAdapter<ComponentProps> {
2481
2480
  */
2482
2481
  declare function createSvelteComponent(descriptor: ComponentDescriptor, svelte: any): any;
2483
2482
 
2483
+ /**
2484
+ * Production realtime render WebSocket endpoint (the rendercenter edge).
2485
+ *
2486
+ * This is the value to connect to for server-side canvas rendering — open
2487
+ * `${REALTIME_WS_URL}?token=<grant>`. Replaces the old un-discoverable
2488
+ * `wss://WS_URL_NOT_CONFIGURED.invalid/realtime` placeholder so a 3rd party
2489
+ * can find the endpoint from the package alone (ADR-0079, Phase 2).
2490
+ */
2491
+ declare const REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
2492
+
2493
+ /**
2494
+ * Realtime grant helpers (ADR-0079, Phase 2).
2495
+ *
2496
+ * A realtime render session is authorized by a short-lived (60s) grant token.
2497
+ * There are two ways to obtain one, mirroring Stripe's pk_/sk_ split:
2498
+ *
2499
+ * - {@link mintRealtimeGrant} — SERVER-SIDE, with a secret API key (sk_).
2500
+ * - {@link fetchRealtimeGrant} — BROWSER, from your own proxy endpoint.
2501
+ *
2502
+ * The browser then opens `${REALTIME_WS_URL}?token=<token>` (RenderSession does
2503
+ * this for you).
2504
+ */
2505
+ /** A short-lived realtime session grant. */
2506
+ interface RealtimeGrant {
2507
+ /** Opaque session token to put on the WS URL as `?token=`. */
2508
+ token: string;
2509
+ /** Expiry, epoch seconds. Renew before this (RenderSession auto-renews). */
2510
+ expiresAt: number;
2511
+ }
2512
+ /** Default backend base URL hosting `POST /realtime/grant`. */
2513
+ declare const DEFAULT_GRANT_BASE = "https://api.snowcone.app";
2514
+ /**
2515
+ * SERVER-SIDE: mint a realtime grant with a secret API key (sk_). Call this
2516
+ * from YOUR backend — never the browser; the API key must stay secret. The key
2517
+ * needs the `mockups:realtime` (or `mockups`) scope and its organization must
2518
+ * own the target `shop`. Returns a 60s grant your browser code opens the WS
2519
+ * with (hand it down via your own endpoint + {@link fetchRealtimeGrant}).
2520
+ *
2521
+ * @example
2522
+ * // your backend route: POST /api/realtime/grant
2523
+ * const grant = await mintRealtimeGrant({ apiKey: process.env.SNOWCONE_API_KEY!, shop });
2524
+ * return Response.json(grant);
2525
+ */
2526
+ declare function mintRealtimeGrant(opts: {
2527
+ /** Secret API key (sk_) with the `mockups:realtime` or `mockups` scope. */
2528
+ apiKey: string;
2529
+ /** Target shop id (= shop.id). Must belong to the key's organization. */
2530
+ shop: string;
2531
+ /** Backend base URL. Defaults to {@link DEFAULT_GRANT_BASE}. */
2532
+ base?: string;
2533
+ /** Override fetch (e.g. in tests / non-global-fetch runtimes). */
2534
+ fetch?: typeof fetch;
2535
+ }): Promise<RealtimeGrant>;
2536
+ /**
2537
+ * BROWSER: fetch a grant from your own proxy endpoint, which calls
2538
+ * {@link mintRealtimeGrant} server-side (so the secret key never reaches the
2539
+ * browser). The proxy receives `POST { shop }` and returns `{ token, expiresAt }`.
2540
+ * This is the default token provider {@link RenderSession} uses when given a
2541
+ * `grantUrl`.
2542
+ */
2543
+ declare function fetchRealtimeGrant(grantUrl: string, shop: string, fetchImpl?: typeof fetch): Promise<RealtimeGrant>;
2544
+
2545
+ /**
2546
+ * RenderSession — a high-level facade over {@link RealtimeMockupService} for the
2547
+ * server-side canvas render flow (ADR-0079, Phase 2).
2548
+ *
2549
+ * It hides the connect → grant → config → renew → canvas_state choreography so a
2550
+ * 3rd party can do what the www PDP does in a few calls, without holding the
2551
+ * artwork bytes or rendering each placement client-side:
2552
+ *
2553
+ * @example
2554
+ * const session = new RenderSession({
2555
+ * shop: 'YOUR_SHOP_ID',
2556
+ * grantUrl: '/api/realtime/grant', // your proxy → mintRealtimeGrant (server)
2557
+ * product: { productId: 'BEEB77', mockupIds: ['front'] },
2558
+ * });
2559
+ * session.onMockups((results) => { img.src = results[0].imageUrl; });
2560
+ * await session.connect();
2561
+ * session.renderState('Front', serializeStateForServer(canvasState));
2562
+ *
2563
+ * For the low-level escape hatch, use {@link RealtimeMockupService} directly.
2564
+ */
2565
+
2566
+ /**
2567
+ * The server-render canvas state — the JSON produced by `serializeStateForServer()`
2568
+ * in `@snowcone-app/canvas` (its `ServerRenderRequest`). Typed structurally here
2569
+ * so the SDK stays dependency-free; if you have `@snowcone-app/canvas`, its
2570
+ * `ServerRenderRequest` is assignable to this. `schemaVersion` is the wire
2571
+ * contract version (`CANVAS_STATE_SCHEMA_VERSION`); a missing value is treated
2572
+ * as `1` by the renderer.
2573
+ */
2574
+ interface RenderState {
2575
+ schemaVersion?: number;
2576
+ artboards?: Array<Record<string, unknown>>;
2577
+ elements?: Array<Record<string, unknown>>;
2578
+ [key: string]: unknown;
2579
+ }
2580
+ /** Product the session renders against (Snowcone catalog ids). */
2581
+ interface RenderProduct {
2582
+ productId: string;
2583
+ /**
2584
+ * The mockup scenes to render — opaque catalog codes (the product's
2585
+ * `mockups[].id`, e.g. `'FV1qjO'`). These are a DIFFERENT namespace from the
2586
+ * `placement` you pass to {@link RenderSession.renderState} (a print-area name
2587
+ * like `'Front'`). Don't pass a placement name here.
2588
+ */
2589
+ mockupIds: string[];
2590
+ /**
2591
+ * Optional variant (gvid). Omit if the product has no variant axis. Required
2592
+ * for products with a color option — it auto-fills the color placement; without
2593
+ * it the render waits for a color blob that never comes.
2594
+ */
2595
+ variantId?: string;
2596
+ /** Render width in px (default 1000). */
2597
+ width?: number;
2598
+ /** Per-placement settings (tiling, scale mode). */
2599
+ placementSettings?: Record<string, PlacementSettings>;
2600
+ }
2601
+ interface RenderSessionOptions {
2602
+ /** Publishable shop id (= shop.id, like Stripe pk_). */
2603
+ shop: string;
2604
+ /** Product config. Can also be set later via {@link RenderSession.setProduct}. */
2605
+ product?: RenderProduct;
2606
+ /** Realtime WS endpoint. Defaults to {@link REALTIME_WS_URL}. */
2607
+ wsUrl?: string;
2608
+ /**
2609
+ * How to authorize the session. Provide exactly one:
2610
+ * - `grantUrl`: your endpoint that returns `{ token, expiresAt }` for
2611
+ * `POST { shop }` (recommended — a same-origin proxy to `mintRealtimeGrant`).
2612
+ * - `getToken`: full control over fetching the grant.
2613
+ */
2614
+ grantUrl?: string;
2615
+ getToken?: () => Promise<RealtimeGrant>;
2616
+ /** Override fetch (used with `grantUrl`). */
2617
+ fetch?: typeof fetch;
2618
+ }
2619
+ declare class RenderSession {
2620
+ private readonly svc;
2621
+ private readonly opts;
2622
+ private product;
2623
+ private mockupCb;
2624
+ private errorCb;
2625
+ private ready;
2626
+ constructor(opts: RenderSessionOptions);
2627
+ /** Register a callback fired whenever rendered mockup URLs update. */
2628
+ onMockups(cb: (results: MockupResult[]) => void): this;
2629
+ /** Register an error callback (server/transport errors). */
2630
+ onError(cb: (error: string) => void): this;
2631
+ /** Set or update the product. Sends config immediately if already connected. */
2632
+ setProduct(product: RenderProduct): void;
2633
+ /**
2634
+ * Connect, authorize, and configure. Resolves once the session is ready to
2635
+ * accept {@link RenderSession.renderState}. Idempotent.
2636
+ */
2637
+ connect(): Promise<void>;
2638
+ /**
2639
+ * Render a canvas state for a placement. The server rasterizes it and fetches
2640
+ * the assets referenced inside — no pixels are uploaded. Results arrive via
2641
+ * {@link RenderSession.onMockups}. Safe to call repeatedly (e.g. on every
2642
+ * canvas edit); pass `throttleMs` to debounce during live dragging.
2643
+ *
2644
+ * `placement` is the print-area NAME (e.g. `'Front'`, the product's
2645
+ * `placements[].label`) — a different id from the product's `mockupIds`, and it
2646
+ * must match an artboard in `state`. The server renders only once it has a state
2647
+ * for EVERY required placement, so on a multi-placement product call this once
2648
+ * per placement; a missing one surfaces as an `incomplete_canvas_placements`
2649
+ * error on {@link RenderSession.onError}.
2650
+ *
2651
+ * `state` is the flattened `serializeStateForServer()` shape — NOT the
2652
+ * un-flattened shape `createDesignState` takes.
2653
+ */
2654
+ renderState(placement: string, state: RenderState, throttleMs?: number): Promise<void>;
2655
+ /**
2656
+ * Render a SAVED canvas by reference (ADR-0079 Phase 4). The server resolves
2657
+ * the `stateId`, fetches the referenced assets, and renders — no pixels are
2658
+ * uploaded and you don't need to hold the canvas JSON. Ideal for re-rendering
2659
+ * a stored design (fulfillment, agents, server-to-server). Results arrive via
2660
+ * {@link RenderSession.onMockups}.
2661
+ */
2662
+ renderSavedState(placement: string, stateId: string): Promise<void>;
2663
+ /** Update only the mockup ids to render (reuses the current state). */
2664
+ updateMockupIds(mockupIds: string[]): void;
2665
+ /** Current rendered results. */
2666
+ getMockups(): MockupResult[];
2667
+ /** Close the WebSocket and stop auto-renew. */
2668
+ close(): void;
2669
+ /** Escape hatch: the underlying low-level service. */
2670
+ get service(): RealtimeMockupService;
2671
+ private toConfig;
2672
+ }
2673
+
2674
+ interface CreateDesignStateInput {
2675
+ /** Catalog product code the design targets. */
2676
+ productId: string;
2677
+ /**
2678
+ * The canvas state to persist — the **raw, un-flattened** stored shape:
2679
+ * top-level `elements` with `transformType` + nested `transformData`, plus
2680
+ * bare `artboards` metadata. The server flattens this at render time
2681
+ * (`normalizeCanvasState`).
2682
+ *
2683
+ * ⚠️ This is NOT the `serializeStateForServer()` output you pass to
2684
+ * `RenderSession.renderState` — that shape is already flattened and will
2685
+ * mis-render if stored here. Persist the raw canvas state (e.g. `toJSON()`
2686
+ * from the editor), not the server-render payload.
2687
+ */
2688
+ state: RenderState | Record<string, unknown>;
2689
+ /**
2690
+ * Preview thumbnail as a base64 PNG/JPEG (no data: prefix). Optional —
2691
+ * defaults to a 1×1 transparent PNG, which is fine for render-only use.
2692
+ */
2693
+ previewBase64?: string;
2694
+ /** Backend base URL. Defaults to {@link DEFAULT_GRANT_BASE}. */
2695
+ base?: string;
2696
+ /** Override fetch (tests / non-global-fetch runtimes). */
2697
+ fetch?: typeof fetch;
2698
+ }
2699
+ interface CreatedDesignState {
2700
+ /** The id to pass to `renderSavedState(placement, stateId)`. */
2701
+ stateId: string;
2702
+ /** Content-addressed URL of the persisted state JSON. */
2703
+ stateUrl: string;
2704
+ /** Content-addressed URL of the preview image. */
2705
+ previewUrl: string;
2706
+ }
2707
+ /**
2708
+ * Persist a canvas state and return its `stateId` (+ URLs). Pair with
2709
+ * `RenderSession.renderSavedState(placement, stateId)`.
2710
+ */
2711
+ declare function createDesignState(input: CreateDesignStateInput): Promise<CreatedDesignState>;
2712
+
2484
2713
  interface ProductPlacement {
2485
2714
  label: string;
2486
2715
  x: number;
@@ -2535,4 +2764,4 @@ declare function getProduct(idOrSlug: string, config?: Partial<SdkConfig>): Prom
2535
2764
  */
2536
2765
  declare function createClient(config: SdkConfig): SnowconeClient;
2537
2766
 
2538
- export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogListResponse, type CatalogProduct$2 as CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_COLOR, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, type RateLimitState, type RegularArtwork, type SdkConfig, type SeamlessPattern, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, autoRegister, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, withContext, withErrorHandling, withSyncErrorHandling };
2767
+ export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogListResponse, type CatalogProduct$2 as CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, autoRegister, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, withContext, withErrorHandling, withSyncErrorHandling };