diff --git a/.changeset/notes-and-color.md b/.changeset/notes-and-color.md new file mode 100644 index 0000000..3480453 --- /dev/null +++ b/.changeset/notes-and-color.md @@ -0,0 +1,10 @@ +--- +"@kadal/store": patch +--- + +`download` and `sync` take `--color ` for recolourable illustrations, and the local MCP +server's `download_to_folder` and `get_download_links` take `color`: the SVGs come in that colour +as `-.svg`, each checked against the store's sha256 for the recoloured file, and a +product that can't be recoloured is refused. The `More:` line under `search` now repeats your +filters, so it pages through the same search. The help, the skill and the README say what `buy` +does without a tier: each item comes with the cheapest licence on sale. diff --git a/README.md b/README.md index 204c6e3..131cd8c 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,12 @@ Done: 0 downloaded, 83 already here. - `sync [dir]` mirrors everything you own into `dir` (default `./kadal-store`), one folder per product. Files already there with the same sha256 are skipped; nothing is ever deleted. `--product ` (repeatable), the edition flags, and `--dry-run` to see what would come down. +- Recolourable illustrations (`show ` says "Recolourable") come in any colour: + `--color ` on `download` or `sync`, such as `--color 2f9e44`, saves each SVG in that colour + as `-2f9e44.svg`, and the rest of the product as it is. Leave out the `#` or quote it + (`"#2f9e44"`): a bare `#` starts a comment in the shell. Each recoloured file is checked against + the store's sha256 for it, so the next run skips it too. `sync --color` recolours the products + that can be and brings the rest as drawn; a product that can't take a colour is refused (exit 2). - Every file is checked against the sha256 the store gives before it is kept. A download that is cut off leaves a `.kadal-part` file, and the next run picks up where it stopped. Downloads run four at a time (`--concurrency `). @@ -197,12 +203,12 @@ Review and pay here: Soft UI Sounds personal $9.00 (you already own this) Total $9.00 -Open the link to review and pay. Nothing is charged until the person pays in Paddle's checkout, and they can change a licence or remove anything there. Already owned, so not charged: soft-ui-sounds. +Open the link to review and pay. Nothing is charged until you pay on that page, and you can change a licence or remove anything there. Already owned, so not charged: soft-ui-sounds. ``` `buy …` makes a page where you see each item, its licence and its price, and anything you already own, which is left out of the total. Without a tier, an item comes with the cheapest -licence it is sold under; add one (`personal`, `standard` or `commercial`) to choose. `--open` +licence on sale for it; add one (`personal`, `standard` or `commercial`) to choose. `--open` opens the page in your browser. Making that page is all `buy` does: you pay there, or not at all.

@@ -321,12 +327,12 @@ its own, and report problems it finds in files you bought. | MCP tools | | | --- | --- | | `search_products`, `get_product`, `list_shelves`, `recommend` | the catalogue, the licence of each product, suggestions from a description of the work | -| `list_library`, `get_download_links` | what you own, and ten-minute download links with each file's sha256 | +| `list_library`, `get_download_links` | what you own, and ten-minute download links with each file's sha256 (a recolourable illustration's SVGs in the `color` you give) | | `create_buy_link` | a review page for you to pay on; it charges nothing | | `report_problem`, `list_my_notes` | a note about a file you own, and Kadal's replies | | `whoami` | who is signed in, with which scopes | | `project_summary` (local) | what `recommend --from` sends: the folder described without its contents | -| `download_to_folder` (local) | files you own into the project, checked by sha256, skipping what is there; only inside the folder the server started in unless it was started with `--allow-outside` | +| `download_to_folder` (local) | files you own into the project, checked by sha256, skipping what is there, in a `color` for recolourable illustrations; only inside the folder the server started in unless it was started with `--allow-outside` | `kadal-store mcp --dir ` serves another folder as the project. Every tool needs the `store:read` scope except `report_problem`, which needs `store:write`. The store's diff --git a/skills/kadal-store/SKILL.md b/skills/kadal-store/SKILL.md index e6d9fa6..24d27d0 100644 --- a/skills/kadal-store/SKILL.md +++ b/skills/kadal-store/SKILL.md @@ -49,6 +49,11 @@ browser to approve. Never try to sign in, enter credentials, or approve anything it if it repeats. - `kadal-store sync

` mirrors everything they own, one folder per product. Use it only when asked; it can be large. +- Recolourable illustrations (`recolor` is not null in `show --json` and `library --json`) come in + any colour: `--color 2f9e44` on `download` or `sync` (MCP `download_to_folder` with `color`) + saves their SVGs in it as `-2f9e44.svg`. Use the project's brand colour when it has one. + Write the hex without `#`, or quote it: an unquoted `#` starts a shell comment. A product that + isn't recolourable refuses a colour (exit 2). - Mind the licence when you move files into a project that will be published or sold. ## Buying: never on your own @@ -58,7 +63,8 @@ browser to approve. Never try to sign in, enter credentials, or approve anything `kadal-store buy [:tier] … --json` (MCP `create_buy_link`), and give them the URL. It shows each item, its licence and price, and anything they already own. Nothing is charged until they pay in the checkout on that page themselves. -- Tiers: `standard` (default), `personal`, `commercial`. Pick the one the licence says the use +- Tiers: `standard`, `personal`, `commercial`. Without one, each item comes with the cheapest + licence on sale for it, which may not cover the use: pick the one the licence says the use needs, and say why. ## Report problems in files they bought diff --git a/src/commands.ts b/src/commands.ts index 1b9ca96..72d272a 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -4,7 +4,13 @@ import { relative, resolve, sep } from "node:path"; import { UsageError, bool, num, str, type Parsed } from "./args.ts"; import { clearSession, loadSession, saveSession } from "./config.ts"; import { editionFrom } from "./editions.ts"; -import { type ProductReport, countOutcomes, fetchProduct } from "./fetch-product.ts"; +import { + type ProductReport, + countOutcomes, + fetchProduct, + hexColor, + notRecolourable, +} from "./fetch-product.ts"; import { AuthError, hostLabel, signedOut } from "./host.ts"; import { DEFAULT_SCOPE, login, revokeSession } from "./oauth.ts"; import * as render from "./render.ts"; @@ -14,6 +20,7 @@ import { CONTEXT_LIMIT, clip, summariseProject } from "./summarise.ts"; import { planSync, transfer } from "./transfer.ts"; import { type BuyLink, + type DownloadLink, type DownloadLinks, type Library, type MyNotes, @@ -218,11 +225,33 @@ export function searchArgs(c: Pick): Record + /^[\w@%+=:,./-]+$/.test(w) ? w : `'${w.replaceAll("'", "'\\''")}'`; + +/** + * searchArgs read backwards: the command that sends the same search again, so the `More:` line + * pages through what was asked for. The store's cursor is an offset into whatever list the call + * names; with the filters left off, the same cursor is a page of a different list. + */ +export function searchAgain(args: Record, host?: string): string { + const words = String(args.query ?? "") + .split(/\s+/) + .filter(Boolean) + .map(shellWord); + const flags = (["shelf", "style", "topic", "format", "kind", "sort", "limit"] as const) + .filter((k) => args[k] !== undefined) + .flatMap((k) => [`--${k}`, shellWord(String(args[k]))]); + if (args.maxCents !== undefined) flags.push("--max", String(Number(args.maxCents) / 100)); + if (host) flags.push("--host", shellWord(host)); + return ["kadal-store search", ...words, ...flags].join(" "); +} + export async function searchCommand(c: Ctx): Promise { const args = searchArgs(c); const r = await withStore(c, (s) => s.call("search_products", args)); if (c.io.json) c.io.emit(r); - else say(c, render.searchText(r, `kadal-store search ${c.args.join(" ")}`.trim())); + else say(c, render.searchText(r, searchAgain(args, str(c.flags.host)))); return EXIT.ok; } @@ -292,6 +321,16 @@ const progress = (c: Ctx) => (line: string) => c.io.say(line.split(c.rt.cwd + se const concurrencyOf = (c: Ctx) => intIn(c.flags.concurrency, "--concurrency", 1, 16) ?? 4; +/** `--color 2f9e44` as "#2f9e44". An unquoted `#2f9e44` never arrives: the shell reads a comment. */ +function colorOf(c: Ctx): string | undefined { + const raw = str(c.flags.color); + if (raw === undefined) return undefined; + const hex = hexColor(raw); + if (!hex) + throw new UsageError(`--color takes a hex colour, like 2f9e44 or "#2f9e44" (got "${raw}")`); + return hex; +} + /** 4 when a file failed its checksum (the store's bytes are wrong, or something in between), 1 for any other failure. */ const transferExit = (files: { status: string; checksum?: boolean }[]) => files.some((f) => f.checksum) @@ -316,6 +355,7 @@ export async function downloadCommand(c: Ctx): Promise { const fileNames = list(c.flags.file); if (zip && (fileNames || edition)) throw new UsageError("--zip is the whole product; leave out --file and the edition flags"); + const color = colorOf(c); c.io.say(`Downloading ${slug} into ${shown(c, dir)}`); const report: ProductReport = await withStore(c, (s) => fetchProduct( @@ -328,6 +368,7 @@ export async function downloadCommand(c: Ctx): Promise { zip, force: c.flags.force === true, concurrency: concurrencyOf(c), + color, }, { fetch: c.rt.fetch, log: progress(c) }, ), @@ -348,19 +389,50 @@ export async function syncCommand(c: Ctx): Promise { const edition = editionFrom(c.flags); const only = list(c.flags.product); const dry = c.flags["dry-run"] === true; + const color = colorOf(c); const result = await withStore(c, async (s) => { const library = await s.call("list_library"); - const plan = await planSync(library, dir, { edition, only }); + // The colour goes to the recolourable products and the rest come as drawn; one named with + // --product that can't take it is refused. Their links are asked for now, because only the + // store knows a recoloured file's sha256, and that is what says it is already here. + const tinted = new Map(); + if (color) { + const picked = library.items.filter((i) => !only?.length || only.includes(i.product.slug)); + const plain = only?.length ? picked.find((i) => !i.recolor) : undefined; + if (plain) throw new UsageError(notRecolourable(plain.product.name)); + for (const i of picked.filter((i) => i.recolor)) { + const slug = i.product.slug; + tinted.set( + slug, + (await s.call("get_download_links", { slug, color })).links, + ); + } + if (!tinted.size) + throw new UsageError( + "Nothing you own is recolourable (the Illustrations shelf), so --color has nothing to change.", + ); + } + const plan = await planSync(library, dir, { edition, only, links: tinted }); c.io.say( - `${library.items.length} product${library.items.length === 1 ? "" : "s"} · ${plan.skip.length} file${plan.skip.length === 1 ? "" : "s"} already in ${shown(c, dir)} · ${plan.download.length} to download${dry ? " (dry run)" : ""}`, + `${library.items.length} product${library.items.length === 1 ? "" : "s"}${color ? ` (${tinted.size} in ${color})` : ""} · ${plan.skip.length} file${plan.skip.length === 1 ? "" : "s"} already in ${shown(c, dir)} · ${plan.download.length} to download${dry ? " (dry run)" : ""}`, ); const skipped = plan.skip.map((p) => ({ ...p, status: "skipped" as const })); if (dry) return [...skipped, ...plan.download.map((p) => ({ ...p, status: "planned" as const }))]; const fetched = await transfer( plan.download, - (slug, fileIds) => s.call("get_download_links", { slug, fileIds }), - { concurrency: concurrencyOf(c), fetch: c.rt.fetch, log: progress(c) }, + (slug, fileIds) => + s.call("get_download_links", { + slug, + fileIds, + ...(tinted.has(slug) ? { color } : {}), + }), + { + concurrency: concurrencyOf(c), + fetch: c.rt.fetch, + log: progress(c), + links: new Map([...tinted.values()].flat().map((l) => [l.fileId, l])), + }, ); return [...skipped, ...fetched]; }); diff --git a/src/fetch-product.ts b/src/fetch-product.ts index 905dc34..7811f83 100644 --- a/src/fetch-product.ts +++ b/src/fetch-product.ts @@ -4,7 +4,7 @@ import { UsageError } from "./args.ts"; import { alreadyHave, downloadTo, safeFileName } from "./download.ts"; import type { Store } from "./store.ts"; import { type FileOutcome, placeLinks, transfer } from "./transfer.ts"; -import type { DownloadLinks, Edition } from "./types.ts"; +import type { DownloadLinks, Edition, Library } from "./types.ts"; /** * One product's files into one folder: what `kadal-store download` and the MCP server's @@ -22,8 +22,24 @@ export interface ProductRequest { /** Download even when a file with the same sha256 is already there. */ force?: boolean; concurrency?: number; + /** A recolourable product's colour, "#rrggbb" (hexColor): its SVGs come in it. */ + color?: string; } +/** + * A colour as the store's recolor.ts reads one: "#2F9E44", "2f9e44" or "#2f9" → "#2f9e44", and + * anything else null. Checked here too, so a typo is a usage error before the store is asked. + */ +export function hexColor(raw: string): string | null { + const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(raw.trim()); + const h = m?.[1]?.toLowerCase(); + return h ? `#${h.length === 3 ? [...h].map((ch) => ch + ch).join("") : h}` : null; +} + +/** Said by `download`, `sync` and download_to_folder alike, so it names no flag. */ +export const notRecolourable = (name: string) => + `${name} comes in its own colours and can't be recoloured; leave the colour out. Only recolourable products (the Illustrations shelf) take one.`; + export interface ProductReport { slug: string; dir: string; @@ -43,7 +59,15 @@ export async function fetchProduct( req: ProductRequest, o: { fetch?: typeof fetch; log?: (line: string) => void } = {}, ): Promise { - const args: Record = { slug: req.slug }; + // A colour needs a recolourable product, and its SVG links come back under coloured names + // (hero-2f9e44.svg): the library says whether it is one, and what its files are called. + const owned = req.color + ? (await store.call("list_library")).items.find((i) => i.product.slug === req.slug) + : undefined; + if (owned && !owned.recolor) throw new UsageError(notRecolourable(owned.product.name)); + // Every ask for links carries the colour, or a renewed link would bring the file as drawn. + const tint = req.color ? { color: req.color } : {}; + const args: Record = { slug: req.slug, ...tint }; if (req.fileIds?.length) args.fileIds = req.fileIds; if (req.edition) args.edition = req.edition; if (req.zip) args.zip = true; @@ -52,7 +76,8 @@ export async function fetchProduct( if (req.zip) { if (!got.zip) throw new UsageError(`${req.slug} has no zip; download its files instead (leave out --zip).`); - const path = join(req.dir, `${safeFileName(req.slug)}.zip`); + const name = `${safeFileName(req.slug)}${req.color ? `-${req.color.slice(1)}` : ""}.zip`; + const path = join(req.dir, name); // The zip is built on request, so the store has no checksum for it; the bytes are the bytes. const z = await downloadTo(got.zip.url, path, {}, o.fetch); o.log?.(` ✓ ${path}`); @@ -68,7 +93,11 @@ export async function fetchProduct( let links = got.links; if (req.fileNames?.length) { const want = new Map(req.fileNames.map((n) => [n.toLowerCase(), n])); - links = links.filter((l) => want.delete(l.name.toLowerCase())); + // People type a file's own name, which a recoloured SVG's link no longer carries. + const own = new Map(owned?.files.map((f) => [f.id, f.name.toLowerCase()])); + links = links.filter( + (l) => want.delete(l.name.toLowerCase()) || want.delete(own.get(l.fileId) ?? ""), + ); if (want.size) throw new UsageError( `No file named ${[...want.values()].map((n) => `"${n}"`).join(", ")} in ${req.slug}${req.edition ? " (in that edition)" : ""}. Its files: ${got.links.map((l) => l.name).join(", ") || "none"}`, @@ -89,7 +118,7 @@ export async function fetchProduct( const fetched = await transfer( todo, - (slug, fileIds) => store.call("get_download_links", { slug, fileIds }), + (slug, fileIds) => store.call("get_download_links", { slug, fileIds, ...tint }), { concurrency: req.concurrency, fetch: o.fetch, diff --git a/src/index.ts b/src/index.ts index f5c6038..fa98e7e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -55,15 +55,19 @@ export const HELP = `kadal-store [options] --file … only those files -o, --out where they go --year 2027 --week sun|mon --lang en|ja|en-ja --size a4|a5|letter… one edition --zip the whole product as one zip --force download files that are already here + --color a recolourable product's SVGs in that colour, e.g. 2f9e44 (quote a + leading #: "#2f9e44"); saved as -2f9e44.svg --concurrency (4). Every file is checked against its sha256 before it is kept; an interrupted download picks up where it stopped sync sync [dir] every file you own into dir (default ./kadal-store), one folder per product; files whose sha256 already matches are skipped, nothing is deleted --product … only those --year --week --lang --size one edition + --color the recolourable products' SVGs in that colour; the rest as drawn --dry-run say what would come down --concurrency (4) buy buy … a link to a page where you review the items and pay; nothing is charged until you pay in the checkout there --open open it in your browser - tiers: standard (default), personal, commercial (see the licence in show) + without a tier, each item comes with the cheapest licence on sale; or name one: + standard, personal, commercial (see the licence in show) report report --kind mistake|question|idea "what is wrong" tell Kadal about a problem in a product --file --page (PDF) | --at (audio, video) Use - instead of the words to read them from stdin @@ -137,12 +141,14 @@ export const COMMAND_FLAGS: Record = { out: { kind: "string", short: "o" }, zip: { kind: "boolean" }, force: { kind: "boolean" }, + color: { kind: "string" }, concurrency: { kind: "number" }, ...EDITION_FLAGS, }, sync: { product: { kind: "string", multiple: true }, "dry-run": { kind: "boolean" }, + color: { kind: "string" }, concurrency: { kind: "number" }, ...EDITION_FLAGS, }, diff --git a/src/mcp.ts b/src/mcp.ts index 2571508..afef79b 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -25,7 +25,7 @@ import { z } from "zod"; import { loadSession } from "./config.ts"; import { safeFileName } from "./download.ts"; -import { fetchProduct } from "./fetch-product.ts"; +import { fetchProduct, hexColor } from "./fetch-product.ts"; import { AuthError, hostLabel } from "./host.ts"; import { Auth } from "./session.ts"; import { Store } from "./store.ts"; @@ -56,6 +56,11 @@ const edition = z .describe( "Narrow a product sold in editions (planners, calendars) to one. Leave an axis out to keep all of it.", ); +const color = z + .string() + .describe( + 'Recolourable products only (get_product\'s recolor is not null; the Illustrations shelf): the accent colour their SVGs come in, as hex, e.g. "#2f9e44" (the brand colour of the project). Leave it out for the files as drawn.', + ); const SIGNED_OUT_HINT = "Ask the person to run `npx -y @kadal/store login` in a terminal (it opens their browser to approve), then try again. Do not try to sign in yourself."; @@ -211,7 +216,7 @@ export function createServer(o: McpOptions): { { title: "What the person owns", description: - "Every product the person owns: the product card, their tier, its files (id, name, bytes, sha256, edition), whether a zip is available, and the latest update. File ids go to download_to_folder or get_download_links.", + "Every product the person owns: the product card, their tier, its files (id, name, bytes, sha256, edition), whether a zip is available, whether it is recolourable (recolor: the colour it is drawn in and the one they last chose), and the latest update. File ids go to download_to_folder or get_download_links.", inputSchema: {}, annotations: READ, }, @@ -223,7 +228,7 @@ export function createServer(o: McpOptions): { { title: "Download links", description: - "Download URLs for files the person owns, each with its name, size and sha256, valid for 10 minutes; no cookie needed (curl -L works). Narrow with fileIds or an edition; zip: true adds one link for the whole product. To put files into the project, download_to_folder does the download and the checksum for you.", + "Download URLs for files the person owns, each with its name, size and sha256, valid for 10 minutes; no cookie needed (curl -L works). Narrow with fileIds or an edition; zip: true adds one link for the whole product; color recolours a recolourable product's SVGs (their names become -.svg and their sha256 is the recoloured file's). To put files into the project, download_to_folder does the download and the checksum for you.", inputSchema: { slug: z.string(), fileIds: z @@ -232,6 +237,7 @@ export function createServer(o: McpOptions): { .describe("Only these files (ids from list_library)."), edition: edition.optional(), zip: z.boolean().optional().describe("Also a link to the whole product as one zip."), + color: color.optional(), }, annotations: READ, }, @@ -252,7 +258,7 @@ export function createServer(o: McpOptions): { tier: tier .optional() .describe( - "standard (default), personal or commercial: see the licence in get_product.", + "Leave it out for the cheapest licence on sale, or name standard, personal or commercial: see the licence in get_product.", ), }), ) @@ -353,7 +359,7 @@ export function createServer(o: McpOptions): { { title: "Download into the project", description: - "Download files the person owns into the project, each checked against its sha256; files already there with the same checksum are skipped. dir is relative to the project (default kadal-store/). Narrow with fileNames or fileIds (from list_library) or an edition, or zip: true for the whole product as one zip. Returns where every file went.", + "Download files the person owns into the project, each checked against its sha256; files already there with the same checksum are skipped. dir is relative to the project (default kadal-store/). Narrow with fileNames or fileIds (from list_library) or an edition, or zip: true for the whole product as one zip. color puts a recolourable product's SVGs in that colour (saved as -.svg). Returns where every file went.", inputSchema: { slug: z.string(), dir: z @@ -366,6 +372,7 @@ export function createServer(o: McpOptions): { fileIds: z.array(z.string()).optional().describe("Only these files, by id."), edition: edition.optional(), zip: z.boolean().optional().describe("The whole product as one zip instead of its files."), + color: color.optional(), overwrite: z .boolean() .optional() @@ -385,10 +392,13 @@ export function createServer(o: McpOptions): { fileIds?: string[]; edition?: Record; zip?: boolean; + color?: string; overwrite?: boolean; }) => { const target = place(a.dir, `kadal-store/${safeFileName(a.slug)}`); if (typeof target !== "string") return target; + const hex = a.color === undefined ? undefined : hexColor(a.color); + if (hex === null) return fail(`“${a.color}” isn't a colour. Send it as hex, e.g. "#2f9e44".`); try { const r = await fetchProduct( store, @@ -400,6 +410,7 @@ export function createServer(o: McpOptions): { edition: a.edition, zip: a.zip, force: a.overwrite, + color: hex, }, { fetch: o.fetch, log: (line) => console.error(line) }, ); diff --git a/src/render.ts b/src/render.ts index 20aa109..e8a4c03 100644 --- a/src/render.ts +++ b/src/render.ts @@ -83,6 +83,11 @@ export function productText(p: ProductDetail): string[] { } if (p.files.length > 40) out.push(` … and ${p.files.length - 40} more`); } + if (p.recolor) + out.push( + "", + `Recolourable: its SVGs are drawn in ${p.recolor.base}; download or sync with --color for your own.`, + ); if (p.contents.length) out.push("", "In this pack:", ...cardLines(p.contents).map((l) => ` ${l}`)); if (p.inPacks.length) out.push("", "Also in:", ...cardLines(p.inPacks).map((l) => ` ${l}`)); diff --git a/src/transfer.ts b/src/transfer.ts index f07ca1a..b0f5d85 100644 --- a/src/transfer.ts +++ b/src/transfer.ts @@ -50,10 +50,13 @@ export async function planSync( { edition, only, + links, hash = sha256File, }: { edition?: Edition; only?: string[]; + /** Links already asked for, per product slug: theirs are the names and sha256s that count. */ + links?: Map; hash?: (path: string) => Promise; } = {}, ): Promise { @@ -63,20 +66,23 @@ export async function planSync( if (only?.length && !only.includes(slug)) continue; const folder = join(dir, safeFileName(slug)); const used = new Set(); + const linked = new Map(links?.get(slug)?.map((l) => [l.fileId, l])); for (const f of item.files) { if (!matchesEdition(f.edition, edition)) continue; - let name = safeFileName(f.name); + // A recoloured SVG arrives as hero-2f9e44.svg with the recoloured file's sha256. + const got = linked.get(f.id) ?? f; + let name = safeFileName(got.name); if (used.has(name.toLowerCase())) name = `${safeFileName(f.id)}-${name}`; used.add(name.toLowerCase()); const planned: Planned = { slug, fileId: f.id, - name: f.name, - bytes: f.bytes, - sha256: f.sha256, + name: got.name, + bytes: got.bytes, + sha256: got.sha256, path: join(folder, name), }; - ((await alreadyHave(planned.path, f, hash)) ? plan.skip : plan.download).push(planned); + ((await alreadyHave(planned.path, got, hash)) ? plan.skip : plan.download).push(planned); } } return plan; diff --git a/src/types.ts b/src/types.ts index 1323a7d..2b8a397 100644 --- a/src/types.ts +++ b/src/types.ts @@ -77,6 +77,8 @@ export interface ProductDetail extends ProductCard { inPacks: ProductCard[]; licence: { model: string; tiers: LicenceTier[] }; updates: { summary: string; at: string; reports: number }[]; + /** Recolourable: its SVGs come in any colour (get_download_links' `color`); base is as drawn. */ + recolor: { base: string } | null; } export interface Recommendations { @@ -97,6 +99,8 @@ export interface LibraryItem { tier: Tier; files: LibraryFile[]; zipAvailable: boolean; + /** Recolourable: the colour it is drawn in, and the one the person last chose in their library. */ + recolor: { base: string; color: string } | null; updatedAt: string; lastUpdate: { summary: string; at: string } | null; } diff --git a/test/args.test.ts b/test/args.test.ts index 6715068..acfc3cf 100644 --- a/test/args.test.ts +++ b/test/args.test.ts @@ -1,8 +1,9 @@ import { describe, expect, test } from "bun:test"; import { UsageError, parseArgs } from "../src/args.ts"; -import { buyItems, reportArgs, searchArgs } from "../src/commands.ts"; -import { COMMAND_FLAGS, commandHelp } from "../src/index.ts"; +import { buyItems, reportArgs, searchAgain, searchArgs } from "../src/commands.ts"; +import { hexColor } from "../src/fetch-product.ts"; +import { COMMAND_FLAGS, HELP, commandHelp } from "../src/index.ts"; import { cli, tempDir } from "./helpers.ts"; const parse = (command: string, argv: string[]) => @@ -31,6 +32,30 @@ describe("flags", () => { }); }); + test("search: the command for the next page sends the same search", () => { + const { flags, positionals } = parse("search", [ + "kid's", + "planner", + "--shelf", + "printables", + "--max", + "4.99", + "--sort", + "price", + ]); + expect(searchAgain(searchArgs({ flags, args: positionals }), "http://localhost:8861")).toBe( + "kadal-store search 'kid'\\''s' planner --shelf printables --sort price --max 4.99 --host http://localhost:8861", + ); + expect(searchAgain({})).toBe("kadal-store search"); + }); + + test("--color: hex as the store reads it, or nothing", () => { + expect(hexColor("2F9E44")).toBe("#2f9e44"); + expect(hexColor("#2f9")).toBe("#22ff99"); + expect(hexColor(" #2f9e44 ")).toBe("#2f9e44"); + for (const bad of ["green", "#2f9e4", "2f9e44ff", "#", ""]) expect(hexColor(bad)).toBeNull(); + }); + test("search: bad values are usage errors, not requests the store refuses", () => { const run = (argv: string[]) => { const { flags, positionals } = parse("search", argv); @@ -144,6 +169,10 @@ describe("main", () => { expect(help.out).toContain("--concurrency"); expect(help.out).not.toContain("recommend [words"); expect(commandHelp("buy")).toContain("nothing is"); + // Without a tier the store's quote() takes the cheapest price on sale, whatever its name. + expect(commandHelp("buy")).toContain("the cheapest licence on sale"); + expect(HELP).not.toContain("standard (default)"); + expect(commandHelp("sync")).toContain("--color "); expect((await run(["--version", "--json"])).json()).toEqual({ version: expect.any(String) }); }); diff --git a/test/fake-store.ts b/test/fake-store.ts index 6659e8e..ced573a 100644 --- a/test/fake-store.ts +++ b/test/fake-store.ts @@ -53,10 +53,27 @@ interface FakeProduct { tags: { style: string[]; topic: string[]; format: string[] }; owned: "standard" | "personal" | "commercial" | null; files: FakeFile[]; + /** Recolourable: the colour its SVGs are drawn in (docs/recolor.md's base). */ + recolor?: string; } const bytesOf = (text: string, n = 1): Uint8Array => new TextEncoder().encode(text.repeat(n)); +/** The store's parseHex (src/recolor.ts): "#ABC", "abc", "#aabbcc" → "#aabbcc"; else null. */ +const parseHex = (raw: string) => { + const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(raw.trim()); + const h = m?.[1]?.toLowerCase(); + return h ? `#${h.length === 3 ? [...h].map((c) => c + c).join("") : h}` : null; +}; +/** + * A stand-in for the store's recolorBytes: the base placeholder becomes the colour. Like the real + * one it keeps the length, and only the bytes (so the sha256) change. + */ +const recolor = (bytes: Uint8Array, base: string, color: string) => + new TextEncoder().encode(new TextDecoder().decode(bytes).replaceAll(base, color)); +const coloredName = (name: string, hex: string) => name.replace(/(\.svg)$/i, `-${hex.slice(1)}$1`); +const isSvg = (name: string) => name.toLowerCase().endsWith(".svg"); + export function fixtures(): FakeProduct[] { return [ { @@ -106,6 +123,28 @@ export function fixtures(): FakeProduct[] { owned: null, files: [], }, + { + slug: "desk-scenes", + name: "Desk scenes", + kind: "asset", + shelf: { slug: "illustrations", name: "Illustrations" }, + cents: 1500, + tags: { style: ["flat"], topic: ["work"], format: ["png", "svg"] }, + // Not owned until a test buys it, so the library and sync tests above stay as they are. + owned: null, + recolor: "#5b4ce6", + files: [ + { + id: "f_hero", + name: "hero.svg", + bytes: bytesOf( + '\n', + ), + edition: null, + }, + { id: "f_hero_png", name: "hero.png", bytes: bytesOf("PNG hero ", 40), edition: null }, + ], + }, ]; } @@ -150,7 +189,7 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { >(); const access = new Map(); const refresh = new Map(); - const dl = new Map(); + const dl = new Map(); let origin = ""; let n = 0; @@ -215,6 +254,8 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { { query: z.string().optional(), shelf: z.string().optional(), + format: z.string().optional(), + kind: z.string().optional(), maxCents: z.number().optional(), limit: z.number().optional(), cursor: z.string().optional(), @@ -232,9 +273,19 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { .includes(w), )) && (!a.shelf || p.shelf.slug === a.shelf) && + (!a.format || p.tags.format.includes(String(a.format))) && + (!a.kind || p.kind === a.kind) && (a.maxCents === undefined || p.cents <= Number(a.maxCents)), ); - return json({ items: hits.map(card), nextCursor: null, total: hits.length }); + // Pages like the store's: the cursor is an offset into the same filtered list. + const from = Number(a.cursor ?? 0); + const limit = Number(a.limit ?? 20); + const next = from + limit < hits.length ? String(from + limit) : null; + return json({ + items: hits.slice(from, from + limit).map(card), + nextCursor: next, + total: hits.length, + }); }, ); tool("get_product", { slug: z.string() }, (a) => { @@ -260,6 +311,7 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { ], }, updates: [], + recolor: p.recolor ? { base: p.recolor } : null, }, }); }); @@ -295,6 +347,7 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { edition: f.edition, })), zipAvailable: true, + recolor: p.recolor ? { base: p.recolor, color: p.recolor } : null, updatedAt: "2026-11-01T00:00:00.000Z", lastUpdate: null, })), @@ -314,12 +367,22 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { }) .optional(), zip: z.boolean().optional(), + color: z.string().optional(), }, (a) => { const p = find(String(a.slug)); + // The store's refusals (src/mcp/tools.ts downloadLinks), word for word. + let color = a.color === undefined ? null : parseHex(String(a.color)); + if (a.color !== undefined && !color) + return toolError(`“${a.color}” isn't a colour. Send six hex digits, e.g. #2f9e44.`); + if (color && !p?.recolor) + return toolError( + `${p?.name ?? a.slug} comes in its own colours only; leave color out. get_product's recolor says which products take one.`, + ); if (!p?.owned) return toolError(`You don't own ${a.slug}.`); + if (color === p.recolor) color = null; calls.push( - `links:${p.slug}:${(a.fileIds as string[] | undefined)?.join(",") ?? "*"}${a.edition ? `:${JSON.stringify(a.edition)}` : ""}`, + `links:${p.slug}:${(a.fileIds as string[] | undefined)?.join(",") ?? "*"}${a.edition ? `:${JSON.stringify(a.edition)}` : ""}${color ? `:${color}` : ""}`, ); const ed = a.edition as Record | undefined; const ids = a.fileIds as string[] | undefined; @@ -334,12 +397,13 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { const exp = Date.now() + 600_000; const links = files.map((f) => { const t = b64url(randomBytes(9)); - dl.set(t, { fileId: f.id, exp }); + const tint = color && isSvg(f.name) ? color : undefined; + dl.set(t, { fileId: f.id, exp, color: tint }); return { fileId: f.id, - name: f.name, + name: tint ? coloredName(f.name, tint) : f.name, bytes: f.bytes.length, - sha256: sha(f.bytes), + sha256: sha(tint ? recolor(f.bytes, p.recolor!, tint) : f.bytes), url: `${origin}/dl/${t}`, expiresAt: new Date(exp).toISOString(), }; @@ -347,7 +411,7 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { let zip = null; if (a.zip) { const t = b64url(randomBytes(9)); - dl.set(t, { slug: p.slug, exp }); + dl.set(t, { slug: p.slug, exp, color: color ?? undefined }); zip = { url: `${origin}/dl/${t}`, expiresAt: new Date(exp).toISOString() }; } return json({ links, zip }); @@ -613,9 +677,11 @@ export function startFakeStore(opts: FakeOptions = {}): FakeStore { calls.push(`dl:zip:${t.slug}`); return new Response(bytesOf(`PK zip of ${t.slug} `, 100)); } - const file = products.flatMap((p) => p.files).find((f) => f.id === t.fileId)!; + const product = products.find((p) => p.files.some((f) => f.id === t.fileId))!; + const file = product.files.find((f) => f.id === t.fileId)!; if (expireOnce.delete(file.id)) return new Response("expired", { status: 403 }); - let body = corrupt.has(file.id) ? bytesOf("x", file.bytes.length) : file.bytes; + const bytes = t.color ? recolor(file.bytes, product.recolor!, t.color) : file.bytes; + let body = corrupt.has(file.id) ? bytesOf("x", bytes.length) : bytes; const range = /^bytes=(\d+)-$/.exec(req.headers.get("range") ?? ""); calls.push(`dl:${file.id}${range ? `@${range[1]}` : ""}`); if (cutOnce.delete(file.id)) { diff --git a/test/integration.test.ts b/test/integration.test.ts index e18f479..b7e74a2 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -277,6 +277,19 @@ describe("search, recommend, report, notes", () => { expect(t.out).toContain("Buy: kadal-store buy fern-pack"); }); + test("search: the More: line is the same search, one page on", async () => { + const first = await run(["search", "--format", "png", "--limit", "1", ...h()]); + expect(first.out).toContain("Fern textures pack"); + expect(first.out).toContain("1 of 2."); + const more = /^More: kadal-store (.+)$/m.exec(first.out)![1]!; + expect(more).toBe(`search --format png --limit 1 --host ${store.url} --cursor 1`); + // Run as printed: the next PNG, not page two of everything. + const next = await run(more.split(" ")); + expect(next.out).toContain("Desk scenes"); + expect(next.out).not.toMatch(/Retro UI|Techo/); + expect(next.out).not.toContain("More:"); + }); + test("recommend --from: the summary is shown on stderr, sent only with --yes", async () => { const project = join(work, "game"); mkdirSync(project, { recursive: true }); @@ -343,6 +356,141 @@ describe("search, recommend, report, notes", () => { }); }); +describe("--color: recolourable illustrations", () => { + const scenes = () => store.products.find((p) => p.slug === "desk-scenes")!; + const drawn = () => new TextDecoder().decode(fileBytes("f_hero")); + beforeAll(() => { + scenes().owned = "standard"; + }); + afterAll(() => { + scenes().owned = null; + }); + + test("download: the SVGs in that colour, checked against the store's sha256 for them", async () => { + const dir = join(work, "brand"); + const r = await run([ + "download", + "desk-scenes", + "--color", + "2F9E44", + "-o", + dir, + ...h(), + "--json", + ]); + expect(r.code).toBe(0); + expect(store.calls).toContain("links:desk-scenes:*:#2f9e44"); + expect(readdirSync(dir).sort()).toEqual(["hero-2f9e44.svg", "hero.png"]); + const svg = readFileSync(join(dir, "hero-2f9e44.svg"), "utf8"); + expect(svg).toBe(drawn().replace("#5b4ce6", "#2f9e44")); + expect(readFileSync(join(dir, "hero.png"))).toEqual(Buffer.from(fileBytes("f_hero_png"))); + const files = r.json<{ files: { name: string; sha256: string }[] }>().files; + expect(files.find((f) => f.name === "hero-2f9e44.svg")!.sha256).toBe(sha(svg)); + + // Again: the recoloured file on disk matches, so nothing comes down. + store.calls.length = 0; + const again = await run([ + "download", + "desk-scenes", + "--color", + "#2f9e44", + "-o", + dir, + ...h(), + "--json", + ]); + expect(again.json<{ counts: Record }>().counts).toMatchObject({ + downloaded: 0, + skipped: 2, + }); + expect(store.calls.filter((c) => c.startsWith("dl:"))).toEqual([]); + }); + + test("download: --file takes the file's own name, and a renewed link keeps the colour", async () => { + const dir = join(work, "brand-one"); + store.expireOnce.add("f_hero"); + const r = await run([ + "download", + "desk-scenes", + "--color", + "f76707", + "--file", + "hero.svg", + "-o", + dir, + ...h(), + ]); + expect(r.code).toBe(0); + expect(store.calls).toContain("links:desk-scenes:f_hero:#f76707"); + expect(readFileSync(join(dir, "hero-f76707.svg"), "utf8")).toBe( + drawn().replace("#5b4ce6", "#f76707"), + ); + }); + + test("download --zip in a colour is named for it", async () => { + const r = await run([ + "download", + "desk-scenes", + "--zip", + "--color", + "2f9e44", + "-o", + "zips", + ...h(), + "--json", + ]); + expect(r.json<{ zip: { path: string } }>().zip.path).toBe( + join(work, "zips", "desk-scenes-2f9e44.zip"), + ); + }); + + test("refused: not a colour (before asking the store), or a product that can't take one", async () => { + store.calls.length = 0; + const bad = await run(["download", "desk-scenes", "--color", "green", ...h()]); + expect(bad.code).toBe(2); + expect(bad.err).toContain('--color takes a hex colour, like 2f9e44 or "#2f9e44" (got "green")'); + expect(store.calls).toEqual([]); + const plain = await run(["download", "retro-ui-sfx", "--color", "2f9e44", ...h()]); + expect(plain.code).toBe(2); + expect(plain.err).toContain( + "Retro UI sound effects comes in its own colours and can't be recoloured; leave the colour out.", + ); + const named = await run([ + "sync", + join(work, "x"), + "--product", + "retro-ui-sfx", + "--color", + "2f9e44", + ...h(), + ]); + expect(named.code).toBe(2); + expect(named.err).toContain("Retro UI sound effects comes in its own colours"); + }); + + test("sync: the recolourable products in the colour, the rest as drawn; then all skipped", async () => { + const dir = join(work, "mirror-brand"); + const first = await run(["sync", dir, "--color", "2f9e44", ...h()]); + expect(first.code).toBe(0); + expect(first.out).toContain("3 products (1 in #2f9e44) · 0 files already in"); + expect(readdirSync(join(dir, "desk-scenes")).sort()).toEqual(["hero-2f9e44.svg", "hero.png"]); + expect(readdirSync(join(dir, "retro-ui-sfx")).sort()).toEqual(["beep.wav", "click.wav"]); + store.calls.length = 0; + const second = await run(["sync", dir, "--color", "2f9e44", ...h(), "--json"]); + expect(second.json<{ counts: Record }>().counts).toEqual({ + downloaded: 0, + skipped: 7, + failed: 0, + }); + expect(store.calls.filter((c) => c.startsWith("dl:"))).toEqual([]); + }); + + test("show says a product is recolourable", async () => { + const t = await run(["show", "desk-scenes", ...h()]); + expect(t.out).toContain("Recolourable: its SVGs are drawn in #5b4ce6"); + }); +}); + describe("kadal-store mcp", () => { let client: Client; let close: () => Promise; @@ -419,6 +567,38 @@ describe("kadal-store mcp", () => { expect(out.content[0]!.text).toContain("outside the project"); }); + test("download_to_folder and get_download_links take a colour", async () => { + const scenes = store.products.find((p) => p.slug === "desk-scenes")!; + scenes.owned = "standard"; + try { + const r = (await client.callTool({ + name: "download_to_folder", + arguments: { slug: "desk-scenes", dir: "art", color: "#2f9e44" }, + })) as { isError?: boolean; content: { text: string }[] }; + expect(r.isError).toBeUndefined(); + expect(readdirSync(join(project, "art")).sort()).toEqual(["hero-2f9e44.svg", "hero.png"]); + const links = (await client.callTool({ + name: "get_download_links", + arguments: { slug: "desk-scenes", color: "2f9e44" }, + })) as { structuredContent: { links: { name: string }[] } }; + expect(links.structuredContent.links.map((l) => l.name)).toContain("hero-2f9e44.svg"); + const bad = (await client.callTool({ + name: "download_to_folder", + arguments: { slug: "desk-scenes", color: "teal" }, + })) as { isError: boolean; content: { text: string }[] }; + expect(bad.isError).toBe(true); + expect(bad.content[0]!.text).toBe(`“teal” isn't a colour. Send it as hex, e.g. "#2f9e44".`); + const plain = (await client.callTool({ + name: "download_to_folder", + arguments: { slug: "retro-ui-sfx", color: "#2f9e44" }, + })) as { isError: boolean; content: { text: string }[] }; + expect(plain.isError).toBe(true); + expect(plain.content[0]!.text).toContain("comes in its own colours and can't be recoloured"); + } finally { + scenes.owned = null; + } + }); + test("project_summary", async () => { writeFileSync( join(project, "package.json"), diff --git a/test/render.test.ts b/test/render.test.ts new file mode 100644 index 0000000..092618e --- /dev/null +++ b/test/render.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from "bun:test"; + +import { buyText } from "../src/render.ts"; +import type { BuyLink } from "../src/types.ts"; + +const link = (note: string): BuyLink => ({ + url: "https://store.kadal.cc/buy?items=soft-ui-sounds&ref=cli", + items: [ + { slug: "soft-ui-sounds", name: "Soft UI Sounds", tier: "personal", cents: 900, owned: false }, + ], + totalCents: 900, + note, +}); +const charged = (lines: string[]) => lines.join("\n").match(/nothing is charged/gi) ?? []; + +describe("buy: nothing is charged, said once", () => { + test("the store's note, said to you, is the one line", () => { + const note = + "Open the link to review and pay. Nothing is charged until you pay on that page, and you can change a licence or remove anything there."; + const out = buyText(link(note)); + expect(out.at(-1)).toBe(note); + expect(charged(out)).toHaveLength(1); + }); + + test("an older store's note, written for an agent, is still not doubled", () => { + const note = + "Open the link to review and pay. Nothing is charged until the person pays in Paddle's checkout, and they can change a licence or remove anything there."; + const out = buyText(link(note)); + expect(out.at(-1)).toBe(note); + expect(charged(out)).toHaveLength(1); + }); + + test("a note that doesn't say it gets the CLI's line", () => { + const out = buyText(link("Already owned, so not charged: soft-ui-sounds.")); + expect(out.slice(-2)).toEqual([ + "Already owned, so not charged: soft-ui-sounds.", + "Nothing is charged until you pay in the checkout on that page.", + ]); + expect(charged(buyText(link("")))).toHaveLength(1); + }); +});