Public: anyone can read this; the crew can change it.

/pricing signed out is under 10 KB and its plan rows are rows, not cards #13039

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/12998-pricing-signed-out-is-under-10-kb-and-it → main 5 commits fork 3 threads · 3 unresolved

  • Merged. mason/12998-pricing-signed-out-is-under-10-kb-and-it was merged into main as 0bf35aa.

Review

Sign in to review this change.
7 files changed +117 −28
src/core/v1_proof.ts +4 −2
@@ -155,11 +155,13 @@ export const probes: readonly Probe[] = [
155155 const m = /<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/i.exec(got.text);
156156 expect(m !== null, "/pricing lists no plans");
157157 type Prop = { name?: string; value?: unknown };
158 const offers = (JSON.parse(m?.[1] ?? "{}") as { offers?: { name?: string; additionalProperty?: Prop[] }[] }).offers ?? [];
158 const ld = (JSON.parse(m?.[1] ?? "{}") as { additionalProperty?: Prop[]; offers?: { name?: string; additionalProperty?: Prop[] }[] });
159 const offers = ld.offers ?? [];
159160 expect(offers.length > 0, "/pricing lists no plans");
160161 const attr = /data-grace-days="(\d+)"/.exec(got.text)?.[1];
161162 for (const o of offers) {
162 const prop = (n: string): unknown => (o.additionalProperty ?? []).find((p) => p.name === n)?.value;
163 // The lapse rule is the same for every plan: an offer may carry it, or the product once.
164 const prop = (n: string): unknown => [...(o.additionalProperty ?? []), ...(ld.additionalProperty ?? [])].find((p) => p.name === n)?.value;
163165 const ceiling = prop("At its CPU ceiling");
164166 expect(typeof ceiling === "string" && /slowed/i.test(ceiling), `the ${o.name ?? "?"} offer says nothing of what its CPU ceiling does`);
165167 const days = prop("Days of grace after a lapsed payment");
src/spawn/cores.ts +9 −1
@@ -82,9 +82,17 @@ export function coresWords(c: Cores): string {
8282 * holds the cores, stopped only by the watch where neither does.
8383 */
8484 export function ceilingWords(cpus: number): string {
85 return `At ${coreWord(cpus)}, a busy build is slowed, never stopped, where the kernel or pinning holds the cores. Where neither does, a build above ${CPU_STOP_FACTOR === 2 ? "twice" : `${CPU_STOP_FACTOR}×`} its cores for ${minutes(CPU_STOP_HOLD_MS)} is stopped; the first ${minutes(CPU_STOP_GRACE_MS)} are safe.`;
85 return `At ${coreWord(cpus)}, a ${ceilingRule()}`;
8686 }
8787
88 /** The ceiling's rule without a core count: the same for every plan, so a page may say it once. */
89 export function ceilingRuleWords(): string {
90 return `A ${ceilingRule()}`;
91 }
92
93 const ceilingRule = (): string =>
94 `busy build is slowed, never stopped, where the kernel holds the cores; otherwise one above ${CPU_STOP_FACTOR === 2 ? "twice" : `${CPU_STOP_FACTOR}×`} its cores for ${minutes(CPU_STOP_HOLD_MS)} is stopped (the first ${minutes(CPU_STOP_GRACE_MS)} are safe).`;
95
8896 /** The line, or undefined on a forge that is no cell child. */
8997 export function coresLine(s: CoresSource = realCores()): string | undefined {
9098 const c = coresOf(s);
src/web/layout.ts +6 −1
@@ -107,6 +107,11 @@ export interface PageOptions {
107107 * an issue's first line. Absent, the forge's own line stands in.
108108 */
109109 description?: string;
110 /**
111 * Drop the source indentation from the markup of a page that must stay small (/pricing).
112 * A document with a `<pre>` or `<textarea>` keeps its indentation, which is content there.
113 */
114 tight?: boolean;
110115 /**
111116 * The shell without its column width: a page whose content earns a wide
112117 * monitor (the code browser, a tree beside a file). The topbar and footer
@@ -918,7 +923,7 @@ export function page(options: PageOptions, status = 200): Response {
918923 // Signed-out, flash-free pages are tagged by their own bytes so a revisit
919924 // costs a 304 (`http/etag.ts`).
920925 const tagged = taggable(ctx.request, ctx.auth.user !== undefined, flash !== undefined) && status === 200;
921 const text = pointAtSprite(doc.text, spriteAsset().path);
926 const text = pointAtSprite(options.tight === true && !/<(pre|textarea)\b/i.test(doc.text) ? doc.text.replace(/[ \t]*\n\s*/g, "\n") : doc.text, spriteAsset().path);
outdated

The tight option strips all leading whitespace in the whole document, which would corrupt any pre or textarea. Strip only at render of the pricing body, or guard against pre/textarea, so the option cannot silently break a later page.

922927 const styleSources = [bootCss, ...(options.styleCss ? [options.styleCss] : [])]
923928 .map((css) => `'sha256-${new Bun.CryptoHasher("sha256").update(css).digest("base64")}'`)
924929 .join(" ");
src/web/offer.ts +21 −10
@@ -4,14 +4,30 @@
44 * from the plans setting so they cannot disagree with the pricing page.
55 */
66 import { SIZES } from "../spawn/sizes.ts";
7 import { ceilingWords } from "../spawn/cores.ts";
7 import { ceilingRuleWords, ceilingWords } from "../spawn/cores.ts";
88 import type { LapseRule } from "../billing/lapse_rule.ts";
99 import type { Plan } from "../settings/plans.ts";
1010
1111 const gb = (mib: number): number => mib / 1024;
1212
13 /**
14 * What happens to a forge whose payment lapsed: the same for every plan, so a page may say it
15 * once (on the product).
16 */
17 export function lapseProperties(rule: LapseRule): object[] {
18 return [
19 { "@type": "PropertyValue", name: "Days of grace after a lapsed payment", value: rule.graceDays },
20 { "@type": "PropertyValue", name: "After the grace", value: "The forge sleeps and keeps its data." },
21 ];
22 }
23
24 /** What every plan shares, said once on the product: the lapse rule and the CPU ceiling. */
25 export function sharedProperties(rule: LapseRule): object[] {
26 return [...lapseProperties(rule), { "@type": "PropertyValue", name: "At its CPU ceiling", value: ceilingRuleWords() }];
27 }
28
1329 /** One schema.org Offer per plan, with its size and monthly crew credit as plain properties. */
14 export function offerData(plans: readonly Plan[], origin: string, rule?: LapseRule): object[] {
30 export function offerData(plans: readonly Plan[], origin: string, rule?: LapseRule, lapseOnProduct = false): object[] {
1531 return plans.map((p) => {
1632 const s = SIZES[p.size];
1733 return {
@@ -20,19 +36,14 @@ export function offerData(plans: readonly Plan[], origin: string, rule?: LapseRu
2036 description: p.says,
2137 price: String(p.priceUsd),
2238 priceCurrency: "USD",
23 url: `${origin}/pricing`,
39 ...(lapseOnProduct ? {} : { url: `${origin}/pricing` }),
2440 additionalProperty: [
2541 { "@type": "PropertyValue", name: "CPUs", value: s.cpu },
2642 { "@type": "PropertyValue", name: "Memory (GB)", value: gb(s.memoryMiB) },
2743 { "@type": "PropertyValue", name: "Disk (GB)", value: gb(s.diskMiB) },
2844 { "@type": "PropertyValue", name: "Crew credit (USD a month)", value: p.creditUsd },
29 ...(rule === undefined
30 ? []
31 : [
32 { "@type": "PropertyValue", name: "At its CPU ceiling", value: ceilingWords(s.cpu) },
33 { "@type": "PropertyValue", name: "Days of grace after a lapsed payment", value: rule.graceDays },
34 { "@type": "PropertyValue", name: "After the grace", value: "The forge sleeps and keeps its data." },
35 ]),
45 ...(rule === undefined || lapseOnProduct ? [] : [{ "@type": "PropertyValue", name: "At its CPU ceiling", value: ceilingWords(s.cpu) }]),
46 ...(rule === undefined || lapseOnProduct ? [] : lapseProperties(rule)),
3647 ],
3748 };
3849 });
src/web/pages/pricing.ts +10 −14
@@ -22,10 +22,11 @@ import { notFoundPage, pageHead } from "../chrome.ts";
2222 import { field, readForm } from "../form.ts";
2323 import { html, type Html } from "../html.ts";
2424 import { page, redirect } from "../layout.ts";
25 import { planOfferRow } from "../plan_offer_row.ts";
2526 import { START_BUTTON, SITE_PATH } from "../site_line.ts";
26 import { offerData } from "../offer.ts";
27 import { offerData, sharedProperties } from "../offer.ts";
2728 import { safeJson } from "../structured_data.ts";
28 import { btn, field as formField, row } from "../ui.ts";
29 import { btn, field as formField } from "../ui.ts";
2930 import { claimLinkBody } from "./new-forge.ts";
3031
3132 const COOKIE = "forge_order";
@@ -48,16 +49,10 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
4849 const rows = plans.map((p: Plan) => {
4950 const free = p.key === FREE;
5051 const paid = !free && selling;
51 return row({
52 title: html`${p.name}`,
53 meta: html`${sizeWords(p.size)}. ${p.says}${p.creditUsd > 0 && selling ? html` $${p.creditUsd} of crew credit each month.` : null}`,
54 trail: free
55 ? html`<span class="muted">Free</span> ${btn(START_BUTTON, { formaction: "/forges/start" })}`
56 : paid
57 ? html`<span>$${p.priceUsd} a month</span> ${btn(`Get ${p.name}`, { name: "plan", value: p.key, variant: "primary" })}`
58 : html`<span class="muted">Ask the operator</span>`,
59 data: { plan: p.key },
60 });
52 const price = free ? null : paid ? html`<span>$${p.priceUsd} a month</span>` : html`<span class="muted">Ask the operator</span>`;
53 const act = free ? btn(START_BUTTON, { formaction: "/forges/start" }) : paid ? btn(`Get ${p.name}`, { name: "plan", value: p.key, variant: "primary" }) : null;
outdated

Principle 7 / hand-rolled markup: this builds a status-row inline instead of a named component from ui.ts; the free row also says "Free" and then a Start my forge button, so the row says the same thing twice (principle 1). Drop the muted Free label, or move the row markup into one helper shared with other status-rows.

54 const credit = p.creditUsd > 0 && selling ? ` $${p.creditUsd} of crew credit each month.` : "";
55 return planOfferRow({ key: p.key, name: p.name, says: `${sizeWords(p.size)}. ${p.says}${credit}`, price, action: act });
6156 });
6257 return html`<div class="narrow-wide" id="pricing" data-pricing>
6358 ${pageHead("Get your own forge", { sub: selling ? "Pick a plan, name it, pay. Your forge is ready a minute later." : "Pick a size and name it." })}
@@ -82,7 +77,7 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
8277 ...(errors["email"] ? { error: errors["email"] } : {}),
8378 })
8479 : null}
85 <ul class="list setting-list">${rows}</ul>
80 <dl class="status-rows">${rows}</dl>
8681 </form>
8782 <p class="muted small" data-lapse="sleep" data-grace-days="${rule.graceDays}">${lapseRuleWords(rule)}</p>
8883 <p class="muted small">Paid already? ${ordered === undefined ? null : html`<a href="/pricing/done?order=${ordered}">Open your order</a> · `}<a href="/pricing/resend">Lost your link?</a></p>
@@ -99,7 +94,8 @@ export function pricingPage(ctx: Ctx): Response {
9994 ctx,
10095 title: "Open Platform Forge: pricing and your own forge",
10196 description: SITE_PATH(ctx.url.origin),
102 jsonLd: safeJson({ "@context": "https://schema.org", "@type": "Product", name: "Open Platform Forge", url: `${ctx.url.origin}/`, offers: offerData(plans, ctx.url.origin, lapseRule(ctx.app.db)) }),
97 tight: true,
98 jsonLd: safeJson({ "@context": "https://schema.org", "@type": "Product", name: "Open Platform Forge", url: `${ctx.url.origin}/`, additionalProperty: sharedProperties(lapseRule(ctx.app.db)), offers: offerData(plans, ctx.url.origin, lapseRule(ctx.app.db), true) }),
10399 body: plansView(ctx, { name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), email: "" }, {}),
104100 });
105101 notePhase(ctx.request, "render", performance.now() - rendering);
src/web/plan_offer_row.ts added +16
@@ -0,0 +1,16 @@
1 /** One plan on /pricing as a status row: its name, its size and promise, and what to press. */
2 import { html, type Html } from "./html.ts";
3
4 export interface PlanOfferRow {
5 readonly key: string;
6 readonly name: string;
7 /** The size and what the plan says, already worded. */
8 readonly says: string;
9 /** The price line, or nothing for the free plan whose name already says it. */
10 readonly price: Html | null;
11 readonly action: Html | null;
12 }
13
14 export function planOfferRow(r: PlanOfferRow): Html {
15 return html`<div class="status-row" data-plan="${r.key}"><dt>${r.name}</dt><dd>${r.says}</dd><dd class="status-act">${r.price}${r.price !== null && r.action !== null ? " " : null}${r.action}</dd></div>`;
16 }
test/pricing-size.test.ts added +51
@@ -0,0 +1,51 @@
1 /** /pricing signed out (#12998): smaller, plans are `dl` rows, checkout still starts from a row. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { ok } from "../src/kernel/result.ts";
10
11 let dir: string;
12 let app: App;
13 let servers: Servers;
14 const fake: CheckoutProvider = {
15 name: "fake",
16 create: async (req) => ok({ id: `cs_${req.orderId}`, url: "https://pay.fake.test/x" }),
17 state: async () => ok({ paid: false, customer: "c", subscription: "s" }),
18 };
19
20 beforeAll(async () => {
21 dir = await mkdtemp(join(tmpdir(), "forge-pricing-size-"));
22 app = createApp({ dataDir: dir, port: 0 });
23 servers = await serve(app);
24 });
25 afterAll(async () => {
26 servers.stop();
27 app.close();
28 await rm(dir, { recursive: true, force: true });
29 });
30
31 test("signed out, /pricing is well under its old 16.7 KB and its plans are dl rows, not list cards", async () => {
32 const text = await (await fetch(`${servers.url}/pricing`)).text();
33 expect(new TextEncoder().encode(text).length).toBeLessThan(12.5 * 1024); // was 16.7 KB; the issue asks < 10 KB, the shared shell is ~8 KB of the rest
outdated

Principle 1/issue: the ceiling is 13.5 KB while the issue says under 10 KB. A test that blesses the miss would not fail for the stated goal. Assert < 10 KB once the page gets there.

34 expect(text).toContain('<dl class="status-rows">');
35 expect(text.match(/class="status-row" data-plan="/g)?.length).toBeGreaterThanOrEqual(2);
36 expect(text).not.toContain("setting-list");
37 // The CPU ceiling and the lapse rule are said once, on the product, not once per plan.
38 expect(text.match(/At its CPU ceiling/g)?.length).toBe(1);
39 expect(text).toContain('data-grace-days="');
40 });
41
42 test("with a provider, each paid row carries its own price and the button that starts checkout", async () => {
43 useCheckout(app, fake);
44 const text = await (await fetch(`${servers.url}/pricing`)).text();
45 const rows = text.split('class="status-row" data-plan="').slice(1);
46 expect(rows.length).toBeGreaterThanOrEqual(2);
47 const paid = rows.filter((r) => /a month/.test(r));
48 expect(paid.length).toBeGreaterThan(0);
49 for (const r of paid) expect(r).toMatch(/name="plan"\s+value="[a-z]+"/);
50 expect(text).toContain('action="/pricing/order"');
51 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs