-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
719 lines (616 loc) · 24.8 KB
/
Copy pathbackground.js
File metadata and controls
719 lines (616 loc) · 24.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
const RATE_LIMIT_DELAY = 500
const MAX_PRODUCTS_PER_PAGE = 250
const MAX_RETRIES = 3
const MAX_PRODUCT_LIMIT = 10000
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max)
}
function round(value, precision = 0) {
const factor = 10 ** precision
return Math.round(value * factor) / factor
}
function toValidNumber(value) {
const number = parseFloat(value)
return Number.isFinite(number) ? number : null
}
function normalizeDomain(rawDomain) {
if (!rawDomain || typeof rawDomain !== 'string') return null
const trimmed = rawDomain.trim()
if (!trimmed) return null
try {
const url = new URL(trimmed.startsWith('http') ? trimmed : `https://${trimmed}`)
return url.hostname
} catch {
return trimmed.replace(/^https?:\/\//, '').split('/')[0]
}
}
function average(values) {
if (!values.length) return 0
return values.reduce((sum, value) => sum + value, 0) / values.length
}
function percentile(sortedValues, percentileValue) {
if (!sortedValues.length) return 0
const index = Math.min(sortedValues.length - 1, Math.max(0, Math.floor((sortedValues.length - 1) * percentileValue)))
return sortedValues[index]
}
function uniqueCount(values) {
return new Set(values.filter(Boolean)).size
}
function fetchTextSignals(pageContent = '') {
const haystack = String(pageContent || '')
return {
bundles: /bundle|build your bundle|mix and match|kit/i.test(haystack),
subscriptions: /subscribe\s*&\s*save|subscription|delivery every|autoship/i.test(haystack),
upsells: /frequently bought together|pair with|complete the look|you may also like/i.test(haystack),
urgency: /limited time|selling fast|low stock|ends tonight|while supplies last/i.test(haystack),
installmentMessaging: /afterpay|klarna|affirm|shop pay installments|sezzle/i.test(haystack),
samples: /sample pack|trial size|starter kit/i.test(haystack),
gifting: /gift card|gift guide|gift set/i.test(haystack),
}
}
async function fetchWithRetry(url, retries = MAX_RETRIES) {
for (let attempt = 0; attempt < retries; attempt += 1) {
try {
const response = await fetch(url)
if (response.ok) {
return await response.json()
}
if (response.status === 429) {
await sleep(RATE_LIMIT_DELAY * (attempt + 2))
continue
}
return null
} catch (error) {
console.error(`Fetch attempt ${attempt + 1} failed:`, error)
if (attempt < retries - 1) {
await sleep(RATE_LIMIT_DELAY)
}
}
}
return null
}
async function fetchAllProducts(baseUrl) {
const allProducts = []
let page = 1
while (true) {
const url = `${baseUrl}/products.json?limit=${MAX_PRODUCTS_PER_PAGE}&page=${page}`
const data = await fetchWithRetry(url)
if (!data || !Array.isArray(data.products) || data.products.length === 0) {
break
}
allProducts.push(...data.products)
page += 1
if (data.products.length < MAX_PRODUCTS_PER_PAGE || allProducts.length >= MAX_PRODUCT_LIMIT) {
break
}
await sleep(RATE_LIMIT_DELAY)
}
return allProducts
}
function extractVariants(products) {
const variants = []
for (const product of products) {
if (!product || !Array.isArray(product.variants)) continue
for (const variant of product.variants) {
const price = toValidNumber(variant?.price)
const compareAtPrice = variant?.compare_at_price ? toValidNumber(variant.compare_at_price) : null
if (!price || price <= 0) continue
variants.push({
productId: product.id,
variantId: variant.id,
sku: variant.sku || null,
price,
compareAtPrice,
available: Boolean(variant.available),
requiresShipping: variant?.requires_shipping !== false,
title: variant.title || '',
productTitle: product.title || '',
})
}
}
return variants
}
function computePriceDistribution(prices) {
const buckets = {
under25: { label: '<$25', count: 0, min: 0, max: 25 },
'25to50': { label: '$25-$50', count: 0, min: 25, max: 50 },
'50to100': { label: '$50-$100', count: 0, min: 50, max: 100 },
'100to250': { label: '$100-$250', count: 0, min: 100, max: 250 },
over250: { label: '$250+', count: 0, min: 250, max: Infinity },
}
for (const price of prices) {
if (price < 25) buckets.under25.count += 1
else if (price < 50) buckets['25to50'].count += 1
else if (price < 100) buckets['50to100'].count += 1
else if (price < 250) buckets['100to250'].count += 1
else buckets.over250.count += 1
}
return Object.values(buckets)
}
function computeDiscountRange(variants) {
const discountPercentages = variants
.filter(variant => variant.compareAtPrice && variant.compareAtPrice > variant.price)
.map(variant => Math.round(((variant.compareAtPrice - variant.price) / variant.compareAtPrice) * 100))
.filter(discountPercent => discountPercent >= 1)
if (!discountPercentages.length) return null
return {
minDiscount: Math.min(...discountPercentages),
maxDiscount: Math.max(...discountPercentages),
avgDiscount: round(average(discountPercentages), 1),
discountedSkuCount: discountPercentages.length,
}
}
function computeAOVRange(medianPrice, upperQuartile, freeShippingThreshold) {
const baseAOV = medianPrice * 0.6 + upperQuartile * 0.4
let aovLow = medianPrice
let aovHigh = upperQuartile
if (freeShippingThreshold && freeShippingThreshold > medianPrice) {
aovLow = Math.max(aovLow, freeShippingThreshold * 0.9)
aovHigh = Math.max(aovHigh, freeShippingThreshold * 1.1)
}
return {
estimatedAOV: round(baseAOV, 2),
estimatedAOVRange: {
low: round(aovLow, 2),
high: round(aovHigh, 2),
},
}
}
function computeMetrics(products, variants, freeShippingThreshold = null) {
if (!variants.length) return null
const prices = variants.map(variant => variant.price).sort((a, b) => a - b)
const minPrice = prices[0]
const maxPrice = prices[prices.length - 1]
const medianPrice = percentile(prices, 0.5)
const avgPrice = average(prices)
const lowerQuartile = percentile(prices, 0.25)
const upperQuartile = percentile(prices, 0.75)
const priceSpread = maxPrice - minPrice
const onSaleVariants = variants.filter(variant => variant.compareAtPrice && variant.compareAtPrice > variant.price)
const availableVariants = variants.filter(variant => variant.available)
const skuCoverage = uniqueCount(variants.map(variant => variant.sku))
const variantPerProduct = variants.length / Math.max(products.length, 1)
const priceDistribution = computePriceDistribution(prices)
const discountRange = computeDiscountRange(variants)
const { estimatedAOV, estimatedAOVRange } = computeAOVRange(medianPrice, upperQuartile, freeShippingThreshold)
return {
productCount: products.length,
skuCount: variants.length,
skuCoverageCount: skuCoverage,
skuCoverageRate: round((skuCoverage / variants.length) * 100, 1),
availableSkuCount: availableVariants.length,
availabilityRate: round((availableVariants.length / variants.length) * 100, 1),
minPrice: round(minPrice, 2),
maxPrice: round(maxPrice, 2),
medianPrice: round(medianPrice, 2),
avgPrice: round(avgPrice, 2),
lowerQuartile: round(lowerQuartile, 2),
upperQuartile: round(upperQuartile, 2),
priceSpread: round(priceSpread, 2),
variantPerProduct: round(variantPerProduct, 2),
estimatedAOV,
estimatedAOVRange,
priceDistribution,
onSaleCount: onSaleVariants.length,
onSalePercentage: round((onSaleVariants.length / variants.length) * 100, 1),
discountRange,
}
}
function detectFreeShippingThreshold(pageContent) {
if (!pageContent) return { dollarThreshold: null, itemThreshold: null }
const dollarPatterns = [
/free\s+shipping\s+(?:on\s+(?:all\s+)?orders?\s+)?(?:over|above)\s+\$(\d+(?:\.\d{2})?)/i,
/free\s+shipping\s+for\s+orders?\s+(?:over|above)\s+\$(\d+(?:\.\d{2})?)/i,
/free\s+shipping\s+when\s+you\s+spend\s+\$(\d+(?:\.\d{2})?)/i,
/spend\s+\$(\d+(?:\.\d{2})?)\s+(?:and\s+)?(?:get\s+|for\s+|to\s+(?:get\s+|enjoy\s+|earn\s+|unlock\s+)?)?free\s+shipping/i,
/\$(\d+(?:\.\d{2})?)\s+(?:for|=)\s+free\s+shipping/i,
/free\s+shipping\s+(?:at\s+)?\$(\d+(?:\.\d{2})?)\+?/i,
/(?:enjoy|get|earn|unlock)\s+free\s+shipping\s+(?:on\s+orders?\s+)?\$(\d+(?:\.\d{2})?)\+?/i,
/orders?\s+(?:over\s+|above\s+)?\$(\d+(?:\.\d{2})?)\+?\s+ship\s+free/i,
/\$(\d+(?:\.\d{2})?)\s+away\s+from\s+free\s+shipping/i,
/complimentary\s+shipping\s+(?:on\s+orders?\s+)?(?:over|above)\s+\$(\d+(?:\.\d{2})?)/i,
/free\s+delivery\s+(?:on\s+(?:all\s+)?orders?\s+)?(?:over|above)\s+\$(\d+(?:\.\d{2})?)/i,
/(?:shippingThreshold|freeShippingMin|freeShippingAmount)["\s:]+(\d+(?:\.\d{2})?)/i,
]
let dollarThreshold = null
for (const pattern of dollarPatterns) {
const match = pageContent.match(pattern)
if (!match?.[1]) continue
const threshold = toValidNumber(match[1])
if (!threshold || threshold <= 0 || threshold >= 1000) continue
if (pattern.source.includes('away') && threshold < 20) continue
dollarThreshold = threshold
break
}
const itemPatterns = [
/free\s+(?:shipping|delivery)\s+(?:on\s+(?:orders?\s+(?:of\s+)?)?)?(\d+)\+?\s+(?:or\s+more\s+)?items?/i,
/buy\s+(\d+)\+?\s+(?:or\s+more\s+)?items?\s*[,.]?\s*(?:and\s+)?(?:get\s+|for\s+|enjoy\s+)?free\s+(?:shipping|delivery)/i,
/(\d+)\+?\s+(?:or\s+more\s+)?items?\s+ship\s+free/i,
/(?:item.?threshold|min.?items?.?free.?shipping)["\s:]+(\d+)/i,
]
let itemThreshold = null
for (const pattern of itemPatterns) {
const match = pageContent.match(pattern)
if (!match?.[1]) continue
const count = parseInt(match[1], 10)
if (Number.isNaN(count) || count < 2 || count > 50) continue
itemThreshold = count
break
}
return { dollarThreshold, itemThreshold }
}
async function detectCanonicalFromEndpoints(baseUrl) {
try {
const metaResponse = await fetchWithRetry(`${baseUrl}/meta.json`, 1)
if (metaResponse?.shop) {
return {
domain: metaResponse.shop.includes('.myshopify.com') ? metaResponse.shop : `${metaResponse.shop}.myshopify.com`,
source: 'endpoint',
}
}
if (metaResponse?.url?.includes('.myshopify.com')) {
const match = metaResponse.url.match(/([a-zA-Z0-9-]+\.myshopify\.com)/)
if (match) return { domain: match[1], source: 'endpoint' }
}
} catch (error) {
console.error('Error detecting canonical from endpoints:', error)
}
return null
}
function summarizeSignals(signals = {}) {
const personalization = signals.personalization || {}
const channels = signals.channels || {}
const emailSms = signals.emailSms || {}
const shippingOffers = signals.shippingOffers || []
const groups = [
...(personalization.loyalty || []),
...(personalization.quizzes || []),
...(personalization.wishlists || []),
...(personalization.reviews || []),
...(channels.affiliates || []),
...((channels.pixels || []).map(item => item.name)),
...(emailSms.esps || []),
...(emailSms.sms || []),
...(emailSms.popups || []),
...shippingOffers,
]
return {
totalDetections: groups.length,
reviewCoverage: (personalization.reviews || []).length,
retentionCoverage: (personalization.loyalty || []).length + (emailSms.esps || []).length + (emailSms.sms || []).length,
acquisitionCoverage: (channels.pixels || []).length + (channels.affiliates || []).length,
personalizationCoverage: (personalization.quizzes || []).length + (personalization.wishlists || []).length,
onsiteConversionCoverage: (emailSms.popups || []).length + shippingOffers.length,
}
}
function classifyPricePosition(metrics) {
if (metrics.medianPrice >= 150) return 'premium'
if (metrics.medianPrice >= 60) return 'mid-market'
return 'value-led'
}
function buildStoreTheme(metrics, signals, textSignals) {
const traits = []
const pricePosition = classifyPricePosition(metrics)
traits.push(pricePosition)
if (metrics.productCount >= 200) traits.push('broad catalog')
else if (metrics.productCount <= 25) traits.push('edited assortment')
if (metrics.onSalePercentage >= 30) traits.push('promotion-heavy')
if ((signals.personalization?.loyalty || []).length || (signals.emailSms?.esps || []).length || (signals.emailSms?.sms || []).length) {
traits.push('retention-led')
}
if (textSignals.subscriptions || textSignals.bundles) traits.push('offer-led')
return traits.slice(0, 4)
}
function buildPatterns(metrics, signals, textSignals) {
const patterns = []
if (textSignals.bundles) patterns.push({ label: 'Bundle merchandising', evidence: 'Bundle or kit language detected on-page.' })
if (textSignals.subscriptions) patterns.push({ label: 'Subscription motion', evidence: 'Recurring purchase messaging detected.' })
if (textSignals.upsells) patterns.push({ label: 'Cross-sell pattern', evidence: 'Upsell or recommendation copy detected.' })
if (textSignals.urgency) patterns.push({ label: 'Urgency cues', evidence: 'Scarcity or deadline language detected.' })
if (textSignals.installmentMessaging) patterns.push({ label: 'Installment messaging', evidence: 'Buy-now-pay-later providers referenced.' })
if ((signals.personalization?.quizzes || []).length) patterns.push({ label: 'Guided selling', evidence: 'Quiz tooling detected.' })
if ((signals.personalization?.reviews || []).length) patterns.push({ label: 'Social proof', evidence: 'Review platform detected.' })
if ((signals.emailSms?.popups || []).length) patterns.push({ label: 'Lead capture', evidence: 'Popup or opt-in tooling detected.' })
return patterns
}
function buildScorecards(metrics, signals, textSignals, freeShippingThreshold, freeShippingItemThreshold) {
const signalSummary = summarizeSignals(signals)
const catalogScore = clamp(
25
+ Math.min(metrics.productCount, 250) / 5
+ Math.min(metrics.variantPerProduct * 8, 18)
+ Math.min(metrics.availabilityRate / 2.5, 22)
+ Math.min(metrics.skuCoverageRate / 4, 15),
0,
100,
)
const pricingScore = clamp(
20
+ Math.min(metrics.priceSpread / 5, 18)
+ Math.min(metrics.upperQuartile / 8, 18)
+ (metrics.discountRange ? Math.min(metrics.discountRange.avgDiscount, 20) : 0)
+ (freeShippingThreshold ? 18 : 0)
+ (metrics.onSalePercentage > 0 && metrics.onSalePercentage < 55 ? 14 : 6),
0,
100,
)
const experienceScore = clamp(
18
+ signalSummary.reviewCoverage * 12
+ signalSummary.personalizationCoverage * 10
+ (textSignals.upsells ? 12 : 0)
+ (textSignals.bundles ? 12 : 0)
+ (freeShippingThreshold || freeShippingItemThreshold ? 12 : 0)
+ (textSignals.installmentMessaging ? 10 : 0),
0,
100,
)
const growthScore = clamp(
16
+ signalSummary.acquisitionCoverage * 12
+ signalSummary.retentionCoverage * 10
+ signalSummary.onsiteConversionCoverage * 10
+ (textSignals.subscriptions ? 14 : 0)
+ (textSignals.urgency ? 8 : 0),
0,
100,
)
const operationalScore = clamp(
20
+ Math.min(metrics.availabilityRate / 2, 30)
+ (metrics.skuCoverageRate >= 60 ? 14 : 6)
+ (freeShippingThreshold && metrics.estimatedAOV >= freeShippingThreshold * 0.8 ? 18 : 8)
+ (metrics.productCount >= 8 ? 10 : 0),
0,
100,
)
const overallScore = round(average([catalogScore, pricingScore, experienceScore, growthScore, operationalScore]))
return {
overallScore,
catalogScore: round(catalogScore),
pricingScore: round(pricingScore),
experienceScore: round(experienceScore),
growthScore: round(growthScore),
operationalScore: round(operationalScore),
}
}
function buildConfidence(metrics, signals, canonicalSource, freeShippingThreshold, patterns) {
let confidence = 40
confidence += Math.min(metrics.productCount, 150) / 5
confidence += Math.min(summarizeSignals(signals).totalDetections * 4, 20)
confidence += freeShippingThreshold ? 8 : 0
confidence += canonicalSource && canonicalSource !== 'fallback' ? 8 : 0
confidence += Math.min(patterns.length * 3, 12)
const score = clamp(round(confidence), 0, 100)
let label = 'Low'
if (score >= 75) label = 'High'
else if (score >= 55) label = 'Medium'
return { score, label }
}
function buildFindings(metrics, signals, textSignals, freeShippingThreshold, freeShippingItemThreshold) {
const strengths = []
const gaps = []
const opportunities = []
if (metrics.productCount >= 100) {
strengths.push('Large catalog footprint with enough breadth to support collection-driven merchandising.')
} else if (metrics.productCount <= 20) {
strengths.push('Tight assortment suggests a focused merchandising story rather than catalog sprawl.')
}
if (metrics.discountRange) {
strengths.push(`Markdown coverage is active across ${metrics.discountRange.discountedSkuCount} SKUs, with an average discount around ${metrics.discountRange.avgDiscount}%.`)
} else {
gaps.push('No clear markdown strategy detected in product data, which may reduce price anchoring on PDPs and collections.')
opportunities.push({
title: 'Add pricing contrast',
impact: 'Conversion',
detail: 'Use compare-at pricing, bundle savings, or threshold messaging to create clearer value framing.',
})
}
if (freeShippingThreshold) {
strengths.push(`Free shipping is signposted at ${round(freeShippingThreshold, 2)}, giving shoppers a concrete cart-building target.`)
} else if (freeShippingItemThreshold) {
strengths.push(`Free shipping is incentivized by item count at ${freeShippingItemThreshold}+ items.`)
} else {
gaps.push('Shipping threshold messaging was not detected, so the scan cannot confirm a cart-building threshold.')
opportunities.push({
title: 'Expose shipping threshold',
impact: 'AOV',
detail: 'Add persistent threshold messaging in the header, cart, or announcement bar to support order uplift.',
})
}
if ((signals.personalization?.reviews || []).length) {
strengths.push('Review infrastructure is present, which supports trust and post-purchase proof.')
} else {
gaps.push('No review platform was detected, leaving a likely trust gap on product pages.')
opportunities.push({
title: 'Strengthen social proof',
impact: 'Trust',
detail: 'Add ratings, UGC, or review syndication so product pages carry more proof at decision time.',
})
}
if ((signals.emailSms?.esps || []).length || (signals.emailSms?.sms || []).length) {
strengths.push('Retention tooling is present, indicating owned-channel follow-up beyond the first session.')
} else {
gaps.push('Email/SMS infrastructure was not clearly detected, which limits lifecycle marketing confidence.')
opportunities.push({
title: 'Improve owned-channel capture',
impact: 'Retention',
detail: 'Pair an ESP with onsite capture to turn first-time traffic into a remarketing audience.',
})
}
if (!textSignals.upsells && metrics.variantPerProduct < 2) {
opportunities.push({
title: 'Add cross-sell surfaces',
impact: 'AOV',
detail: 'Introduce related products, routine builders, or complementary pairings to offset narrow variant depth.',
})
}
if (!textSignals.bundles && metrics.productCount >= 12 && classifyPricePosition(metrics) !== 'premium') {
opportunities.push({
title: 'Test bundles or kits',
impact: 'Merchandising',
detail: 'The assortment is large enough to support bundle architecture, especially for value-led or replenishable catalogs.',
})
}
return {
strengths: strengths.slice(0, 4),
gaps: gaps.slice(0, 4),
opportunities: opportunities.slice(0, 4),
}
}
function buildEvaluation(metrics, signals, canonicalSource, freeShippingThreshold, freeShippingItemThreshold, pageContent) {
const textSignals = fetchTextSignals(pageContent)
const patterns = buildPatterns(metrics, signals, textSignals)
const scorecards = buildScorecards(metrics, signals, textSignals, freeShippingThreshold, freeShippingItemThreshold)
const confidence = buildConfidence(metrics, signals, canonicalSource, freeShippingThreshold, patterns)
const findings = buildFindings(metrics, signals, textSignals, freeShippingThreshold, freeShippingItemThreshold)
const theme = buildStoreTheme(metrics, signals, textSignals)
let verdict = 'Developing'
if (scorecards.overallScore >= 80) verdict = 'Advanced'
else if (scorecards.overallScore >= 65) verdict = 'Maturing'
else if (scorecards.overallScore >= 50) verdict = 'Foundational'
return {
verdict,
confidence,
theme,
patterns,
scorecards,
findings,
summary: {
pricePosition: classifyPricePosition(metrics),
catalogShape: metrics.productCount >= 200 ? 'broad' : metrics.productCount >= 40 ? 'balanced' : 'focused',
signalDensity: summarizeSignals(signals).totalDetections,
},
}
}
async function handleScan(rawDomain, pageContent, canonicalDomain = null, canonicalSource = null, popupShippingThreshold = null, signals = null) {
const startTime = Date.now()
const domain = normalizeDomain(rawDomain)
if (!domain) {
return { success: false, error: 'Invalid or missing domain.', isShopify: false }
}
const baseUrl = `https://${domain}`
try {
const products = await fetchAllProducts(baseUrl)
if (!products.length) {
return {
success: false,
error: 'No products found. This may not be a Shopify store or products.json is blocked.',
isShopify: false,
}
}
let finalCanonicalDomain = canonicalDomain
let finalCanonicalSource = canonicalSource
if (!finalCanonicalDomain) {
const endpointResult = await detectCanonicalFromEndpoints(baseUrl)
if (endpointResult) {
finalCanonicalDomain = endpointResult.domain
finalCanonicalSource = endpointResult.source
} else {
finalCanonicalDomain = domain
finalCanonicalSource = 'fallback'
}
}
const variants = extractVariants(products)
const { dollarThreshold, itemThreshold } = detectFreeShippingThreshold(pageContent)
const freeShippingThreshold = dollarThreshold || popupShippingThreshold || null
const freeShippingItemThreshold = itemThreshold
const metrics = computeMetrics(products, variants, freeShippingThreshold)
if (!metrics) {
return { success: false, error: 'Could not compute metrics from product data.' }
}
const normalizedSignals = signals || {
personalization: {},
channels: {},
emailSms: {},
shippingOffers: [],
}
const evaluation = buildEvaluation(
{ ...metrics, freeShippingThreshold, freeShippingItemThreshold },
normalizedSignals,
finalCanonicalSource,
freeShippingThreshold,
freeShippingItemThreshold,
pageContent,
)
const result = {
success: true,
isShopify: true,
domain,
canonicalDomain: finalCanonicalDomain,
canonicalSource: finalCanonicalSource,
metrics: {
...metrics,
freeShippingThreshold,
freeShippingItemThreshold,
},
signals: normalizedSignals,
evaluation,
scanTime: Date.now() - startTime,
timestamp: new Date().toISOString(),
}
await chrome.storage.local.set({ [domain]: result })
return result
} catch (error) {
console.error('Scan error:', error)
return {
success: false,
error: error?.message || 'An unknown error occurred during scanning.',
}
}
}
async function getCachedScan(domain) {
const normalizedDomain = normalizeDomain(domain)
const result = await chrome.storage.local.get(normalizedDomain)
return result[normalizedDomain] || null
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.action === 'scan') {
handleScan(
message.domain,
message.pageContent,
message.canonicalDomain,
message.canonicalSource,
message.popupShippingThreshold || null,
message.signals || null,
).then(sendResponse)
return true
}
if (message?.action === 'getCached') {
getCachedScan(message.domain).then(sendResponse)
return true
}
if (message?.action === 'clearCache') {
const normalizedDomain = normalizeDomain(message.domain)
if (normalizedDomain) chrome.storage.local.remove(normalizedDomain).then(() => sendResponse({ success: true }))
else sendResponse({ success: true })
return true
}
return false
})
async function configureSidePanel() {
if (!chrome.sidePanel) return
try {
await chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true })
} catch (error) {
console.error('Failed to configure side panel behavior:', error)
}
}
chrome.runtime.onInstalled.addListener(() => {
configureSidePanel()
})
chrome.runtime.onStartup.addListener(() => {
configureSidePanel()
})
chrome.action.onClicked.addListener(async tab => {
if (!chrome.sidePanel || !tab?.id) return
try {
await chrome.sidePanel.open({ tabId: tab.id })
} catch (error) {
console.error('Failed to open side panel on action click:', error)
}
})
configureSidePanel()