create-abcart-theme 0.10.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +133 -127
- package/LICENSE +202 -202
- package/NOTICE +2 -2
- package/README.md +65 -65
- package/bin/create-abcart-theme.mjs +4 -4
- package/package.json +49 -49
- package/src/args.mjs +113 -113
- package/src/banner.mjs +21 -21
- package/src/cli.mjs +119 -119
- package/src/create.mjs +85 -82
- package/src/package-manager.mjs +32 -32
- package/src/style.mjs +17 -17
- package/templates/default/.agents/skills/{wocart-docs → abcart-docs}/SKILL.md +146 -146
- package/templates/default/.agents/skills/{wocart-theme-from-design → abcart-theme-from-design}/SKILL.md +58 -58
- package/templates/default/.agents/skills/{wocart-theme-from-design → abcart-theme-from-design}/references/inputs-and-rights.md +47 -47
- package/templates/default/.agents/skills/{wocart-theme-from-design → abcart-theme-from-design}/references/layout-rtl-and-phone.md +36 -36
- package/templates/default/.agents/skills/{wocart-theme-from-design → abcart-theme-from-design}/references/measure-the-design.md +60 -60
- package/templates/default/.agents/skills/{wocart-theme-from-design → abcart-theme-from-design}/references/tokens-sections-content.md +103 -103
- package/templates/default/.agents/skills/{wocart-theme-from-design → abcart-theme-from-design}/references/verify-and-report.md +102 -102
- package/templates/default/.agents/skills/{wocart-theme-from-design → abcart-theme-from-design}/scripts/compare-design.cjs +230 -230
- package/templates/default/.agents/skills/{wocart-theme-from-design → abcart-theme-from-design}/scripts/qa-pages.cjs +219 -219
- package/templates/default/.agents/skills/shopify-theme-asset-collector/SKILL.md +125 -125
- package/templates/default/.agents/skills/shopify-theme-asset-collector/scripts/collect_public_assets.py +370 -370
- package/templates/default/.dev.vars.example +12 -12
- package/templates/default/AGENTS.md +240 -240
- package/templates/default/README.md +184 -184
- package/templates/default/_gitignore +11 -11
- package/templates/default/astro.config.mjs +85 -85
- package/templates/default/package.json +36 -36
- package/templates/default/public/fonts/OFL.txt +96 -96
- package/templates/default/src/actions/index.ts +22 -22
- package/templates/default/src/components/cart/AddToCartButton.astro +45 -45
- package/templates/default/src/components/cart/CartDrawer.astro +47 -47
- package/templates/default/src/components/cart/CartSummary.astro +11 -11
- package/templates/default/src/components/cart/FreeShipping.astro +7 -7
- package/templates/default/src/components/checkout/CheckoutMain.astro +29 -29
- package/templates/default/src/components/checkout/OrderForm.astro +280 -280
- package/templates/default/src/components/checkout/ThankYouMain.astro +68 -68
- package/templates/default/src/components/landing/LandingImages.astro +51 -51
- package/templates/default/src/components/landing/LandingOrder.astro +46 -46
- package/templates/default/src/components/landing/LandingProduct.astro +41 -41
- package/templates/default/src/components/listing/ListingMain.astro +93 -93
- package/templates/default/src/components/listing/PageMain.astro +52 -52
- package/templates/default/src/components/listing/Pagination.astro +31 -31
- package/templates/default/src/components/listing/SortControl.astro +35 -35
- package/templates/default/src/components/product/BuyBox.astro +96 -96
- package/templates/default/src/components/product/Description.astro +24 -24
- package/templates/default/src/components/product/Gallery.astro +66 -66
- package/templates/default/src/components/product/MobileBuyBar.astro +29 -29
- package/templates/default/src/components/product/OfferChoice.astro +66 -66
- package/templates/default/src/components/product/ProductMain.astro +40 -40
- package/templates/default/src/components/product/ProductReviews.astro +72 -72
- package/templates/default/src/components/product/RelatedProducts.astro +30 -30
- package/templates/default/src/components/product/blocks/BenefitsBlock.astro +13 -13
- package/templates/default/src/components/product/blocks/CollapsibleBlock.astro +20 -20
- package/templates/default/src/components/product/blocks/DescriptionBlock.astro +19 -19
- package/templates/default/src/components/product/blocks/DetailsBlock.astro +33 -33
- package/templates/default/src/components/product/blocks/GalleryBlock.astro +12 -12
- package/templates/default/src/components/product/blocks/OrderBlock.astro +30 -30
- package/templates/default/src/components/product/blocks/PriceBlock.astro +23 -23
- package/templates/default/src/components/product/blocks/RatingBlock.astro +16 -16
- package/templates/default/src/components/product/blocks/StockBlock.astro +22 -22
- package/templates/default/src/components/product/blocks/TextBlock.astro +11 -11
- package/templates/default/src/components/product/blocks/TitleBlock.astro +20 -20
- package/templates/default/src/components/reviews/ReviewCard.astro +46 -46
- package/templates/default/src/components/reviews/ReviewForm.astro +113 -113
- package/templates/default/src/components/reviews/VoiceNote.astro +60 -60
- package/templates/default/src/components/sections/CollectionCards.astro +65 -65
- package/templates/default/src/components/sections/Countdown.astro +57 -57
- package/templates/default/src/components/sections/Faq.astro +44 -44
- package/templates/default/src/components/sections/FeaturedProduct.astro +71 -71
- package/templates/default/src/components/sections/Hero.astro +99 -99
- package/templates/default/src/components/sections/ImageBanner.astro +46 -46
- package/templates/default/src/components/sections/ProductGrid.astro +47 -47
- package/templates/default/src/components/sections/RichText.astro +35 -35
- package/templates/default/src/components/sections/Steps.astro +46 -46
- package/templates/default/src/components/sections/Testimonials.astro +57 -57
- package/templates/default/src/components/shell/Footer.astro +80 -80
- package/templates/default/src/components/shell/Header.astro +89 -89
- package/templates/default/src/components/shell/LanguageMenu.astro +33 -33
- package/templates/default/src/components/shell/MobileMenu.astro +65 -65
- package/templates/default/src/components/shell/SearchDialog.astro +19 -19
- package/templates/default/src/components/shell/TopBar.astro +54 -54
- package/templates/default/src/components/shell/WhatsAppWidget.astro +111 -111
- package/templates/default/src/components/store/ContactMain.astro +79 -79
- package/templates/default/src/components/store/SearchMain.astro +56 -56
- package/templates/default/src/components/store/TrackOrderMain.astro +161 -161
- package/templates/default/src/components/surface/Area.astro +20 -20
- package/templates/default/src/components/surface/PreviewBridge.astro +24 -24
- package/templates/default/src/components/surface/Sections.astro +35 -35
- package/templates/default/src/components/ui/Breadcrumbs.astro +36 -36
- package/templates/default/src/components/ui/Button.astro +45 -45
- package/templates/default/src/components/ui/EditorPlaceholder.astro +24 -24
- package/templates/default/src/components/ui/Icon.astro +93 -93
- package/templates/default/src/components/ui/Logo.astro +36 -36
- package/templates/default/src/components/ui/Photo.astro +46 -46
- package/templates/default/src/components/ui/Price.astro +24 -24
- package/templates/default/src/components/ui/ProductCard.astro +41 -41
- package/templates/default/src/components/ui/Rating.astro +22 -22
- package/templates/default/src/components/ui/Section.astro +34 -34
- package/templates/default/src/components/ui/SectionHeading.astro +19 -19
- package/templates/default/src/env.d.ts +23 -23
- package/templates/default/src/layouts/StoreLayout.astro +145 -145
- package/templates/default/src/lib/browser-copy.ts +37 -37
- package/templates/default/src/lib/context.ts +89 -89
- package/templates/default/src/lib/coupon-notice.ts +47 -47
- package/templates/default/src/lib/i18n.ts +32 -32
- package/templates/default/src/lib/images.ts +38 -38
- package/templates/default/src/lib/listing-query.ts +41 -41
- package/templates/default/src/lib/money.ts +16 -16
- package/templates/default/src/lib/motion.ts +16 -16
- package/templates/default/src/lib/nav.ts +26 -26
- package/templates/default/src/lib/offer-tiles.ts +105 -105
- package/templates/default/src/lib/order-outcome.ts +66 -66
- package/templates/default/src/lib/otp-message.ts +21 -21
- package/templates/default/src/lib/products.ts +38 -38
- package/templates/default/src/lib/review-refusals.ts +31 -31
- package/templates/default/src/lib/store.ts +31 -31
- package/templates/default/src/lib/whatsapp.ts +29 -29
- package/templates/default/src/middleware.ts +23 -23
- package/templates/default/src/pages/404.astro +22 -22
- package/templates/default/src/pages/{wocart-preview.astro → abcart-preview.astro} +43 -43
- package/templates/default/src/pages/{wocart-revalidate.ts → abcart-revalidate.ts} +10 -10
- package/templates/default/src/pages/{wocart-styles.css.ts → abcart-styles.css.ts} +5 -5
- package/templates/default/src/pages/{wocart-theme.json.ts → abcart-theme.json.ts} +5 -5
- package/templates/default/src/pages/api/abandoned/convert.ts +4 -4
- package/templates/default/src/pages/api/abandoned/upsert.ts +4 -4
- package/templates/default/src/pages/api/cart/validate.ts +4 -4
- package/templates/default/src/pages/api/communes/[wilayaId].ts +4 -4
- package/templates/default/src/pages/api/otp/send.ts +4 -4
- package/templates/default/src/pages/api/otp/verify.ts +4 -4
- package/templates/default/src/pages/api/reviews/[productId].ts +3 -3
- package/templates/default/src/pages/api/reviews/eligibility.ts +3 -3
- package/templates/default/src/pages/api/reviews/submit.ts +3 -3
- package/templates/default/src/pages/api/reviews/upload.ts +3 -3
- package/templates/default/src/pages/category/[slug].astro +20 -20
- package/templates/default/src/pages/checkout.astro +25 -25
- package/templates/default/src/pages/collections/[handle].astro +20 -20
- package/templates/default/src/pages/contact.astro +17 -17
- package/templates/default/src/pages/index.astro +9 -9
- package/templates/default/src/pages/lp/[slug].astro +47 -47
- package/templates/default/src/pages/pages/[slug].astro +16 -16
- package/templates/default/src/pages/products/[handle].astro +37 -37
- package/templates/default/src/pages/products/index.astro +15 -15
- package/templates/default/src/pages/robots.txt.ts +9 -9
- package/templates/default/src/pages/search.astro +19 -19
- package/templates/default/src/pages/sitemap.xml.ts +12 -12
- package/templates/default/src/pages/thank-you.astro +33 -33
- package/templates/default/src/pages/track-order.astro +17 -17
- package/templates/default/src/scripts/cart.ts +371 -371
- package/templates/default/src/scripts/checkout/coupon.ts +96 -96
- package/templates/default/src/scripts/checkout/delivery.ts +86 -86
- package/templates/default/src/scripts/checkout/form.ts +54 -54
- package/templates/default/src/scripts/checkout/otp.ts +106 -106
- package/templates/default/src/scripts/checkout/picker.ts +169 -169
- package/templates/default/src/scripts/checkout/quote.ts +169 -169
- package/templates/default/src/scripts/checkout/submit.ts +113 -113
- package/templates/default/src/scripts/checkout/tracking.ts +74 -74
- package/templates/default/src/scripts/countdown.ts +29 -29
- package/templates/default/src/scripts/events.ts +4 -4
- package/templates/default/src/scripts/hero.ts +49 -49
- package/templates/default/src/scripts/listing.ts +13 -13
- package/templates/default/src/scripts/order-form.ts +100 -100
- package/templates/default/src/scripts/product.ts +306 -306
- package/templates/default/src/scripts/public-config.ts +79 -79
- package/templates/default/src/scripts/reviews.ts +358 -358
- package/templates/default/src/scripts/site.ts +131 -131
- package/templates/default/src/scripts/thank-you.ts +11 -11
- package/templates/default/src/scripts/voice-note.ts +94 -94
- package/templates/default/src/styles/base.css +1030 -1030
- package/templates/default/src/styles/checkout.css +1111 -1111
- package/templates/default/src/styles/global.css +12 -12
- package/templates/default/src/styles/product.css +871 -871
- package/templates/default/src/styles/reviews.css +533 -533
- package/templates/default/src/styles/sections.css +931 -931
- package/templates/default/src/styles/shell.css +970 -970
- package/templates/default/src/styles/tokens.css +583 -583
- package/templates/default/src/theme/api-routes.ts +10 -10
- package/templates/default/src/theme/content/catalog.ts +117 -117
- package/templates/default/src/theme/content/checkout.ts +168 -168
- package/templates/default/src/theme/content/editor.ts +21 -21
- package/templates/default/src/theme/content/index.ts +45 -45
- package/templates/default/src/theme/content/reviews.ts +76 -76
- package/templates/default/src/theme/content/shell.ts +59 -59
- package/templates/default/src/theme/content/types.ts +12 -12
- package/templates/default/src/theme/documents/catalog.json +11 -11
- package/templates/default/src/theme/documents/category.json +11 -11
- package/templates/default/src/theme/documents/checkout.json +11 -11
- package/templates/default/src/theme/documents/collection.json +11 -11
- package/templates/default/src/theme/documents/contact.json +11 -11
- package/templates/default/src/theme/documents/footer.area.json +11 -11
- package/templates/default/src/theme/documents/header.area.json +16 -16
- package/templates/default/src/theme/documents/home.json +313 -313
- package/templates/default/src/theme/documents/landing.json +8 -8
- package/templates/default/src/theme/documents/page.json +11 -11
- package/templates/default/src/theme/documents/product.json +125 -125
- package/templates/default/src/theme/documents/search.json +11 -11
- package/templates/default/src/theme/documents/thank-you.json +11 -11
- package/templates/default/src/theme/documents/track-order.json +11 -11
- package/templates/default/src/theme/fields.ts +61 -61
- package/templates/default/src/theme/key.ts +11 -11
- package/templates/default/src/theme/labels.ts +231 -231
- package/templates/default/src/theme/locales.ts +11 -11
- package/templates/default/src/theme/palette.ts +14 -14
- package/templates/default/src/theme/sections/collection-cards.ts +65 -65
- package/templates/default/src/theme/sections/faq.ts +74 -74
- package/templates/default/src/theme/sections/featured-product.ts +42 -42
- package/templates/default/src/theme/sections/hero.ts +47 -47
- package/templates/default/src/theme/sections/image-banner.ts +25 -25
- package/templates/default/src/theme/sections/index.ts +40 -40
- package/templates/default/src/theme/sections/landing.ts +150 -150
- package/templates/default/src/theme/sections/listing.ts +84 -84
- package/templates/default/src/theme/sections/product-grid.ts +42 -42
- package/templates/default/src/theme/sections/product.ts +297 -297
- package/templates/default/src/theme/sections/rich-text.ts +39 -39
- package/templates/default/src/theme/sections/shared.ts +54 -54
- package/templates/default/src/theme/sections/shell.ts +85 -85
- package/templates/default/src/theme/sections/store-pages.ts +101 -101
- package/templates/default/src/theme/sections/testimonials.ts +61 -61
- package/templates/default/src/theme/sections/thank-you.ts +35 -35
- package/templates/default/src/theme/settings.ts +124 -124
- package/templates/default/src/theme/theme.ts +65 -65
- package/templates/default/tests/fixtures/canvas-tote.json +62 -62
- package/templates/default/tests/fixtures/linen-shirt.json +128 -128
- package/templates/default/tests/unit/checkout.test.ts +241 -241
- package/templates/default/tests/unit/contract.test.ts +170 -169
- package/templates/default/tests/unit/contrast.test.ts +68 -68
- package/templates/default/tests/unit/copy.test.ts +101 -101
- package/templates/default/tests/unit/design-values.test.ts +95 -95
- package/templates/default/tests/unit/editability.test.ts +180 -180
- package/templates/default/tests/unit/fixtures.ts +91 -91
- package/templates/default/tests/unit/footer.test.ts +54 -54
- package/templates/default/tests/unit/guards.test.ts +340 -340
- package/templates/default/tests/unit/images.test.ts +26 -26
- package/templates/default/tests/unit/landing.test.ts +151 -151
- package/templates/default/tests/unit/languages.test.ts +42 -42
- package/templates/default/tests/unit/middleware.test.ts +53 -53
- package/templates/default/tests/unit/offer-tiles.test.ts +75 -75
- package/templates/default/tests/unit/render.ts +38 -38
- package/templates/default/tests/unit/reviews.test.ts +25 -25
- package/templates/default/tests/unit/rules.test.ts +59 -59
- package/templates/default/tests/unit/source.ts +75 -75
- package/templates/default/tests/unit/store-pages.test.ts +147 -147
- package/templates/default/tests/unit/studio.test.ts +202 -202
- package/templates/default/tests/unit/testimonials.test.ts +52 -52
- package/templates/default/tests/unit/thank-you.test.ts +52 -52
- package/templates/default/tests/unit/tracking.test.ts +29 -29
- package/templates/default/tests/unit/voice-note.test.ts +42 -42
- package/templates/default/tsconfig.json +13 -13
- package/templates/default/vitest.config.ts +15 -15
- package/templates/default/wrangler.jsonc +16 -16
|
@@ -1,370 +1,370 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""Collect the public frontend of Shopify storefront pages into one folder.
|
|
3
|
-
|
|
4
|
-
For each page URL: the HTML source, the stylesheets, scripts, images, fonts and
|
|
5
|
-
SVGs the page and its stylesheets reference, and which homepage section uses
|
|
6
|
-
each of them. Every file is stored once, under assets/, and the manifest lists
|
|
7
|
-
the pages that use it. Standard library only (Python 3.9+).
|
|
8
|
-
|
|
9
|
-
Usage:
|
|
10
|
-
python3 collect_public_assets.py https://store.myshopify.com/ \\
|
|
11
|
-
https://store.myshopify.com/collections/all --out ./store-assets --zip
|
|
12
|
-
|
|
13
|
-
Only URLs the page itself references are downloaded, and robots.txt is obeyed:
|
|
14
|
-
a path it disallows for this client is skipped and reported. The output is a
|
|
15
|
-
reference for measuring a design. It is not theme code and not a licence to
|
|
16
|
-
ship the store's files; see the skill's rights rules.
|
|
17
|
-
"""
|
|
18
|
-
|
|
19
|
-
from __future__ import annotations
|
|
20
|
-
|
|
21
|
-
import argparse
|
|
22
|
-
import hashlib
|
|
23
|
-
import html
|
|
24
|
-
import json
|
|
25
|
-
import os
|
|
26
|
-
import re
|
|
27
|
-
import shutil
|
|
28
|
-
import ssl
|
|
29
|
-
import sys
|
|
30
|
-
import time
|
|
31
|
-
import urllib.error
|
|
32
|
-
import urllib.parse
|
|
33
|
-
import urllib.request
|
|
34
|
-
import urllib.robotparser
|
|
35
|
-
from dataclasses import dataclass, field
|
|
36
|
-
from html.parser import HTMLParser
|
|
37
|
-
from pathlib import Path
|
|
38
|
-
|
|
39
|
-
USER_AGENT = "
|
|
40
|
-
MAX_BYTES = 30 * 1024 * 1024
|
|
41
|
-
TIMEOUT = 30
|
|
42
|
-
DELAY = 0.2
|
|
43
|
-
MAX_RESOURCES = 2000
|
|
44
|
-
|
|
45
|
-
def tls_context() -> ssl.SSLContext:
|
|
46
|
-
"""Verified TLS: certifi's bundle, else the system bundle. Verification is never turned off."""
|
|
47
|
-
try:
|
|
48
|
-
import certifi
|
|
49
|
-
|
|
50
|
-
return ssl.create_default_context(cafile=certifi.where())
|
|
51
|
-
except ImportError:
|
|
52
|
-
pass
|
|
53
|
-
for bundle in ("/etc/ssl/cert.pem", "/etc/ssl/certs/ca-certificates.crt"):
|
|
54
|
-
if os.path.exists(bundle):
|
|
55
|
-
return ssl.create_default_context(cafile=bundle)
|
|
56
|
-
return ssl.create_default_context()
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
TLS = tls_context()
|
|
60
|
-
|
|
61
|
-
CSS_URL = re.compile(r"url\(\s*(['\"]?)([^'\")]+)\1\s*\)")
|
|
62
|
-
CSS_IMPORT = re.compile(r"@import\s+(?:url\()?\s*['\"]?([^'\")\s;]+)")
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
@dataclass
|
|
66
|
-
class Resource:
|
|
67
|
-
url: str
|
|
68
|
-
kind: str
|
|
69
|
-
file: str | None = None
|
|
70
|
-
bytes: int = 0
|
|
71
|
-
status: str = "pending"
|
|
72
|
-
pages: set = field(default_factory=set)
|
|
73
|
-
sections: set = field(default_factory=set)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
class Collector:
|
|
77
|
-
def __init__(self, out: Path):
|
|
78
|
-
self.out = out
|
|
79
|
-
self.resources: dict[str, Resource] = {}
|
|
80
|
-
self.failures: list[dict] = []
|
|
81
|
-
self.robots: dict[str, urllib.robotparser.RobotFileParser | None] = {}
|
|
82
|
-
self.pending_css: list[str] = []
|
|
83
|
-
self.last = 0.0
|
|
84
|
-
|
|
85
|
-
def allowed(self, url: str) -> bool:
|
|
86
|
-
parts = urllib.parse.urlsplit(url)
|
|
87
|
-
origin = f"{parts.scheme}://{parts.netloc}"
|
|
88
|
-
if origin not in self.robots:
|
|
89
|
-
parser = urllib.robotparser.RobotFileParser()
|
|
90
|
-
try:
|
|
91
|
-
request = urllib.request.Request(origin + "/robots.txt", headers={"User-Agent": USER_AGENT})
|
|
92
|
-
with urllib.request.urlopen(request, timeout=TIMEOUT, context=TLS) as response:
|
|
93
|
-
parser.parse(response.read().decode("utf-8", "replace").splitlines())
|
|
94
|
-
self.robots[origin] = parser
|
|
95
|
-
except (urllib.error.URLError, TimeoutError, OSError):
|
|
96
|
-
self.robots[origin] = None
|
|
97
|
-
parser = self.robots[origin]
|
|
98
|
-
return parser is None or parser.can_fetch(USER_AGENT, url)
|
|
99
|
-
|
|
100
|
-
def get(self, url: str) -> tuple[bytes, str]:
|
|
101
|
-
wait = DELAY - (time.time() - self.last)
|
|
102
|
-
if wait > 0:
|
|
103
|
-
time.sleep(wait)
|
|
104
|
-
self.last = time.time()
|
|
105
|
-
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "text/html,application/xhtml+xml,text/css,application/javascript,image/*,font/*;q=0.9,*/*;q=0.5"})
|
|
106
|
-
with urllib.request.urlopen(request, timeout=TIMEOUT, context=TLS) as response:
|
|
107
|
-
content_type = response.headers.get("Content-Type", "")
|
|
108
|
-
data = response.read(MAX_BYTES + 1)
|
|
109
|
-
if len(data) > MAX_BYTES:
|
|
110
|
-
raise ValueError("larger than the collector's limit")
|
|
111
|
-
return data, content_type
|
|
112
|
-
|
|
113
|
-
def resource(self, url: str, kind: str, page_slug: str, section: str | None) -> Resource | None:
|
|
114
|
-
if not url or url.startswith(("data:", "blob:", "javascript:", "#")):
|
|
115
|
-
return None
|
|
116
|
-
if len(self.resources) >= MAX_RESOURCES and url not in self.resources:
|
|
117
|
-
return None
|
|
118
|
-
item = self.resources.get(url)
|
|
119
|
-
if item is None:
|
|
120
|
-
item = Resource(url=url, kind=kind)
|
|
121
|
-
self.resources[url] = item
|
|
122
|
-
item.pages.add(page_slug)
|
|
123
|
-
if section:
|
|
124
|
-
item.sections.add(section)
|
|
125
|
-
return item
|
|
126
|
-
|
|
127
|
-
def fetch_resource(self, item: Resource) -> None:
|
|
128
|
-
if item.file is not None or item.status not in ("pending",):
|
|
129
|
-
return
|
|
130
|
-
if not self.allowed(item.url):
|
|
131
|
-
item.status = "disallowed by robots.txt"
|
|
132
|
-
self.failures.append({"url": item.url, "reason": item.status})
|
|
133
|
-
return
|
|
134
|
-
digest = hashlib.sha1(item.url.encode()).hexdigest()[:10]
|
|
135
|
-
name = Path(urllib.parse.urlsplit(item.url).path).name or "file"
|
|
136
|
-
name = re.sub(r"[^A-Za-z0-9._-]", "_", name)[:80]
|
|
137
|
-
subfolder = {"css": "css", "js": "js", "font": "fonts", "svg": "svg"}.get(item.kind, "images")
|
|
138
|
-
target = self.out / "assets" / subfolder / f"{digest}-{name}"
|
|
139
|
-
try:
|
|
140
|
-
data, _ = self.get(item.url)
|
|
141
|
-
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
|
|
142
|
-
item.status = f"failed: {error}"
|
|
143
|
-
self.failures.append({"url": item.url, "reason": str(error)})
|
|
144
|
-
return
|
|
145
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
146
|
-
target.write_bytes(data)
|
|
147
|
-
item.file = str(target.relative_to(self.out))
|
|
148
|
-
item.bytes = len(data)
|
|
149
|
-
item.status = "downloaded"
|
|
150
|
-
if item.kind == "css":
|
|
151
|
-
text = data.decode("utf-8", "replace")
|
|
152
|
-
for match in CSS_URL.finditer(text):
|
|
153
|
-
self.queue_css_reference(match.group(2), item.url, item)
|
|
154
|
-
for match in CSS_IMPORT.finditer(text):
|
|
155
|
-
self.queue_css_reference(match.group(1), item.url, item)
|
|
156
|
-
|
|
157
|
-
def queue_css_reference(self, raw: str, base: str, owner: Resource) -> None:
|
|
158
|
-
absolute = urllib.parse.urljoin(base, html.unescape(raw.strip()))
|
|
159
|
-
lower = absolute.lower().split("?")[0]
|
|
160
|
-
kind = "font" if lower.endswith((".woff2", ".woff", ".ttf", ".otf")) else "svg" if lower.endswith(".svg") else "css" if lower.endswith(".css") else "image"
|
|
161
|
-
for page in owner.pages:
|
|
162
|
-
child = self.resource(absolute, kind, page, None)
|
|
163
|
-
if child is not None:
|
|
164
|
-
child.sections |= owner.sections
|
|
165
|
-
self.pending_css.append(absolute)
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
class PageParser(HTMLParser):
|
|
170
|
-
def __init__(self, base: str):
|
|
171
|
-
super().__init__(convert_charrefs=True)
|
|
172
|
-
self.base = base
|
|
173
|
-
self.found: list[tuple[str, str, str | None]] = []
|
|
174
|
-
self.sections: list[dict] = []
|
|
175
|
-
self.section_stack: list[dict] = []
|
|
176
|
-
self.heading_for: dict | None = None
|
|
177
|
-
self.title = ""
|
|
178
|
-
self.in_title = False
|
|
179
|
-
self.inline_css = ""
|
|
180
|
-
self.in_style = False
|
|
181
|
-
|
|
182
|
-
def absolute(self, value: str) -> str:
|
|
183
|
-
return urllib.parse.urljoin(self.base, html.unescape(value.strip()))
|
|
184
|
-
|
|
185
|
-
def current_section(self) -> str | None:
|
|
186
|
-
return self.section_stack[-1]["id"] if self.section_stack else None
|
|
187
|
-
|
|
188
|
-
def handle_starttag(self, tag, attrs):
|
|
189
|
-
a = dict(attrs)
|
|
190
|
-
section = self.current_section()
|
|
191
|
-
if tag == "title":
|
|
192
|
-
self.in_title = True
|
|
193
|
-
if tag == "style":
|
|
194
|
-
self.in_style = True
|
|
195
|
-
if tag == "div" and (a.get("id") or "").startswith("shopify-section-"):
|
|
196
|
-
entry = {"id": a["id"], "order": len(self.sections) + 1, "heading": "", "resources": []}
|
|
197
|
-
self.sections.append(entry)
|
|
198
|
-
self.section_stack.append({"id": a["id"], "depth": 1})
|
|
199
|
-
elif self.section_stack and tag == "div":
|
|
200
|
-
self.section_stack[-1]["depth"] += 1
|
|
201
|
-
if tag in ("h1", "h2", "h3") and section and not any(s["id"] == section and s["heading"] for s in self.sections):
|
|
202
|
-
self.heading_for = next(s for s in self.sections if s["id"] == section)
|
|
203
|
-
if tag == "link" and a.get("href"):
|
|
204
|
-
rel = (a.get("rel") or "").lower()
|
|
205
|
-
if "stylesheet" in rel:
|
|
206
|
-
self.found.append((self.absolute(a["href"]), "css", section))
|
|
207
|
-
elif any(r in rel for r in ("icon", "preload", "modulepreload")):
|
|
208
|
-
kind = "font" if (a.get("as") == "font") else "svg" if a["href"].lower().endswith(".svg") else "image" if "icon" in rel else "js"
|
|
209
|
-
self.found.append((self.absolute(a["href"]), kind, section))
|
|
210
|
-
if tag == "script" and a.get("src"):
|
|
211
|
-
self.found.append((self.absolute(a["src"]), "js", section))
|
|
212
|
-
if tag in ("img", "source", "video", "audio"):
|
|
213
|
-
for key in ("src", "poster", "data-src", "data-srcset"):
|
|
214
|
-
if a.get(key):
|
|
215
|
-
self.found.append((self.absolute(a[key]), "image", section))
|
|
216
|
-
for key in ("srcset", "data-srcset"):
|
|
217
|
-
if a.get(key):
|
|
218
|
-
for candidate in a[key].split(","):
|
|
219
|
-
url = candidate.strip().split(" ")[0]
|
|
220
|
-
if url:
|
|
221
|
-
self.found.append((self.absolute(url), "image", section))
|
|
222
|
-
if tag == "meta" and a.get("property") in ("og:image", "og:image:secure_url", "og:video"):
|
|
223
|
-
self.found.append((self.absolute(a.get("content", "")), "image", section))
|
|
224
|
-
if tag == "video" and a.get("poster"):
|
|
225
|
-
self.found.append((self.absolute(a["poster"]), "image", section))
|
|
226
|
-
if a.get("style") and "url(" in a["style"]:
|
|
227
|
-
for match in CSS_URL.finditer(a["style"]):
|
|
228
|
-
self.found.append((self.absolute(match.group(2)), "image", section))
|
|
229
|
-
if tag == "a" and a.get("href") and a["href"].lower().endswith(".pdf"):
|
|
230
|
-
self.found.append((self.absolute(a["href"]), "image", section))
|
|
231
|
-
|
|
232
|
-
def handle_endtag(self, tag):
|
|
233
|
-
if tag == "title":
|
|
234
|
-
self.in_title = False
|
|
235
|
-
if tag == "style":
|
|
236
|
-
self.in_style = False
|
|
237
|
-
if tag == "div" and self.section_stack:
|
|
238
|
-
self.section_stack[-1]["depth"] -= 1
|
|
239
|
-
if self.section_stack[-1]["depth"] <= 0:
|
|
240
|
-
self.section_stack.pop()
|
|
241
|
-
if tag in ("h1", "h2", "h3"):
|
|
242
|
-
self.heading_for = None
|
|
243
|
-
|
|
244
|
-
def handle_data(self, data):
|
|
245
|
-
if self.in_title:
|
|
246
|
-
self.title += data
|
|
247
|
-
if self.in_style:
|
|
248
|
-
self.inline_css += data
|
|
249
|
-
if self.heading_for is not None and data.strip() and not self.heading_for["heading"]:
|
|
250
|
-
self.heading_for["heading"] = " ".join(data.split())
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
def slug_for(url: str) -> str:
|
|
254
|
-
path = urllib.parse.urlsplit(url).path.strip("/") or "home"
|
|
255
|
-
return re.sub(r"[^A-Za-z0-9]+", "-", path).strip("-").lower() or "home"
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
def main() -> int:
|
|
259
|
-
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
260
|
-
parser.add_argument("urls", nargs="+", help="public storefront page URLs; the first should be the homepage")
|
|
261
|
-
parser.add_argument("--out", default="./store-assets", help="output folder")
|
|
262
|
-
parser.add_argument("--zip", action="store_true", help="also write OUT.zip")
|
|
263
|
-
args = parser.parse_args()
|
|
264
|
-
|
|
265
|
-
out = Path(args.out).resolve()
|
|
266
|
-
if out.exists():
|
|
267
|
-
shutil.rmtree(out)
|
|
268
|
-
(out / "pages").mkdir(parents=True)
|
|
269
|
-
collector = Collector(out)
|
|
270
|
-
pages = []
|
|
271
|
-
section_ids: dict[str, list[str]] = {}
|
|
272
|
-
|
|
273
|
-
for url in args.urls:
|
|
274
|
-
slug = slug_for(url)
|
|
275
|
-
page_dir = out / "pages" / slug
|
|
276
|
-
page_dir.mkdir(parents=True, exist_ok=True)
|
|
277
|
-
entry = {"url": url, "slug": slug, "final_url": url, "title": "", "status": "pending", "sections": [], "navigation": []}
|
|
278
|
-
if not collector.allowed(url):
|
|
279
|
-
entry["status"] = "disallowed by robots.txt"
|
|
280
|
-
collector.failures.append({"url": url, "reason": entry["status"]})
|
|
281
|
-
pages.append(entry)
|
|
282
|
-
continue
|
|
283
|
-
try:
|
|
284
|
-
data, content_type = collector.get(url)
|
|
285
|
-
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
|
|
286
|
-
entry["status"] = f"failed: {error}"
|
|
287
|
-
collector.failures.append({"url": url, "reason": str(error)})
|
|
288
|
-
pages.append(entry)
|
|
289
|
-
continue
|
|
290
|
-
text = data.decode("utf-8", "replace")
|
|
291
|
-
entry["status"] = "downloaded"
|
|
292
|
-
entry["final_url"] = url
|
|
293
|
-
(page_dir / "source.html").write_text(text, encoding="utf-8")
|
|
294
|
-
|
|
295
|
-
page = PageParser(url)
|
|
296
|
-
page.feed(text)
|
|
297
|
-
entry["title"] = " ".join(page.title.split())
|
|
298
|
-
entry["sections"] = [{"order": s["order"], "id": s["id"], "heading": s["heading"], "resources": []} for s in page.sections]
|
|
299
|
-
section_ids[slug] = [s["id"] for s in page.sections]
|
|
300
|
-
entry["navigation"] = sorted({urllib.parse.urljoin(url, h) for h in re.findall(r'href="([^"#]+)"', text) if h.startswith("/")})[:200]
|
|
301
|
-
|
|
302
|
-
for ref, kind, section in page.found:
|
|
303
|
-
resource = collector.resource(ref, kind, slug, section)
|
|
304
|
-
if resource is not None:
|
|
305
|
-
collector.fetch_resource(resource)
|
|
306
|
-
for match in CSS_URL.finditer(page.inline_css):
|
|
307
|
-
resource = collector.resource(urllib.parse.urljoin(url, match.group(2)), "image", slug, None)
|
|
308
|
-
if resource is not None:
|
|
309
|
-
collector.fetch_resource(resource)
|
|
310
|
-
|
|
311
|
-
pages.append(entry)
|
|
312
|
-
|
|
313
|
-
while collector.pending_css:
|
|
314
|
-
css_url = collector.pending_css.pop()
|
|
315
|
-
resource = collector.resources.get(css_url)
|
|
316
|
-
if resource is None:
|
|
317
|
-
resource = collector.resource(css_url, "css", "shared", None)
|
|
318
|
-
if resource is not None:
|
|
319
|
-
collector.fetch_resource(resource)
|
|
320
|
-
|
|
321
|
-
for resource in collector.resources.values():
|
|
322
|
-
if resource.status == "pending":
|
|
323
|
-
collector.fetch_resource(resource)
|
|
324
|
-
|
|
325
|
-
for entry in pages:
|
|
326
|
-
for section in entry["sections"]:
|
|
327
|
-
section["resources"] = sorted(r.url for r in collector.resources.values() if entry["slug"] in r.pages and section["id"] in r.sections)
|
|
328
|
-
|
|
329
|
-
resources = [
|
|
330
|
-
{
|
|
331
|
-
"url": r.url,
|
|
332
|
-
"kind": r.kind,
|
|
333
|
-
"file": r.file,
|
|
334
|
-
"bytes": r.bytes,
|
|
335
|
-
"status": r.status,
|
|
336
|
-
"pages": sorted(r.pages),
|
|
337
|
-
"sections": sorted(r.sections),
|
|
338
|
-
}
|
|
339
|
-
for r in sorted(collector.resources.values(), key=lambda x: (x.kind, x.url))
|
|
340
|
-
]
|
|
341
|
-
counts: dict[str, int] = {}
|
|
342
|
-
for r in resources:
|
|
343
|
-
if r["status"] == "downloaded":
|
|
344
|
-
counts[r["kind"]] = counts.get(r["kind"], 0) + 1
|
|
345
|
-
|
|
346
|
-
manifest = {
|
|
347
|
-
"collected_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
348
|
-
"client": USER_AGENT,
|
|
349
|
-
"pages": pages,
|
|
350
|
-
"homepage_sections": pages[0]["sections"] if pages else [],
|
|
351
|
-
"resources": resources,
|
|
352
|
-
"downloaded_by_kind": counts,
|
|
353
|
-
"failures": collector.failures,
|
|
354
|
-
}
|
|
355
|
-
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
356
|
-
(out / "README.txt").write_text(
|
|
357
|
-
"Public storefront reference collected for measuring a design.\n"
|
|
358
|
-
"manifest.json lists every page, section and resource; pages/<slug>/source.html is each page's HTML.\n"
|
|
359
|
-
"Do not ship these files in a theme. Measure from them, and write the theme's own code and tokens.\n",
|
|
360
|
-
encoding="utf-8",
|
|
361
|
-
)
|
|
362
|
-
print(json.dumps({"out": str(out), "pages": len(pages), "resources": counts, "failures": len(collector.failures)}, indent=2))
|
|
363
|
-
if args.zip:
|
|
364
|
-
archive = shutil.make_archive(str(out), "zip", root_dir=out.parent, base_dir=out.name)
|
|
365
|
-
print(f"archive: {archive}")
|
|
366
|
-
return 0
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
if __name__ == "__main__":
|
|
370
|
-
sys.exit(main())
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Collect the public frontend of Shopify storefront pages into one folder.
|
|
3
|
+
|
|
4
|
+
For each page URL: the HTML source, the stylesheets, scripts, images, fonts and
|
|
5
|
+
SVGs the page and its stylesheets reference, and which homepage section uses
|
|
6
|
+
each of them. Every file is stored once, under assets/, and the manifest lists
|
|
7
|
+
the pages that use it. Standard library only (Python 3.9+).
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
python3 collect_public_assets.py https://store.myshopify.com/ \\
|
|
11
|
+
https://store.myshopify.com/collections/all --out ./store-assets --zip
|
|
12
|
+
|
|
13
|
+
Only URLs the page itself references are downloaded, and robots.txt is obeyed:
|
|
14
|
+
a path it disallows for this client is skipped and reported. The output is a
|
|
15
|
+
reference for measuring a design. It is not theme code and not a licence to
|
|
16
|
+
ship the store's files; see the skill's rights rules.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import hashlib
|
|
23
|
+
import html
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import shutil
|
|
28
|
+
import ssl
|
|
29
|
+
import sys
|
|
30
|
+
import time
|
|
31
|
+
import urllib.error
|
|
32
|
+
import urllib.parse
|
|
33
|
+
import urllib.request
|
|
34
|
+
import urllib.robotparser
|
|
35
|
+
from dataclasses import dataclass, field
|
|
36
|
+
from html.parser import HTMLParser
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
|
|
39
|
+
USER_AGENT = "abcart-asset-collector/1.0 (design reference; the developer owns the rights to use it)"
|
|
40
|
+
MAX_BYTES = 30 * 1024 * 1024
|
|
41
|
+
TIMEOUT = 30
|
|
42
|
+
DELAY = 0.2
|
|
43
|
+
MAX_RESOURCES = 2000
|
|
44
|
+
|
|
45
|
+
def tls_context() -> ssl.SSLContext:
|
|
46
|
+
"""Verified TLS: certifi's bundle, else the system bundle. Verification is never turned off."""
|
|
47
|
+
try:
|
|
48
|
+
import certifi
|
|
49
|
+
|
|
50
|
+
return ssl.create_default_context(cafile=certifi.where())
|
|
51
|
+
except ImportError:
|
|
52
|
+
pass
|
|
53
|
+
for bundle in ("/etc/ssl/cert.pem", "/etc/ssl/certs/ca-certificates.crt"):
|
|
54
|
+
if os.path.exists(bundle):
|
|
55
|
+
return ssl.create_default_context(cafile=bundle)
|
|
56
|
+
return ssl.create_default_context()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
TLS = tls_context()
|
|
60
|
+
|
|
61
|
+
CSS_URL = re.compile(r"url\(\s*(['\"]?)([^'\")]+)\1\s*\)")
|
|
62
|
+
CSS_IMPORT = re.compile(r"@import\s+(?:url\()?\s*['\"]?([^'\")\s;]+)")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class Resource:
|
|
67
|
+
url: str
|
|
68
|
+
kind: str
|
|
69
|
+
file: str | None = None
|
|
70
|
+
bytes: int = 0
|
|
71
|
+
status: str = "pending"
|
|
72
|
+
pages: set = field(default_factory=set)
|
|
73
|
+
sections: set = field(default_factory=set)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Collector:
|
|
77
|
+
def __init__(self, out: Path):
|
|
78
|
+
self.out = out
|
|
79
|
+
self.resources: dict[str, Resource] = {}
|
|
80
|
+
self.failures: list[dict] = []
|
|
81
|
+
self.robots: dict[str, urllib.robotparser.RobotFileParser | None] = {}
|
|
82
|
+
self.pending_css: list[str] = []
|
|
83
|
+
self.last = 0.0
|
|
84
|
+
|
|
85
|
+
def allowed(self, url: str) -> bool:
|
|
86
|
+
parts = urllib.parse.urlsplit(url)
|
|
87
|
+
origin = f"{parts.scheme}://{parts.netloc}"
|
|
88
|
+
if origin not in self.robots:
|
|
89
|
+
parser = urllib.robotparser.RobotFileParser()
|
|
90
|
+
try:
|
|
91
|
+
request = urllib.request.Request(origin + "/robots.txt", headers={"User-Agent": USER_AGENT})
|
|
92
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT, context=TLS) as response:
|
|
93
|
+
parser.parse(response.read().decode("utf-8", "replace").splitlines())
|
|
94
|
+
self.robots[origin] = parser
|
|
95
|
+
except (urllib.error.URLError, TimeoutError, OSError):
|
|
96
|
+
self.robots[origin] = None
|
|
97
|
+
parser = self.robots[origin]
|
|
98
|
+
return parser is None or parser.can_fetch(USER_AGENT, url)
|
|
99
|
+
|
|
100
|
+
def get(self, url: str) -> tuple[bytes, str]:
|
|
101
|
+
wait = DELAY - (time.time() - self.last)
|
|
102
|
+
if wait > 0:
|
|
103
|
+
time.sleep(wait)
|
|
104
|
+
self.last = time.time()
|
|
105
|
+
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "text/html,application/xhtml+xml,text/css,application/javascript,image/*,font/*;q=0.9,*/*;q=0.5"})
|
|
106
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT, context=TLS) as response:
|
|
107
|
+
content_type = response.headers.get("Content-Type", "")
|
|
108
|
+
data = response.read(MAX_BYTES + 1)
|
|
109
|
+
if len(data) > MAX_BYTES:
|
|
110
|
+
raise ValueError("larger than the collector's limit")
|
|
111
|
+
return data, content_type
|
|
112
|
+
|
|
113
|
+
def resource(self, url: str, kind: str, page_slug: str, section: str | None) -> Resource | None:
|
|
114
|
+
if not url or url.startswith(("data:", "blob:", "javascript:", "#")):
|
|
115
|
+
return None
|
|
116
|
+
if len(self.resources) >= MAX_RESOURCES and url not in self.resources:
|
|
117
|
+
return None
|
|
118
|
+
item = self.resources.get(url)
|
|
119
|
+
if item is None:
|
|
120
|
+
item = Resource(url=url, kind=kind)
|
|
121
|
+
self.resources[url] = item
|
|
122
|
+
item.pages.add(page_slug)
|
|
123
|
+
if section:
|
|
124
|
+
item.sections.add(section)
|
|
125
|
+
return item
|
|
126
|
+
|
|
127
|
+
def fetch_resource(self, item: Resource) -> None:
|
|
128
|
+
if item.file is not None or item.status not in ("pending",):
|
|
129
|
+
return
|
|
130
|
+
if not self.allowed(item.url):
|
|
131
|
+
item.status = "disallowed by robots.txt"
|
|
132
|
+
self.failures.append({"url": item.url, "reason": item.status})
|
|
133
|
+
return
|
|
134
|
+
digest = hashlib.sha1(item.url.encode()).hexdigest()[:10]
|
|
135
|
+
name = Path(urllib.parse.urlsplit(item.url).path).name or "file"
|
|
136
|
+
name = re.sub(r"[^A-Za-z0-9._-]", "_", name)[:80]
|
|
137
|
+
subfolder = {"css": "css", "js": "js", "font": "fonts", "svg": "svg"}.get(item.kind, "images")
|
|
138
|
+
target = self.out / "assets" / subfolder / f"{digest}-{name}"
|
|
139
|
+
try:
|
|
140
|
+
data, _ = self.get(item.url)
|
|
141
|
+
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
|
|
142
|
+
item.status = f"failed: {error}"
|
|
143
|
+
self.failures.append({"url": item.url, "reason": str(error)})
|
|
144
|
+
return
|
|
145
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
146
|
+
target.write_bytes(data)
|
|
147
|
+
item.file = str(target.relative_to(self.out))
|
|
148
|
+
item.bytes = len(data)
|
|
149
|
+
item.status = "downloaded"
|
|
150
|
+
if item.kind == "css":
|
|
151
|
+
text = data.decode("utf-8", "replace")
|
|
152
|
+
for match in CSS_URL.finditer(text):
|
|
153
|
+
self.queue_css_reference(match.group(2), item.url, item)
|
|
154
|
+
for match in CSS_IMPORT.finditer(text):
|
|
155
|
+
self.queue_css_reference(match.group(1), item.url, item)
|
|
156
|
+
|
|
157
|
+
def queue_css_reference(self, raw: str, base: str, owner: Resource) -> None:
|
|
158
|
+
absolute = urllib.parse.urljoin(base, html.unescape(raw.strip()))
|
|
159
|
+
lower = absolute.lower().split("?")[0]
|
|
160
|
+
kind = "font" if lower.endswith((".woff2", ".woff", ".ttf", ".otf")) else "svg" if lower.endswith(".svg") else "css" if lower.endswith(".css") else "image"
|
|
161
|
+
for page in owner.pages:
|
|
162
|
+
child = self.resource(absolute, kind, page, None)
|
|
163
|
+
if child is not None:
|
|
164
|
+
child.sections |= owner.sections
|
|
165
|
+
self.pending_css.append(absolute)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class PageParser(HTMLParser):
|
|
170
|
+
def __init__(self, base: str):
|
|
171
|
+
super().__init__(convert_charrefs=True)
|
|
172
|
+
self.base = base
|
|
173
|
+
self.found: list[tuple[str, str, str | None]] = []
|
|
174
|
+
self.sections: list[dict] = []
|
|
175
|
+
self.section_stack: list[dict] = []
|
|
176
|
+
self.heading_for: dict | None = None
|
|
177
|
+
self.title = ""
|
|
178
|
+
self.in_title = False
|
|
179
|
+
self.inline_css = ""
|
|
180
|
+
self.in_style = False
|
|
181
|
+
|
|
182
|
+
def absolute(self, value: str) -> str:
|
|
183
|
+
return urllib.parse.urljoin(self.base, html.unescape(value.strip()))
|
|
184
|
+
|
|
185
|
+
def current_section(self) -> str | None:
|
|
186
|
+
return self.section_stack[-1]["id"] if self.section_stack else None
|
|
187
|
+
|
|
188
|
+
def handle_starttag(self, tag, attrs):
|
|
189
|
+
a = dict(attrs)
|
|
190
|
+
section = self.current_section()
|
|
191
|
+
if tag == "title":
|
|
192
|
+
self.in_title = True
|
|
193
|
+
if tag == "style":
|
|
194
|
+
self.in_style = True
|
|
195
|
+
if tag == "div" and (a.get("id") or "").startswith("shopify-section-"):
|
|
196
|
+
entry = {"id": a["id"], "order": len(self.sections) + 1, "heading": "", "resources": []}
|
|
197
|
+
self.sections.append(entry)
|
|
198
|
+
self.section_stack.append({"id": a["id"], "depth": 1})
|
|
199
|
+
elif self.section_stack and tag == "div":
|
|
200
|
+
self.section_stack[-1]["depth"] += 1
|
|
201
|
+
if tag in ("h1", "h2", "h3") and section and not any(s["id"] == section and s["heading"] for s in self.sections):
|
|
202
|
+
self.heading_for = next(s for s in self.sections if s["id"] == section)
|
|
203
|
+
if tag == "link" and a.get("href"):
|
|
204
|
+
rel = (a.get("rel") or "").lower()
|
|
205
|
+
if "stylesheet" in rel:
|
|
206
|
+
self.found.append((self.absolute(a["href"]), "css", section))
|
|
207
|
+
elif any(r in rel for r in ("icon", "preload", "modulepreload")):
|
|
208
|
+
kind = "font" if (a.get("as") == "font") else "svg" if a["href"].lower().endswith(".svg") else "image" if "icon" in rel else "js"
|
|
209
|
+
self.found.append((self.absolute(a["href"]), kind, section))
|
|
210
|
+
if tag == "script" and a.get("src"):
|
|
211
|
+
self.found.append((self.absolute(a["src"]), "js", section))
|
|
212
|
+
if tag in ("img", "source", "video", "audio"):
|
|
213
|
+
for key in ("src", "poster", "data-src", "data-srcset"):
|
|
214
|
+
if a.get(key):
|
|
215
|
+
self.found.append((self.absolute(a[key]), "image", section))
|
|
216
|
+
for key in ("srcset", "data-srcset"):
|
|
217
|
+
if a.get(key):
|
|
218
|
+
for candidate in a[key].split(","):
|
|
219
|
+
url = candidate.strip().split(" ")[0]
|
|
220
|
+
if url:
|
|
221
|
+
self.found.append((self.absolute(url), "image", section))
|
|
222
|
+
if tag == "meta" and a.get("property") in ("og:image", "og:image:secure_url", "og:video"):
|
|
223
|
+
self.found.append((self.absolute(a.get("content", "")), "image", section))
|
|
224
|
+
if tag == "video" and a.get("poster"):
|
|
225
|
+
self.found.append((self.absolute(a["poster"]), "image", section))
|
|
226
|
+
if a.get("style") and "url(" in a["style"]:
|
|
227
|
+
for match in CSS_URL.finditer(a["style"]):
|
|
228
|
+
self.found.append((self.absolute(match.group(2)), "image", section))
|
|
229
|
+
if tag == "a" and a.get("href") and a["href"].lower().endswith(".pdf"):
|
|
230
|
+
self.found.append((self.absolute(a["href"]), "image", section))
|
|
231
|
+
|
|
232
|
+
def handle_endtag(self, tag):
|
|
233
|
+
if tag == "title":
|
|
234
|
+
self.in_title = False
|
|
235
|
+
if tag == "style":
|
|
236
|
+
self.in_style = False
|
|
237
|
+
if tag == "div" and self.section_stack:
|
|
238
|
+
self.section_stack[-1]["depth"] -= 1
|
|
239
|
+
if self.section_stack[-1]["depth"] <= 0:
|
|
240
|
+
self.section_stack.pop()
|
|
241
|
+
if tag in ("h1", "h2", "h3"):
|
|
242
|
+
self.heading_for = None
|
|
243
|
+
|
|
244
|
+
def handle_data(self, data):
|
|
245
|
+
if self.in_title:
|
|
246
|
+
self.title += data
|
|
247
|
+
if self.in_style:
|
|
248
|
+
self.inline_css += data
|
|
249
|
+
if self.heading_for is not None and data.strip() and not self.heading_for["heading"]:
|
|
250
|
+
self.heading_for["heading"] = " ".join(data.split())
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def slug_for(url: str) -> str:
|
|
254
|
+
path = urllib.parse.urlsplit(url).path.strip("/") or "home"
|
|
255
|
+
return re.sub(r"[^A-Za-z0-9]+", "-", path).strip("-").lower() or "home"
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def main() -> int:
|
|
259
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
260
|
+
parser.add_argument("urls", nargs="+", help="public storefront page URLs; the first should be the homepage")
|
|
261
|
+
parser.add_argument("--out", default="./store-assets", help="output folder")
|
|
262
|
+
parser.add_argument("--zip", action="store_true", help="also write OUT.zip")
|
|
263
|
+
args = parser.parse_args()
|
|
264
|
+
|
|
265
|
+
out = Path(args.out).resolve()
|
|
266
|
+
if out.exists():
|
|
267
|
+
shutil.rmtree(out)
|
|
268
|
+
(out / "pages").mkdir(parents=True)
|
|
269
|
+
collector = Collector(out)
|
|
270
|
+
pages = []
|
|
271
|
+
section_ids: dict[str, list[str]] = {}
|
|
272
|
+
|
|
273
|
+
for url in args.urls:
|
|
274
|
+
slug = slug_for(url)
|
|
275
|
+
page_dir = out / "pages" / slug
|
|
276
|
+
page_dir.mkdir(parents=True, exist_ok=True)
|
|
277
|
+
entry = {"url": url, "slug": slug, "final_url": url, "title": "", "status": "pending", "sections": [], "navigation": []}
|
|
278
|
+
if not collector.allowed(url):
|
|
279
|
+
entry["status"] = "disallowed by robots.txt"
|
|
280
|
+
collector.failures.append({"url": url, "reason": entry["status"]})
|
|
281
|
+
pages.append(entry)
|
|
282
|
+
continue
|
|
283
|
+
try:
|
|
284
|
+
data, content_type = collector.get(url)
|
|
285
|
+
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
|
|
286
|
+
entry["status"] = f"failed: {error}"
|
|
287
|
+
collector.failures.append({"url": url, "reason": str(error)})
|
|
288
|
+
pages.append(entry)
|
|
289
|
+
continue
|
|
290
|
+
text = data.decode("utf-8", "replace")
|
|
291
|
+
entry["status"] = "downloaded"
|
|
292
|
+
entry["final_url"] = url
|
|
293
|
+
(page_dir / "source.html").write_text(text, encoding="utf-8")
|
|
294
|
+
|
|
295
|
+
page = PageParser(url)
|
|
296
|
+
page.feed(text)
|
|
297
|
+
entry["title"] = " ".join(page.title.split())
|
|
298
|
+
entry["sections"] = [{"order": s["order"], "id": s["id"], "heading": s["heading"], "resources": []} for s in page.sections]
|
|
299
|
+
section_ids[slug] = [s["id"] for s in page.sections]
|
|
300
|
+
entry["navigation"] = sorted({urllib.parse.urljoin(url, h) for h in re.findall(r'href="([^"#]+)"', text) if h.startswith("/")})[:200]
|
|
301
|
+
|
|
302
|
+
for ref, kind, section in page.found:
|
|
303
|
+
resource = collector.resource(ref, kind, slug, section)
|
|
304
|
+
if resource is not None:
|
|
305
|
+
collector.fetch_resource(resource)
|
|
306
|
+
for match in CSS_URL.finditer(page.inline_css):
|
|
307
|
+
resource = collector.resource(urllib.parse.urljoin(url, match.group(2)), "image", slug, None)
|
|
308
|
+
if resource is not None:
|
|
309
|
+
collector.fetch_resource(resource)
|
|
310
|
+
|
|
311
|
+
pages.append(entry)
|
|
312
|
+
|
|
313
|
+
while collector.pending_css:
|
|
314
|
+
css_url = collector.pending_css.pop()
|
|
315
|
+
resource = collector.resources.get(css_url)
|
|
316
|
+
if resource is None:
|
|
317
|
+
resource = collector.resource(css_url, "css", "shared", None)
|
|
318
|
+
if resource is not None:
|
|
319
|
+
collector.fetch_resource(resource)
|
|
320
|
+
|
|
321
|
+
for resource in collector.resources.values():
|
|
322
|
+
if resource.status == "pending":
|
|
323
|
+
collector.fetch_resource(resource)
|
|
324
|
+
|
|
325
|
+
for entry in pages:
|
|
326
|
+
for section in entry["sections"]:
|
|
327
|
+
section["resources"] = sorted(r.url for r in collector.resources.values() if entry["slug"] in r.pages and section["id"] in r.sections)
|
|
328
|
+
|
|
329
|
+
resources = [
|
|
330
|
+
{
|
|
331
|
+
"url": r.url,
|
|
332
|
+
"kind": r.kind,
|
|
333
|
+
"file": r.file,
|
|
334
|
+
"bytes": r.bytes,
|
|
335
|
+
"status": r.status,
|
|
336
|
+
"pages": sorted(r.pages),
|
|
337
|
+
"sections": sorted(r.sections),
|
|
338
|
+
}
|
|
339
|
+
for r in sorted(collector.resources.values(), key=lambda x: (x.kind, x.url))
|
|
340
|
+
]
|
|
341
|
+
counts: dict[str, int] = {}
|
|
342
|
+
for r in resources:
|
|
343
|
+
if r["status"] == "downloaded":
|
|
344
|
+
counts[r["kind"]] = counts.get(r["kind"], 0) + 1
|
|
345
|
+
|
|
346
|
+
manifest = {
|
|
347
|
+
"collected_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
348
|
+
"client": USER_AGENT,
|
|
349
|
+
"pages": pages,
|
|
350
|
+
"homepage_sections": pages[0]["sections"] if pages else [],
|
|
351
|
+
"resources": resources,
|
|
352
|
+
"downloaded_by_kind": counts,
|
|
353
|
+
"failures": collector.failures,
|
|
354
|
+
}
|
|
355
|
+
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
356
|
+
(out / "README.txt").write_text(
|
|
357
|
+
"Public storefront reference collected for measuring a design.\n"
|
|
358
|
+
"manifest.json lists every page, section and resource; pages/<slug>/source.html is each page's HTML.\n"
|
|
359
|
+
"Do not ship these files in a theme. Measure from them, and write the theme's own code and tokens.\n",
|
|
360
|
+
encoding="utf-8",
|
|
361
|
+
)
|
|
362
|
+
print(json.dumps({"out": str(out), "pages": len(pages), "resources": counts, "failures": len(collector.failures)}, indent=2))
|
|
363
|
+
if args.zip:
|
|
364
|
+
archive = shutil.make_archive(str(out), "zip", root_dir=out.parent, base_dir=out.name)
|
|
365
|
+
print(f"archive: {archive}")
|
|
366
|
+
return 0
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
if __name__ == "__main__":
|
|
370
|
+
sys.exit(main())
|