Files
MichilisandClaude Opus 5.5 f09445b6ad
ci / check (push) Canceled after 0s
ci / images (push) Canceled after 0s
ci / e2e (push) Canceled after 0s
Initial commit
Paper Sats: design and print paper notes that carry sats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 05:15:30 +00:00

353 lines
13 KiB
TypeScript

/**
* `pnpm dev:seed`: two test keys and one design per template, on the local dev relay and Blossom.
* Start them first: `pnpm --filter @paper-sats/devservers relay` and `... blossom`.
*
* It reads DEFAULT_RELAYS and DEFAULT_BLOSSOM_SERVERS from the process environment only, never from
* .env, and refuses to run unless every URL is localhost. Seeds must never reach a public relay.
* Previews are rendered in headless Chromium, so the cards show real fonts.
*/
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
BlossomClient,
LocalKeySigner,
publishDesign,
RelayPool,
sha256Hex,
type DesignConfig,
type WebSocketConstructor,
} from '../packages/nostr/src/index';
import {
buildTemplate,
qrGeometry,
renderFace,
samplePayload,
sampleValues,
type DrawOp,
type TemplateName,
} from '../packages/note-render/src/index';
const here = path.dirname(fileURLToPath(import.meta.url));
const webRequire = createRequire(path.join(here, '../apps/web/package.json'));
const devRequire = createRequire(path.join(here, '../packages/devservers/package.json'));
function list(raw: string | undefined, fallback: string): string[] {
return (raw ?? fallback)
.split(',')
.map((s) => s.trim())
.filter(Boolean);
}
const relays = list(process.env.DEFAULT_RELAYS, 'ws://localhost:7778');
const servers = list(process.env.DEFAULT_BLOSSOM_SERVERS, 'http://localhost:3301');
function isLocal(url: string): boolean {
try {
const { hostname, protocol } = new URL(url);
return (
['localhost', '127.0.0.1', '[::1]'].includes(hostname) &&
['ws:', 'wss:', 'http:', 'https:'].includes(protocol)
);
} catch {
return false;
}
}
const outside = [...relays, ...servers].filter((u) => !isLocal(u));
if (outside.length > 0) {
console.error(`Refusing to seed: not localhost: ${outside.join(', ')}`);
process.exit(1);
}
const config: DesignConfig = {
kind: Number(process.env.DESIGN_KIND ?? 32040),
tag: process.env.DESIGN_TAG ?? 'paper-sats-design',
allowLocalUrls: true,
};
type Plan = {
template: TemplateName;
size: { wMm: number; hMm: number };
sides: 1 | 2;
name: string;
description: string;
author: 0 | 1;
license: string;
};
const PLANS: Plan[] = [
{
template: 'classic',
size: { wMm: 150, hMm: 70 },
sides: 2,
name: 'Forest banknote',
description: 'Guilloche banknote in deep green, with the QR on the back.',
author: 0,
license: 'CC0-1.0',
},
{
template: 'vertical',
size: { wMm: 70, hMm: 150 },
sides: 2,
name: 'Night market vertical',
description: 'A tall note for wallets and shirt pockets.',
author: 1,
license: 'CC0-1.0',
},
{
template: 'coupon',
size: { wMm: 100, hMm: 100 },
sides: 1,
name: 'Corner cafe coupon',
description: 'A square coupon to hand out at the counter.',
author: 0,
license: 'CC-BY-4.0',
},
{
template: 'card',
size: { wMm: 85.6, hMm: 54 },
sides: 1,
name: 'Meetup card',
description: 'Business card size, single-sided, for meetups.',
author: 1,
license: 'CC0-1.0',
},
{
template: 'ticket',
size: { wMm: 60, hMm: 150 },
sides: 2,
name: 'Raffle ticket',
description: 'A long ticket with room for a serial on the stub.',
author: 0,
license: 'CC-BY-SA-4.0',
},
{
template: 'minimal',
size: { wMm: 150, hMm: 70 },
sides: 1,
name: 'Plain ink',
description: 'Black on white, cheap to print.',
author: 1,
license: 'CC0-1.0',
},
];
/* Previews ---------------------------------------------------------------------------------------- */
const FONT_FILES: [string, string, number][] = [
['Space Grotesk', '@fontsource/space-grotesk/files/space-grotesk-latin-500-normal.woff2', 500],
['Space Grotesk', '@fontsource/space-grotesk/files/space-grotesk-latin-700-normal.woff2', 700],
['Inter', '@fontsource/inter/files/inter-latin-400-normal.woff2', 400],
['Inter', '@fontsource/inter/files/inter-latin-500-normal.woff2', 500],
['JetBrains Mono', '@fontsource/jetbrains-mono/files/jetbrains-mono-latin-400-normal.woff2', 400],
['JetBrains Mono', '@fontsource/jetbrains-mono/files/jetbrains-mono-latin-500-normal.woff2', 500],
['Bodoni Moda', '@fontsource/bodoni-moda/files/bodoni-moda-latin-500-normal.woff2', 500],
['Bodoni Moda', '@fontsource/bodoni-moda/files/bodoni-moda-latin-700-normal.woff2', 700],
[
'Bricolage Grotesque',
'@fontsource/bricolage-grotesque/files/bricolage-grotesque-latin-500-normal.woff2',
500,
],
[
'Bricolage Grotesque',
'@fontsource/bricolage-grotesque/files/bricolage-grotesque-latin-700-normal.woff2',
700,
],
];
function fontFaces(): string {
return FONT_FILES.flatMap(([family, file, weight]) => {
try {
const data = readFileSync(webRequire.resolve(file)).toString('base64');
return [
`@font-face{font-family:'${family}';font-weight:${String(weight)};src:url(data:font/woff2;base64,${data})}`,
];
} catch {
return [];
}
}).join('');
}
function esc(text: string): string {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
const PT_TO_MM = 25.4 / 72;
function opSvg(op: DrawOp): string {
switch (op.kind) {
case 'rect':
return `<rect x="${String(op.xMm)}" y="${String(op.yMm)}" width="${String(op.wMm)}" height="${String(op.hMm)}" rx="${String(op.radiusMm)}" fill="${op.fill ?? 'none'}" stroke="${op.stroke ?? 'none'}" stroke-width="${String(op.stroke ? op.strokeWidthMm : 0)}" opacity="${String(op.opacity)}"/>`;
case 'ellipse':
return `<ellipse cx="${String(op.xMm + op.wMm / 2)}" cy="${String(op.yMm + op.hMm / 2)}" rx="${String(op.wMm / 2)}" ry="${String(op.hMm / 2)}" fill="${op.fill ?? 'none'}" stroke="${op.stroke ?? 'none'}" stroke-width="${String(op.stroke ? op.strokeWidthMm : 0)}" opacity="${String(op.opacity)}"/>`;
case 'path': {
const d = op.lines
.map(
(l) =>
l.points
.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(2)} ${y.toFixed(2)}`)
.join('') + (l.closed ? 'Z' : ''),
)
.join('');
return `<path d="${d}" fill="${op.fill ?? 'none'}" stroke="${op.stroke}" stroke-width="${String(op.strokeWidthMm)}" stroke-linecap="round" stroke-linejoin="round" opacity="${String(op.opacity)}"/>`;
}
case 'text': {
const size = op.sizePt * PT_TO_MM;
const x =
op.align === 'left'
? op.xMm
: op.align === 'center'
? op.xMm + op.wMm / 2
: op.xMm + op.wMm;
const anchor = op.align === 'left' ? 'start' : op.align === 'center' ? 'middle' : 'end';
const lines = op.text
.split('\n')
.map(
(line, i) =>
`<tspan x="${String(x)}" dy="${String(i === 0 ? 0 : size * op.lineHeight)}">${esc(line)}</tspan>`,
)
.join('');
const rotate = op.rotation
? ` transform="rotate(${String(op.rotation)} ${String(op.xMm)} ${String(op.yMm)})"`
: '';
return `<text x="${String(x)}" y="${String(op.yMm + size * 0.8)}" font-family="'${op.family}'" font-weight="${String(op.weight)}" font-size="${String(size)}" fill="${op.color}" opacity="${String(op.opacity)}" letter-spacing="${String(op.letterSpacingEm * size)}" text-anchor="${anchor}"${rotate}>${lines}</text>`;
}
case 'image':
return '';
case 'qr': {
const geo = qrGeometry(op);
let d = '';
op.modules.forEach((row, r) => {
row.forEach((dark, c) => {
if (dark) {
d += `M${String(geo.matrixXMm + c * geo.moduleMm)} ${String(geo.matrixYMm + r * geo.moduleMm)}h${String(geo.moduleMm)}v${String(geo.moduleMm)}h${String(-geo.moduleMm)}Z`;
}
});
});
const frame =
geo.frame && op.frame
? `<rect x="${String(geo.frame.xMm)}" y="${String(geo.frame.yMm)}" width="${String(geo.frame.sizeMm)}" height="${String(geo.frame.sizeMm)}" rx="${String(geo.frame.radiusMm)}" fill="none" stroke="${op.frame.color}" stroke-width="${String(geo.frame.widthMm)}"/>`
: '';
return `<rect x="${String(op.xMm)}" y="${String(op.yMm)}" width="${String(op.sizeMm)}" height="${String(op.sizeMm)}" rx="${String(geo.backgroundRadiusMm)}" fill="${op.background}"/>${frame}<path d="${d}" fill="${op.foreground}"/>`;
}
}
}
type PwPage = {
setViewportSize: (s: { width: number; height: number }) => Promise<void>;
setContent: (html: string) => Promise<void>;
evaluate: <T, A>(fn: (arg: A) => T | Promise<T>, arg: A) => Promise<T>;
screenshot: (o: { type: 'png'; omitBackground: boolean }) => Promise<Buffer>;
};
async function previewWebp(
page: PwPage,
fonts: string,
design: ReturnType<typeof buildTemplate>,
face: 'front' | 'back',
): Promise<Uint8Array> {
const { ops } = renderFace(design, face, sampleValues('lnurlcash', 5000), {
qrPayload: samplePayload('lnurlcash', 5000),
ecc: 'M',
});
const { wMm, hMm } = design.size;
const scale = 800 / Math.max(wMm, hMm);
const width = Math.round(wMm * scale);
const height = Math.round(hMm * scale);
await page.setViewportSize({ width, height });
await page.setContent(
`<!doctype html><style>${fonts}html,body{margin:0;background:transparent}svg{display:block}</style><svg xmlns="http://www.w3.org/2000/svg" width="${String(width)}" height="${String(height)}" viewBox="0 0 ${String(wMm)} ${String(hMm)}"><clipPath id="c"><rect width="${String(wMm)}" height="${String(hMm)}" rx="${String(design.cornerRadiusMm)}"/></clipPath><g clip-path="url(#c)">${ops.map(opSvg).join('')}</g></svg>`,
);
await page.evaluate(() => document.fonts.ready.then(() => undefined), undefined);
const png = await page.screenshot({ type: 'png', omitBackground: true });
// Canvas in the same browser encodes WebP. The screenshot is the source image.
const encoded = await page.evaluate(async (base64: string) => {
const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
const bitmap = await createImageBitmap(new Blob([bytes], { type: 'image/png' }));
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext('2d')?.drawImage(bitmap, 0, 0);
return canvas.toDataURL('image/webp', 0.86).split(',')[1] ?? '';
}, png.toString('base64'));
return new Uint8Array(Buffer.from(encoded, 'base64'));
}
/* Run --------------------------------------------------------------------------------------------- */
/** Stable keys and stable `d` values, so running again replaces rather than piles up. */
function testKey(label: string): LocalKeySigner {
return new LocalKeySigner(
Uint8Array.from(
Buffer.from(sha256Hex(new TextEncoder().encode(`paper-sats-seed:${label}`)), 'hex'),
),
);
}
async function main(): Promise<void> {
const { chromium } = webRequire('@playwright/test') as {
chromium: {
launch: () => Promise<{ newPage: () => Promise<PwPage>; close: () => Promise<void> }>;
};
};
const { WebSocket } = devRequire('ws') as { WebSocket: WebSocketConstructor };
const pool = new RelayPool({ WebSocket });
const blossom = new BlossomClient();
const signers = [testKey('alice'), testKey('bob')];
const fonts = fontFaces();
const browser = await chromium.launch();
const page = await browser.newPage();
const now = Math.floor(Date.now() / 1000);
let failed = 0;
for (const [index, plan] of PLANS.entries()) {
const signer = signers[plan.author] as LocalKeySigner;
const template = buildTemplate(plan.template, plan.size, plan.sides);
const design = {
...template,
name: plan.name,
meta: { ...template.meta, license: plan.license },
};
const front = await previewWebp(page, fonts, design, 'front');
const back = plan.sides === 2 ? await previewWebp(page, fonts, design, 'back') : undefined;
const seedBytes = new TextEncoder().encode(plan.template.padEnd(4, 'x').slice(0, 4));
const result = await publishDesign(
{
design,
art: [],
previews: { front, ...(back ? { back } : {}) },
description: plan.description,
},
{
signer,
blossom,
pool,
config,
userServers: [],
defaultServers: servers,
writeRelays: [],
defaultRelays: relays,
now: now - index * 3600,
random: () => seedBytes,
},
);
if (result.ok) {
console.log(`seeded ${plan.template}: ${result.naddr}`);
} else {
failed += 1;
console.error(`could not seed ${plan.template}: ${result.stage}: ${result.message}`);
}
}
await browser.close();
pool.close();
if (failed > 0) process.exit(1);
process.exit(0);
}
main().catch((err: unknown) => {
console.error(err);
process.exit(1);
});