Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
push:
branches: [master]
pull_request:
workflow_dispatch:

# The jobs only read the repository; nothing here needs to write.
permissions:
Expand Down
4 changes: 3 additions & 1 deletion backend/src/handler.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
// POST /api/subscribe -> email signup into the Square customer directory (subscribe.mjs)
// GET /p/<item id> -> the page for one piece, in the site's own shell (piece.mjs)
// GET /p/sitemap.xml -> every piece's address, for search engines (piece.mjs)
// GET /p/feed.xml -> Atom feed of available pieces, for RSS and Pinterest (piece.mjs)
// Each function serves only the routes in ROUTES (the template gives checkout its own function).
import { SquareError } from "square";
import { respond, clientIp } from "./http.mjs";
import { loadCatalog } from "./catalog.mjs";
import { quote, checkout, declineMessage } from "./checkout.mjs";
import { subscribe, _resetLimits as resetSubscribeLimits } from "./subscribe.mjs";
import { _resetSales } from "./stock.mjs";
import { piece, sitemap } from "./piece.mjs";
import { piece, sitemap, feed } from "./piece.mjs";

const routes = new Set((process.env.ROUTES ?? "catalog,quote,subscribe,checkout,piece").split(",").map((r) => r.trim()));
const posts = { "/api/quote": quote, "/api/checkout": checkout, "/api/subscribe": subscribe };
Expand Down Expand Up @@ -40,6 +41,7 @@ export async function handler(event) {
// Square ids are plain letters and digits: the path is passed on as sent (piece() checks it), never
// decoded, since a malformed escape like /p/%E0 would throw and be answered as an unhandled error.
if (method === "GET" && routes.has("piece") && path === "/p/sitemap.xml") return await sitemap();
if (method === "GET" && routes.has("piece") && path === "/p/feed.xml") return await feed();
if (method === "GET" && routes.has("piece") && path?.startsWith("/p/")) return await piece(path.slice(3));
if (method === "POST" && posts[path]) {
const body = readBody(event);
Expand Down
1 change: 1 addition & 0 deletions backend/src/http.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const respond = (status, body, extra = {}) => ({
headers: {
"cache-control": "no-store",
"content-type": "application/json",
"x-robots-tag": "noindex",
"access-control-allow-origin": ALLOWED_ORIGIN,
"access-control-allow-headers": "content-type, x-amz-content-sha256",
"access-control-allow-methods": "GET,POST,OPTIONS",
Expand Down
84 changes: 82 additions & 2 deletions backend/src/piece-page.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,52 @@ function picture(url, { alt, sizes, widths, eager }) {
);
}

/** OfferShippingDetails for one parcel of billed weight shipLb (WA state + US ceiling), or null when unpriced. */
const FRACTIONS = { "¼": 0.25, "½": 0.5, "¾": 0.75, "⅛": 0.125, "⅜": 0.375, "⅝": 0.625, "⅞": 0.875 };
const toInches = (whole, dec, frac) => (dec ? Number(`${whole}.${dec}`) : Number(whole) + (FRACTIONS[frac] ?? 0));
const qvIn = (n) => ({ "@type": "QuantitativeValue", value: +n.toFixed(3), unitCode: "INH" });

/** Parses dimensions (e.g. "9½″ × 3¾″" or "5½″ wide × 3″ tall") from a piece's spec line, in inches. */
export function parseDimensions(item) {
const spec = specLine(item.description);
if (!spec) return {};
for (const raw of spec.split("·")) {
const seg = raw.trim();
if (!seg || seg.length > 60 || /,|\band\b|\bset\b/i.test(seg)) continue;
const pair = seg.match(
/^(\d{1,2})(?:\.(\d{1,2})|([¼½¾⅛⅜⅝⅞]))?\s*[″"]\s*(wide|across|tall|high)?\s*[×x]\s*(\d{1,2})(?:\.(\d{1,2})|([¼½¾⅛⅜⅝⅞]))?\s*[″"]\s*(wide|across|tall|high)?$/i,
);
if (pair) {
const a = toInches(pair[1], pair[2], pair[3]);
const la = (pair[4] ?? "").toLowerCase();
const b = toInches(pair[5], pair[6], pair[7]);
const lb = (pair[8] ?? "").toLowerCase();
if (!(a > 0 && b > 0)) return {};
const tallFirst =
la === "tall" ||
la === "high" ||
lb === "wide" ||
lb === "across" ||
(!la && !lb && (item.category === "Vases" || /\b(vase|bottle|pitcher|ewer|cylinder|tower)\b/i.test(item.name ?? "")));
return tallFirst ? { height: a, width: b } : { width: a, height: b };
}
const single = seg.match(/^(\d{1,2})(?:\.(\d{1,2})|([¼½¾⅛⅜⅝⅞]))?\s*[″"]\s*(wide|across)$/i);
if (single) {
const w = toInches(single[1], single[2], single[3]);
return w > 0 ? { width: w } : {};
}
}
return {};
}

/** OfferShippingDetails for one parcel (WA Zone 3 + US Zone 8 ceiling), or doesNotShip when pickup-only. */
function shippingDetailsFor(shipLb) {
if (!(shipLb > 0)) return null;
if (!(shipLb > 0)) {
return {
"@type": "OfferShippingDetails",
doesNotShip: true,
shippingDestination: { "@type": "DefinedRegion", addressCountry: "US" },
};
}
const maxForZone = (zone) => {
const ups = labelDollars("ups", zone, shipLb);
if (ups === null) return null;
Expand Down Expand Up @@ -119,6 +162,7 @@ function shippingDetailsFor(shipLb) {
export function structuredData(item, site) {
const url = `${site}/p/${item.id}`;
const many = item.variations.length > 1;
const dims = parseDimensions(item);
const delivery =
item.shipLb > 0 ? ["https://schema.org/OnSitePickup", "https://schema.org/ParcelService"] : ["https://schema.org/OnSitePickup"];
const shippingDetails = shippingDetailsFor(item.shipLb);
Expand All @@ -142,6 +186,8 @@ export function structuredData(item, site) {
...(item.category ? { category: item.category } : {}),
material: materialOf(item),
countryOfOrigin: "US",
...(dims.width ? { width: qvIn(dims.width) } : {}),
...(dims.height ? { height: qvIn(dims.height) } : {}),
...(item.shipLb > 0 ? { weight: { "@type": "QuantitativeValue", value: item.shipLb, unitCode: "LBR" } } : {}),
creator: { "@type": "Person", "@id": `${site}/about.html#aaron`, name: "Aaron Filson" },
brand: { "@type": "Brand", name: SITE_NAME },
Expand Down Expand Up @@ -303,3 +349,37 @@ export function piecesSitemap(items, site) {
`${urls.join("\n")}\n</urlset>\n`
);
}

/** Atom 1.0 feed of pieces currently available in the shop (/p/feed.xml), for RSS readers and Pinterest. */
export function piecesFeed(items, site) {
const open = items.filter((i) => i.variations.some(isOpen));
const dates = open.filter((i) => i.updatedAt).map((i) => i.updatedAt);
const updated = dates.sort().at(-1) ?? "2026-01-01T00:00:00Z";
const entries = open.map((i) => {
const url = `${site}/p/${i.id}`;
const photo = photosOf(i)[0];
const enclosure = photo ? `<link rel="enclosure" type="image/jpeg" href="${esc(site + sized(photo, 1200, "jpeg"))}"/>` : "";
return (
` <entry>` +
`<id>${esc(url)}</id>` +
`<title>${esc(`${i.name} · ${priceText(i)}`)}</title>` +
`<link href="${esc(url)}"/>` +
enclosure +
`<updated>${esc(i.updatedAt || updated)}</updated>` +
`<summary>${esc(metaDescription(i))}</summary>` +
`</entry>`
);
});
return (
`<?xml version="1.0" encoding="UTF-8"?>\n` +
`<feed xmlns="http://www.w3.org/2005/Atom">\n` +
` <id>${esc(`${site}/p/feed.xml`)}</id>\n` +
` <title>${esc(`${SITE_NAME} — Available Pieces`)}</title>\n` +
` <link href="${esc(`${site}/shop.html`)}"/>\n` +
` <link href="${esc(`${site}/p/feed.xml`)}" rel="self" type="application/atom+xml"/>\n` +
` <updated>${esc(updated)}</updated>\n` +
` <author><name>Aaron Filson</name></author>\n` +
`${entries.join("\n")}\n` +
`</feed>\n`
);
}
13 changes: 9 additions & 4 deletions backend/src/piece.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
// under /p/ may only list pages under /p/, which is all it needs, and the /p/* route is already here.
import { ALLOWED_ORIGIN } from "./config.mjs";
import { loadCatalog } from "./catalog.mjs";
import { renderPiece, gonePage, piecesSitemap } from "./piece-page.mjs";
import { renderPiece, gonePage, piecesSitemap, piecesFeed } from "./piece-page.mjs";

const site = () => (ALLOWED_ORIGIN === "*" ? "" : ALLOWED_ORIGIN);
const reply = (status, type, body, cache) => ({
const reply = (status, type, body, cache, extra = {}) => ({
statusCode: status,
headers: { "content-type": `${type}; charset=utf-8`, "cache-control": cache },
headers: { "content-type": `${type}; charset=utf-8`, "cache-control": cache, ...extra },
body,
});

Expand Down Expand Up @@ -44,17 +44,22 @@ export async function piece(id) {
const item = items.find((i) => i.id === id);
// 410 Gone, not 404: CloudFront swaps every 403/404 for the site's error page (deploy/site.yaml), and
// someone following an old link should hear that the piece has gone, with a way to the shop.
if (!item) return reply(410, "text/html", gonePage(), "public, max-age=60");
if (!item) return reply(410, "text/html", gonePage(), "public, max-age=60", { "x-robots-tag": "noindex" });
const html = await pageShell();
// Without the shell the page is the plain fallback: kept only briefly.
return reply(
200,
"text/html",
renderPiece({ item, items, shell: html, site: site() }),
html ? "public, max-age=300" : "public, max-age=60",
html ? {} : { "x-robots-tag": "noindex" },
);
}

export async function sitemap() {
return reply(200, "application/xml", piecesSitemap(await loadCatalog(), site()), "public, max-age=300");
}

export async function feed() {
return reply(200, "application/atom+xml", piecesFeed(await loadCatalog(), site()), "public, max-age=300");
}
48 changes: 37 additions & 11 deletions backend/test/shop-pages.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { handler, _setSquare } from "../src/handler.mjs";
import sharp from "sharp";
import { parseRequest, handler as images, _resetCatalog, _catalogWaits } from "../src/images.mjs";
import { _resetShell } from "../src/piece.mjs";
import { renderPiece, structuredData, pieceTitle } from "../src/piece-page.mjs";
import { renderPiece, structuredData, pieceTitle, parseDimensions } from "../src/piece-page.mjs";

const SQUARE_PHOTO = "https://items-images-sandbox.s3.us-west-2.amazonaws.com/files/abc/original.jpeg";

Expand Down Expand Up @@ -148,7 +148,9 @@ const get = (path) => handler({ requestContext: { http: { method: "GET" } }, raw

test("the catalog lists every photo, in order, the piece's type and its shipping weight", async () => {
_setSquare(fakeCatalog());
const { items } = JSON.parse((await get("/api/catalog")).body);
const res = await get("/api/catalog");
assert.equal(res.headers["x-robots-tag"], "noindex");
const { items } = JSON.parse(res.body);
assert.equal(items[0].image, SQUARE_PHOTO);
assert.deepEqual(items[0].images, [SQUARE_PHOTO, SQUARE_PHOTO.replace("abc", "def")]);
assert.equal(items[0].category, "Bowls");
Expand Down Expand Up @@ -200,12 +202,6 @@ test("a piece's page has its name, price, photos, words and product data, and no
["US", "52.00"],
],
);
assert.equal(
structuredData({ id: "P", name: "Pot", variations: [{ id: "V", name: "R", price: 1000, stock: 1 }] }, "")["@graph"][0].offers[0]
.shippingDetails,
undefined,
"pickup-only or unweighted items omit parcel shippingDetails",
);
assert.equal(product.image.length, 2);
assert.deepEqual(
crumbs.itemListElement.map((c) => c.name),
Expand All @@ -216,6 +212,27 @@ test("a piece's page has its name, price, photos, words and product data, and no
assert.deepEqual(data.variations, [{ id: "V1", name: "R", price: 6500, currency: "USD", stock: 1 }]);
});

test("dimensions and pickup-only shipping details are derived cleanly from piece metadata", () => {
assert.deepEqual(parseDimensions({ name: "Lantern bowl", category: "Bowls", description: "Crackle · 9½″ × 3¾″" }), {
width: 9.5,
height: 3.75,
});
assert.deepEqual(parseDimensions({ name: "Tall flared lantern vase", category: "Vases", description: "Crackle · 11¾″ × 6½″" }), {
height: 11.75,
width: 6.5,
});
assert.deepEqual(parseDimensions({ name: "Bowl", description: "Cone 10 · 5½″ wide × 3″ tall" }), { width: 5.5, height: 3 });
assert.deepEqual(parseDimensions({ name: "Nested bowls", description: "7¼″, 7¾″ and 8″ × 4½″, set of 3" }), {});

const pickupOnly = structuredData(
{ id: "P1", name: "Large sculpture", description: "Cone 10 · 8″ × 5″", variations: [{ id: "V", name: "R", price: 20000, stock: 1 }] },
"https://s.example",
)["@graph"][0];
assert.deepEqual(pickupOnly.width, { "@type": "QuantitativeValue", value: 8, unitCode: "INH" });
assert.deepEqual(pickupOnly.height, { "@type": "QuantitativeValue", value: 5, unitCode: "INH" });
assert.equal(pickupOnly.offers[0].shippingDetails.doesNotShip, true);
});

test("piece titles include 'Handmade pottery' when short enough, and stay within 60 characters", () => {
assert.equal(pieceTitle({ name: "Lantern bowl" }), "Lantern bowl – Handmade pottery | Updraft Pottery Studio");
assert.equal(pieceTitle({ name: "Celadon footed bowl" }), "Celadon footed bowl | Updraft Pottery Studio");
Expand Down Expand Up @@ -253,6 +270,7 @@ test("a piece's page goes into the site's shell; without one it's a plain page k
const fetched = t.mock.method(globalThis, "fetch", async () => new Response(SHELL));
const plain = await get("/p/I1");
assert.match(plain.body, /<meta name="robots" content="noindex">/);
assert.equal(plain.headers["x-robots-tag"], "noindex");
assert.match(plain.headers["cache-control"], /max-age=60/, "kept briefly, so the styled page soon takes over");
assert.equal(fetched.mock.callCount(), 0);
});
Expand All @@ -276,18 +294,26 @@ test("other pieces still for sale are linked from a piece's page, and its text i
test("unknown or odd ids are gone (410), never an error", async () => {
_setSquare(fakeCatalog());
// 410 rather than 404, which CloudFront would replace with the site's generic error page.
assert.equal((await get("/p/NOPE")).statusCode, 410);
assert.match((await get("/p/NOPE")).body, /isn't listed any more/);
const gone = await get("/p/NOPE");
assert.equal(gone.statusCode, 410);
assert.equal(gone.headers["x-robots-tag"], "noindex");
assert.match(gone.body, /isn't listed any more/);
assert.equal((await get("/p/..%2Fapi%2Fcatalog")).statusCode, 410);
assert.equal((await get("/p/%E0")).statusCode, 410, "a malformed escape is not an unhandled error");
});

test("the pieces' sitemap lists every listed piece with the day it last changed and its photos", async () => {
test("the pieces' sitemap and Atom feed list pieces with dates and photos", async () => {
_setSquare(fakeCatalog());
const res = await get("/p/sitemap.xml");
assert.equal(res.statusCode, 200);
assert.match(res.headers["content-type"], /application\/xml/);
assert.match(res.body, /xmlns:image="http:\/\/www\.google\.com\/schemas\/sitemap-image\/1\.1"/);
assert.match(res.body, /<url><loc>\/p\/I1<\/loc><lastmod>2026-10-15<\/lastmod><image:image><image:loc>\/api\/img\?u=/);
assert.equal([...res.body.matchAll(/<image:loc>/g)].length, 2);

const atom = await get("/p/feed.xml");
assert.equal(atom.statusCode, 200);
assert.match(atom.headers["content-type"], /application\/atom\+xml/);
assert.ok(atom.body.includes("<title>Celadon bowl · $65.00</title>"));
assert.ok(atom.body.includes('rel="enclosure" type="image/jpeg"'));
});
2 changes: 1 addition & 1 deletion deploy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ which only reaches resources named `updraft-*`, parameters under `/updraft/`, an

| Piece | What |
|---|---|
| site stack ([`site.yaml`](site.yaml)) | Private S3 bucket, CloudFront, HTTPS certificate, security headers; `/api/checkout`, `/api/img` (cached a year) and `/api/*` routed to the functions through origin access control, so the functions only accept requests CloudFront signed; `/p/*` piece pages and `/p/sitemap.xml` (cached 5 minutes) go to `Api`. Staging's DNS record is in the stack. |
| site stack ([`site.yaml`](site.yaml)) | Private S3 bucket, CloudFront, HTTPS certificate, security headers, and a CloudFront Function for canonical 301 redirects (`www` → apex, `/index.html` → `/`, `/shop` → `/shop.html`, etc., enabled automatically once `updraft-publish-ssm` includes `cloudfront:*Function*`); `/api/checkout`, `/api/img` (cached a year) and `/api/*` routed to the functions through origin access control, so the functions only accept requests CloudFront signed; `/p/*` piece pages, `/p/sitemap.xml` and `/p/feed.xml` (cached 5 minutes) go to `Api`. Staging's DNS record is in the stack and carries `X-Robots-Tag: noindex`; production includes the Bing verification CNAME. |
| API stack ([`../backend/template.yaml`](../backend/template.yaml)) | `Api` (catalog, tax quote, signup, `/p/` piece pages, drawn in the published `piece-shell.html`) and `Checkout` (one order at a time, so a one-of-a-kind piece can't sell twice), from one bundle; `Images` (shop photos resized with sharp, its own package). Square token read from SSM. 30-day log groups, and alarms emailed through SNS. |
| Square token | SSM Parameter Store SecureString `/updraft/<stage>/square-access-token` |
| Production DNS | apex + `www` A/AAAA aliases to CloudFront, switched with `node scripts/dns-cutover.mjs` |
Expand Down
1 change: 1 addition & 0 deletions deploy/copper-bell-publish-policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"Effect": "Allow",
"Action": [
"cloudfront:*Distribution*",
"cloudfront:*Function*",
"cloudfront:*OriginAccessControl*",
"cloudfront:*ResponseHeadersPolicy*",
"cloudfront:*Invalidation*",
Expand Down
Loading
Loading