@snowcone-app/sdk 0.20.2 → 0.23.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/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.23.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#2249](https://github.com/snowcone-app/snowcone-monorepo/pull/2249) [`19f7ee5`](https://github.com/snowcone-app/snowcone-monorepo/commit/19f7ee583638ccedd8fd5f309ad3e5ba6a06c0f9) Thanks [@kevinsproles](https://github.com/kevinsproles)! - A mockup whose scene failed render parity is refused by the server (`E_MOCKUP_NOT_BLESSED`) instead of silently rendering on the slow path. `RealtimeRenderError` gains `mockupId` for per-mockup errors; `RealtimeProvider` exposes `unavailableMockups` (mockupId → error) and `HeroProductImage` shows that mockup as unavailable (`data-mockup-unavailable`) while the others keep streaming.
8
+
9
+ ## 0.22.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#2240](https://github.com/snowcone-app/snowcone-monorepo/pull/2240) [`61c4826`](https://github.com/snowcone-app/snowcone-monorepo/commit/61c48267d77b93628ef525df5a6aee66421d67f7) Thanks [@kevinsproles](https://github.com/kevinsproles)! - Realtime send policy: pipeline depth two. `CanvasExportService` now keeps up to two edits in flight (`maxInFlight`, default 2) before holding the latest state — the box's window is ~30 ms of a ~96 ms edit→frame, so one in flight left it idle ~70% of every drag cycle. `RealtimeProvider` settles once per landed send (every mockup of a `requestVersion`) instead of on the first frame after any send, using the SDK's new `getLastSentVersion()` on the realtime service and hook.
14
+
15
+ ## 0.21.0
16
+
17
+ ### Minor Changes
18
+
19
+ - [#2223](https://github.com/snowcone-app/snowcone-monorepo/pull/2223) [`aaa73cc`](https://github.com/snowcone-app/snowcone-monorepo/commit/aaa73ccb4b2d4c7c107b66f18be29f67032422b8) Thanks [@kevinsproles](https://github.com/kevinsproles)! - Realtime frames now carry their own timing. Every `MockupResult` gets `rtTiming` (the render node's per-frame Server-Timing envelope: receive → guard → canvas raster → coalesce wait → composite → store → deliver, with byte sizes and the box id), `clientRoundTripMs` (the canvas_state send this frame answers → its arrival, as the client saw it) and `imageDelivery` ('ws' | 'url'). `onConnected` receives `{ box }` and `getState().box` names the render node that answered the handshake.
20
+
21
+ ## 0.20.3
22
+
23
+ ### Patch Changes
24
+
25
+ - [#1630](https://github.com/snowcone-app/snowcone-monorepo/pull/1630) [`e57a5bc`](https://github.com/snowcone-app/snowcone-monorepo/commit/e57a5bcb3b62ac612e43c47ab2709992ef6db385) Thanks [@kevinsproles](https://github.com/kevinsproles)! - Realtime: keep a ws-delivered `blob:` frame when the `all_mockups_rendered` summary repeats the fallback `imageUrl`. The summary merge matched on URL equality, which never matched a frame-swapped entry, so the client re-fetched the fallback URL (on fleet nodes an unreachable internal address).
26
+
3
27
  ## 0.20.2
4
28
 
5
29
  ### Patch Changes
@@ -85,6 +85,7 @@ var ALLOWED_WIDTHS = [
85
85
  3e3,
86
86
  4e3
87
87
  ];
88
+ var MAX_RENDER_URL_LENGTH = 12 * 1024;
88
89
  function normalizeWidth(width) {
89
90
  for (let i = ALLOWED_WIDTHS.length - 1; i >= 0; i--) {
90
91
  if (ALLOWED_WIDTHS[i] <= width) return ALLOWED_WIDTHS[i];
@@ -262,6 +263,7 @@ function canonicalForSig(url) {
262
263
  const rawValue = eq === -1 ? "" : segment.slice(eq + 1);
263
264
  const key = decodeURIComponent(rawKey);
264
265
  if (key === "signature") continue;
266
+ if (key === "debug") continue;
265
267
  pairs.push({ key, raw: rawValue });
266
268
  }
267
269
  }
@@ -2,6 +2,13 @@
2
2
  var REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
3
3
 
4
4
  // src/realtime/websocket.ts
5
+ function pruneUndefined(obj) {
6
+ const out = {};
7
+ for (const [k, v] of Object.entries(obj)) {
8
+ if (v !== void 0) out[k] = v;
9
+ }
10
+ return out;
11
+ }
5
12
  function randHex(len) {
6
13
  const arr = new Uint8Array(len);
7
14
  globalThis.crypto.getRandomValues(arr);
@@ -20,6 +27,9 @@ var RealtimeMockupService = class {
20
27
  config = null;
21
28
  configSent = false;
22
29
  sessionId = null;
30
+ // Render node that answered the handshake (`connected.box`), for labs and
31
+ // support: a realtime session has no response headers to read it from.
32
+ box = null;
23
33
  isConfigured = false;
24
34
  mockupResults = [];
25
35
  status = "Disconnected";
@@ -65,6 +75,13 @@ var RealtimeMockupService = class {
65
75
  // Session-grant auth: when set, connect() fetches a short-lived token, opens
66
76
  // the WS with `?token=`, and renews ~15s before expiry via a `renew` message.
67
77
  tokenProvider;
78
+ // Binary-delivered frames waiting for their mockup_rendered metadata,
79
+ // keyed `${requestId ?? ''}:${mockupId}`. The server sends the binary
80
+ // frame before the JSON result on the same socket, so ordering guarantees
81
+ // the entry exists when the result arrives.
82
+ pendingFrames = /* @__PURE__ */ new Map();
83
+ // Last object URL handed out per mockup — revoked when replaced.
84
+ liveObjectUrls = /* @__PURE__ */ new Map();
68
85
  renewTimer = null;
69
86
  isConnecting = false;
70
87
  connectAttempt = 0;
@@ -79,6 +96,7 @@ var RealtimeMockupService = class {
79
96
  return {
80
97
  isConnected: this.ws?.readyState === WebSocket.OPEN,
81
98
  sessionId: this.sessionId,
99
+ box: this.box,
82
100
  isConfigured: this.isConfigured,
83
101
  mockupResults: [...this.mockupResults],
84
102
  status: this.status,
@@ -119,6 +137,7 @@ var RealtimeMockupService = class {
119
137
  const url = token ? `${this.wsUrl}${this.wsUrl.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}` : this.wsUrl;
120
138
  this.addLog(`Connecting to ${this.wsUrl}...`);
121
139
  this.ws = new WebSocket(url);
140
+ this.ws.binaryType = "arraybuffer";
122
141
  this.ws.onopen = () => {
123
142
  console.log(`[WS] connection OPENED to ${this.wsUrl}`);
124
143
  this.addLog("WebSocket connection opened");
@@ -126,6 +145,10 @@ var RealtimeMockupService = class {
126
145
  this.isConnecting = false;
127
146
  };
128
147
  this.ws.onmessage = (event) => {
148
+ if (event.data instanceof ArrayBuffer) {
149
+ this.handleBinaryFrame(event.data);
150
+ return;
151
+ }
129
152
  try {
130
153
  const data = JSON.parse(event.data);
131
154
  this.addLog(JSON.stringify(data, null, 2), "received");
@@ -139,6 +162,7 @@ var RealtimeMockupService = class {
139
162
  this.addLog(`WebSocket connection closed (code: ${event.code})`);
140
163
  this.status = "Disconnected";
141
164
  this.sessionId = null;
165
+ this.box = null;
142
166
  this.isConfigured = false;
143
167
  this.configSent = false;
144
168
  this.clearRenew();
@@ -178,10 +202,11 @@ var RealtimeMockupService = class {
178
202
  switch (data.type) {
179
203
  case "connected":
180
204
  this.sessionId = data.sessionId || null;
205
+ this.box = data.box ?? null;
181
206
  this.status = `Connected (Session: ${data.sessionId || "N/A"})`;
182
- this.addLog(`\u2705 Session established: ${data.sessionId}`);
207
+ this.addLog(`\u2705 Session established: ${data.sessionId}${this.box ? ` on ${this.box}` : ""}`);
183
208
  if (data.sessionId) {
184
- this.callbacks.onConnected?.(data.sessionId);
209
+ this.callbacks.onConnected?.(data.sessionId, { box: this.box ?? void 0 });
185
210
  }
186
211
  if (this.config && !this.configSent) {
187
212
  this.addLog("\u{1F4E4} Auto-sending cached config after connection...");
@@ -235,6 +260,7 @@ var RealtimeMockupService = class {
235
260
  this.addLog("\u{1F3A8} Mockup rendering has started...");
236
261
  break;
237
262
  case "mockup_rendered": {
263
+ this.applyBinaryFrame(data);
238
264
  const sentAt = data.requestId ? this.requestSendTimes.get(data.requestId) : void 0;
239
265
  const clientRoundTripMs = sentAt !== void 0 ? Date.now() - sentAt : void 0;
240
266
  console.log(`[WS] mockup_rendered received: mockupId=${data.mockupId} hasImageUrl=${!!data.imageUrl} v=${data.requestVersion} req=${data.requestId ?? "?"} placement="${data.placement}" renderMs=${data.renderMs} blobToRenderMs=${data.blobToRenderMs} clientRoundTripMs=${clientRoundTripMs ?? "?"} at ${Date.now()}`);
@@ -262,7 +288,12 @@ var RealtimeMockupService = class {
262
288
  blobToRenderMs: data.blobToRenderMs,
263
289
  costUsd: data.costUsd,
264
290
  renderCache: data.renderCache,
265
- canvasRenderTiming: data.canvasRenderTiming
291
+ cropRect: data.cropRect,
292
+ serverTiming: data.serverTiming,
293
+ canvasRenderTiming: data.canvasRenderTiming,
294
+ rtTiming: data.rtTiming,
295
+ clientRoundTripMs,
296
+ imageDelivery: data.imageDelivery === "ws" ? "ws" : "url"
266
297
  };
267
298
  const existingIndex = this.mockupResults.findIndex((m) => m.mockupId === data.mockupId);
268
299
  if (existingIndex >= 0) {
@@ -297,7 +328,18 @@ var RealtimeMockupService = class {
297
328
  }
298
329
  return true;
299
330
  });
300
- this.mockupResults = freshMockups;
331
+ this.mockupResults = freshMockups.map((mockup) => {
332
+ const existing = this.mockupResults.find(
333
+ (m) => m.mockupId === mockup.mockupId && (mockup.requestId === void 0 || m.requestId === mockup.requestId)
334
+ );
335
+ if (!existing) return mockup;
336
+ const merged = { ...existing, ...pruneUndefined(mockup) };
337
+ if (existing.imageUrl.startsWith("blob:")) {
338
+ merged.imageUrl = existing.imageUrl;
339
+ merged.renderUrl = existing.renderUrl;
340
+ }
341
+ return merged;
342
+ });
301
343
  this.lastError = null;
302
344
  this.renderError = null;
303
345
  this.addLog(`\u{1F389} All mockups rendered: ${freshMockups.length} fresh (${data.mockups.length - freshMockups.length} stale filtered)`);
@@ -310,7 +352,8 @@ var RealtimeMockupService = class {
310
352
  const errorMessage = data.message || "Unknown error occurred";
311
353
  const renderError = {
312
354
  code: data.code || "render_error",
313
- message: errorMessage
355
+ message: errorMessage,
356
+ ...typeof data.mockupId === "string" ? { mockupId: data.mockupId } : {}
314
357
  };
315
358
  this.lastError = errorMessage;
316
359
  this.renderError = renderError;
@@ -333,6 +376,35 @@ var RealtimeMockupService = class {
333
376
  this.ws = null;
334
377
  }
335
378
  }
379
+ handleBinaryFrame(buf) {
380
+ try {
381
+ const view = new DataView(buf);
382
+ const headerLen = view.getUint32(0);
383
+ const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, 4, headerLen)));
384
+ if (header.type !== "mockup_frame") return;
385
+ const bytes = new Uint8Array(buf, 4 + headerLen);
386
+ const objectUrl = URL.createObjectURL(new Blob([bytes], { type: header.contentType || "image/avif" }));
387
+ const key = `${header.requestId ?? ""}:${header.mockupId}`;
388
+ const prev = this.pendingFrames.get(key);
389
+ if (prev) URL.revokeObjectURL(prev.objectUrl);
390
+ this.pendingFrames.set(key, { objectUrl, bytes: bytes.byteLength });
391
+ this.addLog(`\u{1F4E6} mockup_frame received over ws: ${header.mockupId} (${bytes.byteLength}B)`);
392
+ } catch (e) {
393
+ this.addLog(`\u26A0\uFE0F failed to parse binary frame: ${e}`);
394
+ }
395
+ }
396
+ /** Swap a ws-delivered frame in for the imageUrl on a render result. */
397
+ applyBinaryFrame(data) {
398
+ if (data.imageDelivery !== "ws" || !data.mockupId) return;
399
+ const key = `${data.requestId ?? ""}:${data.mockupId}`;
400
+ const frame = this.pendingFrames.get(key);
401
+ if (!frame) return;
402
+ this.pendingFrames.delete(key);
403
+ const prevLive = this.liveObjectUrls.get(data.mockupId);
404
+ if (prevLive) URL.revokeObjectURL(prevLive);
405
+ this.liveObjectUrls.set(data.mockupId, frame.objectUrl);
406
+ data.imageUrl = frame.objectUrl;
407
+ }
336
408
  sendConfig(config) {
337
409
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
338
410
  this.addLog("WebSocket not connected, caching config");
@@ -379,7 +451,11 @@ var RealtimeMockupService = class {
379
451
  this.configSent = true;
380
452
  const message = {
381
453
  type: "config",
382
- config
454
+ // binaryFrames: ask the server to push rendered image bytes down this
455
+ // socket (mockup_frame binary messages) instead of making us fetch the
456
+ // imageUrl — saves a network round trip per render. Servers that don't
457
+ // know the flag ignore it and we fall back to the URL.
458
+ config: { ...config, binaryFrames: true }
383
459
  };
384
460
  const messageStr = JSON.stringify(message);
385
461
  this.addLog(`\u{1F4E4} Sending config: ${JSON.stringify(message, null, 2)}`, "sent");
@@ -673,6 +749,15 @@ ${versionToSend}
673
749
  hasPendingBlobs() {
674
750
  return Object.keys(this.throttleTimeouts).length > 0;
675
751
  }
752
+ /**
753
+ * Version stamped on the most recent canvas_state send (0 before any).
754
+ * Every frame answers with `requestVersion`, so a caller can tell which
755
+ * send a frame belongs to — the pipeline-depth send policy counts a send
756
+ * as landed when every mockup of its version has arrived.
757
+ */
758
+ getLastSentVersion() {
759
+ return this.lastSentVersion;
760
+ }
676
761
  sendColorBlob(placement, hexColor) {
677
762
  this.colors.set(placement, hexColor);
678
763
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN || !this.isConfigured) {
package/dist/index.cjs CHANGED
@@ -564,6 +564,7 @@ var ALLOWED_WIDTHS = [
564
564
  3e3,
565
565
  4e3
566
566
  ];
567
+ var MAX_RENDER_URL_LENGTH = 12 * 1024;
567
568
  function normalizeWidth(width) {
568
569
  for (let i = ALLOWED_WIDTHS.length - 1; i >= 0; i--) {
569
570
  if (ALLOWED_WIDTHS[i] <= width) return ALLOWED_WIDTHS[i];
@@ -741,6 +742,7 @@ function canonicalForSig(url) {
741
742
  const rawValue = eq === -1 ? "" : segment.slice(eq + 1);
742
743
  const key = decodeURIComponent(rawKey);
743
744
  if (key === "signature") continue;
745
+ if (key === "debug") continue;
744
746
  pairs.push({ key, raw: rawValue });
745
747
  }
746
748
  }
@@ -4996,6 +4998,13 @@ function createSvelteComponent(descriptor, svelte) {
4996
4998
  var REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
4997
4999
 
4998
5000
  // src/realtime/websocket.ts
5001
+ function pruneUndefined(obj) {
5002
+ const out = {};
5003
+ for (const [k, v] of Object.entries(obj)) {
5004
+ if (v !== void 0) out[k] = v;
5005
+ }
5006
+ return out;
5007
+ }
4999
5008
  function randHex(len) {
5000
5009
  const arr = new Uint8Array(len);
5001
5010
  globalThis.crypto.getRandomValues(arr);
@@ -5014,6 +5023,9 @@ var RealtimeMockupService = class {
5014
5023
  config = null;
5015
5024
  configSent = false;
5016
5025
  sessionId = null;
5026
+ // Render node that answered the handshake (`connected.box`), for labs and
5027
+ // support: a realtime session has no response headers to read it from.
5028
+ box = null;
5017
5029
  isConfigured = false;
5018
5030
  mockupResults = [];
5019
5031
  status = "Disconnected";
@@ -5059,6 +5071,13 @@ var RealtimeMockupService = class {
5059
5071
  // Session-grant auth: when set, connect() fetches a short-lived token, opens
5060
5072
  // the WS with `?token=`, and renews ~15s before expiry via a `renew` message.
5061
5073
  tokenProvider;
5074
+ // Binary-delivered frames waiting for their mockup_rendered metadata,
5075
+ // keyed `${requestId ?? ''}:${mockupId}`. The server sends the binary
5076
+ // frame before the JSON result on the same socket, so ordering guarantees
5077
+ // the entry exists when the result arrives.
5078
+ pendingFrames = /* @__PURE__ */ new Map();
5079
+ // Last object URL handed out per mockup — revoked when replaced.
5080
+ liveObjectUrls = /* @__PURE__ */ new Map();
5062
5081
  renewTimer = null;
5063
5082
  isConnecting = false;
5064
5083
  connectAttempt = 0;
@@ -5073,6 +5092,7 @@ var RealtimeMockupService = class {
5073
5092
  return {
5074
5093
  isConnected: this.ws?.readyState === WebSocket.OPEN,
5075
5094
  sessionId: this.sessionId,
5095
+ box: this.box,
5076
5096
  isConfigured: this.isConfigured,
5077
5097
  mockupResults: [...this.mockupResults],
5078
5098
  status: this.status,
@@ -5113,6 +5133,7 @@ var RealtimeMockupService = class {
5113
5133
  const url = token ? `${this.wsUrl}${this.wsUrl.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}` : this.wsUrl;
5114
5134
  this.addLog(`Connecting to ${this.wsUrl}...`);
5115
5135
  this.ws = new WebSocket(url);
5136
+ this.ws.binaryType = "arraybuffer";
5116
5137
  this.ws.onopen = () => {
5117
5138
  console.log(`[WS] connection OPENED to ${this.wsUrl}`);
5118
5139
  this.addLog("WebSocket connection opened");
@@ -5120,6 +5141,10 @@ var RealtimeMockupService = class {
5120
5141
  this.isConnecting = false;
5121
5142
  };
5122
5143
  this.ws.onmessage = (event) => {
5144
+ if (event.data instanceof ArrayBuffer) {
5145
+ this.handleBinaryFrame(event.data);
5146
+ return;
5147
+ }
5123
5148
  try {
5124
5149
  const data = JSON.parse(event.data);
5125
5150
  this.addLog(JSON.stringify(data, null, 2), "received");
@@ -5133,6 +5158,7 @@ var RealtimeMockupService = class {
5133
5158
  this.addLog(`WebSocket connection closed (code: ${event.code})`);
5134
5159
  this.status = "Disconnected";
5135
5160
  this.sessionId = null;
5161
+ this.box = null;
5136
5162
  this.isConfigured = false;
5137
5163
  this.configSent = false;
5138
5164
  this.clearRenew();
@@ -5172,10 +5198,11 @@ var RealtimeMockupService = class {
5172
5198
  switch (data.type) {
5173
5199
  case "connected":
5174
5200
  this.sessionId = data.sessionId || null;
5201
+ this.box = data.box ?? null;
5175
5202
  this.status = `Connected (Session: ${data.sessionId || "N/A"})`;
5176
- this.addLog(`\u2705 Session established: ${data.sessionId}`);
5203
+ this.addLog(`\u2705 Session established: ${data.sessionId}${this.box ? ` on ${this.box}` : ""}`);
5177
5204
  if (data.sessionId) {
5178
- this.callbacks.onConnected?.(data.sessionId);
5205
+ this.callbacks.onConnected?.(data.sessionId, { box: this.box ?? void 0 });
5179
5206
  }
5180
5207
  if (this.config && !this.configSent) {
5181
5208
  this.addLog("\u{1F4E4} Auto-sending cached config after connection...");
@@ -5229,6 +5256,7 @@ var RealtimeMockupService = class {
5229
5256
  this.addLog("\u{1F3A8} Mockup rendering has started...");
5230
5257
  break;
5231
5258
  case "mockup_rendered": {
5259
+ this.applyBinaryFrame(data);
5232
5260
  const sentAt = data.requestId ? this.requestSendTimes.get(data.requestId) : void 0;
5233
5261
  const clientRoundTripMs = sentAt !== void 0 ? Date.now() - sentAt : void 0;
5234
5262
  console.log(`[WS] mockup_rendered received: mockupId=${data.mockupId} hasImageUrl=${!!data.imageUrl} v=${data.requestVersion} req=${data.requestId ?? "?"} placement="${data.placement}" renderMs=${data.renderMs} blobToRenderMs=${data.blobToRenderMs} clientRoundTripMs=${clientRoundTripMs ?? "?"} at ${Date.now()}`);
@@ -5256,7 +5284,12 @@ var RealtimeMockupService = class {
5256
5284
  blobToRenderMs: data.blobToRenderMs,
5257
5285
  costUsd: data.costUsd,
5258
5286
  renderCache: data.renderCache,
5259
- canvasRenderTiming: data.canvasRenderTiming
5287
+ cropRect: data.cropRect,
5288
+ serverTiming: data.serverTiming,
5289
+ canvasRenderTiming: data.canvasRenderTiming,
5290
+ rtTiming: data.rtTiming,
5291
+ clientRoundTripMs,
5292
+ imageDelivery: data.imageDelivery === "ws" ? "ws" : "url"
5260
5293
  };
5261
5294
  const existingIndex = this.mockupResults.findIndex((m) => m.mockupId === data.mockupId);
5262
5295
  if (existingIndex >= 0) {
@@ -5291,7 +5324,18 @@ var RealtimeMockupService = class {
5291
5324
  }
5292
5325
  return true;
5293
5326
  });
5294
- this.mockupResults = freshMockups;
5327
+ this.mockupResults = freshMockups.map((mockup) => {
5328
+ const existing = this.mockupResults.find(
5329
+ (m) => m.mockupId === mockup.mockupId && (mockup.requestId === void 0 || m.requestId === mockup.requestId)
5330
+ );
5331
+ if (!existing) return mockup;
5332
+ const merged = { ...existing, ...pruneUndefined(mockup) };
5333
+ if (existing.imageUrl.startsWith("blob:")) {
5334
+ merged.imageUrl = existing.imageUrl;
5335
+ merged.renderUrl = existing.renderUrl;
5336
+ }
5337
+ return merged;
5338
+ });
5295
5339
  this.lastError = null;
5296
5340
  this.renderError = null;
5297
5341
  this.addLog(`\u{1F389} All mockups rendered: ${freshMockups.length} fresh (${data.mockups.length - freshMockups.length} stale filtered)`);
@@ -5304,7 +5348,8 @@ var RealtimeMockupService = class {
5304
5348
  const errorMessage = data.message || "Unknown error occurred";
5305
5349
  const renderError = {
5306
5350
  code: data.code || "render_error",
5307
- message: errorMessage
5351
+ message: errorMessage,
5352
+ ...typeof data.mockupId === "string" ? { mockupId: data.mockupId } : {}
5308
5353
  };
5309
5354
  this.lastError = errorMessage;
5310
5355
  this.renderError = renderError;
@@ -5327,6 +5372,35 @@ var RealtimeMockupService = class {
5327
5372
  this.ws = null;
5328
5373
  }
5329
5374
  }
5375
+ handleBinaryFrame(buf) {
5376
+ try {
5377
+ const view = new DataView(buf);
5378
+ const headerLen = view.getUint32(0);
5379
+ const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, 4, headerLen)));
5380
+ if (header.type !== "mockup_frame") return;
5381
+ const bytes = new Uint8Array(buf, 4 + headerLen);
5382
+ const objectUrl = URL.createObjectURL(new Blob([bytes], { type: header.contentType || "image/avif" }));
5383
+ const key = `${header.requestId ?? ""}:${header.mockupId}`;
5384
+ const prev = this.pendingFrames.get(key);
5385
+ if (prev) URL.revokeObjectURL(prev.objectUrl);
5386
+ this.pendingFrames.set(key, { objectUrl, bytes: bytes.byteLength });
5387
+ this.addLog(`\u{1F4E6} mockup_frame received over ws: ${header.mockupId} (${bytes.byteLength}B)`);
5388
+ } catch (e) {
5389
+ this.addLog(`\u26A0\uFE0F failed to parse binary frame: ${e}`);
5390
+ }
5391
+ }
5392
+ /** Swap a ws-delivered frame in for the imageUrl on a render result. */
5393
+ applyBinaryFrame(data) {
5394
+ if (data.imageDelivery !== "ws" || !data.mockupId) return;
5395
+ const key = `${data.requestId ?? ""}:${data.mockupId}`;
5396
+ const frame = this.pendingFrames.get(key);
5397
+ if (!frame) return;
5398
+ this.pendingFrames.delete(key);
5399
+ const prevLive = this.liveObjectUrls.get(data.mockupId);
5400
+ if (prevLive) URL.revokeObjectURL(prevLive);
5401
+ this.liveObjectUrls.set(data.mockupId, frame.objectUrl);
5402
+ data.imageUrl = frame.objectUrl;
5403
+ }
5330
5404
  sendConfig(config) {
5331
5405
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
5332
5406
  this.addLog("WebSocket not connected, caching config");
@@ -5373,7 +5447,11 @@ var RealtimeMockupService = class {
5373
5447
  this.configSent = true;
5374
5448
  const message = {
5375
5449
  type: "config",
5376
- config
5450
+ // binaryFrames: ask the server to push rendered image bytes down this
5451
+ // socket (mockup_frame binary messages) instead of making us fetch the
5452
+ // imageUrl — saves a network round trip per render. Servers that don't
5453
+ // know the flag ignore it and we fall back to the URL.
5454
+ config: { ...config, binaryFrames: true }
5377
5455
  };
5378
5456
  const messageStr = JSON.stringify(message);
5379
5457
  this.addLog(`\u{1F4E4} Sending config: ${JSON.stringify(message, null, 2)}`, "sent");
@@ -5667,6 +5745,15 @@ ${versionToSend}
5667
5745
  hasPendingBlobs() {
5668
5746
  return Object.keys(this.throttleTimeouts).length > 0;
5669
5747
  }
5748
+ /**
5749
+ * Version stamped on the most recent canvas_state send (0 before any).
5750
+ * Every frame answers with `requestVersion`, so a caller can tell which
5751
+ * send a frame belongs to — the pipeline-depth send policy counts a send
5752
+ * as landed when every mockup of its version has arrived.
5753
+ */
5754
+ getLastSentVersion() {
5755
+ return this.lastSentVersion;
5756
+ }
5670
5757
  sendColorBlob(placement, hexColor) {
5671
5758
  this.colors.set(placement, hexColor);
5672
5759
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN || !this.isConfigured) {
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, P as PlacementSettings, M as MockupResult, R as RealtimeRenderError, h as RealtimeMockupService } from './websocket-BG81_dZv.cjs';
4
- export { A as AdapterRegistry, i as ProductComponentContext, j as RealtimeMockupCallbacks, k as RealtimeMockupState, l as RenderResult, W as WebSocketConfig, m as WebSocketMessage, n as adapterRegistry, o as computeDisabledChoices, p as createComponent, q as defineComponent, r as deriveDefaultSelection, s as findBestCombination, t as getPricePreview, u as isOptionAvailable, v as resolveBestCombination } from './websocket-BG81_dZv.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 RealtimeRenderError, h as RealtimeMockupService } from './websocket-DjAOhBaN.cjs';
4
+ export { A as AdapterRegistry, i as ProductComponentContext, j as RealtimeMockupCallbacks, k as RealtimeMockupState, l as RenderResult, W as WebSocketConfig, m as WebSocketMessage, n as adapterRegistry, o as computeDisabledChoices, p as createComponent, q as defineComponent, r as deriveDefaultSelection, s as findBestCombination, t as getPricePreview, u as isOptionAvailable, v as resolveBestCombination } from './websocket-DjAOhBaN.cjs';
5
5
 
6
6
  interface CatalogProduct {
7
7
  id: string;
@@ -372,7 +372,13 @@ declare function getBuyUrl(productCode: string, opts: GetMockupUrlOptions): stri
372
372
  * ```
373
373
  */
374
374
  interface BffSignerOptions {
375
- /** Override fetch (tests / non-global-fetch runtimes). */
375
+ /**
376
+ * Override fetch (tests / non-global-fetch runtimes). If your sign endpoint
377
+ * sits behind a bot/abuse gate that 401s first-time anonymous visitors
378
+ * (e.g. a Turnstile challenge dance), pass the fetch wrapper that solves it —
379
+ * the default fetch makes ONE attempt and this signer fails open to the
380
+ * unsigned URL, which a signed-URL shop will refuse to serve.
381
+ */
376
382
  fetch?: typeof fetch;
377
383
  /** Max URLs per `/api/sign` request (default 50; matches the handler default). */
378
384
  maxBatch?: number;
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, P as PlacementSettings, M as MockupResult, R as RealtimeRenderError, h as RealtimeMockupService } from './websocket-BG81_dZv.js';
4
- export { A as AdapterRegistry, i as ProductComponentContext, j as RealtimeMockupCallbacks, k as RealtimeMockupState, l as RenderResult, W as WebSocketConfig, m as WebSocketMessage, n as adapterRegistry, o as computeDisabledChoices, p as createComponent, q as defineComponent, r as deriveDefaultSelection, s as findBestCombination, t as getPricePreview, u as isOptionAvailable, v as resolveBestCombination } from './websocket-BG81_dZv.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 RealtimeRenderError, h as RealtimeMockupService } from './websocket-DjAOhBaN.js';
4
+ export { A as AdapterRegistry, i as ProductComponentContext, j as RealtimeMockupCallbacks, k as RealtimeMockupState, l as RenderResult, W as WebSocketConfig, m as WebSocketMessage, n as adapterRegistry, o as computeDisabledChoices, p as createComponent, q as defineComponent, r as deriveDefaultSelection, s as findBestCombination, t as getPricePreview, u as isOptionAvailable, v as resolveBestCombination } from './websocket-DjAOhBaN.js';
5
5
 
6
6
  interface CatalogProduct {
7
7
  id: string;
@@ -372,7 +372,13 @@ declare function getBuyUrl(productCode: string, opts: GetMockupUrlOptions): stri
372
372
  * ```
373
373
  */
374
374
  interface BffSignerOptions {
375
- /** Override fetch (tests / non-global-fetch runtimes). */
375
+ /**
376
+ * Override fetch (tests / non-global-fetch runtimes). If your sign endpoint
377
+ * sits behind a bot/abuse gate that 401s first-time anonymous visitors
378
+ * (e.g. a Turnstile challenge dance), pass the fetch wrapper that solves it —
379
+ * the default fetch makes ONE attempt and this signer fails open to the
380
+ * unsigned URL, which a signed-URL shop will refuse to serve.
381
+ */
376
382
  fetch?: typeof fetch;
377
383
  /** Max URLs per `/api/sign` request (default 50; matches the handler default). */
378
384
  maxBatch?: number;
package/dist/index.js CHANGED
@@ -4,14 +4,14 @@ import {
4
4
  import {
5
5
  REALTIME_WS_URL,
6
6
  RealtimeMockupService
7
- } from "./chunk-MKLLTNKJ.js";
7
+ } from "./chunk-P3ZYTA5F.js";
8
8
  import {
9
9
  buildMockupUrl,
10
10
  buildPublicMockupUrl,
11
11
  canonicalForSig,
12
12
  normalizeDesignElements,
13
13
  normalizeWidth
14
- } from "./chunk-IL3FXE2X.js";
14
+ } from "./chunk-FPR6ABXM.js";
15
15
 
16
16
  // src/validation.ts
17
17
  import { z } from "zod";