@snowcone-app/mockup-resolver 1.0.8 → 1.0.10

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,6 @@
1
+ /** Per-IP public rate-limit exemption for our own load generators (the metro relays).
2
+ * Exact-IP match only: no CIDR, no wildcards. The list is a plain wrangler var. */
3
+ export function isLoadtestExempt(clientIp: string, list: string | undefined): boolean {
4
+ if (!list || !clientIp || clientIp === "unknown-ip") return false;
5
+ return list.split(",").map((s) => s.trim()).filter(Boolean).includes(clientIp);
6
+ }
package/src/resolve.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // logic in `apps/www/app/api/harness/mockup/route.ts` (the prototype) and the
5
5
  // SDK's `getProduct`. Edge-safe: plain fetch + JSON. (ADR-0073 §10.)
6
6
 
7
+ import { edgeCachedRecord } from "./edge-record-cache";
7
8
  import {
8
9
  PARAMS,
9
10
  type DesignElement,
@@ -35,7 +36,12 @@ export function looksLikeResolveRequest(
35
36
  host: string,
36
37
  url: URL
37
38
  ): boolean {
38
- if (method !== "GET") return false;
39
+ // HEAD mirrors GET: uptime checks and agents that verify a mockup URL with
40
+ // `curl -I` used to fall through to the "Mockup Resolver API" JSON default
41
+ // route (200 + application/json) and conclude the image was broken
42
+ // (growth/0013 F3, eng/0049). The runtime drops the body on HEAD, so the
43
+ // same 302 → image redirect is returned with the real headers.
44
+ if (method !== "GET" && method !== "HEAD") return false;
39
45
 
40
46
  const segments = url.pathname.split("/").filter(Boolean);
41
47
  if (segments.length !== 1) return false;
@@ -57,6 +63,38 @@ export interface MeiliConfig {
57
63
  index: string;
58
64
  }
59
65
 
66
+ interface RawOptions {
67
+ attributes?: Record<
68
+ string,
69
+ { affectsCombinations?: boolean; choices?: { label?: string }[] }
70
+ >;
71
+ // Flat rows: each is `{ <AttrName>: <choiceLabel>, …, price, variantId }`.
72
+ combinations?: Array<Record<string, unknown>>;
73
+ }
74
+
75
+ interface RawVariant {
76
+ gvid?: string;
77
+ id?: string;
78
+ /** The RENDER gvid (variant_id_for_mockups) when it differs from the SKU gvid — ADR-0099 V1. */
79
+ gvidForMockup?: string | null;
80
+ }
81
+
82
+ /** ADR-0099: the published `bundle` block (catalog/src/bundle.ts `pareBundleForDoc`). */
83
+ interface RawBundle {
84
+ members?: Array<{
85
+ role?: string;
86
+ required?: boolean;
87
+ products?: Array<{
88
+ productId?: string;
89
+ defaultGvid?: string | null;
90
+ variants?: RawVariant[];
91
+ options?: RawOptions;
92
+ }>;
93
+ }>;
94
+ priceRule?: unknown;
95
+ uncoveredPickSets?: unknown;
96
+ }
97
+
60
98
  interface RawProduct {
61
99
  id: string;
62
100
  placements?: {
@@ -65,23 +103,20 @@ interface RawProduct {
65
103
  type?: string | null;
66
104
  width?: number;
67
105
  height?: number;
106
+ /** ADR-0099: bundle member slot + product this placement belongs to. */
107
+ role?: string;
108
+ memberProductId?: string;
68
109
  }[];
69
- variants?: { gvid?: string; id?: string }[];
70
- mockups?: { id: string; gvids?: string[] }[];
110
+ variants?: RawVariant[];
111
+ mockups?: { id: string; gvids?: string[]; picks?: Record<string, string> }[];
71
112
  defaultGvid?: string | null;
72
- options?: {
73
- attributes?: Record<
74
- string,
75
- { affectsCombinations?: boolean; choices?: { label?: string }[] }
76
- >;
77
- // Flat rows: each is `{ <AttrName>: <choiceLabel>, …, price, variantId }`.
78
- combinations?: Array<Record<string, unknown>>;
79
- };
113
+ options?: RawOptions;
80
114
  album?: {
81
115
  pagePlacement?: string;
82
116
  pageAxis?: string;
83
117
  pageExtent?: { min?: number; max?: number; step?: number };
84
118
  };
119
+ bundle?: RawBundle | null;
85
120
  }
86
121
 
87
122
  /**
@@ -99,18 +134,53 @@ export interface AlbumBlock {
99
134
  }
100
135
 
101
136
  export interface ResolvedPlacement {
102
- /** URL-safe slug (catalog `key`, or a slug derived from `label` as a fallback). */
137
+ /** URL-safe slug (catalog `key`, or a slug derived from `label` as a fallback).
138
+ * On a bundle record: the role-scoped wire key `<role>.<key>` (ADR-0099 D3). */
103
139
  key: string;
104
140
  label: string;
105
141
  type: "image" | "color";
106
142
  width: number;
107
143
  height: number;
144
+ /** ADR-0099: the bundle slot this placement belongs to; absent on single products. */
145
+ role?: string;
146
+ /** ADR-0099: the member product (alternative) this placement belongs to. */
147
+ memberProductId?: string;
148
+ }
149
+
150
+ /** ADR-0099: one alternative product of a bundle slot, with what per-role variant resolution needs. */
151
+ export interface ResolvedBundleAlternative {
152
+ productId: string;
153
+ defaultGvid: string | null;
154
+ variants: { gvid: string; gvidForMockup: string | null }[];
155
+ attributes: Record<string, { affectsCombinations: boolean; choices: string[] }>;
156
+ combinations: { variantId: string; options: Record<string, string> }[];
157
+ }
158
+
159
+ export interface ResolvedBundleMember {
160
+ role: string;
161
+ required: boolean;
162
+ /** Alternatives; `[0]` is the default pick. Never empty. */
163
+ products: ResolvedBundleAlternative[];
164
+ }
165
+
166
+ export interface ResolvedBundle {
167
+ members: ResolvedBundleMember[];
168
+ priceRule: unknown;
108
169
  }
109
170
 
110
171
  export interface ResolvedProduct {
172
+ /** Content version of the published record (ADR-0097). */
173
+ version: string;
174
+ /** Render version: hash of the product's pixel-affecting config (full
175
+ * mockups/masks, placements, variants, options), minted by the backend
176
+ * (catalog/src/resolver-record.ts). Sealed onto every render URL as
177
+ * `pv=` so box, edge and browser caches all key on it — a catalog fix
178
+ * changes it and pre-fix pixels stop being served everywhere at once.
179
+ * Falls back to `version` for records published before it existed. */
180
+ renderVersion: string;
111
181
  id: string;
112
- variants: { gvid: string }[];
113
- mockups: { id: string; gvids: string[] }[];
182
+ variants: { gvid: string; gvidForMockup?: string | null }[];
183
+ mockups: { id: string; gvids: string[]; picks?: Record<string, string> | null }[];
114
184
  placements: ResolvedPlacement[];
115
185
  defaultGvid: string | null;
116
186
  /** Attribute name → metadata (whether it selects a SKU + its choice labels). */
@@ -119,8 +189,13 @@ export interface ResolvedProduct {
119
189
  combinations: { variantId: string; options: Record<string, string> }[];
120
190
  /** The album block (ADR-0086), or null for ordinary products. */
121
191
  album: AlbumBlock | null;
192
+ /** The bundle block (ADR-0099), or null for ordinary products. */
193
+ bundle?: ResolvedBundle | null;
122
194
  }
123
195
 
196
+ /** The subset of a product that variant/option resolution reads — a bundle member alternative satisfies it too. */
197
+ export type VariantResolvable = Pick<ResolvedProduct, "attributes" | "combinations" | "defaultGvid" | "variants">;
198
+
124
199
  export interface ResolveDefaults {
125
200
  variantId: string;
126
201
  mockupId: string;
@@ -135,9 +210,15 @@ export interface VariantResolution {
135
210
  optionSelections: Record<string, string>;
136
211
  }
137
212
 
138
- const CACHE_TTL_SECONDS = 300; // 5 min — see ADR-0073 open question #1 (TTL vs event-driven)
139
- // Bump when ResolvedProduct's shape changes, so stale-shape cache entries are skipped.
140
- const CACHE_VERSION = "v3";
213
+ /**
214
+ * ADR-0097: the product record is PUBLISHED to KV by the backend in the same
215
+ * step that writes Meilisearch — no TTL, no Meili fetch here. `prod:<code>`
216
+ * holds `{ version, publishedAt, raw }`; a missing key means "not published"
217
+ * and resolves to 404 exactly as a Meili miss did. Concurrent requests for
218
+ * the same product share one in-flight read.
219
+ */
220
+ const RESOLVER_PRODUCT_KEY = (code: string) => `prod:${code}`;
221
+ const inflightProducts = new Map<string, Promise<ResolvedProduct | null>>();
141
222
 
142
223
  /** Lowercase + collapse non-alphanumerics to `_` — the fallback slug for a
143
224
  * placement that has no catalog `key` yet (pre-P1). */
@@ -248,6 +329,17 @@ export type AssembleArtworkResult =
248
329
  | { ok: true; elements: DesignElement[] }
249
330
  | { ok: false; status: number; code: string; message: string };
250
331
 
332
+ /**
333
+ * The `placement` a render element carries to the box. Single products: the
334
+ * catalog label (what the box's masks are labelled with). Bundle placements
335
+ * (ADR-0099 D2/D3): the role-scoped wire key — two members both have a
336
+ * "Front", so the label is ambiguous; the render box maps the key back to
337
+ * the member placement's label + printable before matching masks.
338
+ */
339
+ export function wirePlacement(pl: ResolvedPlacement): string {
340
+ return pl.role ? pl.key : pl.label;
341
+ }
342
+
251
343
  /** Build one image/color `DesignElement` for a placement from a parsed fill. */
252
344
  function elementFromFill(
253
345
  fill: ParsedFill,
@@ -258,7 +350,7 @@ function elementFromFill(
258
350
  return {
259
351
  type: "color",
260
352
  hex: fill.color,
261
- placement: pl.label,
353
+ placement: wirePlacement(pl),
262
354
  width: pl.width,
263
355
  height: pl.height,
264
356
  };
@@ -267,7 +359,7 @@ function elementFromFill(
267
359
  const el: DesignElement = {
268
360
  type: "image",
269
361
  imageUrl: fill.src === DEFAULT_ASSET_TOKEN ? house : fill.src,
270
- placement: pl.label,
362
+ placement: wirePlacement(pl),
271
363
  width: pl.width,
272
364
  height: pl.height,
273
365
  alignment:
@@ -311,7 +403,7 @@ export function assembleArtwork(
311
403
  byKey.set(pl.key, {
312
404
  type: "image",
313
405
  imageUrl: baseUrl,
314
- placement: pl.label,
406
+ placement: wirePlacement(pl),
315
407
  width: pl.width,
316
408
  height: pl.height,
317
409
  alignment: "center",
@@ -342,25 +434,43 @@ export function assembleArtwork(
342
434
  return { ok: true, elements: [...byKey.values()] };
343
435
  }
344
436
 
345
- /** Fetch a product from Meilisearch (KV-cached). Returns null if not found. */
437
+ /** Read a product's published record from KV (ADR-0097). Returns null if not published. */
346
438
  export async function fetchProduct(
347
439
  productCode: string,
348
- meili: MeiliConfig,
349
- kv: KVNamespace
440
+ kv: KVNamespace,
441
+ ctx?: { waitUntil(p: Promise<unknown>): void }
350
442
  ): Promise<ResolvedProduct | null> {
351
- const cacheKey = `prod:${CACHE_VERSION}:${productCode}`;
352
- const cached = await kv.get(cacheKey, "json");
353
- if (cached) return cached as ResolvedProduct;
354
-
355
- const url = `${meili.host}/indexes/${meili.index}/documents/${encodeURIComponent(productCode)}`;
356
- const res = await fetch(url, {
357
- headers: { Authorization: `Bearer ${meili.apiKey}` },
358
- });
359
- if (!res.ok) return null;
360
-
361
- const raw = (await res.json()) as RawProduct;
443
+ const key = RESOLVER_PRODUCT_KEY(productCode);
444
+ const pending = inflightProducts.get(key);
445
+ if (pending) return pending;
446
+ const p = (async () => {
447
+ // POP cache first (edge-record-cache.ts): a year-long entry the backend
448
+ // purges by URL on every publish. Miss → the KV read, then fill.
449
+ const { value: rec } = await edgeCachedRecord<{ version?: string; renderVersion?: string; raw?: RawProduct }>(
450
+ "product",
451
+ productCode,
452
+ async () => (await kv.get(key, "json")) as { version?: string; renderVersion?: string; raw?: RawProduct } | null,
453
+ ctx,
454
+ );
455
+ if (!rec || !rec.raw) return null;
456
+ const version = typeof rec.version === "string" ? rec.version : "";
457
+ const renderVersion = typeof rec.renderVersion === "string" && rec.renderVersion ? rec.renderVersion : version;
458
+ return toResolvedProduct(rec.raw, version, renderVersion);
459
+ })();
460
+ inflightProducts.set(key, p);
461
+ try {
462
+ return await p;
463
+ } finally {
464
+ inflightProducts.delete(key);
465
+ }
466
+ }
362
467
 
363
- const rawAttrs = raw.options?.attributes ?? {};
468
+ /** Normalize a raw catalog `options` block into attribute metadata + SKU rows. */
469
+ function normalizeOptions(options: RawOptions | undefined): {
470
+ attributes: ResolvedProduct["attributes"];
471
+ combinations: ResolvedProduct["combinations"];
472
+ } {
473
+ const rawAttrs = options?.attributes ?? {};
364
474
  const attributes: ResolvedProduct["attributes"] = {};
365
475
  for (const [name, meta] of Object.entries(rawAttrs)) {
366
476
  attributes[name] = {
@@ -374,39 +484,89 @@ export async function fetchProduct(
374
484
  const attributeNames = Object.keys(attributes);
375
485
 
376
486
  const combinations: ResolvedProduct["combinations"] = [];
377
- for (const row of raw.options?.combinations ?? []) {
487
+ for (const row of options?.combinations ?? []) {
378
488
  const variantId = typeof row.variantId === "string" ? row.variantId : "";
379
489
  if (!variantId) continue;
380
- const options: Record<string, string> = {};
490
+ const opts: Record<string, string> = {};
381
491
  for (const name of attributeNames) {
382
492
  const v = row[name];
383
- if (typeof v === "string") options[name] = v;
493
+ if (typeof v === "string") opts[name] = v;
494
+ }
495
+ combinations.push({ variantId, options: opts });
496
+ }
497
+ return { attributes, combinations };
498
+ }
499
+
500
+ function normalizeVariants(raw: RawVariant[] | undefined): { gvid: string; gvidForMockup: string | null }[] {
501
+ return (raw ?? [])
502
+ .map((v) => ({
503
+ gvid: v.gvid ?? v.id ?? "",
504
+ gvidForMockup: typeof v.gvidForMockup === "string" && v.gvidForMockup ? v.gvidForMockup : null,
505
+ }))
506
+ .filter((v) => v.gvid);
507
+ }
508
+
509
+ /**
510
+ * Normalize the published `bundle` block (ADR-0099). Null unless it carries
511
+ * at least one slot with at least one alternative — a malformed block makes
512
+ * the product behave like an ordinary (non-bundle) product, which then fails
513
+ * loudly on its empty placements rather than half-rendering.
514
+ */
515
+ export function normalizeBundle(raw: RawBundle | null | undefined): ResolvedBundle | null {
516
+ if (!raw || !Array.isArray(raw.members) || raw.members.length === 0) return null;
517
+ const members: ResolvedBundleMember[] = [];
518
+ for (const m of raw.members) {
519
+ if (!m || typeof m.role !== "string" || !m.role) continue;
520
+ const products: ResolvedBundleAlternative[] = [];
521
+ for (const p of m.products ?? []) {
522
+ if (!p || typeof p.productId !== "string" || !p.productId) continue;
523
+ const { attributes, combinations } = normalizeOptions(p.options);
524
+ products.push({
525
+ productId: p.productId,
526
+ defaultGvid: typeof p.defaultGvid === "string" && p.defaultGvid ? p.defaultGvid : null,
527
+ variants: normalizeVariants(p.variants),
528
+ attributes,
529
+ combinations,
530
+ });
384
531
  }
385
- combinations.push({ variantId, options });
532
+ if (products.length === 0) continue;
533
+ members.push({ role: m.role, required: m.required !== false, products });
386
534
  }
535
+ if (members.length === 0) return null;
536
+ return { members, priceRule: raw.priceRule ?? null };
537
+ }
538
+
539
+ function toResolvedProduct(raw: RawProduct, version: string, renderVersion: string = version): ResolvedProduct {
540
+ const { attributes, combinations } = normalizeOptions(raw.options);
387
541
 
388
542
  const resolved: ResolvedProduct = {
543
+ version,
544
+ renderVersion,
389
545
  id: raw.id,
390
- variants: (raw.variants ?? [])
391
- .map((v) => ({ gvid: v.gvid ?? v.id ?? "" }))
392
- .filter((v) => v.gvid),
393
- mockups: (raw.mockups ?? []).map((m) => ({ id: m.id, gvids: m.gvids ?? [] })),
546
+ variants: normalizeVariants(raw.variants),
547
+ mockups: (raw.mockups ?? []).map((m) => ({
548
+ id: m.id,
549
+ gvids: m.gvids ?? [],
550
+ ...(m.picks && typeof m.picks === "object" ? { picks: m.picks } : {}),
551
+ })),
394
552
  placements: (raw.placements ?? []).map((p) => ({
395
553
  key: p.key && p.key.length > 0 ? p.key : slugify(p.label),
396
554
  label: p.label,
397
555
  type: p.type === "color" ? "color" : "image",
398
556
  width: p.width ?? 4000,
399
557
  height: p.height ?? 4000,
558
+ ...(typeof p.role === "string" && p.role ? { role: p.role } : {}),
559
+ ...(typeof p.memberProductId === "string" && p.memberProductId
560
+ ? { memberProductId: p.memberProductId }
561
+ : {}),
400
562
  })),
401
563
  defaultGvid: raw.defaultGvid ?? null,
402
564
  attributes,
403
565
  combinations,
404
566
  album: normalizeAlbum(raw.album),
567
+ bundle: normalizeBundle(raw.bundle),
405
568
  };
406
569
 
407
- await kv.put(cacheKey, JSON.stringify(resolved), {
408
- expirationTtl: CACHE_TTL_SECONDS,
409
- });
410
570
  return resolved;
411
571
  }
412
572
 
@@ -440,6 +600,46 @@ export function resolveDefaults(
440
600
  return { variantId, mockupId: mockup.id, placement };
441
601
  }
442
602
 
603
+ export interface UnknownOptionPick {
604
+ /** The attribute as the caller wrote it (unknown attribute) or the catalog's name (unknown choice). */
605
+ attribute: string;
606
+ choice: string;
607
+ validAttributes: string[];
608
+ /** null when the ATTRIBUTE is unknown; the attribute's choices when the CHOICE is. */
609
+ validChoices: string[] | null;
610
+ }
611
+
612
+ /**
613
+ * The first `opt.<attr>=<choice>` pick that names no catalog attribute, or a
614
+ * choice the attribute does not list (both case-insensitive), or null when
615
+ * every pick is valid. An attribute with no listed choices accepts any value
616
+ * (nothing to validate against).
617
+ *
618
+ * Without this, a wrong pick was SILENT: an unknown render-only choice rode
619
+ * `optionSelections` to the render box, which found no choice and rendered
620
+ * the product with no underlay; an unknown combination choice matched no
621
+ * SKU row and fell through to the default variant. Same policy as placement
622
+ * keys — fail loudly, name the valid values (ADR-0089 house style).
623
+ */
624
+ export function unknownOptionPick(
625
+ product: VariantResolvable,
626
+ picks: Record<string, string>
627
+ ): UnknownOptionPick | null {
628
+ const attrs = product.attributes ?? {};
629
+ const validAttributes = Object.keys(attrs);
630
+ const byLower = new Map(validAttributes.map((n) => [n.toLowerCase(), n]));
631
+ for (const [rawAttr, rawChoice] of Object.entries(picks)) {
632
+ const name = byLower.get(rawAttr.toLowerCase());
633
+ if (!name) return { attribute: rawAttr, choice: rawChoice, validAttributes, validChoices: null };
634
+ const choices = attrs[name]?.choices ?? [];
635
+ if (choices.length === 0) continue;
636
+ if (!choices.some((c) => c.toLowerCase() === rawChoice.toLowerCase())) {
637
+ return { attribute: name, choice: rawChoice, validAttributes, validChoices: choices };
638
+ }
639
+ }
640
+ return null;
641
+ }
642
+
443
643
  /**
444
644
  * Resolve public option picks (`opt.<attr>=<choice>`, matched case-insensitively)
445
645
  * to a variant gvid + the render-only `optionSelections` rendercenter consumes.
@@ -454,7 +654,7 @@ export function resolveDefaults(
454
654
  * Returns null only if no variant can be determined at all.
455
655
  */
456
656
  export function resolveVariant(
457
- product: ResolvedProduct,
657
+ product: VariantResolvable,
458
658
  picks: Record<string, string>,
459
659
  variantOverride?: string
460
660
  ): VariantResolution | null {
@@ -500,3 +700,196 @@ export function resolveVariant(
500
700
 
501
701
  return { variantId, optionSelections };
502
702
  }
703
+
704
+ // ─── Bundles (ADR-0099): picks, per-role variants, the mockup, the placements ──
705
+
706
+ export interface BundleSceneInput {
707
+ /** `pick.<role>=<productCode>` — which alternative fills each slot (default: `products[0]`). */
708
+ picks: Record<string, string>;
709
+ /** `variant.<role>=<gvid>` — the SKU per slot. */
710
+ variants: Record<string, string>;
711
+ /** Every `opt.*` pick as parsed; on a bundle each key must be `<role>.<attribute>`. */
712
+ options: Record<string, string>;
713
+ /** A bare `variant=` (rejected on bundles — it names no slot). */
714
+ variantOverride?: string;
715
+ mockupOverride?: string;
716
+ }
717
+
718
+ export interface BundleScene {
719
+ /** The resolved pick set: role → member product code. */
720
+ picks: Record<string, string>;
721
+ /** role → the SKU gvid (what a cart line needs) and the RENDER gvid the box keys on (V1). */
722
+ variantByRole: Record<string, { skuGvid: string; renderGvid: string }>;
723
+ /** Render-only picks, role-qualified (`"<role>.<attr>": choice`). */
724
+ optionSelections: Record<string, string>;
725
+ mockupId: string;
726
+ /** The picked alternatives' placements — the record's placements narrowed to this pick set. */
727
+ placements: ResolvedPlacement[];
728
+ /**
729
+ * The per-role render-gvid set as ONE token, `role:gvid,…` sorted by role —
730
+ * the value the box URL carries in `variant=` so the box's render cache and
731
+ * scene keys are distinct per member-variant set (V1). The box parses it
732
+ * per role once rc-6 lands; until then it is an opaque, deterministic key.
733
+ */
734
+ variantToken: string;
735
+ }
736
+
737
+ export type BundleSceneResult =
738
+ | { ok: true; scene: BundleScene }
739
+ | { ok: false; status: number; code: string; message: string };
740
+
741
+ /** `role:gvid,…` sorted by role — deterministic (the URL is a cache key). */
742
+ export function bundleVariantToken(variantByRole: Record<string, { renderGvid: string }>): string {
743
+ return Object.keys(variantByRole)
744
+ .sort()
745
+ .map((role) => `${role}:${variantByRole[role].renderGvid}`)
746
+ .join(",");
747
+ }
748
+
749
+ /**
750
+ * Resolve a bundle render (ADR-0099 D3/V1, swappable-slots amendment):
751
+ * picks first (they decide which placements exist and which mockup fits),
752
+ * then one variant per slot from `variant.<role>` / `opt.<role>.<attr>`
753
+ * through the member's own combinations, then the mockup whose `picks`
754
+ * cover the most slots. Every wrong input fails loudly with a typed code
755
+ * that lists the valid values — a bare `variant=` / `opt.<attr>` names no
756
+ * slot and is refused rather than guessed.
757
+ */
758
+ export function resolveBundleScene(
759
+ product: ResolvedProduct,
760
+ input: BundleSceneInput
761
+ ): BundleSceneResult {
762
+ const bundle = product.bundle;
763
+ if (!bundle) {
764
+ return { ok: false, status: 500, code: "E_NOT_A_BUNDLE", message: `${product.id} has no bundle block` };
765
+ }
766
+ const roles = bundle.members.map((m) => m.role);
767
+ const rolesList = roles.join(", ");
768
+ const fail = (status: number, code: string, message: string): BundleSceneResult => ({ ok: false, status, code, message });
769
+
770
+ if (input.variantOverride !== undefined) {
771
+ return fail(
772
+ 400,
773
+ "E_BUNDLE_ROLE_REQUIRED",
774
+ `variant= names no slot on bundle ${product.id} — use variant.<role>=<gvid>. Roles: ${rolesList}.`
775
+ );
776
+ }
777
+ for (const role of Object.keys(input.picks)) {
778
+ if (!roles.includes(role)) {
779
+ return fail(400, "E_BUNDLE_ROLE_NOT_FOUND", `Unknown role "${role}" in pick.${role}= on bundle ${product.id}. Roles: ${rolesList}.`);
780
+ }
781
+ }
782
+ for (const role of Object.keys(input.variants)) {
783
+ if (!roles.includes(role)) {
784
+ return fail(400, "E_BUNDLE_ROLE_NOT_FOUND", `Unknown role "${role}" in variant.${role}= on bundle ${product.id}. Roles: ${rolesList}.`);
785
+ }
786
+ }
787
+ const optionsByRole: Record<string, Record<string, string>> = {};
788
+ for (const [key, value] of Object.entries(input.options)) {
789
+ const dot = key.indexOf(".");
790
+ if (dot <= 0 || dot === key.length - 1) {
791
+ return fail(
792
+ 400,
793
+ "E_BUNDLE_ROLE_REQUIRED",
794
+ `opt.${key}= names no slot on bundle ${product.id} — use opt.<role>.<attribute>=<choice>. Roles: ${rolesList}.`
795
+ );
796
+ }
797
+ const role = key.slice(0, dot);
798
+ const attr = key.slice(dot + 1);
799
+ if (!roles.includes(role)) {
800
+ return fail(400, "E_BUNDLE_ROLE_NOT_FOUND", `Unknown role "${role}" in opt.${key}= on bundle ${product.id}. Roles: ${rolesList}.`);
801
+ }
802
+ (optionsByRole[role] ??= {})[attr] = value;
803
+ }
804
+
805
+ const picks: Record<string, string> = {};
806
+ const variantByRole: BundleScene["variantByRole"] = {};
807
+ const optionSelections: Record<string, string> = {};
808
+ for (const member of bundle.members) {
809
+ const wanted = input.picks[member.role];
810
+ const alt = wanted === undefined
811
+ ? member.products[0]
812
+ : member.products.find((p) => p.productId === wanted);
813
+ if (!alt) {
814
+ return fail(
815
+ 400,
816
+ "E_BUNDLE_PICK_NOT_FOUND",
817
+ `Unknown pick "${wanted}" for role "${member.role}" on bundle ${product.id}. ` +
818
+ `Alternatives: ${member.products.map((p) => p.productId).join(", ")}.`
819
+ );
820
+ }
821
+ picks[member.role] = alt.productId;
822
+ const roleOpts = optionsByRole[member.role] ?? {};
823
+ const bad = unknownOptionPick(alt, roleOpts);
824
+ if (bad) {
825
+ return bad.validChoices
826
+ ? fail(
827
+ 400,
828
+ "E_OPTION_CHOICE_NOT_FOUND",
829
+ `Unknown choice "${bad.choice}" for option "${bad.attribute}" on ${alt.productId} (role "${member.role}"). ` +
830
+ `Valid choices: ${bad.validChoices.join(", ")}.`
831
+ )
832
+ : fail(
833
+ 400,
834
+ "E_OPTION_NOT_FOUND",
835
+ `Unknown option "${bad.attribute}" on ${alt.productId} (role "${member.role}"). ` +
836
+ (bad.validAttributes.length
837
+ ? `Valid options: ${bad.validAttributes.join(", ")}.`
838
+ : `This product has no options.`)
839
+ );
840
+ }
841
+ const vr = resolveVariant(alt, roleOpts, input.variants[member.role]);
842
+ if (!vr) {
843
+ return fail(422, "E_BUNDLE_MEMBER_NO_VARIANT", `${alt.productId} (role "${member.role}") has no renderable combination`);
844
+ }
845
+ const renderGvid = alt.variants.find((v) => v.gvid === vr.variantId)?.gvidForMockup ?? vr.variantId;
846
+ variantByRole[member.role] = { skuGvid: vr.variantId, renderGvid };
847
+ for (const [attr, choice] of Object.entries(vr.optionSelections)) {
848
+ optionSelections[`${member.role}.${attr}`] = choice;
849
+ }
850
+ }
851
+
852
+ // The mockup: an explicit override, else the one whose picks cover the most
853
+ // slots (a photo depicts exactly one alternative per slot; unmatched slots
854
+ // render blank — their masks belong to a product not in the photo).
855
+ let mockup: ResolvedProduct["mockups"][number] | undefined;
856
+ if (input.mockupOverride) {
857
+ mockup = product.mockups.find((m) => m.id === input.mockupOverride);
858
+ if (!mockup) {
859
+ return fail(
860
+ 400,
861
+ "E_MOCKUP_NOT_FOUND",
862
+ `Unknown mockup "${input.mockupOverride}" for bundle ${product.id}. Mockups: ${product.mockups.map((m) => m.id).join(", ") || "(none)"}.`
863
+ );
864
+ }
865
+ } else {
866
+ let best = -1;
867
+ for (const m of product.mockups) {
868
+ const score = roles.filter((r) => m.picks?.[r] === picks[r]).length;
869
+ if (score > best) {
870
+ best = score;
871
+ mockup = m;
872
+ }
873
+ }
874
+ }
875
+ if (!mockup) {
876
+ return fail(422, "E_BUNDLE_NO_MOCKUP", `Bundle ${product.id} has no published mockup`);
877
+ }
878
+
879
+ const placements = product.placements.filter((p) => p.role && picks[p.role] === p.memberProductId);
880
+ if (placements.length === 0) {
881
+ return fail(422, "E_BUNDLE_NO_PLACEMENTS", `Bundle ${product.id} has no placements for the pick set ${JSON.stringify(picks)}`);
882
+ }
883
+
884
+ return {
885
+ ok: true,
886
+ scene: {
887
+ picks,
888
+ variantByRole,
889
+ optionSelections,
890
+ mockupId: mockup.id,
891
+ placements,
892
+ variantToken: bundleVariantToken(variantByRole),
893
+ },
894
+ };
895
+ }