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
10 changes: 10 additions & 0 deletions .changeset/notes-and-color.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"@kadal/store": patch
---

`download` and `sync` take `--color <hex>` 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 `<name>-<rrggbb>.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.
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <slug>` (repeatable), the edition flags, and `--dry-run` to see what would come down.
- Recolourable illustrations (`show <slug>` says "Recolourable") come in any colour:
`--color <hex>` on `download` or `sync`, such as `--color 2f9e44`, saves each SVG in that colour
as `<name>-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 <n>`).
Expand All @@ -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 <slug[:tier]>…` 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.

<p align="center">
Expand Down Expand Up @@ -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 <path>` serves another folder as the project. Every tool needs the
`store:read` scope except `report_problem`, which needs `store:write`. The store's
Expand Down
8 changes: 7 additions & 1 deletion skills/kadal-store/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ browser to approve. Never try to sign in, enter credentials, or approve anything
it if it repeats.
- `kadal-store sync <dir>` 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 `<name>-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
Expand All @@ -58,7 +63,8 @@ browser to approve. Never try to sign in, enter credentials, or approve anything
`kadal-store buy <slug>[: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
Expand Down
84 changes: 78 additions & 6 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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,
Expand Down Expand Up @@ -218,11 +225,33 @@ export function searchArgs(c: Pick<Ctx, "flags" | "args">): Record<string, unkno
});
}

/** A word as a shell takes it back: bare when it is safe, else in single quotes. */
const shellWord = (w: string) =>
/^[\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<string, unknown>, 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<number> {
const args = searchArgs(c);
const r = await withStore(c, (s) => s.call<SearchResult>("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;
}

Expand Down Expand Up @@ -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)
Expand All @@ -316,6 +355,7 @@ export async function downloadCommand(c: Ctx): Promise<number> {
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(
Expand All @@ -328,6 +368,7 @@ export async function downloadCommand(c: Ctx): Promise<number> {
zip,
force: c.flags.force === true,
concurrency: concurrencyOf(c),
color,
},
{ fetch: c.rt.fetch, log: progress(c) },
),
Expand All @@ -348,19 +389,50 @@ export async function syncCommand(c: Ctx): Promise<number> {
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<Library>("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<string, DownloadLink[]>();
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<DownloadLinks>("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<DownloadLinks>("get_download_links", { slug, fileIds }),
{ concurrency: concurrencyOf(c), fetch: c.rt.fetch, log: progress(c) },
(slug, fileIds) =>
s.call<DownloadLinks>("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];
});
Expand Down
39 changes: 34 additions & 5 deletions src/fetch-product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -43,7 +59,15 @@ export async function fetchProduct(
req: ProductRequest,
o: { fetch?: typeof fetch; log?: (line: string) => void } = {},
): Promise<ProductReport> {
const args: Record<string, unknown> = { 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<Library>("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<string, unknown> = { 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;
Expand All @@ -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}`);
Expand All @@ -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"}`,
Expand All @@ -89,7 +118,7 @@ export async function fetchProduct(

const fetched = await transfer(
todo,
(slug, fileIds) => store.call<DownloadLinks>("get_download_links", { slug, fileIds }),
(slug, fileIds) => store.call<DownloadLinks>("get_download_links", { slug, fileIds, ...tint }),
{
concurrency: req.concurrency,
fetch: o.fetch,
Expand Down
8 changes: 7 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,19 @@ export const HELP = `kadal-store <command> [options]
--file <name>… only those files -o, --out <dir> 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 <hex> a recolourable product's SVGs in that colour, e.g. 2f9e44 (quote a
leading #: "#2f9e44"); saved as <name>-2f9e44.svg
--concurrency <n> (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 <slug>… only those --year --week --lang --size one edition
--color <hex> the recolourable products' SVGs in that colour; the rest as drawn
--dry-run say what would come down --concurrency <n> (4)
buy buy <slug[:tier]>… 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 <slug> --kind mistake|question|idea "what is wrong" tell Kadal about a
problem in a product --file <name> --page <n> (PDF) | --at <seconds> (audio, video)
Use - instead of the words to read them from stdin
Expand Down Expand Up @@ -137,12 +141,14 @@ export const COMMAND_FLAGS: Record<string, FlagSpecs> = {
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,
},
Expand Down
Loading
Loading