Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c437ec2f1 | ||
|
|
9db91b1b9c | ||
|
|
ed7d662d56 | ||
|
|
b717ccaedf | ||
|
|
eb15a05668 | ||
|
|
7091a4653f | ||
|
|
da6c3f02ce | ||
|
|
1177fc86b6 | ||
|
|
6348422012 |
No files matched your search
+6
-11
@@ -1,12 +1,7 @@
|
||||
# local working artifacts
|
||||
.node_modules
|
||||
.zig-cache/
|
||||
zig-out/
|
||||
zig-pkg/
|
||||
.dfx/
|
||||
node_modules/
|
||||
.dev.vars
|
||||
.env
|
||||
.dev.vars*
|
||||
dist/
|
||||
.astro/
|
||||
.wrangler/
|
||||
worker-configuration.d.ts
|
||||
emdash-env.d.ts# diigo exports: personal data
|
||||
export/
|
||||
.icp/
|
||||
*.key
|
||||
@@ -1,50 +0,0 @@
|
||||
# capsite working rules
|
||||
|
||||
Applies to AI agents working in `capsite/` (goal tree + how-to-run:
|
||||
[capsite-checklist.md](capsite-checklist.md); background:
|
||||
[the capsite notes](capsite-notes.md); workspace-wide policy:
|
||||
[AGENTS.md](../AGENTS.md) — points to the workspace skills, incl. commit trailers).
|
||||
|
||||
## Dev servers are the user's job
|
||||
|
||||
The assistant never starts, stops, or restarts long-running dev servers
|
||||
(`wrangler dev`, `pnpm dev`/`astro dev`). The user runs them and owns the
|
||||
terminals; the assistant observes via `.tmp/capsite.script` (the `script`
|
||||
capture; use `watchme`). One-shot codegen (`wrangler types`), linters,
|
||||
typechecks, and tests are fine.
|
||||
|
||||
## Durable state: be LOUD and conservative about breaking changes
|
||||
|
||||
Persistence is a big deal here: DO ids (cache ids, webapp ids, public
|
||||
ids) are headed toward representing real-world assets. A change that
|
||||
leaves existing stored state unreadable, unreachable, or differently
|
||||
interpreted is a **breaking change**, even in dev.
|
||||
|
||||
- **Before** making it, say so, prominently: what stored state breaks,
|
||||
why, and the options (migrate, stay compatible, or reset). Get the
|
||||
user's go-ahead; don't discover it after the fact.
|
||||
- Prefer compatibility: read old shapes, add fields rather than repurpose
|
||||
them, migrate in place (schema steps like `SCHEMA_V1` → `V2`).
|
||||
- No silent resets. "Wipe `.wrangler/state`" is a last resort the user
|
||||
chooses, never the default advice.
|
||||
- Cover it with a test: old-shape state in, current code reads it.
|
||||
|
||||
(Prompted 2026-10-07: making `PublicCache` fetch through its own wiring
|
||||
left public caches created by the earlier `ingest` code unwired — a 502,
|
||||
and no way back through publish.)
|
||||
|
||||
## Secrets discipline
|
||||
|
||||
Worker secrets never in source or wrangler config. `.dev.vars` (gitignored)
|
||||
locally; `wrangler secret put` deployed. Since the 1c cache evolution, no
|
||||
worker secret is needed at all: the cookie lives only in the webapp DO's
|
||||
storage; the webapp-instance id rides the cache DO's wiring; the cache id
|
||||
is a user-held capability (password manager / per-POST paste). Error
|
||||
messages must not contain header or param values (they cross RPC as
|
||||
exceptions and land in logs); URLs appear query-stripped.
|
||||
|
||||
## Keep config types generated
|
||||
|
||||
Run `wrangler types` after any wrangler.jsonc change
|
||||
(`worker-configuration.d.ts` is generated, gitignored; hand-rolled
|
||||
`cloudflare:workers` shims drift and gave red squiggles).
|
||||
@@ -0,0 +1,107 @@
|
||||
# A Counter in a canister, over OCapN
|
||||
|
||||
An Internet Computer canister hosts counters as an [OCapN](https://github.com/ocapn/ocapn) peer: a client makes one, calls `incr` and `decr` on it over CapTP, pipelined, and keeps it in a home that survives a canister upgrade. Both peers are [glowcap](https://github.com/glowcap-org/glowcap) compiled to WebAssembly; this is an exploratory prototype for [vattr97#5](https://github.com/dckc/vattr97/issues/5), canisters as vats.
|
||||
|
||||
## Getting started
|
||||
|
||||
You need [Nix](https://nixos.org/) with flakes; it supplies Zig 0.17.1 and Node.
|
||||
|
||||
```sh
|
||||
nix develop
|
||||
(cd client && npm ci --ignore-scripts)
|
||||
export DO_NOT_TRACK=1 # icp-cli reports usage by default
|
||||
icp() { npx --prefix client icp "$@"; }
|
||||
icp network start -d
|
||||
icp deploy -y counter --args "(blob \"$(head -c32 /dev/urandom | od -An -tx1 | tr -d ' \n' | sed 's/../\\&/g')\")"
|
||||
ID=$(icp canister status counter --id-only)
|
||||
node client/counter.mjs http://127.0.0.1:4960 $ID alice.key init c1
|
||||
icp canister install counter --mode upgrade -y
|
||||
node client/counter.mjs http://127.0.0.1:4960 $ID alice.key use c1 incr value
|
||||
```
|
||||
|
||||
A principal has one CapTP session at a time. Here the upgrade ended Alice's; without one, her next run needs `--abandon-all`, which ends her open session and breaks every reference and pending answer that lived only in it.
|
||||
|
||||
The output shows each update call and each answer; after the upgrade, Alice's counter picks up where it left off:
|
||||
|
||||
```
|
||||
start 329B -> 345B in 319ms
|
||||
session open
|
||||
deliver 551B -> 807B in 258ms
|
||||
incr 1
|
||||
incr 2
|
||||
decr 1
|
||||
deliver 180B -> 120B in 247ms
|
||||
kept as c1
|
||||
Canister counter installed successfully
|
||||
start 329B -> 345B in 295ms
|
||||
session open
|
||||
deliver 363B -> 538B in 261ms
|
||||
incr 2
|
||||
value 2
|
||||
```
|
||||
|
||||
With another key file, `use c1` breaks: that home is someone else's. `icp network stop` stops the local network. `zig build test` runs the same story in memory.
|
||||
|
||||
## Alice buys a widget from Bob
|
||||
|
||||
[ertp.zig](src/ertp.zig) is a small [ERTP](https://docs.agoric.com/guides/ertp/): mints, issuers, purses, payments, and a shop that sells one unit of stock for an exact price. A sale moves the payment, the proceeds, and the stock in one Loam transaction. With the network and canister from above:
|
||||
|
||||
```sh
|
||||
shop() { node client/shop.mjs http://127.0.0.1:4960 $ID "$@"; }
|
||||
shop alice.key mint # moola: 10 into Alice's wallet; issuer on the board
|
||||
shop bob.key open # widgets: 1 in stock; shop on the board at 3 moola
|
||||
shop alice.key buy --abandon-all
|
||||
shop alice.key buy --abandon-all # sold out: the payment goes back to the wallet
|
||||
icp canister install counter --mode upgrade -y
|
||||
shop alice.key balances
|
||||
shop bob.key balances
|
||||
```
|
||||
|
||||
```
|
||||
bought 1 widget into closet
|
||||
refunded 3 moola to wallet
|
||||
Error: answer 5 broke: SoldOut
|
||||
Canister counter installed successfully
|
||||
wallet 7
|
||||
closet 1
|
||||
proceeds 3
|
||||
```
|
||||
|
||||
(Update-call lines omitted. Alice's `balances` also reports `proceeds none`, and Bob's reports no wallet or closet: each home holds only its own.)
|
||||
|
||||
## Homes, not swiss numbers
|
||||
|
||||
Nodes on a canister's subnet can read its state, so a canister can't keep a swiss number secret. Authority here starts instead with the caller principal, whose signature the Internet Computer checks:
|
||||
|
||||
- `fetch("home")` answers the caller's own home, a durable store of named objects: `init(name, object)` and `get(name)`. It's made the first time the caller asks.
|
||||
- `fetch("board")` answers a home every caller shares, where Alice and Bob post issuers and the shop.
|
||||
- `fetch("makeCounter")`, `fetch("makeIssuerKit")`, and `fetch("makeShop")` answer public makers; each one's `make(...)` answers what it makes.
|
||||
- The anonymous principal is refused, since everyone who uses it would share one home.
|
||||
|
||||
Homes, counters, and the canister's CapTP identity live in a [Loam](https://github.com/glowcap-org/glowcap) store whose engine ([stable_log.zig](src/stable_log.zig)) appends each committed transaction to stable memory, the part of a canister's state that survives an upgrade; `post_upgrade` replays it. CapTP sessions live in the heap, so an upgrade ends them, and a client starts a new one and fetches its home again.
|
||||
|
||||
## One update call per round trip
|
||||
|
||||
- **The wire.** The canister's Candid interface is two update methods, `start` and `deliver`, each taking and returning a `blob` of CapTP frames in Syrup byte-string envelopes, and an install argument of 32 bytes of entropy ([counter.did](counter.did)). The OCapN locator transport is `icp`, its designator the canister's principal.
|
||||
- **Sessions.** The canister keeps one CapTP session per caller principal, so the Internet Computer's request signature is what tells sessions apart. `start` carries the caller's `op:start-session`.
|
||||
- **Pipelining.** The client sends to an answer before it settles, so the handshake is one call and making a counter plus every send to it is another: about 2.6 s on mainnet, 0.6 s on icp-cli's local network. Keeping it with `init` takes a third, since the client passes only settled references as arguments.
|
||||
- **Answer releases** (`op:gc-answer`) ride ahead of the client's next message rather than costing a call of their own.
|
||||
- **No server push.** The canister can only answer what a call delivers; promise resolutions it learns of later would need a query to poll.
|
||||
|
||||
## Testnets
|
||||
|
||||
| Where | How | Update call | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| icp-cli local network | `icp network start -d` | ~250 ms | [icp-cli](https://cli.internetcomputer.org/) 1.8 succeeds dfx; state in `.icp/` |
|
||||
| dfx local replica | `dfx start` (project-local network in [dfx.json](dfx.json)) | ~1.25 s | dfx 0.30 is deprecated; not in nixpkgs |
|
||||
| Playground (mainnet) | `dfx deploy --playground` | ~1.2 s | free; canister reclaimed after 20 min; icp-cli has no equivalent |
|
||||
| Mainnet | `icp deploy -e ic` | ~1.2 s | budget 1–2T cycles (about 1 XDR per T) per canister |
|
||||
|
||||
## Known gaps
|
||||
|
||||
- **The entropy is not secret** from the subnet's nodes, nor from whoever installs; nothing rests on it but the CapTP keys. A real deployment would draw it from `raw_rand` in a first call after install.
|
||||
- **One session per principal.** A second `start` traps until the caller's `abandonAll` or an upgrade ends the first.
|
||||
- **Not offer-safe.** A buyer hands over a payment and trusts the shop's code, which is right here because it's in the same vat; across vats this needs Zoe's escrow. The board is init-only, but anyone may post any name first.
|
||||
- **No removal or collection.** A home holds 8 names and can't drop one; spent payments keep their records; Loam garbage collection never runs.
|
||||
- **The canister pays for every call** and admits any signed caller; it should refuse strangers before doing work (`canister_inspect_message`).
|
||||
- **Third-party handoffs** need gift ids from entropy and dials to other peers; the canister refuses both.
|
||||
@@ -0,0 +1,50 @@
|
||||
const std = @import("std");
|
||||
|
||||
pub fn build(b: *std.Build) void {
|
||||
const target = b.standardTargetOptions(.{});
|
||||
const optimize = b.standardOptimizeOption(.{});
|
||||
|
||||
const glowcap = b.dependency("glowcap", .{ .target = target, .optimize = optimize });
|
||||
const test_step = b.step("test", "Run the unit tests and the in-memory client/canister round trip");
|
||||
for ([_][]const u8{ "src/pair_test.zig", "src/candid.zig", "src/principal.zig", "src/stable_log.zig" }) |root| {
|
||||
const t = b.addTest(.{ .root_module = b.createModule(.{
|
||||
.root_source_file = b.path(root),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
.imports = &.{.{ .name = "glowcap", .module = glowcap.module("glowcap") }},
|
||||
}) });
|
||||
test_step.dependOn(&b.addRunArtifact(t).step);
|
||||
}
|
||||
|
||||
// The canister: freestanding 32-bit Wasm whose only imports are `ic0`.
|
||||
const wasm32 = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding });
|
||||
const canister_glowcap = b.dependency("glowcap", .{ .target = wasm32, .optimize = .ReleaseSmall });
|
||||
const canister = b.addExecutable(.{
|
||||
.name = "counter",
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/canister.zig"),
|
||||
.target = wasm32,
|
||||
.optimize = .ReleaseSmall,
|
||||
.imports = &.{.{ .name = "glowcap", .module = canister_glowcap.module("glowcap") }},
|
||||
}),
|
||||
});
|
||||
canister.entry = .disabled;
|
||||
canister.root_module.export_symbol_names = &.{ "canister_init", "canister_post_upgrade", "canister_update start", "canister_update deliver", "canister_update abandonAll" };
|
||||
const canister_step = b.step("canister", "Build the canister to zig-out/bin/counter.wasm");
|
||||
canister_step.dependOn(&b.addInstallArtifact(canister, .{}).step);
|
||||
|
||||
// The client peer, for a JavaScript host to drive.
|
||||
const client = b.addExecutable(.{
|
||||
.name = "client",
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/client.zig"),
|
||||
.target = wasm32,
|
||||
.optimize = .ReleaseSmall,
|
||||
.imports = &.{.{ .name = "glowcap", .module = canister_glowcap.module("glowcap") }},
|
||||
}),
|
||||
});
|
||||
client.entry = .disabled;
|
||||
client.rdynamic = true;
|
||||
const client_step = b.step("client", "Build the client peer to zig-out/bin/client.wasm");
|
||||
client_step.dependOn(&b.addInstallArtifact(client, .{}).step);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
.{
|
||||
.name = .icp_ocapn_counter,
|
||||
.version = "0.0.0",
|
||||
.fingerprint = 0xe943337525286da8,
|
||||
.minimum_zig_version = "0.17.1",
|
||||
.dependencies = .{
|
||||
.glowcap = .{
|
||||
.url = "git+https://github.com/glowcap-org/glowcap#349e2f9523096a0e77916511e10b1a9a9ba87119",
|
||||
.hash = "glowcap-0.1.7-jdWOP7VktwB5muPJABefGNmsq-kOzfbNF4W3fBIykMby",
|
||||
},
|
||||
},
|
||||
.paths = .{ "build.zig", "build.zig.zon", "src" },
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
# capsite goal tree
|
||||
|
||||
Nested checkboxes form the goal tree itself: each `- [ ]` is a goal; its
|
||||
indented children are the subgoals/steps that must pass before it (an item
|
||||
is only checked when **all** its children are checked — or, for leaf
|
||||
items, when it has passed verification itself). Working notes live under
|
||||
each goal; [the capsite notes](capsite-notes.md) carry the background
|
||||
narrative.
|
||||
|
||||
- [ ] **madmode publishes a weekly roundup of diigo bookmarks**
|
||||
([#23](https://github.com/dckc/madmode-blog/issues/23)); the diigo
|
||||
session stays inside webapp, so madmode holds no credential at all
|
||||
(background: [the capsite notes](capsite-notes.md); after that,
|
||||
[bib sync #195](https://github.com/dckc/madmode-blog/issues/195))
|
||||
|
||||
- [x] Credential discipline: no worker secrets; the cookie lives only
|
||||
in webapp's DO storage, ids are held by the user
|
||||
([AGENTS.md](AGENTS.md), secrets section).
|
||||
- [x] **1. Cookie-path dump worker**: port of mm-diigo's diigo-dump.mjs
|
||||
(verified 2026-10-06: 200, `total: 1674`); evolved into 1c.
|
||||
- [x] **1b. webapp DO factory** ([webapp/README.md](webapp/README.md));
|
||||
mint verified end-to-end in dev 2026-10-07 (via 1c). Prod mint is
|
||||
goal 5.
|
||||
|
||||
- [x] **1c. diigo-dump evolves into a bookmark cache**
|
||||
([diigo-cache/README.md](diigo-cache/README.md); design in the
|
||||
JSDoc of `src/cache.ts`, `src/index.ts`, `src/pm-save.ts`):
|
||||
- [x] 1c-i. Two independent page caches, private and public
|
||||
(`PagedCache`, `DiigoCache`, `PublicCache`).
|
||||
- [x] 1c-ii. Create flow on one port: `/_connect` → `/_mint`
|
||||
→ `/_wire` (`mintPage`, `proxyMint`, `wire`).
|
||||
- [x] 1c-iii. Ids saved by explicit user action under the
|
||||
holder's petname (`pmSave`); pages show a fingerprint
|
||||
(`nick`).
|
||||
- [x] 1c-iv. Verified against live diigo in dev, 2026-10-07:
|
||||
create, dump, publish; `/public/dckc-madmode?page=4` →
|
||||
`cache: HIT`.
|
||||
- [x] 1c-v. Tests: `pnpm lint && pnpm test` (the real worker +
|
||||
DOs against [a fake webapp](diigo-cache/tests/fake-webapp.js)).
|
||||
- [x] 1c-vi. Complete: a filled cache holds everything in diigo's
|
||||
RSS export (16,744 of 16,744; differences are form only),
|
||||
2026-10-07, via `scripts/compare-export.ts`. Getting there
|
||||
found diigo's `page_num` is 0-based (schema v2 migration).
|
||||
|
||||
- [ ] **1d. Date windows and search on the public page**, toward the
|
||||
weekly PESOS roundup of [#23](https://github.com/dckc/madmode-blog/issues/23)
|
||||
(a week's permalink: `in=2026-W41`). One filter, two spellings:
|
||||
devs pass `{ days: 7, q: "#weekly" }`, URLs the same fields;
|
||||
`q` takes gmail/Slack/GitHub operators. UTC, ISO weeks, half-open
|
||||
windows; a fetch budget per request. Design: the API in
|
||||
`diigo-cache/src/query.ts` and the skipped suites in
|
||||
`tests/query.test.ts` and `tests/caches.test.ts` ("public page
|
||||
filters"); done when they're unskipped and green.
|
||||
Reconcile with 1f first: `query.ts` plans to filter while walking
|
||||
diigo's pages (binary search by `updated`), but after 1c-vi a
|
||||
filled cache holds every item, so 1d can query `items` in sqlite
|
||||
and spend diigo fetches only on a head refresh (1f). Choose
|
||||
before implementing; the skipped suites may need adjusting.
|
||||
|
||||
- [x] **1e. Fill job: a button that grabs every page** into a cache
|
||||
from the webkey page `/cache/#<key>`, which trades the key for a
|
||||
capability over Cap'n Web (`diigo-cache/src/api.ts`;
|
||||
`startFill`/`fillStatus`/`stopFill` in `src/cache.ts`;
|
||||
`tests/fill.test.ts`). `/cache/` without a key is a login form
|
||||
the password manager fills.
|
||||
|
||||
- [ ] **1f. Cached pages go stale: the head must refresh.** A page hit
|
||||
never expires, and diigo pages are updated-desc, so every new or
|
||||
edited bookmark shifts the page boundaries: this week's bookmarks
|
||||
sit on page 1, cached last week. Proposal: refetch the head
|
||||
(pages from 1 until a fetched page's items are all already stored
|
||||
with the same `updated`), upserting into `items` (already keyed by
|
||||
`item_id`); the window/search reads of 1d run over `items`, not
|
||||
over cached page numbers. A fill or a cron alarm (`ctx.storage`
|
||||
alarm in the cache DO, not in madmode) can drive it.
|
||||
**Durable state**: additive only if `pages`/`page_members` keep
|
||||
their meaning; say so before changing them (capsite AGENTS.md).
|
||||
Needs a test: an item added to the fake webapp shows up after a
|
||||
refresh. Stopgap today: "invalidate the last N days" on the
|
||||
webkey page (`invalidateRecent`), then fill.
|
||||
|
||||
- [ ] **1g. Policy: notes on public items are public too.** The public
|
||||
cache drops private *items* (`publicOnly`) but keeps public items
|
||||
whole, including annotations, comments, and sticky notes that
|
||||
diigo marks private (`pri_a_count`/`pri_c_count`/
|
||||
`pri_sticky_count`: 2,525 of 14,645 stored public items, found
|
||||
2026-10-08), and `/public/<username>` JSON serves them. **Dan
|
||||
finds this acceptable as is**; this goal is to finish thinking
|
||||
it through, not to fix a leak. Open points: does diigo.com's
|
||||
own public view hide them (so readers are surprised)? the
|
||||
`comments` array may carry *other people's* words; which fields
|
||||
does potluck quote (annotations are the best commentary: see
|
||||
[the issues sketch](potluck/issues-sketch.md))? If the policy
|
||||
changes, stripping stored rows is a durable-state migration.
|
||||
|
||||
- [ ] **2. madmode reads the public cache**: public data, so no
|
||||
capability, no cookie, no plugin sync job, no cron on madmode's
|
||||
side. madmode fetches `GET /public/dckc-madmode` with
|
||||
`Accept: application/json` (plus 1d's `in=`/`days=`/`q=`).
|
||||
- [ ] 2-i. Transport: a service binding to diigo-cache when both
|
||||
are deployed (no public hop, so no rate-limit exposure);
|
||||
in dev, a base URL (`http://localhost:8787`).
|
||||
- [ ] 2-ii. The JSON shape of the public page is a contract
|
||||
between two workers: pin it in a diigo-cache test (and
|
||||
madmode's reader tests against the same fixture).
|
||||
- [ ] 2-iii. Decide `DiigoBridge`'s fate: madmode doesn't need it
|
||||
(public reads need no cache id), so its "cache-id source"
|
||||
TODO (`src/index.ts`, README "RPC use") is either dropped
|
||||
with the entrypoint or kept for a private-reading caller.
|
||||
- [ ] **3. `/bookmarks` renders real data** — titles, tags, dates at
|
||||
http://localhost:4321/bookmarks, newest first.
|
||||
- [ ] **4. The weekly page**: `/bookmarks/2026-W41` → the cache's
|
||||
`in=2026-W41` (needs 1d and 1f). Decide (user's call): a raw
|
||||
week list, or a draft post the user edits before publishing
|
||||
(the PESOS practice is editorial; a tag like `#weekly` in `q`
|
||||
is one cheap form of discretion).
|
||||
- [ ] **5. Deployed end-to-end** (order matters):
|
||||
- [ ] 5-i. webapp: `cd webapp && npx wrangler deploy`
|
||||
- [ ] 5-ii. diigo-cache: rate-limit `/api` (and `/public/*`) first
|
||||
(diigo-cache README, "Deployment concern"); deploy; create
|
||||
against prod (ids → password manager; no worker secret);
|
||||
run the fill job.
|
||||
- [ ] 5-iii. madmode: deploy with the service binding; the
|
||||
weekly page renders against prod.
|
||||
- [ ] **6. Cookie expiry**: when diigo's session ends, head refreshes
|
||||
fail; the public page keeps serving what's stored (say so on the
|
||||
page, don't fail silently). Rotation is manual: re-mint via
|
||||
`/_connect`. Open question: can an existing cache be re-wired to
|
||||
a new webapp id (keeping its cache id and public username), or
|
||||
does re-mint mean a new cache? Prefer re-wire — durable ids.
|
||||
- [ ] **7. bib sync #195**: repeat the pattern for the next
|
||||
read-access need (webapp mints for any origin; the cache's
|
||||
item shape is diigo-specific): [the zotero goal tree](zotero-checklist.md).
|
||||
The social.coop account is next after that:
|
||||
[the social.coop goal tree](social-coop-checklist.md).
|
||||
- [ ] **webapp graduates from prototype** (optional; only if it earns it)
|
||||
- [ ] TODO(webapp): one canonical mint form — proxy-page (current) vs
|
||||
running webapp as the primary worker so its own port serves the
|
||||
form directly; revisit as the UI grows.
|
||||
- [ ] @endo/errors for structured error details (needs node_modules).
|
||||
- [ ] **toybox: typed pieces that fit together, peer to peer** (working
|
||||
name; tinker toys per the madmode.com home page). Kinds are typed
|
||||
interfaces, à la Genode session interfaces, but wired by
|
||||
introduction (E's Granovetter diagram), not a parent tree; named by
|
||||
petnames; each piece guards its own resources. Why:
|
||||
[the toybox user stories](toybox-stories.md).
|
||||
- [ ] **T1. Changed signal**: a reader can subscribe to "this cache
|
||||
changed" instead of polling (Genode's ROM-session sigh is the
|
||||
model: public cache ≈ ROM, `/_publish` ≈ report). Fires on 1f's
|
||||
head refresh when it upserts anything new. Shape TBD: a Cap'n Web
|
||||
callback stub the cache holds (live only), or a durable
|
||||
subscription it calls back via a webkey (survives eviction).
|
||||
- [ ] **T2. Compose with [Blockly](https://developers.google.com/blockly)**:
|
||||
connector checks (`setCheck(kind)`) are the shapes; a workspace
|
||||
is a set of introductions. **Blocks refer to capabilities by
|
||||
petname**, never by key: workspace JSON is shareable; the keys
|
||||
live with whatever runs it.
|
||||
- [ ] **T3. Run compositions in [Dynamic Workers](https://developers.cloudflare.com/dynamic-workers/)**:
|
||||
code from anywhere: Blockly's JS generator, code written by
|
||||
agents, by hand. Confinement makes codegen safe: the Worker
|
||||
Loader isolate's `env` holds only the stubs its petnames resolve
|
||||
to, with `globalOutbound: null`, so the code's authority is
|
||||
exactly what it was handed. (Ordinary Workers forbid `eval`;
|
||||
lifting that is the point of the Worker Loader.)
|
||||
|
||||
## How to run (continuation prompts)
|
||||
|
||||
Dev (diigo-cache + webapp in one workerd):
|
||||
|
||||
cd ~/oros-bots/capsite/diigo-cache
|
||||
pnpm dev # → http://localhost:8787
|
||||
# webapp rides along (binding-only)
|
||||
|
||||
First connect (or re-connect after cookie expiry) — browser flow, two steps:
|
||||
|
||||
open http://localhost:8787/
|
||||
# 1. "mint the diigo session at webapp" → webapp's own mint form
|
||||
# (diigo-prefilled, served on :8787); paste the Cookie header from
|
||||
# diigo.com devtools → mint (the cookie transits diigo-cache as an
|
||||
# opaque relay into webapp's DO only)
|
||||
# 2. the wire step: webapp id pre-filled, choose public|private →
|
||||
# cacheId; copy the ids somewhere you control (password manager),
|
||||
# paste the cacheId into the dump form
|
||||
# (no .dev.vars, no restarts: ids ride the form POSTs / your paste)
|
||||
|
||||
Terminal flow (the same shape, scripted):
|
||||
|
||||
wid=$(curl -s -X POST http://localhost:8787/_mint --data-urlencode \
|
||||
'url=https://www.diigo.com/interact_api/' --data-urlencode \
|
||||
'headers={"user-agent":"Mozilla/5.0","x-requested-with":"XMLHttpRequest","cookie":"<paste>"}' \
|
||||
--data-urlencode 'msPerCall=500' -D - -o /dev/null | grep -i x-webapp-id)
|
||||
curl -s -X POST http://localhost:8787/_wire -H 'content-type: application/json' \
|
||||
-d "{\"webappId\":\"<from $wid>\",\"mode\":\"private\"}"
|
||||
|
||||
Then: enter a page number, dump → JSON rows with a `cache: HIT/MISS`
|
||||
line (a repeat page is answered from DO sqlite storage). GET / is inert
|
||||
(dumps happen only on POST submits). Public pages:
|
||||
/public/<username>?page=n (each page fills from diigo on first visit).
|
||||
A private-only cache can be published later from its created page
|
||||
(`POST /_publish`, cache id in the body).
|
||||
|
||||
Fill and invalidate a cache: http://localhost:8787/cache/ (log in with
|
||||
the cache id from the password manager).
|
||||
|
||||
Checks: `cd diigo-cache && pnpm lint && pnpm test`. Against a diigo RSS
|
||||
export: `node scripts/compare-export.ts <cache.sqlite> <export.xml> <out-dir>`.
|
||||
|
||||
potluck (EmDash site, fresh out of the box: `pnpm create emdash@latest
|
||||
potluck --pm pnpm --install --yes` → cloudflare:blog, 2026-10-08, per
|
||||
[Create your first EmDash site](https://docs.emdashcms.com/); replaces
|
||||
the old madmode/ starter):
|
||||
|
||||
cd ~/oros-bots/capsite/potluck && pnpm dev # → :4321
|
||||
# first run: the setup wizard at /_emdash/admin (site title, email)
|
||||
# dev-bypass auth helper:
|
||||
# /_emdash/api/setup/dev-bypass?redirect=/_emdash/admin
|
||||
|
||||
## Working rules
|
||||
|
||||
Agent working rules are in [AGENTS.md](AGENTS.md) — dev servers are the
|
||||
user's job; durable state (loud about breaking changes); secrets
|
||||
discipline; keep config types generated. They apply
|
||||
to every goal in this tree.
|
||||
|
||||
## Pointers
|
||||
|
||||
- [the toybox user stories](toybox-stories.md) — what the pieces are for
|
||||
- [the zotero goal tree](zotero-checklist.md) and
|
||||
[the social.coop goal tree](social-coop-checklist.md) — the next caches
|
||||
- [the capsite notes](capsite-notes.md) — the original goal and the EmDash
|
||||
native-plugin wiring details
|
||||
- [docs/webkeys.md](docs/webkeys.md) — the Waterken URL-capability
|
||||
pattern, abstracted from the E-on-Java sources (bearer secrets,
|
||||
YURL32, secret≠address); the reason ids ride only fragments and POST
|
||||
bodies
|
||||
- [the mm-diigo diigo-bak scripts](https://github.com/dckc/mm-diigo) —
|
||||
provenance of the fluent client and dump generator (`projects/diigo-bak/`:
|
||||
WebApp.js, diigo-dump.mjs, diigo-interact.mjs; mm-diigo commit 7dbb367,
|
||||
Oct 6 2026)
|
||||
- [webapp/README.md](webapp/README.md) — HTTP + RPC surfaces of the
|
||||
factory worker; open TODO on the mint-form placement
|
||||
- [diigo-cache/README.md](diigo-cache/README.md) — the cache worker:
|
||||
create flow, the two DOs, run/deploy details
|
||||
@@ -1,165 +0,0 @@
|
||||
`madmode.com` follows the "bake, don't fry" static site generator pattern, which avoids all sorts of security issues.
|
||||
|
||||
For years ([#23](https://github.com/dckc/madmode-blog/issues/23) was created in 2016) I have been wishing for a way to exercise read capabilities to get things like bookmarks as well as write access to put it on my site.
|
||||
|
||||
Let's give this a try:
|
||||
|
||||
- [EmDash 1.0: the stable CMS with a secure plugin registry | Cloudflare Blog](https://blog.cloudflare.com/emdash-cms-plugin-registry/) September 28, 2026
|
||||
|
||||
Goal: confine the code that has access to the diigo.com secret to a small,
|
||||
auditable piece behind an attenuated interface (originally "the API key held
|
||||
by the host, never inside the plugin"; the API-key path turned out dead —
|
||||
see [the goal tree](capsite-checklist.md) for the current credential story).
|
||||
If it works out well, we should be able to expand to [bib sync #195](https://github.com/dckc/madmode-blog/issues/195).
|
||||
|
||||
## What we built
|
||||
|
||||
- `webapp/` — site-agnostic Durable-Object factory for attenuated credentialed
|
||||
web clients (fluent client, ids are bearer capabilities);
|
||||
[webapp/README.md](webapp/README.md)
|
||||
- `diigo-cache/` — the webapp consumer, evolved from the diigo-dump worker:
|
||||
bookmark dumps cached in DO SQLite storage (private cache by unique id,
|
||||
public-only cache by username-in-path); the mint call carries all diigo
|
||||
knowledge; the cookie lives in the DO's storage (see
|
||||
[the checklist's goal tree](capsite-checklist.md) for the verified/not-yet
|
||||
split)
|
||||
- `madmode/` — Cloudflare Workers EmDash site (Starter template), local dev via `pnpm dev`.
|
||||
- `diigo-bookmarks/` — **native** EmDash plugin (converted from sandboxed):
|
||||
- `src/index.ts` exports `createPlugin()` which returns `definePlugin({...})`.
|
||||
- Declares `capabilities: ["network:request"]`, `allowedHosts: ["secure.diigo.com", "www.diigo.com"]`
|
||||
(Diigo 301s `secure.diigo.com` → `www.diigo.com`; the host gate re-validates every redirect hop).
|
||||
- Fetches `https://www.diigo.com/api/v2/bookmarks` with HTTP Basic auth into plugin storage,
|
||||
serves a public JSON route, and has a Block Kit admin page ("Sync now" button + table).
|
||||
- Site `/bookmarks` page renders the collected bookmarks (linked from the primary menu).
|
||||
|
||||
## diigo-cache UX map (2026-10-07)
|
||||
|
||||
What a person can do, where, and with what authority. Input to aligning
|
||||
the admin UX with the RPC interface (checklist: the store refactor and
|
||||
"align admin UX and RPC").
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
home["/ home<br/>(no authority)"]
|
||||
connect["/_connect<br/>mint form"]
|
||||
wire["wire step<br/>(webapp id)"]
|
||||
created["cache created<br/>(cache id)"]
|
||||
login["/cache/ login<br/>(password manager)"]
|
||||
admin["webkey page<br/>/cache/ + key in fragment"]
|
||||
public["/public/username<br/>(anyone)"]
|
||||
|
||||
home -->|create| connect
|
||||
connect -->|"POST /_mint (cookie)"| wire
|
||||
home -->|"POST /_wire (webapp id)"| created
|
||||
wire -->|"POST /_wire"| created
|
||||
created -->|"POST /_publish (cache id)"| created
|
||||
created -->|"open this cache"| admin
|
||||
home -->|"open a cache"| login
|
||||
login -->|"cache id"| admin
|
||||
home -->|"dump: POST / (cache id + page)"| home
|
||||
admin -->|"api.cache(key) …"| admin
|
||||
created -->|"link (public mode)"| public
|
||||
```
|
||||
|
||||
| action | where | transport | authority |
|
||||
|---|---|---|---|
|
||||
| mint the diigo session | `/_connect` | HTTP `POST /_mint` (relays webapp's form) | the cookie |
|
||||
| wire a cache (private/public) | wire step, home | HTTP `POST /_wire` | webapp id |
|
||||
| save the ids | created page | browser (copy, password manager) | — |
|
||||
| publish later | created page | HTTP `POST /_publish` ⚠ | cache id |
|
||||
| dump a page (raw rows) | home | HTTP `POST /` ⚠ | cache id |
|
||||
| fingerprint, has-public | webkey page | RPC `fingerprint()`, `hasPublic()` | cache key |
|
||||
| fill / stop / status | webkey page | RPC `startFill()`, `stopFill()`, `fillStatus()` | cache key |
|
||||
| …of the public companion | webkey page | RPC `publicCache().…` | cache key |
|
||||
| invalidate the last N days | webkey page | RPC `invalidateRecent(days)` | cache key |
|
||||
| read public bookmarks | `/public/<u>` | HTTP GET (HTML or JSON) ⚠ | none |
|
||||
| bulk dump for another worker | — | service binding `DiigoBridge.dumpNdjson` | worker config |
|
||||
|
||||
⚠ misalignments:
|
||||
- publish and dump are admin actions held by the cache key, but live on
|
||||
HTTP form routes rather than the RPC facet the webkey page uses
|
||||
- ~~the public page can write~~ — resolved: it reads only through the
|
||||
read-only `viewer()` facet; unfetched pages say so
|
||||
- the webkey page has no dump or publish; the home page has no fill
|
||||
|
||||
## Native-plugin wiring (the part that took a while)
|
||||
|
||||
`emdash()`'s `plugins: []` takes **descriptors**, not plugin objects — the Astro
|
||||
integration needs a module specifier it can statically import at build time:
|
||||
|
||||
```js
|
||||
// astro.config.mjs
|
||||
plugins: [{ id: "diigo-bookmarks", version: "0.1.0", entrypoint: "diigo-bookmarks" }]
|
||||
```
|
||||
|
||||
The generated runtime module does `import { createPlugin } from "diigo-bookmarks"`
|
||||
and calls it. `definePlugin(...)` results have no `entrypoint` and are rejected
|
||||
with a build-time error. An in-config factory call also fails ("has no entrypoint").
|
||||
|
||||
Key facts verified from emdash source:
|
||||
- `PluginContext` has **no `env`**. Worker secrets are read via dynamic
|
||||
`import("virtual:emdash/env")` (generated module re-exports `cloudflare:workers`
|
||||
`env` under @astrojs/cloudflare; `undefined` on other adapters).
|
||||
- GET plugin routes get query params in `ctx.input` (a `PluginRouteQuery` record),
|
||||
not `ctx.query` or `ctx.request.url` parsing.
|
||||
- Admin (Block Kit) route: the admin frontend POSTs JSON
|
||||
`{ type: "page_load", page: "<declared page path>" }` and button clicks as
|
||||
`{ type: "block_action", action_id, page }` to `/_emdash/api/plugins/<id>/admin`;
|
||||
the handler returns `{ blocks, toast? }`. CSRF requires the `X-EmDash-Request: 1`
|
||||
header (the frontend sends it; curl must add it explicitly).
|
||||
- Admin pages/widgets for **native** plugins must be declared in the plugin's own
|
||||
`definePlugin({ admin: { pages: [...] } })` — the build descriptor's
|
||||
`adminPages` is NOT merged into the manifest; the admin sidebar reads
|
||||
`plugin.admin.pages` from the entrypoint's ResolvedPlugin. With `admin.pages`
|
||||
set, the manifest reports `adminMode: "blocks"` and the sidebar gains
|
||||
Plugins → Diigo Sync at `/_emdash/admin/plugins/diigo-bookmarks/sync`.
|
||||
- `ctx.cron.schedule()` upserts, so calling it on every sync is a safe bootstrap
|
||||
for configured plugins (which don't get a `plugin:activate` run by default).
|
||||
- Local `.pnpm` hardlinks mean source edits reach the site only after a full
|
||||
dev-server restart; if you delete a stale `node_modules/.vite/deps_ssr/*.js`
|
||||
by hand the server 500s until `rm -rf node_modules/.vite` + full restart.
|
||||
|
||||
## Where the Diigo credentials go
|
||||
|
||||
The credential story moved twice; [the goal tree](capsite-checklist.md) is
|
||||
authoritative. Current shape: the session cookie lives only in the webapp
|
||||
DO's storage; `madmode/.dev.vars` still holds placeholder
|
||||
`DIIGO_API_KEY` / `DIIGO_USERNAME` for the (dead) API-key path — both
|
||||
documented schemes return 401 unconditionally, verified against both known
|
||||
real keys (opencode session ses_eec320fe4ffehaMAn44U1nTKJU: `key=` param,
|
||||
`key`+`user=`, and HTTP Basic, on both /api/v2/bookmarks and /api/v2/notes,
|
||||
though the same creds downloaded 13.5k bookmarks in 2024–2025; diigo
|
||||
evidently revoked v2 key auth). Deployed secrets: `cd madmode && pnpm
|
||||
wrangler secret put <NAME>`; the sync rides the cookie path since the API
|
||||
path died.
|
||||
|
||||
`EMDASH_ENCRYPTION_KEY` (in `madmode/.env` locally) is only needed for sandboxed
|
||||
plugins' secret settings; the native plugin doesn't use it, but keep it backed up
|
||||
for the site.
|
||||
|
||||
## How to run it
|
||||
|
||||
```bash
|
||||
cd madmode
|
||||
pnpm dev # → http://localhost:4321, admin at /_emdash/admin
|
||||
# one-time auth helper (skips passkey):
|
||||
# http://localhost:4321/_emdash/api/setup/dev-bypass?redirect=/_emdash/admin
|
||||
```
|
||||
|
||||
- Admin page: `/_emdash/admin` → plugins → Diigo Sync → "Sync now"
|
||||
- Public JSON: `/_emdash/api/plugins/diigo-bookmarks/bookmarks?limit=20`
|
||||
- Site page: `/bookmarks`
|
||||
- Sync also self-schedules via cron (`0 */6 * * *`), stored in `_emdash_cron_tasks`.
|
||||
|
||||
Note: private Diigo bookmarks need the session-cookie channel (which is what
|
||||
the sync will use after goal 2; the API-key path is dead).
|
||||
|
||||
## Plugin dev loop
|
||||
|
||||
```bash
|
||||
cd diigo-bookmarks
|
||||
pnpm typecheck # tsc --noEmit
|
||||
```
|
||||
|
||||
Then restart `pnpm dev` in `madmode/` (full stop + start; config/plugin changes
|
||||
are not hot-reloaded through the .pnpm hardlink path).
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* @file Open a CapTP session to the canister as the principal of a key file.
|
||||
*/
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { HttpAgent, Actor } from '@icp-sdk/core/agent';
|
||||
import { Ed25519KeyIdentity } from '@icp-sdk/core/identity';
|
||||
import { openPeer } from './peer.js';
|
||||
|
||||
/** The Candid interface in counter.did. */
|
||||
const idlFactory = ({ IDL }) => {
|
||||
const Frames = IDL.Vec(IDL.Nat8);
|
||||
return IDL.Service({
|
||||
start: IDL.Func([Frames], [Frames], []),
|
||||
deliver: IDL.Func([Frames], [Frames], []),
|
||||
abandonAll: IDL.Func([], [], []),
|
||||
});
|
||||
};
|
||||
|
||||
/** The seed in `path`, or a fresh one written there. */
|
||||
const keySeed = async path => {
|
||||
try {
|
||||
return new Uint8Array(await readFile(path));
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') throw err;
|
||||
const seed = crypto.getRandomValues(new Uint8Array(32));
|
||||
await writeFile(path, seed, { mode: 0o600, flag: 'wx' });
|
||||
return seed;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Open a session to `canisterId` at `host` as the principal whose Ed25519
|
||||
* seed is in `keyFile` (32 bytes, made if missing), logging each update call.
|
||||
*
|
||||
* @param {string} host the replica, e.g. https://icp-api.io
|
||||
* @param {string} canisterId
|
||||
* @param {string} keyFile
|
||||
* @param {object} [opts]
|
||||
* @param {boolean} [opts.abandonAll] first end the principal's open session,
|
||||
* breaking every reference and pending answer that lives only in it
|
||||
*/
|
||||
export const connect = async (host, canisterId, keyFile, { abandonAll = false } = {}) => {
|
||||
const { hostname } = new URL(host);
|
||||
const agent = await HttpAgent.create({
|
||||
host,
|
||||
identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)),
|
||||
// A local replica's root key is its own; mainnet's is built in.
|
||||
shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost',
|
||||
});
|
||||
const actor = Actor.createActor(idlFactory, { agent, canisterId });
|
||||
if (abandonAll) {
|
||||
await actor.abandonAll();
|
||||
console.error(' abandoned the previous session');
|
||||
}
|
||||
const carry = async (method, frames) => {
|
||||
const t0 = performance.now();
|
||||
const reply = await actor[method](frames);
|
||||
console.error(` ${method} ${frames.length}B -> ${reply.length}B in ${Math.round(performance.now() - t0)}ms`);
|
||||
return reply;
|
||||
};
|
||||
const module = await WebAssembly.compile(
|
||||
await readFile(new URL('../zig-out/bin/client.wasm', import.meta.url)),
|
||||
);
|
||||
const seed = crypto.getRandomValues(new Uint8Array(64));
|
||||
return openPeer({ module, seed, carry }, canisterId);
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @file Call the Counter canister over OCapN.
|
||||
*/
|
||||
const HELP = `usage: counter.mjs HOST CANISTER_ID KEY_FILE init NAME [--abandon-all]
|
||||
counter.mjs HOST CANISTER_ID KEY_FILE use NAME [VERB...] [--abandon-all]
|
||||
|
||||
Open a CapTP session to the canister as the principal whose Ed25519 seed is
|
||||
in KEY_FILE (32 bytes, made if missing), then:
|
||||
|
||||
init NAME make a counter, count on it (incr incr decr), and keep it in
|
||||
your home under NAME
|
||||
use NAME get the counter kept under NAME and send it each VERB
|
||||
(incr, decr, value; default: incr value)
|
||||
|
||||
Each run's sends are pipelined: one update call after the handshake, plus
|
||||
one for init. A principal has one session at a time; --abandon-all first
|
||||
ends the one a previous run left open. HOST is the replica, e.g. http://127.0.0.1:4960, or
|
||||
https://icp-api.io.`;
|
||||
|
||||
import { connect } from './connect.js';
|
||||
|
||||
const main = async argv => {
|
||||
const abandonAll = argv.includes('--abandon-all');
|
||||
const [host, canisterId, keyFile, command, name, ...verbs] = argv.filter(arg => arg !== '--abandon-all');
|
||||
if (!name || !['init', 'use'].includes(command)) {
|
||||
console.error(HELP);
|
||||
process.exitCode = 2;
|
||||
return;
|
||||
}
|
||||
const peer = await connect(host, canisterId, keyFile, { abandonAll });
|
||||
console.log('session open');
|
||||
const home = peer.fetch('home');
|
||||
/** Send each verb without waiting, then print each answer. */
|
||||
const countOn = async (counter, sends) => {
|
||||
const answers = sends.map(verb => [verb, peer.send(counter, verb)]);
|
||||
await peer.flush();
|
||||
for (const [verb, answer] of answers) console.log(verb, peer.valueOf(answer));
|
||||
};
|
||||
if (command === 'init') {
|
||||
const counter = peer.send(peer.fetch('makeCounter'), 'make');
|
||||
await countOn(counter, ['incr', 'incr', 'decr']);
|
||||
const kept = peer.send(home, 'init', name, counter);
|
||||
await peer.flush();
|
||||
peer.valueOf(kept);
|
||||
console.log(`kept as ${name}`);
|
||||
} else {
|
||||
await countOn(peer.send(home, 'get', name), verbs.length ? verbs : ['incr', 'value']);
|
||||
}
|
||||
};
|
||||
|
||||
main(process.argv.slice(2)).catch(err => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Generated
+227
@@ -0,0 +1,227 @@
|
||||
{
|
||||
"name": "icp-ocapn-counter-client",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "icp-ocapn-counter-client",
|
||||
"dependencies": {
|
||||
"@icp-sdk/core": "6.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@icp-sdk/icp-cli": "1.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dfinity/cbor": {
|
||||
"version": "0.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@dfinity/cbor/-/cbor-0.2.3.tgz",
|
||||
"integrity": "sha512-5GX+9tAf29r94Pxv8nCzrv2/t+AkOfem/c/G61+FA2Wadq7THvc5cvr/AVLH0LpukVfNSWRRHvl1fkCdiB9MMQ==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@icp-sdk/core": {
|
||||
"version": "6.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@icp-sdk/core/-/core-6.1.1.tgz",
|
||||
"integrity": "sha512-bMRKAJg0zwJyd53feg8D6Qd+ikoxrxzsVrvzmyjxgSwn7znKxBVyCN8GR/NEQ+dYaE+yWuXV0O3C8AiHL2JUqg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@dfinity/cbor": "^0.2.3",
|
||||
"@noble/curves": "^2.2.0",
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@scure/bip32": "^2.2.0",
|
||||
"@scure/bip39": "^2.2.0",
|
||||
"asn1js": "^3.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@icp-sdk/icp-cli": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli/-/icp-cli-1.8.0.tgz",
|
||||
"integrity": "sha512-5wdTxakBoYKqCVvApwlEgZZat9Y0qPxvrPVO31eAem2IO3+Xu3gn/k4EAHb9K9DTfCKyJ+Ll2O8Nm5GEPUldpQ==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"icp": "bin/icp.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@icp-sdk/icp-cli-darwin-arm64": "1.8.0",
|
||||
"@icp-sdk/icp-cli-darwin-x64": "1.8.0",
|
||||
"@icp-sdk/icp-cli-linux-arm64": "1.8.0",
|
||||
"@icp-sdk/icp-cli-linux-x64": "1.8.0",
|
||||
"@icp-sdk/icp-cli-win32-x64": "1.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@icp-sdk/icp-cli-darwin-arm64": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-darwin-arm64/-/icp-cli-darwin-arm64-1.8.0.tgz",
|
||||
"integrity": "sha512-4RO/r1p1h74wuePwat0vMPfYagzFO2CiYmAR33ZnrPfo22aGVcdwldpePZYBV8egjq7BMnI2LPY3UVLVHnSing==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
]
|
||||
},
|
||||
"node_modules/@icp-sdk/icp-cli-darwin-x64": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-darwin-x64/-/icp-cli-darwin-x64-1.8.0.tgz",
|
||||
"integrity": "sha512-+/MDaDmleZ43kY14dvMHGxxSIW7Z+brccSqy6Vr+CwvRWqJcDG6QzwYXqk+owgLcmTrF11vufMhZbWN7n/yv0g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
]
|
||||
},
|
||||
"node_modules/@icp-sdk/icp-cli-linux-arm64": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-linux-arm64/-/icp-cli-linux-arm64-1.8.0.tgz",
|
||||
"integrity": "sha512-E/unBg0Kh8jfdf9IWVdbTP5FeMMtnQSDo1Cw+qb1WfX0lYYsFndS6bLW4KujKloETPKBwUPrH9gGc2AjDDhlKQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
"node_modules/@icp-sdk/icp-cli-linux-x64": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-linux-x64/-/icp-cli-linux-x64-1.8.0.tgz",
|
||||
"integrity": "sha512-f6NSdFIrr2eSmNe0JjQWedaiRkJWqCTbaS6GjZFbPtRnd52Eb+Ichrom2zmx/4CZ/DW71BfU9iE8D+OFTDsyow==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
"node_modules/@icp-sdk/icp-cli-win32-x64": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-win32-x64/-/icp-cli-win32-x64-1.8.0.tgz",
|
||||
"integrity": "sha512-4x3JZwLljFNK67c3ClYDbluE2Lw98q5pE+Jomn0wq8MqGV/UqtQHdKeWqB73NWdeaeuGar3Hl15i81gxJJXAGg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
|
||||
"integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "2.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
|
||||
"integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@scure/base": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.4.0.tgz",
|
||||
"integrity": "sha512-thZ1TuJwFwBblOhgsjDKvvGirBxNp+wSvY/DR6tJBJOTDhdAAcHJ8Vbr2eFnqaxeca4+t0i9KBf+uHYGWwZORg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@scure/bip32": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-2.4.0.tgz",
|
||||
"integrity": "sha512-i3DS0CptAocyvqE4n3SUkpzeQK4vJMFwWLofTwRiiKo2aWojBOfyMCgfKw9HVpO6fSY5AK86sHS/Uzn8kK9Few==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "2.4.0",
|
||||
"@noble/hashes": "2.4.0",
|
||||
"@scure/base": "2.4.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@scure/bip39": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.4.0.tgz",
|
||||
"integrity": "sha512-82dxFbZUYboyOf0AXiydsQrFQ5Q4h9mX+O2UkE91ROYmsc0BKMGZLwDmy96Jpa2+vrtoxomjUhy1RPIgH/r2nA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "2.4.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1js": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz",
|
||||
"integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"pvtsutils": "^1.3.6",
|
||||
"pvutils": "^1.2.0",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pvtsutils": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
|
||||
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.1"
|
||||
}
|
||||
},
|
||||
"node_modules/pvutils": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
|
||||
"integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.9.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
|
||||
"integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
|
||||
"license": "0BSD"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "icp-ocapn-counter-client",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@icp-sdk/core": "6.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@icp-sdk/icp-cli": "1.8.0"
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* @file The client peer (`zig-out/bin/client.wasm`) driven over a canister's
|
||||
* `start` and `deliver` update calls.
|
||||
*/
|
||||
|
||||
const { freeze } = Object;
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/**
|
||||
* @typedef {(method: 'start' | 'deliver', frames: Uint8Array) => Promise<Uint8Array>} Carry
|
||||
* one update call: the frames out, the frames in the reply
|
||||
*/
|
||||
|
||||
/**
|
||||
* Instantiate the client peer and open a session to `canisterId`.
|
||||
*
|
||||
* @param {object} io
|
||||
* @param {WebAssembly.Module} io.module the compiled client.wasm
|
||||
* @param {Uint8Array} io.seed 64 bytes of fresh entropy
|
||||
* @param {Carry} io.carry
|
||||
* @param {string} canisterId the canister's principal, as text
|
||||
*/
|
||||
export const openPeer = async ({ module, seed, carry }, canisterId) => {
|
||||
const { exports: wasm } = await WebAssembly.instantiate(module, {
|
||||
env: { report: (ptr, len) => console.error(readText(ptr, len)) },
|
||||
});
|
||||
const memory = () => new Uint8Array(wasm.memory.buffer);
|
||||
const readText = (ptr, len) => decoder.decode(memory().slice(ptr, ptr + len));
|
||||
|
||||
/** Copy `bytes` into wasm memory for the length of `fn`. */
|
||||
const withBytes = (bytes, fn) => {
|
||||
const ptr = wasm.client_alloc(bytes.length || 1);
|
||||
memory().set(bytes, ptr);
|
||||
try {
|
||||
return fn(ptr, bytes.length);
|
||||
} finally {
|
||||
wasm.client_free(ptr, bytes.length || 1);
|
||||
}
|
||||
};
|
||||
const staged = () => memory().slice(wasm.client_out_ptr(), wasm.client_out_ptr() + wasm.client_out_len());
|
||||
const check = (status, what) => {
|
||||
if (status !== 0) throw Error(`${what}: ${decoder.decode(staged())}`);
|
||||
};
|
||||
|
||||
/**
|
||||
* Carry staged frames until the canister has nothing more to say. The
|
||||
* first call of a session is `start`.
|
||||
*/
|
||||
let method = 'start';
|
||||
const pump = async () => {
|
||||
for (;;) {
|
||||
const frames = staged();
|
||||
if (frames.length === 0) return;
|
||||
const reply = await carry(method, frames);
|
||||
method = 'deliver';
|
||||
check(withBytes(reply, wasm.client_feed), 'feed');
|
||||
check(wasm.client_outbound(), 'outbound');
|
||||
}
|
||||
};
|
||||
|
||||
check(withBytes(seed, wasm.client_init), 'init');
|
||||
check(withBytes(encoder.encode(canisterId), wasm.client_dial), 'dial');
|
||||
await pump();
|
||||
if (!wasm.client_session_open()) throw Error('session did not open');
|
||||
|
||||
const slotOf = (status, what) => {
|
||||
if (status < 0) throw Error(`${what}: ${decoder.decode(staged())}`);
|
||||
return status;
|
||||
};
|
||||
/** Stage what the Host queued, then carry it until the canister is quiet. */
|
||||
const flush = async () => {
|
||||
check(wasm.client_outbound(), 'outbound');
|
||||
await pump();
|
||||
};
|
||||
/** Read a settled answer, or throw. */
|
||||
const valueOf = slot => {
|
||||
const kind = wasm.client_result_kind(slot);
|
||||
if (kind === 0) throw Error(`answer ${slot} still pending after the canister went quiet`);
|
||||
if (kind === 3) {
|
||||
check(wasm.client_result_broken(slot), 'broken');
|
||||
throw Error(`answer ${slot} broke: ${decoder.decode(staged())}`);
|
||||
}
|
||||
if (kind === 4) return undefined;
|
||||
return kind === 2 ? Number(wasm.client_result_integer(slot)) : { slot };
|
||||
};
|
||||
|
||||
/**
|
||||
* An answer: what `fetch` or `send` will settle to. Sends can target one
|
||||
* before it settles; nothing crosses the wire until `flush`.
|
||||
*
|
||||
* @typedef {{ slot: number }} Answer
|
||||
*/
|
||||
|
||||
return freeze({
|
||||
/** @returns {Answer} the capability published as `name` */
|
||||
fetch: name => ({ slot: slotOf(withBytes(encoder.encode(name), (p, n) => wasm.client_fetch(p, n)), 'fetch') }),
|
||||
/**
|
||||
* Send `verb` to `target`, without waiting for it to settle.
|
||||
*
|
||||
* @param {Answer} target
|
||||
* @param {string} verb
|
||||
* @param {...(string | bigint | Answer)} args strings, integers, and
|
||||
* answers that have settled to references
|
||||
* @returns {Answer} `target`'s answer
|
||||
*/
|
||||
send: (target, verb, ...args) => {
|
||||
for (const arg of args) {
|
||||
if (typeof arg === 'string') check(withBytes(encoder.encode(arg), wasm.client_arg_text), 'argument');
|
||||
else if (typeof arg === 'bigint') check(wasm.client_arg_integer(arg), 'argument');
|
||||
else check(wasm.client_arg_reference(arg.slot), 'argument');
|
||||
}
|
||||
const status = withBytes(encoder.encode(verb), (p, n) => wasm.client_send(target.slot, p, n));
|
||||
return { slot: slotOf(status, 'send') };
|
||||
},
|
||||
flush,
|
||||
/** @param {Answer} answer */
|
||||
valueOf: answer => valueOf(answer.slot),
|
||||
});
|
||||
};
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @file Alice buys a widget from Bob, over ERTP in the canister.
|
||||
*/
|
||||
const HELP = `usage: shop.mjs HOST CANISTER_ID KEY_FILE STEP [--abandon-all]
|
||||
|
||||
Each STEP runs as the principal whose key is in KEY_FILE (made if missing):
|
||||
|
||||
mint issue moola, mint 10 into a purse kept at home as "wallet",
|
||||
and post the moola issuer on the board
|
||||
open issue widgets, stock one, and post a shop selling it for 3
|
||||
moola, paid into a purse kept at home as "proceeds"
|
||||
buy pay 3 moola from "wallet" for the widget, and keep it in a
|
||||
purse at home as "closet"
|
||||
balances show each purse kept at home
|
||||
|
||||
Run mint and buy as Alice, open as Bob. A principal has one session at a
|
||||
time; --abandon-all first ends the one a previous run left open, breaking
|
||||
everything that lived only in it.`;
|
||||
|
||||
import { connect } from './connect.js';
|
||||
|
||||
const steps = {
|
||||
async mint(peer, home, board) {
|
||||
const mint = peer.send(peer.fetch('makeIssuerKit'), 'make', 'moola');
|
||||
const moola = peer.send(mint, 'getIssuer');
|
||||
const wallet = peer.send(moola, 'makeEmptyPurse');
|
||||
const minted = peer.send(mint, 'mintPayment', 10n);
|
||||
await peer.flush();
|
||||
const deposited = peer.send(wallet, 'deposit', minted);
|
||||
peer.send(home, 'init', 'wallet', wallet);
|
||||
peer.send(board, 'init', 'moola', moola);
|
||||
await peer.flush();
|
||||
console.log('minted', peer.valueOf(deposited), 'moola into wallet');
|
||||
},
|
||||
async open(peer, home, board) {
|
||||
const mint = peer.send(peer.fetch('makeIssuerKit'), 'make', 'widget');
|
||||
const widgets = peer.send(mint, 'getIssuer');
|
||||
const stock = peer.send(widgets, 'makeEmptyPurse');
|
||||
const widget = peer.send(mint, 'mintPayment', 1n);
|
||||
const proceeds = peer.send(peer.send(board, 'get', 'moola'), 'makeEmptyPurse');
|
||||
await peer.flush();
|
||||
const stocked = peer.send(stock, 'deposit', widget);
|
||||
const shop = peer.send(peer.fetch('makeShop'), 'make', 3n, proceeds, stock);
|
||||
peer.send(home, 'init', 'proceeds', proceeds);
|
||||
peer.send(board, 'init', 'widget', widgets);
|
||||
await peer.flush();
|
||||
peer.send(board, 'init', 'bobs-shop', shop);
|
||||
await peer.flush();
|
||||
console.log('stocked', peer.valueOf(stocked), 'widget; shop open at 3 moola');
|
||||
},
|
||||
async buy(peer, home, board) {
|
||||
const wallet = peer.send(home, 'get', 'wallet');
|
||||
const pay = peer.send(wallet, 'withdraw', 3n);
|
||||
const shop = peer.send(board, 'get', 'bobs-shop');
|
||||
await peer.flush();
|
||||
const goods = peer.send(shop, 'buy', pay);
|
||||
await peer.flush();
|
||||
try {
|
||||
peer.valueOf(goods);
|
||||
} catch (err) {
|
||||
// The shop refused; the payment still holds what was withdrawn.
|
||||
const back = peer.send(wallet, 'deposit', pay);
|
||||
await peer.flush();
|
||||
console.log('refunded', peer.valueOf(back), 'moola to wallet');
|
||||
throw err;
|
||||
}
|
||||
const closet = peer.send(peer.send(board, 'get', 'widget'), 'makeEmptyPurse');
|
||||
await peer.flush();
|
||||
const got = peer.send(closet, 'deposit', goods);
|
||||
peer.send(home, 'init', 'closet', closet);
|
||||
await peer.flush();
|
||||
console.log('bought', peer.valueOf(got), 'widget into closet');
|
||||
},
|
||||
async balances(peer, home) {
|
||||
const names = ['wallet', 'closet', 'proceeds'];
|
||||
const amounts = names.map(name => peer.send(peer.send(home, 'get', name), 'getCurrentAmount'));
|
||||
await peer.flush();
|
||||
names.forEach((name, i) => {
|
||||
let amount;
|
||||
try {
|
||||
amount = peer.valueOf(amounts[i]);
|
||||
} catch (err) {
|
||||
amount = `none (${err.message})`;
|
||||
}
|
||||
console.log(name, amount);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const main = async argv => {
|
||||
const abandonAll = argv.includes('--abandon-all');
|
||||
const [host, canisterId, keyFile, step] = argv.filter(arg => arg !== '--abandon-all');
|
||||
if (!Object.hasOwn(steps, step ?? '')) {
|
||||
console.error(HELP);
|
||||
process.exitCode = 2;
|
||||
return;
|
||||
}
|
||||
const peer = await connect(host, canisterId, keyFile, { abandonAll });
|
||||
await steps[step](peer, peer.fetch('home'), peer.fetch('board'));
|
||||
};
|
||||
|
||||
main(process.argv.slice(2)).catch(err => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
// Each blob of frames is CapTP frames in Syrup byte-string envelopes.
|
||||
// Install with 32 bytes of fresh entropy.
|
||||
service : (entropy : blob) -> {
|
||||
// Open the caller's session with its `op:start-session`.
|
||||
start : (frames : blob) -> (blob);
|
||||
// Carry later frames on the caller's session.
|
||||
deliver : (frames : blob) -> (blob);
|
||||
// End the caller's session: every reference held through it and every
|
||||
// pending answer breaks. What the caller keeps at home stays.
|
||||
abandonAll : () -> ();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"canisters": {
|
||||
"counter": {
|
||||
"type": "custom",
|
||||
"build": "zig build canister",
|
||||
"wasm": "zig-out/bin/counter.wasm",
|
||||
"candid": "counter.did"
|
||||
}
|
||||
},
|
||||
"networks": {
|
||||
"local": { "bind": "127.0.0.1:4959", "type": "ephemeral" }
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
# diigo-bookmarks
|
||||
|
||||
A **native** plugin for [EmDash CMS](https://emdashcms.com) (converted from
|
||||
the sandboxed scaffold; wired via the `plugins: []` descriptor list in the
|
||||
site's astro.config — see [the capsite notes](../capsite-notes.md)).
|
||||
|
||||
Note: this README's Develop/Publish sections below are inherited from the
|
||||
sandboxed scaffold and do not match the native wiring.
|
||||
|
||||
## Develop
|
||||
|
||||
```sh
|
||||
pnpm install
|
||||
pnpm run validate
|
||||
pnpm run typecheck
|
||||
pnpm run test
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
To test against a running EmDash site, run `pnpm run dev` in this
|
||||
directory (rebuilds on save) and `pnpm add file:../path/to/this`
|
||||
in the site. Then `import diigoBookmarks from "diigo-bookmarks"` and pass
|
||||
it into `emdash({ sandboxed: [diigoBookmarks] })`.
|
||||
|
||||
`pnpm run test` builds the plugin and runs its tests through Worker Loader using
|
||||
EmDash's production sandbox wrapper and host bridge.
|
||||
|
||||
## Publish
|
||||
|
||||
```sh
|
||||
pnpm run login -- alice.example.com
|
||||
pnpm run publish # builds and uploads artifacts to your PDS
|
||||
```
|
||||
|
||||
To publish from GitHub Actions, run `pnpm run release:setup`. The command
|
||||
creates one shared workflow at the Git repository root.
|
||||
|
||||
## Version bumps
|
||||
|
||||
Bump `version` in `package.json` when you ship a release. The
|
||||
scaffold's `emdash-plugin.jsonc` deliberately omits `version` —
|
||||
the build pipeline reads it from `package.json` so there's a single
|
||||
source of truth. **Bump major** for breaking changes, **bump minor**
|
||||
for new routes or hooks, **bump patch** for fixes.
|
||||
|
||||
You MUST bump version whenever you change `capabilities`, `allowedHosts`,
|
||||
or `storage` in the manifest. Installed users have consented to the
|
||||
old trust contract; a change without a version bump would let new
|
||||
behaviour slip past consent.
|
||||
@@ -1,120 +0,0 @@
|
||||
# diigo-cache
|
||||
|
||||
Cloudflare Worker cache over [the webapp factory](../webapp/README.md):
|
||||
session-cookie reads of diigo bookmarks, cached in Durable-Object SQLite
|
||||
storage. Evolved from the diigo-dump worker (provenance:
|
||||
[mm-diigo `projects/diigo-bak/`](https://github.com/dckc/mm-diigo)); the
|
||||
static API-key path is dead (see [the capsite checklist](../capsite-checklist.md),
|
||||
goal 2 preamble).
|
||||
|
||||
## What it holds
|
||||
|
||||
- **The create flow, on one port**: `/_connect` renders webapp's own
|
||||
mint form (diigo-prefilled, cookie blank) — wrangler multi-config dev
|
||||
doesn't serve aux workers' HTTP, so `/_mint` relays the form opaquely
|
||||
into the WEBAPP binding (the cookie crosses; nothing on this side opens
|
||||
or logs it). Mint → `/_wire` (webapp id pre-filled, mode
|
||||
public|private) → the created page, where the user saves the ids.
|
||||
- **Two independent page caches** (`src/cache.ts`), one behavior: a
|
||||
page hit is served from storage with no diigo call; a miss asks the
|
||||
webapp instance in the cache's wiring and etches the page.
|
||||
- `DiigoCache` (binding `CACHE_DO`): every item. Addressed by its
|
||||
cache id.
|
||||
- `PublicCache` (binding `PUBLIC_DO`): shared items only — private
|
||||
rows are dropped *before* etching (`publicOnly`), so its storage
|
||||
holds nothing private. Same cookie webapp as the private cache.
|
||||
Public page n is diigo page n, filtered (may show fewer than
|
||||
`PAGE_SIZE`, 100: diigo's cap).
|
||||
`/public/<username>` resolves through the `idFromName("index")`
|
||||
registry, and reads through `viewer()`, a read-only facet: it shows
|
||||
stored pages and fill progress, and can't fetch from diigo or write.
|
||||
- **Storage**: SQL lives in `src/cache-read.sql` (selects only) and
|
||||
`src/cache-write.sql`; `src/store.ts` turns them into a reader and a
|
||||
writer facet, so the cache logic holds no SQL text.
|
||||
- **Pages**: home's dump form (cache id + page number, POST) shows raw
|
||||
dump rows; `/public/<username>?page=n` shows an HTML list with a page
|
||||
form (JSON for `Accept: application/json`). Both say `cache: HIT` or
|
||||
`MISS`; every page read also logs `{event: "cache", kind, page,
|
||||
outcome}`.
|
||||
- **Publish later**: `POST /_publish` (cache id in the body) wires a
|
||||
public companion to a private-only cache.
|
||||
- **The webkey page and Cap'n Web**: `/cache/#<cache id>` is a skeleton
|
||||
page, the same for every key; its script reads the key from the
|
||||
fragment and trades it in-band for a capability over
|
||||
[Cap'n Web](https://github.com/cloudflare/capnweb) at `/api`
|
||||
(`CacheApi.cache(key)` → a `CacheCap` facet: fill, status, the public
|
||||
companion; `src/api.ts`). The worker serves capnweb's browser build
|
||||
itself at `/_capnweb.js`.
|
||||
- **Fill job**: walks every diigo page into a cache in the background —
|
||||
DO alarms, a few pages per step, progress stored in the DO
|
||||
(`startFill`/`fillStatus`/`stopFill`), driven from the webkey page;
|
||||
the public page shows progress. "Invalidate the last N days" there
|
||||
drops the cached pages holding anything updated that recently
|
||||
(`invalidateRecent`), so the next fill refetches them.
|
||||
- The `DiigoBridge` entrypoint for other workers (its cache-id source is
|
||||
the goal-2 wiring TODO).
|
||||
|
||||
## State surface
|
||||
|
||||
Ids are **webkeys** ([the pattern](../docs/webkeys.md)): 256-bit bearer
|
||||
secrets that never ride a query string or path. The webkey page carries
|
||||
the cache id in the URL fragment (never sent to the server) and passes
|
||||
it in-band over Cap'n Web; forms carry ids in POST bodies; logs and pages
|
||||
show only a fingerprint (a prefix of the id's one-way hash).
|
||||
|
||||
- **The cache id**: the cache's read capability (bearer; not logged).
|
||||
Held by the user — saved to the password manager under a petname they
|
||||
choose (the username field; never sent to the server) — and passed
|
||||
per POST.
|
||||
- **The webapp instance id**: the diigo-read capability; lives in each
|
||||
cache DO's wiring, arrives from the mint step.
|
||||
- **The cookie**: lives **only in webapp's DO storage**; crosses the
|
||||
wire once, at mint time, as an opaque relay.
|
||||
- **The public cache**: no capability — `/public/<username>` is public
|
||||
by design (a guessable URL; hiding the link doesn't hide the page).
|
||||
|
||||
Stored state is meant to be durable: see the breaking-change rule in
|
||||
[capsite AGENTS.md](../AGENTS.md).
|
||||
|
||||
## Deployment concern: rate-limit `/api`
|
||||
|
||||
Public pages only read storage, so strangers can't make the cache spend
|
||||
your diigo session. `/api` is keyed (a cache id is needed), but Cap'n
|
||||
Web pipelining makes calls cheap to send. Before exposing a deployment:
|
||||
|
||||
- rate-limit `/api` (and `/public/*`, which reads storage) — on
|
||||
Cloudflare, the
|
||||
[Workers rate-limit binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/)
|
||||
(keyed by client and/or username); on other workerd hosts, a rate
|
||||
limit in the proxy in front;
|
||||
- run the fill job (goal 1e): public pages show only what's stored.
|
||||
|
||||
## RPC use (from another worker, same account)
|
||||
|
||||
```jsonc
|
||||
// wrangler.jsonc of the caller
|
||||
"services": [{ "binding": "DIIGO", "service": "diigo-cache", "entrypoint": "DiigoBridge" }]
|
||||
```
|
||||
|
||||
```ts
|
||||
// cache ids ride goal-2's wiring; see the capsite checklist
|
||||
const ndjson = await env.DIIGO.dumpNdjson(4); // 4 pages of PAGE_SIZE
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
pnpm types # regenerate worker-configuration.d.ts (after wrangler.jsonc changes)
|
||||
pnpm lint # fails if those types are stale; tsc over src/ and tests/
|
||||
pnpm test # vitest
|
||||
|
||||
Tests run the real worker and both DOs in the vitest pool, with
|
||||
`WEBAPP` bound to [a fake webapp](tests/fake-webapp.js) serving
|
||||
diigo-shaped items (`wrangler.tests.jsonc`).
|
||||
|
||||
## Run, deploy
|
||||
|
||||
[How to run / connect / deploy is maintained in the capsite checklist](../capsite-checklist.md)
|
||||
(single source; this README keeps only worker-level facts).
|
||||
|
||||
Status: create, dump, publish, and public pages exercised against live
|
||||
diigo in dev (2026-10-07); not yet deployed.
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "diigo-cache",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "wrangler dev -c wrangler.jsonc -c ../webapp/wrangler.jsonc",
|
||||
"types": "wrangler types",
|
||||
"lint": "wrangler types --check && tsc -p tsconfig.json && tsc -p tests/tsconfig.json && tsc -p scripts/tsconfig.json",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/vitest-plugin": "1.3.6",
|
||||
"@types/node": "^22",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "4.1.11",
|
||||
"wrangler": "^4.148.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"capnweb": "^0.12.0"
|
||||
}
|
||||
}
|
||||
Generated
-1713
File diff suppressed because it is too large.
Load diff
@@ -1,171 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/** @file Does a cache hold everything in a diigo RSS export? See {@link HELP}. */
|
||||
|
||||
/** printed on bad usage */
|
||||
const HELP = `usage: node scripts/compare-export.ts <cache.sqlite> <export.xml> <out-dir>
|
||||
|
||||
Generates RSS from the cache's items (src/rss.ts) and compares it with the
|
||||
export, keyed on link: title, tags, description, highlights and sticky
|
||||
notes. Prints counts to stdout; writes <out-dir>/from-cache.rss and
|
||||
<out-dir>/report.json (mismatched links, by category).
|
||||
`;
|
||||
|
||||
import * as nodeFs from "node:fs/promises";
|
||||
import { basename, join } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { itemDescription, toRss } from "../src/rss.ts";
|
||||
|
||||
type Item = Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* the exit status for incorrect usage (invalid options, missing
|
||||
* arguments): the shell's convention
|
||||
*
|
||||
* @see https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html
|
||||
*/
|
||||
const BAD_USAGE = 2;
|
||||
|
||||
/** one export item, as read */
|
||||
type Exported = { title: string; link: string; description: string };
|
||||
|
||||
/** a new object with each value mapped; keys kept (as `objectMap` in
|
||||
* @endo/common) */
|
||||
export function objectMap<V, W>(original: Record<string, V>, mapFn: (value: V, key: string) => W): Record<string, W> {
|
||||
return Object.fromEntries(Object.entries(original).map(([k, v]) => [k, mapFn(v, k)]));
|
||||
}
|
||||
|
||||
const FORBIDDEN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
|
||||
const clean = (s: string) => s.replace(FORBIDDEN, "");
|
||||
|
||||
/** diigo's RSS export, read leniently item by item (it isn't well-formed
|
||||
* XML: it carries characters XML forbids) */
|
||||
export function parseExport(xml: string): Exported[] {
|
||||
const field = (it: string, name: string) =>
|
||||
it.match(new RegExp(`<${name}><!\\[CDATA\\[([\\s\\S]*?)\\]\\]></${name}>`))?.[1] ?? "";
|
||||
return [...xml.matchAll(/<item>([\s\S]*?)<\/item>/g)].map((m) => ({
|
||||
title: clean(field(m[1], "title")),
|
||||
link: clean(field(m[1], "link")),
|
||||
description: clean(field(m[1], "description")),
|
||||
}));
|
||||
}
|
||||
|
||||
const PARTS = /^Tags:([\s\S]*?);Description:([\s\S]*?);Annotations and Sticky notes:([\s\S]*)$/;
|
||||
|
||||
/** what's wrong with `ours` as a rendering of `theirs` (empty: nothing) */
|
||||
function problems(o: Item, t: Exported): string[] {
|
||||
const found: string[] = [];
|
||||
const title = clean(String(o.title ?? ""));
|
||||
// the export cuts titles at 255
|
||||
if (title !== t.title && !(t.title.length === 255 && title.startsWith(t.title))) found.push("title differs");
|
||||
const mine = clean(itemDescription(o)).match(PARTS);
|
||||
const yours = t.description.match(PARTS);
|
||||
if (!mine || !yours) return [...found, "description unparsed"];
|
||||
if (mine[1] !== yours[1]) found.push("tags differ");
|
||||
if (mine[2] !== yours[2]) found.push("description differs");
|
||||
if (mine[3] !== yours[3]) found.push("annotations differ");
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* compare cached items with an export, keyed on link: each export item
|
||||
* is complete, missing, or has problems by category; cached links absent
|
||||
* from the export are reported too. Links only, never contents.
|
||||
*/
|
||||
export function compare(ours: Item[], theirs: Exported[]): { complete: number; report: Record<string, string[]> } {
|
||||
const byUrl = new Map<string, Item[]>();
|
||||
for (const it of ours) {
|
||||
const url = String(it.url ?? "");
|
||||
byUrl.set(url, [...(byUrl.get(url) ?? []), it]);
|
||||
}
|
||||
const report: Record<string, string[]> = {};
|
||||
const note = (category: string, link: string) => (report[category] ??= []).push(link);
|
||||
let complete = 0;
|
||||
for (const t of theirs) {
|
||||
const candidates = byUrl.get(t.link);
|
||||
if (!candidates) {
|
||||
note("missing from cache", t.link);
|
||||
continue;
|
||||
}
|
||||
// a link bookmarked twice: the best-matching candidate counts
|
||||
const best = candidates.map((o) => problems(o, t)).reduce((a, b) => (b.length < a.length ? b : a));
|
||||
if (best.length === 0) complete += 1;
|
||||
for (const p of best) note(p, t.link);
|
||||
}
|
||||
const exportLinks = new Set(theirs.map((t) => t.link));
|
||||
for (const url of byUrl.keys()) if (!exportLinks.has(url)) note("in cache, not in export", url);
|
||||
return { complete, report };
|
||||
}
|
||||
|
||||
/** read-only access to one cache's items: attenuates a database */
|
||||
export function cacheItems(db: { prepare(sql: string): { all(): unknown[] } }) {
|
||||
return {
|
||||
/** every item, newest update first */
|
||||
all: (): Item[] =>
|
||||
(db.prepare("select json from items order by updated desc").all() as { json: string }[]).map(
|
||||
(r) => JSON.parse(r.json) as Item,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** write access to files directly inside one directory: attenuates fs */
|
||||
export function outDir(fs: Pick<typeof nodeFs, "writeFile">, dir: string) {
|
||||
return {
|
||||
async write(name: string, text: string): Promise<void> {
|
||||
if (basename(name) !== name) throw new Error(`not a plain file name: ${name}`);
|
||||
await fs.writeFile(join(dir, name), text);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the comparison. Every power it uses comes in as a default argument
|
||||
* and is narrowed here — the database to {@link cacheItems}, the output
|
||||
* directory to {@link outDir} — before anything else uses it.
|
||||
*/
|
||||
export async function main(
|
||||
argv = process.argv.slice(2),
|
||||
{
|
||||
fs = nodeFs,
|
||||
// node:sqlite has only a synchronous API; one read of a local file
|
||||
connect = (path: string) => new DatabaseSync(path, { readOnly: true }),
|
||||
now = () => new Date(),
|
||||
stdout = process.stdout,
|
||||
stderr = process.stderr,
|
||||
exit = (code: number) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
}: {
|
||||
fs?: Pick<typeof nodeFs, "readFile" | "writeFile">;
|
||||
connect?: (path: string) => { prepare(sql: string): { all(): unknown[] } };
|
||||
now?: () => Date;
|
||||
stdout?: { write(text: string): unknown };
|
||||
stderr?: { write(text: string): unknown };
|
||||
exit?: (code: number) => void;
|
||||
} = {},
|
||||
): Promise<void> {
|
||||
const [dbPath, exportPath, outPath] = argv;
|
||||
if (!dbPath || !exportPath || !outPath) {
|
||||
stderr.write(HELP);
|
||||
return exit(BAD_USAGE);
|
||||
}
|
||||
const cache = cacheItems(connect(dbPath));
|
||||
const out = outDir(fs, outPath);
|
||||
const exportXml = await fs.readFile(exportPath, "utf8");
|
||||
|
||||
const ours = cache.all();
|
||||
await out.write("from-cache.rss", toRss(ours, { title: "from the cache", pubDate: now().toUTCString() }));
|
||||
const theirs = parseExport(exportXml);
|
||||
const { complete, report } = compare(ours, theirs);
|
||||
await out.write("report.json", JSON.stringify(report, null, 1));
|
||||
const counts = {
|
||||
export: theirs.length,
|
||||
cache: ours.length,
|
||||
complete,
|
||||
...objectMap(report, (links) => links.length),
|
||||
};
|
||||
stdout.write(`${JSON.stringify(counts, null, 1)}\n`);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
// run only as a program, not when imported (e.g. by a test)
|
||||
if (import.meta.main) await main();
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
// program scripts run under node (type stripping), so they get node's
|
||||
// types; the worker's own tsconfig keeps them out
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"lib": ["ES2022", "ESNext.Disposable"],
|
||||
"allowImportingTsExtensions": true
|
||||
},
|
||||
"include": ["./**/*.ts", "../src/rss.ts", "../src/items.ts"]
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
/** @file the Cap'n Web API at /api: trade a cache's webkey for a capability. */
|
||||
|
||||
import { RpcTarget } from "capnweb";
|
||||
import type { DiigoCacheLogic, FillStatus, PublicCacheLogic } from "./cache.js";
|
||||
import { idFromWebkey, isWebkey, shashKey } from "./webkeys.js";
|
||||
|
||||
/** the bindings the API reaches (structural) */
|
||||
export type ApiEnv = {
|
||||
CACHE_DO: DurableObjectNamespace<DiigoCacheLogic>;
|
||||
PUBLIC_DO: DurableObjectNamespace<PublicCacheLogic>;
|
||||
};
|
||||
|
||||
/** the fill-job surface of one cache (private or public) */
|
||||
type Fillable = {
|
||||
startFill(opts?: { pagesPerStep?: number }): Promise<FillStatus>;
|
||||
fillStatus(): Promise<FillStatus | undefined>;
|
||||
stopFill(): Promise<FillStatus>;
|
||||
invalidateRecent(days: number): Promise<{ pages: number }>;
|
||||
};
|
||||
|
||||
/** a cache's fill job and page invalidation, and nothing else */
|
||||
export class FillCap extends RpcTarget {
|
||||
#cache: Fillable;
|
||||
|
||||
constructor(cache: Fillable) {
|
||||
super();
|
||||
this.#cache = cache;
|
||||
}
|
||||
|
||||
/** start (or rejoin) the job; `pagesPerStep` 1–50 */
|
||||
async startFill(opts: unknown = {}): Promise<FillStatus> {
|
||||
const step = (opts as { pagesPerStep?: unknown } | null)?.pagesPerStep;
|
||||
if (step !== undefined && typeof step !== "number") throw new Error("pagesPerStep: expected a number");
|
||||
return this.#cache.startFill(step === undefined ? {} : { pagesPerStep: step });
|
||||
}
|
||||
|
||||
/** the job's progress, or undefined if none was started */
|
||||
async fillStatus(): Promise<FillStatus | undefined> {
|
||||
return this.#cache.fillStatus();
|
||||
}
|
||||
|
||||
/** stop the job; cached pages stay */
|
||||
async stopFill(): Promise<FillStatus> {
|
||||
return this.#cache.stopFill();
|
||||
}
|
||||
|
||||
/** drop the cached pages holding anything updated in the last `days`
|
||||
* days (1–3650), so they refetch */
|
||||
async invalidateRecent(days: unknown): Promise<{ pages: number }> {
|
||||
if (typeof days !== "number") throw new Error("days: expected a number");
|
||||
return this.#cache.invalidateRecent(days);
|
||||
}
|
||||
}
|
||||
|
||||
/** what the holder of a private cache's key may do */
|
||||
export class CacheCap extends FillCap {
|
||||
#key: string;
|
||||
#publicId: string | undefined;
|
||||
#env: ApiEnv;
|
||||
|
||||
constructor(env: ApiEnv, key: string, cache: Fillable, publicId: string | undefined) {
|
||||
super(cache);
|
||||
this.#env = env;
|
||||
this.#key = key;
|
||||
this.#publicId = publicId;
|
||||
}
|
||||
|
||||
/** a prefix of the key's one-way hash: names it without granting it */
|
||||
async fingerprint(): Promise<string> {
|
||||
return (await shashKey(this.#key)).slice(0, 8);
|
||||
}
|
||||
|
||||
/** whether a public companion exists (see {@link publicCache}) */
|
||||
hasPublic(): boolean {
|
||||
return this.#publicId !== undefined;
|
||||
}
|
||||
|
||||
/** the public companion's fill job; refused if never published (a
|
||||
* stub, not a maybe-null, so calls on it pipeline) */
|
||||
publicCache(): FillCap {
|
||||
if (!this.#publicId) throw new Error("no public cache: publish this cache first");
|
||||
const ns = this.#env.PUBLIC_DO;
|
||||
return new FillCap(ns.get(ns.idFromString(idFromWebkey(this.#publicId))));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* the main interface at /api. The browser holds a cache's key in a URL
|
||||
* fragment (`/cache/#<key>`, docs/webkeys.md), so it never reaches the
|
||||
* server in a URL; the webkey page passes it *in-band* to {@link cache}
|
||||
* and gets back a {@link CacheCap}. With authorization in-band,
|
||||
* cross-origin calls are safe (capnweb's note on `newWorkersRpcResponse`);
|
||||
* arguments are checked at runtime, since types are erased on the wire.
|
||||
*
|
||||
* @see https://github.com/cloudflare/capnweb
|
||||
*/
|
||||
export class CacheApi extends RpcTarget {
|
||||
#env: ApiEnv;
|
||||
|
||||
constructor(env: ApiEnv) {
|
||||
super();
|
||||
this.#env = env;
|
||||
}
|
||||
|
||||
/**
|
||||
* trade a cache's webkey for its capability. Refused keys get one
|
||||
* message for malformed and unknown alike, which never echoes the key.
|
||||
*/
|
||||
async cache(key: unknown): Promise<CacheCap> {
|
||||
const refused = () => new Error("no such cache");
|
||||
if (typeof key !== "string" || !isWebkey(key, 256)) {
|
||||
console.log({ event: "api", refused: "cache", reason: "malformed key" });
|
||||
throw refused();
|
||||
}
|
||||
const ns = this.#env.CACHE_DO;
|
||||
let stub;
|
||||
try {
|
||||
// a well-formed id from another namespace throws here
|
||||
stub = ns.get(ns.idFromString(idFromWebkey(key)));
|
||||
} catch (err) {
|
||||
// the key is never logged: it is the bearer secret
|
||||
console.log({ event: "api", refused: "cache", reason: String(err) });
|
||||
throw refused();
|
||||
}
|
||||
const wiring = await stub.wiring();
|
||||
if (!wiring) {
|
||||
console.log({ event: "api", refused: "cache", reason: "not wired" });
|
||||
throw refused();
|
||||
}
|
||||
return new CacheCap(this.#env, key, stub, wiring.publicId);
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
/** @file the webkey page at /cache/: a skeleton the key's holder drives over /api. */
|
||||
|
||||
/**
|
||||
* the webkey page, identical for every key (docs/webkeys.md): the key
|
||||
* rides the URL fragment, which browsers never send to the server or in a
|
||||
* Referer. Its script reads it, trades it for a capability
|
||||
* (`api.cache(key)`, Cap'n Web over /api, in-band), and drives the fill
|
||||
* job. Each round trip is its own HTTP batch session.
|
||||
*
|
||||
* Without a fragment it is a login form a password manager fills
|
||||
* (petname as username, cache id as password). The inputs have no
|
||||
* `name`, so a native submit (script failed) sends nothing; the key stays
|
||||
* in memory, out of the address bar and history.
|
||||
*/
|
||||
export const CACHE_PAGE_HTML = `<!doctype html>
|
||||
<html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer">
|
||||
<title>diigo cache</title></head>
|
||||
<body>
|
||||
<h1>diigo cache <code id="fingerprint"></code></h1>
|
||||
<p id="problem" hidden></p>
|
||||
<form id="login" hidden>
|
||||
<p><label>petname <input id="login-petname" autocomplete="username" size="24"></label></p>
|
||||
<p><label>cache id <input id="login-key" type="password" autocomplete="current-password" size="24" required></label></p>
|
||||
<p><button type="submit">open</button></p>
|
||||
</form>
|
||||
<section id="private" hidden>
|
||||
<h2>private cache</h2>
|
||||
<p id="private-status">no fill job yet</p>
|
||||
<button type="button" data-target="private" data-action="start">fill</button>
|
||||
<button type="button" data-target="private" data-action="stop">stop</button>
|
||||
<p><label>invalidate the last <input type="number" id="private-days" min="1" max="3650" value="7" size="5"> days</label>
|
||||
<button type="button" data-target="private" data-action="invalidate">invalidate</button>
|
||||
<span id="private-invalidated"></span></p>
|
||||
</section>
|
||||
<section id="public" hidden>
|
||||
<h2>public cache</h2>
|
||||
<p id="public-status">no fill job yet</p>
|
||||
<button type="button" data-target="public" data-action="start">fill</button>
|
||||
<button type="button" data-target="public" data-action="stop">stop</button>
|
||||
<p><label>invalidate the last <input type="number" id="public-days" min="1" max="3650" value="7" size="5"> days</label>
|
||||
<button type="button" data-target="public" data-action="invalidate">invalidate</button>
|
||||
<span id="public-invalidated"></span></p>
|
||||
</section>
|
||||
<p><a href="/">← home</a></p>
|
||||
<script type="module">
|
||||
import { newHttpBatchRpcSession } from "/_capnweb.js";
|
||||
|
||||
let key = location.hash.slice(1);
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const problem = (text) => {
|
||||
$("problem").textContent = text;
|
||||
$("problem").hidden = false;
|
||||
};
|
||||
/** a fresh batch session, traded for this key's capability */
|
||||
const cap = () => newHttpBatchRpcSession("/api").cache(key);
|
||||
/** the fill-job stub for a target */
|
||||
const job = (target) => (target === "public" ? cap().publicCache() : cap());
|
||||
|
||||
const describe = (s) => {
|
||||
if (!s) return "no fill job yet";
|
||||
const of = Math.max(0, s.nextPage - 1) + " of " + (s.pages ?? "?") + " pages";
|
||||
return {
|
||||
running: "filling: " + of,
|
||||
done: "filled: " + of,
|
||||
stopped: "fill stopped: " + of,
|
||||
failed: "fill failed at page " + s.nextPage + ": " + (s.error ?? "unknown error"),
|
||||
}[s.state];
|
||||
};
|
||||
|
||||
let polling = false;
|
||||
async function refresh(hasPublic) {
|
||||
const targets = hasPublic ? ["private", "public"] : ["private"];
|
||||
const statuses = await Promise.all(targets.map((t) => job(t).fillStatus()));
|
||||
targets.forEach((t, i) => ($(t + "-status").textContent = describe(statuses[i])));
|
||||
const running = statuses.some((s) => s?.state === "running");
|
||||
if (running && !polling) {
|
||||
polling = true;
|
||||
setTimeout(() => {
|
||||
polling = false;
|
||||
refresh(hasPublic).catch(report);
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
function report(err) {
|
||||
console.error({ event: "cache-page", error: String(err) });
|
||||
problem(String(err));
|
||||
}
|
||||
|
||||
/** no fragment: ask for the key (the password manager fills it in) */
|
||||
function login() {
|
||||
const form = $("login");
|
||||
form.hidden = false;
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
key = $("login-key").value.trim();
|
||||
if (!key) return;
|
||||
form.hidden = true;
|
||||
main().catch(report);
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (!key) return login();
|
||||
const c = cap();
|
||||
const [fingerprint, hasPublic] = await Promise.all([c.fingerprint(), c.hasPublic()]);
|
||||
$("fingerprint").textContent = fingerprint;
|
||||
$("private").hidden = false;
|
||||
$("public").hidden = !hasPublic;
|
||||
for (const button of document.querySelectorAll("button[data-target]")) {
|
||||
button.addEventListener("click", () => {
|
||||
const { target, action } = button.dataset;
|
||||
const j = job(target);
|
||||
if (action === "invalidate") {
|
||||
const days = Number($(target + "-days").value);
|
||||
j.invalidateRecent(days)
|
||||
.then((r) => ($(target + "-invalidated").textContent = "dropped " + r.pages + " cached pages; fill to refetch"))
|
||||
.catch(report);
|
||||
return;
|
||||
}
|
||||
(action === "start" ? j.startFill() : j.stopFill())
|
||||
.then(() => refresh(hasPublic))
|
||||
.catch(report);
|
||||
});
|
||||
}
|
||||
await refresh(hasPublic);
|
||||
}
|
||||
main().catch(report);
|
||||
</script>
|
||||
</body></html>`;
|
||||
@@ -1,21 +0,0 @@
|
||||
-- pageHeader:
|
||||
select total, etched_at from pages where page_num = ? and count = ?;
|
||||
|
||||
-- pageItems:
|
||||
select items.json
|
||||
from page_members
|
||||
join items on items.item_id = page_members.item_id
|
||||
where page_members.page_num = ?
|
||||
order by page_members.pos;
|
||||
|
||||
-- knownTotal:
|
||||
select total from pages where total > 0 order by etched_at desc limit 1;
|
||||
|
||||
-- deepestPageSince:
|
||||
select max(page_members.page_num) as last
|
||||
from page_members
|
||||
join items on items.item_id = page_members.item_id
|
||||
where cast(items.updated as integer) >= ?;
|
||||
|
||||
-- pagesThrough:
|
||||
select count(*) as n from pages where page_num <= ?;
|
||||
@@ -1,51 +0,0 @@
|
||||
-- schemaV1:
|
||||
create table if not exists items (
|
||||
item_id text primary key,
|
||||
url text not null,
|
||||
title text not null,
|
||||
private integer not null,
|
||||
json text not null,
|
||||
updated text not null
|
||||
);
|
||||
create table if not exists pages (
|
||||
page_num integer primary key,
|
||||
count integer not null,
|
||||
total integer,
|
||||
etched_at text not null
|
||||
);
|
||||
create table if not exists page_members (
|
||||
page_num integer not null,
|
||||
pos integer not null,
|
||||
item_id text not null,
|
||||
primary key (page_num, pos)
|
||||
);
|
||||
|
||||
-- renumberV2:
|
||||
update page_members set page_num = -(page_num + 1);
|
||||
update page_members set page_num = -page_num;
|
||||
update pages set page_num = -(page_num + 1);
|
||||
update pages set page_num = -page_num;
|
||||
|
||||
-- clearPageMembers:
|
||||
delete from page_members where page_num = ?;
|
||||
|
||||
-- upsertItem:
|
||||
insert into items (item_id, url, title, private, json, updated)
|
||||
values (?, ?, ?, ?, ?, ?)
|
||||
on conflict(item_id) do update set
|
||||
url = excluded.url, title = excluded.title, private = excluded.private,
|
||||
json = excluded.json, updated = excluded.updated;
|
||||
|
||||
-- insertPageMember:
|
||||
insert into page_members (page_num, pos, item_id) values (?, ?, ?);
|
||||
|
||||
-- upsertPage:
|
||||
insert into pages (page_num, count, total, etched_at) values (?, ?, ?, ?)
|
||||
on conflict(page_num) do update set
|
||||
count = excluded.count, total = excluded.total, etched_at = excluded.etched_at;
|
||||
|
||||
-- dropPageMembersThrough:
|
||||
delete from page_members where page_num <= ?;
|
||||
|
||||
-- dropPagesThrough:
|
||||
delete from pages where page_num <= ?;
|
||||
@@ -1,486 +0,0 @@
|
||||
/**
|
||||
* @file the cache Durable Objects' logic: a private and a public page cache.
|
||||
* The runtime classes are made at the edge (src/index.ts).
|
||||
*/
|
||||
|
||||
import { DurableObject, RpcTarget } from "cloudflare:workers";
|
||||
import type { PagedGet } from "./diigo.js";
|
||||
import { publicOnly, toRows } from "./items.js";
|
||||
import { makeReader, makeWriter, SCHEMA_VERSION } from "./store.js";
|
||||
import type { Reader, Writer } from "./store.js";
|
||||
import type { Item, ItemRow } from "./items.js";
|
||||
|
||||
export type { Item };
|
||||
|
||||
/** one cached page, raw: `items` are the dump rows (JSON strings), ready
|
||||
* to re-join with newlines */
|
||||
export type CachePage = {
|
||||
total: number;
|
||||
items: string[];
|
||||
/** true when answered from storage (no diigo call) */
|
||||
cached: boolean;
|
||||
/** when the page was stored (absent on a fresh fetch) */
|
||||
etchedAt?: string;
|
||||
};
|
||||
|
||||
const MS_PER_CALL = 500;
|
||||
|
||||
/**
|
||||
* items per diigo page — the one size the worker asks for everywhere
|
||||
* (fill, public pages, dumps), so a cache never mixes sizes. Pages are
|
||||
* cached by (page number, size): changing this turns every cached page
|
||||
* into a miss (items survive; pages refetch), and fails any fill job
|
||||
* counting in the old size. 100 is diigo's cap: asked for 128, it
|
||||
* returned 100 (observed 2026-10-07).
|
||||
*/
|
||||
export const PAGE_SIZE = 100;
|
||||
|
||||
/** the size fill jobs counted in before FillStatus recorded it */
|
||||
const LEGACY_FILL_PAGE_SIZE = 24;
|
||||
|
||||
/** the pause before each fill step's alarm: a step already paces its
|
||||
* pages at MS_PER_CALL; this keeps steps from running back to back */
|
||||
const FILL_STEP_DELAY_MS = 1000;
|
||||
|
||||
/**
|
||||
* a fill job's progress (goal 1e; tests/fill.test.ts). Stored in the DO
|
||||
* (new state, additive), so it survives eviction; advanced by alarms.
|
||||
*/
|
||||
export type FillStatus = {
|
||||
state: "running" | "done" | "stopped" | "failed";
|
||||
/** the next diigo page to fetch (pages already cached are skipped) */
|
||||
nextPage: number;
|
||||
/** diigo's page count, known after page 1 */
|
||||
pages: number | null;
|
||||
/** the page size `nextPage` and `pages` count in; absent on jobs
|
||||
* saved before this field existed (they counted in 24s) */
|
||||
pageSize?: number;
|
||||
/** the page numbering `nextPage` counts in: 2 since diigo's 0-based
|
||||
* page_num is translated; absent on jobs that sent it unchanged */
|
||||
numbering?: number;
|
||||
/** pages fetched from diigo by this job (cache hits not counted) */
|
||||
fetched: number;
|
||||
startedAt: string;
|
||||
updatedAt: string;
|
||||
/** why it failed: safe to show and log (no ids, no header values) */
|
||||
error?: string;
|
||||
};
|
||||
|
||||
/** the page size a fill job counts in (old jobs didn't record it) */
|
||||
function fillPageSize(status: FillStatus): number {
|
||||
return status.pageSize ?? LEGACY_FILL_PAGE_SIZE;
|
||||
}
|
||||
|
||||
/** does a stored fill job count pages the way this code does? */
|
||||
function fillCountsAsNow(status: FillStatus): boolean {
|
||||
return fillPageSize(status) === PAGE_SIZE && status.numbering === SCHEMA_VERSION;
|
||||
}
|
||||
|
||||
/** release an RPC stub, if it is one (plain objects are left alone) */
|
||||
function disposeStub(stub: unknown): void {
|
||||
const dispose = (stub as { [Symbol.dispose]?: () => void } | null)?.[Symbol.dispose];
|
||||
if (typeof dispose === "function") dispose.call(stub);
|
||||
}
|
||||
|
||||
/** the clock authority a cache uses: reading time, and waiting. Passed
|
||||
* in (ocap discipline), so tests can interpose a fixed clock. */
|
||||
export type Clock = {
|
||||
/** epoch milliseconds */
|
||||
now(): number;
|
||||
sleep(ms: number): Promise<void>;
|
||||
};
|
||||
|
||||
|
||||
/** a cache's wiring: the webapp instance it asks on a miss, plus (private
|
||||
* cache only) the public companion's id, recorded once published */
|
||||
type Wiring = { webappId: string; publicId?: string | undefined };
|
||||
|
||||
/** the diigo-cache DO's bindings (structural; `at` mirrors webapp's
|
||||
* WebAppFactory) */
|
||||
export type CacheEnv = {
|
||||
WEBAPP: {
|
||||
at(id: string): Promise<PagedGet>;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* the shared page-cache behavior; {@link DiigoCacheLogic} and
|
||||
* {@link PublicCacheLogic} are independent and differ only in what they
|
||||
* `keep` of a fetched page (the public one drops private rows before
|
||||
* storing, {@link publicOnly}). Pages are the unit of caching: a hit is
|
||||
* served from storage with no diigo call; a miss asks the webapp instance
|
||||
* in the cache's wiring and stores the page.
|
||||
*
|
||||
* The webapp id in the wiring authorizes diigo reads (the cookie rides in
|
||||
* that DO's storage); the id this DO is addressed by authorizes cache
|
||||
* reads. Neither is logged. The {@link Clock} is required: time comes from
|
||||
* the edge that constructs the DO.
|
||||
*/
|
||||
abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
#step = 0;
|
||||
#pause?: Promise<void>;
|
||||
#clock: Clock;
|
||||
|
||||
/** `clock` is required: time comes from the edge that constructs us
|
||||
* (src/index.ts in the worker, tests/test-worker.ts in tests) */
|
||||
#reader: Reader;
|
||||
#writer: Writer;
|
||||
|
||||
constructor(ctx: DurableObjectState, env: CacheEnv, clock: Clock) {
|
||||
super(ctx, env);
|
||||
this.#clock = clock;
|
||||
this.#reader = makeReader(ctx.storage.sql);
|
||||
this.#writer = makeWriter(ctx.storage);
|
||||
// tables exist (and old storage is migrated) before any request, so
|
||||
// a read-only viewer never meets a missing table
|
||||
void ctx.blockConcurrencyWhile(async () => {
|
||||
await null; // let the subclass constructor finish: `kind` is its field
|
||||
const from = this.#writer.migrate();
|
||||
if (from < SCHEMA_VERSION) console.log({ event: "schema", kind: this.kind, from, to: SCHEMA_VERSION });
|
||||
});
|
||||
}
|
||||
|
||||
/** now, as an ISO timestamp */
|
||||
#iso(): string {
|
||||
return new Date(this.#clock.now()).toISOString();
|
||||
}
|
||||
|
||||
/** one-shot wiring. Idempotent; different values are refused (mint a
|
||||
* new cache instead). */
|
||||
async setup(init: Wiring): Promise<void> {
|
||||
const stored = await this.ctx.storage.get<Wiring>("init");
|
||||
if (stored) {
|
||||
if (stored.webappId !== init.webappId || stored.publicId !== init.publicId) {
|
||||
throw new Error("already wired to different ids; mint a new cache instead");
|
||||
}
|
||||
return;
|
||||
}
|
||||
await this.ctx.storage.put("init", init);
|
||||
}
|
||||
|
||||
/** the stored wiring */
|
||||
async wiring(): Promise<Wiring | undefined> {
|
||||
return this.ctx.storage.get<Wiring>("init");
|
||||
}
|
||||
|
||||
/** which rows of a fetched page this cache stores */
|
||||
protected abstract keep(rows: ItemRow[]): ItemRow[];
|
||||
|
||||
/** which cache this is, for logs (never the id: that's the bearer key) */
|
||||
protected abstract readonly kind: "private" | "public";
|
||||
|
||||
/**
|
||||
* start (or rejoin) the fill job: walk every diigo page into this
|
||||
* cache, `pagesPerStep` per alarm (default 20, 1–50). Starting while a
|
||||
* job runs returns that job unchanged; a finished, stopped, or failed
|
||||
* job is replaced by a fresh one (cached pages are skipped anyway).
|
||||
*/
|
||||
async startFill(opts: { pagesPerStep?: number } = {}): Promise<FillStatus> {
|
||||
const current = await this.fillStatus();
|
||||
if (current?.state === "running" && fillCountsAsNow(current)) return current;
|
||||
const step = Math.trunc(opts.pagesPerStep ?? 20);
|
||||
if (!(step >= 1 && step <= 50)) throw new Error("pagesPerStep: expected 1–50");
|
||||
const now = this.#iso();
|
||||
const status: FillStatus = {
|
||||
state: "running",
|
||||
nextPage: 1,
|
||||
pages: this.#knownPages(),
|
||||
pageSize: PAGE_SIZE,
|
||||
numbering: SCHEMA_VERSION,
|
||||
fetched: 0,
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
await this.ctx.storage.put({ fill: status, fillStep: step });
|
||||
await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
|
||||
console.log({ event: "fill", kind: this.kind, state: status.state, pagesPerStep: step });
|
||||
return status;
|
||||
}
|
||||
|
||||
/** the fill job's progress, or undefined if none was ever started;
|
||||
* the page count comes from any cached page until the job learns it */
|
||||
async fillStatus(): Promise<FillStatus | undefined> {
|
||||
const fill = await this.ctx.storage.get<FillStatus>("fill");
|
||||
return fill && fill.pages === null ? { ...fill, pages: this.#knownPages() } : fill;
|
||||
}
|
||||
|
||||
/** stop the fill job after its current step; cached pages stay */
|
||||
async stopFill(): Promise<FillStatus> {
|
||||
const current = await this.fillStatus();
|
||||
if (!current) throw new Error("no fill job to stop");
|
||||
if (current.state !== "running") return current;
|
||||
const stopped: FillStatus = { ...current, state: "stopped", updatedAt: this.#iso() };
|
||||
await this.ctx.storage.put("fill", stopped);
|
||||
await this.ctx.storage.deleteAlarm();
|
||||
console.log({ event: "fill", kind: this.kind, state: "stopped", nextPage: stopped.nextPage, pages: stopped.pages });
|
||||
return stopped;
|
||||
}
|
||||
|
||||
/**
|
||||
* drop the cached pages holding anything diigo updated in the last
|
||||
* `days` days, and every page before them (newer still; and new
|
||||
* updates push items back), so the next read or fill refetches them.
|
||||
* Item rows stay. Returns how many pages were dropped.
|
||||
*/
|
||||
async invalidateRecent(days: number): Promise<{ pages: number }> {
|
||||
if (!Number.isInteger(days) || days < 1 || days > 3650) throw new Error("days: expected a whole number from 1 to 3650");
|
||||
const cutoff = Math.floor(this.#clock.now() / 1000) - days * 24 * 60 * 60;
|
||||
const deepest = this.#reader.deepestPageSince(cutoff);
|
||||
if (!deepest) {
|
||||
console.log({ event: "cache", kind: this.kind, outcome: "invalidated", days, pages: 0 });
|
||||
return { pages: 0 };
|
||||
}
|
||||
const pages = this.#reader.pagesThrough(deepest);
|
||||
this.#writer.dropPagesThrough(deepest);
|
||||
console.log({ event: "cache", kind: this.kind, outcome: "invalidated", days, pages });
|
||||
return { pages };
|
||||
}
|
||||
|
||||
/** one fill step: up to `fillStep` pages, progress saved after each,
|
||||
* then the next step is scheduled (or the job ends) */
|
||||
async alarm(): Promise<void> {
|
||||
const step = (await this.ctx.storage.get<number>("fillStep")) ?? 20;
|
||||
let status = await this.fillStatus();
|
||||
// a job saved under another page size or numbering counts its pages
|
||||
// differently: resuming it would skip or repeat items, so it fails
|
||||
if (status?.state === "running" && !fillCountsAsNow(status)) {
|
||||
const error =
|
||||
fillPageSize(status) !== PAGE_SIZE
|
||||
? `page size changed (from ${fillPageSize(status)} to ${PAGE_SIZE}); start the fill again`
|
||||
: "page numbering changed (diigo counts pages from 0); start the fill again";
|
||||
status = { ...status, state: "failed", error, updatedAt: this.#iso() };
|
||||
console.error({ event: "fill", kind: this.kind, state: "failed", error });
|
||||
await this.ctx.storage.put("fill", status);
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < step && status?.state === "running"; i += 1) {
|
||||
if (status.pages !== null && status.nextPage > status.pages) {
|
||||
status = { ...status, state: "done" };
|
||||
break;
|
||||
}
|
||||
try {
|
||||
const page = await this.page(status.nextPage, PAGE_SIZE);
|
||||
const fetched = status.fetched + (page.cached ? 0 : 1);
|
||||
// a page whose own total says the data ended before it (diigo
|
||||
// answers total 0 past the end) ends the walk; the count is the
|
||||
// last page with items. Judged by total, not by items: the
|
||||
// public cache may keep none of a page that isn't the end.
|
||||
if (page.total <= (status.nextPage - 1) * PAGE_SIZE) {
|
||||
status = { ...status, state: "done", pages: status.nextPage - 1, fetched, updatedAt: this.#iso() };
|
||||
break;
|
||||
}
|
||||
status = {
|
||||
...status,
|
||||
nextPage: status.nextPage + 1,
|
||||
pages: Math.ceil(page.total / PAGE_SIZE),
|
||||
fetched,
|
||||
updatedAt: this.#iso(),
|
||||
};
|
||||
} catch (err) {
|
||||
status = { ...status, state: "failed", error: String(err), updatedAt: this.#iso() };
|
||||
console.error({ event: "fill", kind: this.kind, state: "failed", page: status.nextPage, error: status.error });
|
||||
}
|
||||
// a stop that landed mid-step wins
|
||||
if ((await this.fillStatus())?.state === "stopped") return;
|
||||
await this.ctx.storage.put("fill", status);
|
||||
}
|
||||
if (!status) return;
|
||||
if (status.state === "running" && status.pages !== null && status.nextPage > status.pages) {
|
||||
status = { ...status, state: "done", updatedAt: this.#iso() };
|
||||
}
|
||||
await this.ctx.storage.put("fill", status);
|
||||
console.log({ event: "fill", kind: this.kind, state: status.state, nextPage: status.nextPage, pages: status.pages, fetched: status.fetched });
|
||||
if (status.state === "running") await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
|
||||
}
|
||||
|
||||
/** diigo's page count, if any cached page recorded `total` (pages past
|
||||
* the end record 0, so they don't count) */
|
||||
#knownPages(): number | null {
|
||||
const total = this.#reader.knownTotal();
|
||||
return total === null ? null : Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
}
|
||||
|
||||
/**
|
||||
* read page `pageNum` (`count` per page, diigo's updated-desc order):
|
||||
* storage first; on miss, fetch that one page through the webapp
|
||||
* instance (every page carries `total`) and etch. Cache provenance
|
||||
* rides in the result (`cached`).
|
||||
*/
|
||||
async page(pageNum: number, count: number): Promise<CachePage> {
|
||||
const init = await this.wiring();
|
||||
if (!init) throw new Error("not wired: this cache id was never set up");
|
||||
|
||||
const hit = await this.#pageFromStorage(pageNum, count);
|
||||
if (hit) {
|
||||
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: hit.items.length });
|
||||
return hit;
|
||||
}
|
||||
|
||||
// a miss calls diigo: one call path at a time, min spacing
|
||||
// MS_PER_CALL (webapp's Gate pattern; per activation). Hits above
|
||||
// never wait.
|
||||
let before;
|
||||
do {
|
||||
before = this.#step;
|
||||
if (this.#pause) await this.#pause;
|
||||
} while (before !== this.#step);
|
||||
this.#step += 1;
|
||||
this.#pause = this.#clock.sleep(MS_PER_CALL);
|
||||
// a request ahead of us at the gate may have etched this page
|
||||
const late = await this.#pageFromStorage(pageNum, count);
|
||||
if (late) {
|
||||
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: late.items.length });
|
||||
return late;
|
||||
}
|
||||
|
||||
// RPC stubs (the app and each pipelined step) are disposed once the
|
||||
// page is in hand: undisposed stubs keep this DO from being evicted
|
||||
const data = await this.#fetchPage(init.webappId, pageNum, count);
|
||||
// diigo may cap the page size below what we asked: a short page that
|
||||
// isn't the last would silently skip items. If `total` ever
|
||||
// overstated what diigo returns, the true last page would look short
|
||||
// too. The next page tells them apart: empty means the data ends
|
||||
// here; anything else means items would be skipped — refuse loudly.
|
||||
const lastPage = Math.max(1, Math.ceil(data.total / count));
|
||||
if (data.items.length < count && pageNum < lastPage) {
|
||||
await this.#clock.sleep(MS_PER_CALL);
|
||||
const next = await this.#fetchPage(init.webappId, pageNum + 1, count);
|
||||
if (next.items.length > 0) {
|
||||
const error = `diigo returned ${data.items.length} items for page ${pageNum} of ${lastPage} (asked for ${count}), then ${next.items.length} for page ${pageNum + 1}: page size not honored?`;
|
||||
console.error({ event: "cache", kind: this.kind, page: pageNum, outcome: "short-page", fetched: data.items.length, asked: count, nextFetched: next.items.length });
|
||||
throw new Error(error);
|
||||
}
|
||||
const actual = (pageNum - 1) * count + data.items.length;
|
||||
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "total-overstated", total: data.total, actual });
|
||||
}
|
||||
const kept = this.keep(toRows(data.items, console));
|
||||
// fetched vs kept: the public cache's drop of private rows shows here
|
||||
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "miss", fetched: data.items.length, kept: kept.length });
|
||||
return this.#etch(pageNum, count, data.total, kept);
|
||||
}
|
||||
|
||||
/** one diigo page, raw, through the webapp instance; the RPC stubs (the
|
||||
* app and each pipelined step) are disposed once the page is in hand —
|
||||
* undisposed stubs keep this DO from being evicted */
|
||||
async #fetchPage(webappId: string, pageNum: number, count: number): Promise<{ total: number; items: Item[] }> {
|
||||
const app = await this.env.WEBAPP.at(webappId);
|
||||
const joined = app.pathjoin("load_user_items");
|
||||
// diigo's page_num counts from 0; ours from 1
|
||||
const queried = joined.query({ sort: "updated", count, page_num: pageNum - 1 });
|
||||
try {
|
||||
return JSON.parse(await queried.get()) as { total: number; items: Item[] };
|
||||
} finally {
|
||||
for (const stub of [queried, joined, app]) disposeStub(stub);
|
||||
}
|
||||
}
|
||||
|
||||
/** etch a page (one transaction): upsert items, mark the page, keep
|
||||
* the fetch-time order; returns the cache-page shape */
|
||||
#etch(pageNum: number, count: number, total: number, rows: ItemRow[]): CachePage {
|
||||
this.#writer.etch(pageNum, count, total, rows, this.#iso());
|
||||
return { total, items: rows.map((r) => r.json), cached: false };
|
||||
}
|
||||
|
||||
/** storage-backed page read; null = cache miss. Replay order comes
|
||||
* from `page_members`. */
|
||||
async #pageFromStorage(pageNum: number, count: number): Promise<CachePage | null> {
|
||||
const stored = this.#reader.page(pageNum, count);
|
||||
return stored && { ...stored, cached: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* a read-only view of this cache, for pages anyone may read (the public
|
||||
* page): stored pages and fill progress, from the reader facet only —
|
||||
* it cannot fetch from diigo or change storage
|
||||
*/
|
||||
viewer(): PageViewer {
|
||||
return new PageViewer(this.#reader, () => this.fillStatus());
|
||||
}
|
||||
}
|
||||
|
||||
/** what anyone may see of a cache: stored pages and fill progress */
|
||||
export class PageViewer extends RpcTarget {
|
||||
#reader: Reader;
|
||||
#fillStatus: () => Promise<FillStatus | undefined>;
|
||||
|
||||
constructor(reader: Reader, fillStatus: () => Promise<FillStatus | undefined>) {
|
||||
super();
|
||||
this.#reader = reader;
|
||||
this.#fillStatus = fillStatus;
|
||||
}
|
||||
|
||||
/** a stored page, or null if it hasn't been fetched (at this size) */
|
||||
page(pageNum: number, count: number): CachePage | null {
|
||||
const stored = this.#reader.page(pageNum, count);
|
||||
return stored && { ...stored, cached: true };
|
||||
}
|
||||
|
||||
/** diigo's total, as last stored, or null if nothing is stored */
|
||||
knownTotal(): number | null {
|
||||
return this.#reader.knownTotal();
|
||||
}
|
||||
|
||||
/** the cache's fill job, if any */
|
||||
fillStatus(): Promise<FillStatus | undefined> {
|
||||
return this.#fillStatus();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* the private cache's logic (exported to the runtime as `DiigoCache` by
|
||||
* src/index.ts): public+private items, addressed by its cache id (a
|
||||
* webkey, held by the user).
|
||||
*/
|
||||
export class DiigoCacheLogic extends PagedCache {
|
||||
protected readonly kind = "private";
|
||||
|
||||
protected keep(rows: ItemRow[]): ItemRow[] {
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** one-way addition of the public companion (private → public
|
||||
* publishable later; once set, immutable). The webapp id already in
|
||||
* the wiring is what makes this work without re-minting. */
|
||||
async addPublic(publicId: string): Promise<void> {
|
||||
const stored = await this.ctx.storage.get<Wiring>("init");
|
||||
if (!stored) throw new Error("not wired");
|
||||
if (stored.publicId) {
|
||||
if (stored.publicId !== publicId) {
|
||||
throw new Error("already has a public cache");
|
||||
}
|
||||
return;
|
||||
}
|
||||
await this.ctx.storage.put("init", { ...stored, publicId });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* the public cache: shared items only — {@link publicOnly} drops private
|
||||
* rows before they are stored, so this DO's storage holds nothing
|
||||
* private. Widely shared: addressed by diigo username in the worker's
|
||||
* route path (`/public/<username>`). It does hold the webapp id (the same
|
||||
* cookie session the private cache uses), so it *could* read private
|
||||
* items; it keeps none. Public page n is diigo page n, filtered: it may
|
||||
* hold fewer than `count` items. Doubles as the username→instance index
|
||||
* (the idFromName("index") instance holds the kv mapping and is never
|
||||
* wired).
|
||||
*/
|
||||
export class PublicCacheLogic extends PagedCache {
|
||||
protected readonly kind = "public";
|
||||
|
||||
protected keep(rows: ItemRow[]): ItemRow[] {
|
||||
return publicOnly(rows);
|
||||
}
|
||||
|
||||
/** register/replace the username → this-instance mapping (called on
|
||||
* the idFromName("index") instance) */
|
||||
async register(username: string, publicId: string): Promise<void> {
|
||||
this.ctx.storage.kv.put(`user:${username}`, publicId);
|
||||
}
|
||||
|
||||
/** resolve a username to a public-cache instance id (index role);
|
||||
* undefined = not registered */
|
||||
async lookup(username: string): Promise<string | undefined> {
|
||||
return this.ctx.storage.kv.get<string>(`user:${username}`);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
/** @file capnweb's browser build, as text, for the worker to serve. */
|
||||
// @ts-expect-error: a Text-rule import (wrangler.jsonc "rules"), not code
|
||||
import source from "../node_modules/capnweb/dist/index.js";
|
||||
|
||||
/**
|
||||
* capnweb's browser build (a self-contained ES module), served at
|
||||
* /_capnweb.js; wrangler's Text rule makes the import a string.
|
||||
* Self-hosted: no third-party script on a page that holds a bearer key.
|
||||
*/
|
||||
export const CAPNWEB_BROWSER_JS: string = source;
|
||||
@@ -1,44 +0,0 @@
|
||||
/** @file the diigo bookmark generator over a fluent handle (not used by the worker today). */
|
||||
|
||||
export type PagedGet = {
|
||||
pathjoin(ref: string): PagedGet;
|
||||
query(params: Record<string, string | number>): PagedGet;
|
||||
get(): Promise<string>;
|
||||
};
|
||||
|
||||
export type DumpOptions = {
|
||||
/** fluent handle for the diigo account, cookie attached upstream */
|
||||
diigoAPI: PagedGet;
|
||||
pages?: number;
|
||||
count?: number;
|
||||
log?: (event: Record<string, unknown>) => void;
|
||||
};
|
||||
|
||||
/** yield diigo bookmarks, most-recently-updated first, `pages * count` at
|
||||
* most. `diigoAPI` is attenuated authority; over RPC the generator runs in
|
||||
* the caller's address space against a stub. */
|
||||
export async function* dumpBookmarks({
|
||||
diigoAPI,
|
||||
pages = 2,
|
||||
count = 24,
|
||||
log = () => {},
|
||||
}: DumpOptions): AsyncGenerator<Record<string, unknown>> {
|
||||
const getUserItems = (page: number) =>
|
||||
diigoAPI
|
||||
.pathjoin("load_user_items")
|
||||
.query({ sort: "updated", count, page_num: page })
|
||||
.get()
|
||||
.then(JSON.parse) as Promise<{ total: number; items: Record<string, unknown>[] }>;
|
||||
|
||||
const first = await getUserItems(1);
|
||||
const totalPages = Math.ceil(first.total / count);
|
||||
log({ event: "start", total: first.total, pages, totalPages });
|
||||
|
||||
let got = 0;
|
||||
for (let page = 1; page <= Math.min(pages, totalPages); page += 1) {
|
||||
const data = page === 1 ? first : await getUserItems(page);
|
||||
yield* data.items;
|
||||
got += data.items.length;
|
||||
log({ event: "page", page, of: pages, got });
|
||||
}
|
||||
}
|
||||
@@ -1,591 +0,0 @@
|
||||
/**
|
||||
* @file diigo-cache worker: the create flow, the webkey page and its API,
|
||||
* and public pages. See the default export for its routes.
|
||||
*/
|
||||
|
||||
import { WorkerEntrypoint } from "cloudflare:workers";
|
||||
import { newWorkersRpcResponse } from "capnweb";
|
||||
import { CacheApi } from "./api.js";
|
||||
import { CAPNWEB_BROWSER_JS } from "./capnweb-browser.js";
|
||||
import { CACHE_PAGE_HTML } from "./cache-page.js";
|
||||
import { DiigoCacheLogic, PublicCacheLogic } from "./cache.js";
|
||||
import { PAGE_SIZE } from "./cache.js";
|
||||
import type { CacheEnv, Clock, FillStatus } from "./cache.js";
|
||||
import type { Item } from "./cache.js";
|
||||
import { updatedISO, usernameOf } from "./items.js";
|
||||
import { toWebkey, idFromWebkey, isWebkey, shashKey } from "./webkeys.js";
|
||||
import { pmSave } from "./pm-save.js";
|
||||
|
||||
/** the live clock: the worker's entry module reads ambient time and hands
|
||||
* it to the cache logic, which uses only the clock it is given */
|
||||
function liveClock(): Clock {
|
||||
return { now: () => Date.now(), sleep: (ms) => new Promise((r) => setTimeout(r, ms)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* the private cache, as the runtime constructs it. DO classes must be
|
||||
* exports of the main module, and the runtime passes only (ctx, env): a
|
||||
* Cloudflare constraint, met here at the edge by supplying the live clock.
|
||||
*/
|
||||
export class DiigoCache extends DiigoCacheLogic {
|
||||
constructor(ctx: DurableObjectState, env: CacheEnv) {
|
||||
super(ctx, env, liveClock());
|
||||
}
|
||||
}
|
||||
|
||||
/** the public cache, as the runtime constructs it (see {@link DiigoCache}) */
|
||||
export class PublicCache extends PublicCacheLogic {
|
||||
constructor(ctx: DurableObjectState, env: CacheEnv) {
|
||||
super(ctx, env, liveClock());
|
||||
}
|
||||
}
|
||||
|
||||
/** worker bindings (structural until wrangler types regenerates) */
|
||||
type Env = {
|
||||
WEBAPP: {
|
||||
fetch(request: Request): Promise<Response>;
|
||||
};
|
||||
CACHE_DO: DurableObjectNamespace<DiigoCache>;
|
||||
PUBLIC_DO: DurableObjectNamespace<PublicCache>;
|
||||
DIIGO_CACHE_ID?: string;
|
||||
};
|
||||
|
||||
const UA = "Mozilla/5.0 (X11; Linux x86_64) Gecko/20100101 Firefox/141.0";
|
||||
const DIIGO_INTERACT = "https://www.diigo.com/interact_api/";
|
||||
|
||||
/** the diigo export (DiigoBridge lives on; the dumpNdjson cache-id source
|
||||
* is TODO(2-i): ride the create form's handoff instead of a worker secret) */
|
||||
export class DiigoBridge extends WorkerEntrypoint {
|
||||
/** bulk dump from the caller's address space: `pages * count` bookmarks
|
||||
* through the cache (cache-hits are storage reads) */
|
||||
async dumpNdjson(pages: number, count = PAGE_SIZE): Promise<string> {
|
||||
const ns = (this.env as unknown as Env).CACHE_DO;
|
||||
const cacheId = (this.env as unknown as Env).DIIGO_CACHE_ID;
|
||||
if (!cacheId) throw new Error("no cache id supplied (caller config error)");
|
||||
const cache = ns.get(ns.idFromString(idFromWebkey(cacheId)));
|
||||
const lines: string[] = [];
|
||||
for (let p = 1; p <= pages; p += 1) {
|
||||
const page = await cache.page(p, count);
|
||||
lines.push(...(p === 1 ? page.items.slice(0, count) : page.items));
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* the worker's routes:
|
||||
*
|
||||
* - `GET /`: home ({@link home}); `POST /`: dump a page by cache id ({@link dump})
|
||||
* - `GET /_connect`: webapp's mint form, relayed ({@link mintPage});
|
||||
* `POST /_mint`: the mint ({@link proxyMint})
|
||||
* - `POST /_wire`: wire a cache to a webapp id ({@link wire});
|
||||
* `POST /_publish`: add a public companion later ({@link publishCache})
|
||||
* - `GET /cache/`: the webkey page ({@link CACHE_PAGE_HTML});
|
||||
* `/api`: its Cap'n Web API ({@link CacheApi}); `GET /_capnweb.js`
|
||||
* - `GET /public/<username>`: public pages, read-only ({@link publicPage})
|
||||
*
|
||||
* Cache ids are webkeys (docs/webkeys.md): they ride POST bodies and URL
|
||||
* fragments, never query strings or paths.
|
||||
*/
|
||||
export default {
|
||||
async fetch(request: Request, env: Env): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
|
||||
const pub = url.pathname.match(/^\/public\/([A-Za-z0-9_-]+)$/);
|
||||
if (pub) return publicPage(request, env, pub[1]);
|
||||
|
||||
if (url.pathname === "/_connect" && request.method === "GET") {
|
||||
return mintPage(env);
|
||||
}
|
||||
if (url.pathname === "/_mint" && request.method === "POST") {
|
||||
return proxyMint(request, env);
|
||||
}
|
||||
if (url.pathname === "/_wire" && request.method === "POST") {
|
||||
return wire(request, env);
|
||||
}
|
||||
if (url.pathname === "/_publish" && request.method === "POST") {
|
||||
return publishCache(request, env);
|
||||
}
|
||||
if (url.pathname === "/cache/" && request.method === "GET") {
|
||||
return new Response(CACHE_PAGE_HTML, { headers: { "content-type": "text/html;charset=utf-8" } });
|
||||
}
|
||||
if (url.pathname === "/_capnweb.js" && request.method === "GET") {
|
||||
return new Response(CAPNWEB_BROWSER_JS, { headers: { "content-type": "text/javascript;charset=utf-8" } });
|
||||
}
|
||||
if (url.pathname === "/api") {
|
||||
return newWorkersRpcResponse(request, new CacheApi(env));
|
||||
}
|
||||
|
||||
if (url.pathname !== "/") return new Response("not found", { status: 404 });
|
||||
if (request.method === "POST") {
|
||||
return dump(request, env);
|
||||
}
|
||||
// GET is inert: a cache id never rides a query string
|
||||
return home(env, { error: "GET is inert: dumps happen on POST submits" }, null);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* the connect page: webapp's own mint form HTML, fetched over the service
|
||||
* binding with diigo's prefill (base URL, UA headers) and its action
|
||||
* rewritten to our relay. Served here because wrangler's multi-config dev
|
||||
* doesn't serve an aux worker's HTTP. diigo-cache authors no fields of its
|
||||
* own; the init params stay editable, webapp's.
|
||||
*/
|
||||
async function mintPage(env: Env): Promise<Response> {
|
||||
const prefill =
|
||||
`?render=1&title=${encodeURIComponent("diigo cache: mint the session")}` +
|
||||
`&url=${encodeURIComponent(DIIGO_INTERACT)}` +
|
||||
`&headers=${encodeURIComponent(JSON.stringify({ "user-agent": UA, "x-requested-with": "XMLHttpRequest" }))}` +
|
||||
`&msPerCall=500`;
|
||||
let html: string;
|
||||
try {
|
||||
// a plain fetch() from inside the worker goes to the internet, not
|
||||
// to the service binding — binding calls need a Request handed to
|
||||
// the stub (workerd's entrypoint-fetch protocol)
|
||||
const res = await env.WEBAPP.fetch(
|
||||
new Request(`https://form${prefill}`, { redirect: "manual" }),
|
||||
);
|
||||
html = await res.text();
|
||||
html = html.replace('action="ACTION"', 'action="/_mint"');
|
||||
} catch (err) {
|
||||
console.error({ event: "mint-page", error: String(err) });
|
||||
return home(env, { error: "mint form unreachable (webapp worker down?)" }, null);
|
||||
}
|
||||
return new Response(html, { headers: { "content-type": "text/html;charset=utf-8" } });
|
||||
}
|
||||
|
||||
/** the mint relay: the raw form body passes through untouched into the
|
||||
* WEBAPP entrypoint's HTTP surface (webapp parses its own fields; the
|
||||
* cookie crosses browser→here→binding→webapp's DO and no code on this
|
||||
* side opens it) — a true conduit */
|
||||
async function proxyMint(request: Request, env: Env): Promise<Response> {
|
||||
try {
|
||||
const res = await env.WEBAPP.fetch(
|
||||
new Request("https://mint/", {
|
||||
method: "POST",
|
||||
headers: request.headers,
|
||||
body: await request.arrayBuffer(),
|
||||
}),
|
||||
);
|
||||
if (!res.ok) {
|
||||
const detail = (await res.text()).slice(0, 200);
|
||||
return home(env, { error: `mint said ${res.status}: ${detail}` }, null);
|
||||
}
|
||||
// webapp answers {id} (+ x-webapp-id); the id rides the header, the
|
||||
// wire page is ours
|
||||
const id = res.headers.get("x-webapp-id");
|
||||
if (!id) return home(env, { error: "mint produced no id" }, null);
|
||||
return await wirePage(id);
|
||||
} catch (err) {
|
||||
console.error({ event: "mint", error: String(err) });
|
||||
return home(env, { error: `mint failed: ${String(err)}` }, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** the credential-save helper, once per page (see ./pm-save.ts) */
|
||||
const PM_SAVE_JS = pmSave.toString();
|
||||
|
||||
/** the suggested petname gets the holder's local hh:mm (the worker only
|
||||
* knows UTC), so two saves the same day are told apart at a glance */
|
||||
const PETNAME_TIME_JS = `{
|
||||
const p = document.getElementById("petname");
|
||||
const d = new Date();
|
||||
p.value += " " + String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0");
|
||||
}`;
|
||||
|
||||
/** the onclick that hands pmSave its browser powers */
|
||||
function pmSaveClick(value: string): string {
|
||||
return `pmSave(this, ${JSON.stringify(value)}, { petname: document.getElementById("petname"), credentials: navigator.credentials, PasswordCredential: window.PasswordCredential, log: console })`;
|
||||
}
|
||||
|
||||
/** the wire step, with the freshly-minted webapp id pre-filled */
|
||||
async function wirePage(webappId: string): Promise<Response> {
|
||||
const fingerprint = await nick(webappId);
|
||||
const body = `<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>diigo cache: step 2 — wire the cache</title></head>
|
||||
<body>
|
||||
<h1>step 2: wire the cache</h1>
|
||||
<p>minted: webapp id, fingerprint <code>${esc(fingerprint)}</code>
|
||||
<button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(webappId)}).then(() => this.textContent = "copied ✓")'>copy</button></p>
|
||||
<p><label>your petname for it <input id="petname" autocomplete="off" size="30" value="${esc(`diigo webapp ${fingerprint}`)}"></label>
|
||||
<small>(private to you: the password-manager username; never sent to the server)</small></p>
|
||||
<script>${PETNAME_TIME_JS}</script>
|
||||
<p><button type="button" onclick='${pmSaveClick(webappId)}'>save to password manager</button></p>
|
||||
<p>choose the cache mode, then <b>wire</b> — the next page shows the
|
||||
<b>cache id</b> (copy that too), after which you land back on home:</p>
|
||||
<form method="post" action="/_wire">
|
||||
<input type="hidden" name="webappId" value="${esc(webappId)}">
|
||||
<p><label>mode <select name="mode"><option value="private">private</option><option value="public">public (serves /public/<your-diigo-username>)</option></select></label> <button type="submit">wire →</button></p>
|
||||
</form>
|
||||
<p>change your mind? <a href="/_connect">mint again</a> · <a href="/">home</a></p>
|
||||
<script>${PM_SAVE_JS}</script>
|
||||
</body></html>`;
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
"content-type": "text/html;charset=utf-8",
|
||||
"x-webapp-id": webappId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* the wire step: a webapp id plus the public/private choice. The cache is
|
||||
* minted, wired to {webappId, publicId}, and page 1 is stored. In public
|
||||
* mode the diigo username is read from the fetched items (the cookie's
|
||||
* own account, never form input), and the public cache is wired to the
|
||||
* same webapp id and registered under it. No cookie arrives here.
|
||||
*/
|
||||
async function wire(request: Request, env: Env): Promise<Response> {
|
||||
const ct = request.headers.get("content-type") ?? "";
|
||||
let webappId = "";
|
||||
let mode = "private";
|
||||
let wantsJson = false;
|
||||
try {
|
||||
if (ct.includes("application/json")) {
|
||||
const body = (await request.json()) as { webappId?: string; mode?: string };
|
||||
webappId = String(body.webappId ?? "");
|
||||
mode = String(body.mode ?? "private");
|
||||
wantsJson = true;
|
||||
} else {
|
||||
const form = await request.formData();
|
||||
webappId = String(form.get("webappId") || "");
|
||||
mode = String(form.get("mode") || "private");
|
||||
// a browser form POST stays on the html path; only explicit JSON
|
||||
// (service callers) gets the bare-JSON response
|
||||
wantsJson = false;
|
||||
}
|
||||
} catch (err) {
|
||||
return bad(`bad input: ${String(err)}`);
|
||||
}
|
||||
if (!/^[A-Za-z0-9-]+$/.test(webappId)) return bad("no webapp id supplied");
|
||||
|
||||
const publicId = mode === "public" ? toWebkey(env.PUBLIC_DO.newUniqueId()) : undefined;
|
||||
const cacheId = toWebkey(env.CACHE_DO.newUniqueId());
|
||||
const cacheStub = env.CACHE_DO.get(env.CACHE_DO.idFromString(idFromWebkey(cacheId)));
|
||||
await cacheStub.setup({ webappId, publicId });
|
||||
const first = await cacheStub.page(1, PAGE_SIZE);
|
||||
|
||||
if (publicId) {
|
||||
const firstItem = first.items[0] ? (JSON.parse(first.items[0]) as Item) : undefined;
|
||||
const username = usernameOf(firstItem);
|
||||
if (!username) {
|
||||
// diagnostic context without item contents (privacy: items may
|
||||
// carry URL/titles; the count + cached flag are safe)
|
||||
console.error({
|
||||
event: "wire",
|
||||
stage: "username-derive",
|
||||
// field names, not values: says which shape we got
|
||||
itemFields: firstItem ? Object.keys(firstItem) : null,
|
||||
itemsOnPage1: first.items.length,
|
||||
total: first.total,
|
||||
cached: first.cached,
|
||||
});
|
||||
return bad("could not read your diigo username (u_name) from the fetched items");
|
||||
}
|
||||
const index = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromName("index"));
|
||||
const pubStub = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
|
||||
await pubStub.setup({ webappId });
|
||||
await index.register(username, publicId);
|
||||
if (wantsJson) return Response.json({ cacheId, publicId, username });
|
||||
return wiredPage(cacheId, `public cache live at <a href="/public/${esc(encodeURIComponent(username))}">/public/${esc(username)}</a>`, true);
|
||||
}
|
||||
if (wantsJson) {
|
||||
return Response.json({
|
||||
cacheId,
|
||||
publishLater: { method: "POST", url: `${new URL(request.url).origin}/_publish`, body: { cacheId } },
|
||||
});
|
||||
}
|
||||
return wiredPage(
|
||||
cacheId,
|
||||
`private-only for now — to add the public cache later:
|
||||
<form method="post" action="/_publish" style="display:inline">
|
||||
<input type="hidden" name="cacheId" value="${esc(cacheId)}">
|
||||
<button type="submit">publish</button></form>
|
||||
(or <code>POST /_publish</code> with <code>cacheId</code> in the body)`,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
/** the created-cache page: ids + save/copy buttons + the pointer home */
|
||||
async function wiredPage(cacheId: string, note: string, hasPublic: boolean): Promise<Response> {
|
||||
const fingerprint = await nick(cacheId);
|
||||
const body = `<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>diigo cache: created</title></head>
|
||||
<body>
|
||||
<h1>cache created</h1>
|
||||
<p><b>cache id</b>, fingerprint <code>${esc(fingerprint)}</code>
|
||||
<button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(cacheId)}).then(() => this.textContent = "copied ✓")'>copy</button></p>
|
||||
<p><label>your petname for it <input id="petname" autocomplete="off" size="30" value="${esc(`diigo cache ${fingerprint}`)}"></label>
|
||||
<small>(private to you: the password-manager username; never sent to the server)</small></p>
|
||||
<script>${PETNAME_TIME_JS}</script>
|
||||
<p><button type="button" onclick='${pmSaveClick(cacheId)}'>save to password manager</button></p>
|
||||
<p>${note}</p>
|
||||
<p><a href="/cache/#${esc(cacheId)}">open this cache</a> — its <b>webkey</b>
|
||||
(bookmark it, or save the id above): fill it, watch progress${hasPublic ? ", fill its public companion" : ""}.</p>
|
||||
<p>the cache id is the only way back to this cache — saved (above) it lives
|
||||
with the rest of your credentials. it is a <b>webkey</b>: it never rides a
|
||||
query string or path (those leak to history/Referer/logs). the link above
|
||||
carries it in the fragment, which browsers never send; the dump POST
|
||||
carries it in its body. the webapp id rides inside the cache's wiring;
|
||||
hold it separately only if you want another cache off the same session.</p>
|
||||
<a href="/">← home (paste the cache id into the dump form)</a>
|
||||
<script>${PM_SAVE_JS}</script>
|
||||
</body></html>`;
|
||||
return new Response(body, { headers: { "content-type": "text/html;charset=utf-8" } });
|
||||
}
|
||||
|
||||
/** a fill job's progress, as one line of page text */
|
||||
function fillLine(fill: FillStatus): string {
|
||||
const of = `${Math.max(0, fill.nextPage - 1)} of ${fill.pages ?? "?"} pages`;
|
||||
const said = {
|
||||
running: `filling: ${of}`,
|
||||
done: `filled: ${of}`,
|
||||
stopped: `fill stopped: ${of}`,
|
||||
failed: `fill failed at page ${fill.nextPage}: ${fill.error ?? "unknown error"}`,
|
||||
}[fill.state];
|
||||
return `<p>${esc(said)}</p>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* publish, later: adds a public companion to a cache wired private-only.
|
||||
* Its wiring already holds the webapp id, so no re-mint; the username
|
||||
* comes from the items already cached. The cache id rides the POST body.
|
||||
*/
|
||||
async function publishCache(request: Request, env: Env): Promise<Response> {
|
||||
let cacheId = "";
|
||||
try {
|
||||
const ct = request.headers.get("content-type") ?? "";
|
||||
if (ct.includes("application/json")) {
|
||||
const body = (await request.json()) as { cacheId?: string };
|
||||
cacheId = String(body.cacheId ?? "");
|
||||
} else {
|
||||
const form = await request.formData();
|
||||
cacheId = String(form.get("cacheId") || "");
|
||||
}
|
||||
} catch (err) {
|
||||
return bad(`bad input: ${String(err)}`);
|
||||
}
|
||||
if (!isWebkey(cacheId) && !/^[0-9a-fA-F]{64}$/.test(cacheId)) {
|
||||
return bad("no cache id supplied (POST body: cacheId)");
|
||||
}
|
||||
try {
|
||||
const ns = env.CACHE_DO;
|
||||
const cache = ns.get(ns.idFromString(idFromWebkey(cacheId)));
|
||||
const wiring = await cache.wiring();
|
||||
if (!wiring) {
|
||||
return Response.json({ error: "unknown cache id" }, { status: 404 });
|
||||
}
|
||||
if (wiring.publicId) {
|
||||
return Response.json({ cacheId, publicId: wiring.publicId, status: "already published" });
|
||||
}
|
||||
// the username comes from the items: the cookie's own account
|
||||
const firstPage = await cache.page(1, PAGE_SIZE);
|
||||
const firstItem = firstPage.items[0] ? (JSON.parse(firstPage.items[0]) as Item) : undefined;
|
||||
const username = usernameOf(firstItem);
|
||||
if (!username) {
|
||||
console.error({
|
||||
event: "publish",
|
||||
stage: "username-derive",
|
||||
// field names, not values: says which shape we got
|
||||
itemFields: firstItem ? Object.keys(firstItem) : null,
|
||||
itemsOnPage1: firstPage.items.length,
|
||||
total: firstPage.total,
|
||||
cached: firstPage.cached,
|
||||
});
|
||||
return Response.json(
|
||||
{ error: "could not read your diigo username (u_name) from the cached items" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const publicId = toWebkey(env.PUBLIC_DO.newUniqueId());
|
||||
const pubStub = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
|
||||
await pubStub.setup({ webappId: wiring.webappId });
|
||||
await cache.addPublic(publicId);
|
||||
const index = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromName("index"));
|
||||
await index.register(username, publicId);
|
||||
return Response.json({ cacheId, publicId, username, public: `/public/${username}` });
|
||||
} catch (err) {
|
||||
// no cacheId in the log: it is the bearer secret
|
||||
console.error({ event: "publish", error: String(err) });
|
||||
return Response.json({ error: `publish failed: ${String(err)}` }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
function bad(message: string): Response {
|
||||
return Response.json({ error: message }, { status: 400 });
|
||||
}
|
||||
|
||||
/** the private dump POST: cache id from the (client-wired) form value */
|
||||
async function dump(request: Request, env: Env): Promise<Response> {
|
||||
const form = await request.formData();
|
||||
const cacheId = String(form.get("cacheId") || "");
|
||||
const raw = form.get("page");
|
||||
const pageN = typeof raw === "string" ? Number.parseInt(raw, 10) : Number.NaN;
|
||||
if (!isWebkey(cacheId) && !/^[0-9a-fA-F]{64}$/.test(cacheId)) {
|
||||
return home(env, { error: "wire a cache id first (create flow, then copy/paste)" }, null);
|
||||
}
|
||||
if (Number.isNaN(pageN) || pageN < 1 || pageN > 10000) {
|
||||
return home(env, { error: "enter a page number (1 = most recently updated)" }, null);
|
||||
}
|
||||
try {
|
||||
const ns = env.CACHE_DO;
|
||||
const cache = ns.get(ns.idFromString(idFromWebkey(cacheId)));
|
||||
const page = await cache.page(pageN, PAGE_SIZE);
|
||||
const data = `total: ${page.total}\nitems: ${page.items.length}\ncache: ${page.cached ? "HIT (from storage)" : "MISS (etched now)"}` +
|
||||
`\n\n${page.items.join("\n")}`;
|
||||
return home(env, null, data, cacheId);
|
||||
} catch (err) {
|
||||
console.error({ event: "dump", page: pageN, error: String(err) });
|
||||
return home(env, null, String(err), cacheId);
|
||||
}
|
||||
}
|
||||
|
||||
const PUBLIC_PER_PAGE = PAGE_SIZE;
|
||||
|
||||
/**
|
||||
* the public page for a username: stored pages only, through the cache's
|
||||
* read-only `viewer()` (it can't fetch or write). HTML with a page-number
|
||||
* form, or JSON for `Accept: application/json`. `?page=` in the URL is
|
||||
* fine here: nothing on this page is secret.
|
||||
*/
|
||||
async function publicPage(request: Request, env: Env, username: string): Promise<Response> {
|
||||
const index = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromName("index"));
|
||||
const publicId = await index.lookup(username);
|
||||
if (!publicId) return new Response("no such public cache", { status: 404 });
|
||||
const ns = env.PUBLIC_DO;
|
||||
const cache = ns.get(ns.idFromString(idFromWebkey(publicId)));
|
||||
|
||||
const raw = new URL(request.url).searchParams.get("page");
|
||||
const pageN = raw === null ? 1 : Number.parseInt(raw, 10);
|
||||
const valid = !Number.isNaN(pageN) && pageN >= 1 && pageN <= 10000;
|
||||
const viewer = await cache.viewer();
|
||||
let page, total, fill;
|
||||
try {
|
||||
page = await viewer.page(valid ? pageN : 1, PUBLIC_PER_PAGE);
|
||||
total = page ? page.total : await viewer.knownTotal();
|
||||
fill = await viewer.fillStatus();
|
||||
} catch (err) {
|
||||
console.error({ event: "public-page", page: pageN, error: String(err) });
|
||||
return new Response(`could not load page ${valid ? pageN : 1}: ${String(err)}`, { status: 502 });
|
||||
} finally {
|
||||
viewer[Symbol.dispose]();
|
||||
}
|
||||
// total and pages count all of diigo's items: public page n is diigo
|
||||
// page n with the private rows dropped
|
||||
const pages = total === null ? 1 : Math.max(1, Math.ceil(total / PUBLIC_PER_PAGE));
|
||||
const items = page ? page.items.map((j) => JSON.parse(j) as Item) : [];
|
||||
|
||||
const accept = request.headers.get("accept") ?? "";
|
||||
if (accept.includes("application/json") && !accept.includes("text/html")) {
|
||||
return Response.json({ username, page: pageN, pages, total, stored: page !== null, etchedAt: page?.etchedAt ?? null, items });
|
||||
}
|
||||
|
||||
let notice = "";
|
||||
if (!valid || pageN > pages) {
|
||||
console.log({ event: "notice", page: "public", text: "page out of range", pages });
|
||||
notice = `<p><em>no page ${esc(String(raw))}: pages run 1–${pages}</em></p>`;
|
||||
}
|
||||
const here = `/public/${encodeURIComponent(username)}`;
|
||||
const nav = (n: number, label: string) =>
|
||||
n >= 1 && n <= pages ? `<a href="${here}?page=${n}">${label}</a>` : `<span>${label}</span>`;
|
||||
const list = notice
|
||||
? ""
|
||||
: `<ol>
|
||||
${items
|
||||
.map((it) => {
|
||||
const url = typeof it.url === "string" ? it.url : "";
|
||||
const title = typeof it.title === "string" && it.title ? it.title : url;
|
||||
const desc = typeof it.description === "string" && it.description ? `<br><small>${esc(it.description)}</small>` : "";
|
||||
const href = /^https?:\/\//i.test(url) ? url : "#";
|
||||
const when = updatedISO(it);
|
||||
const date = when ? `<time datetime="${when}">${when}</time>` : "(no date)";
|
||||
return `<li>${date} <a href="${esc(href)}">${esc(title)}</a>${desc}</li>`;
|
||||
})
|
||||
.join("\n")}
|
||||
</ol>`;
|
||||
const body = `<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>${esc(username)}'s shared bookmarks</title></head>
|
||||
<body>
|
||||
<h1>${esc(username)}'s shared bookmarks</h1>
|
||||
<p>${pages} page${pages === 1 ? "" : "s"} (diigo's, ${PUBLIC_PER_PAGE} bookmarks each; private ones are left out, so a page may show fewer).</p>
|
||||
<p>${page ? `<strong>stored ${esc(page.etchedAt ?? "")}</strong> — page ${valid ? pageN : 1}, ${items.length} shared` : `<strong>not fetched yet</strong> — page ${valid ? pageN : 1}; the cache's owner fills it`}</p>
|
||||
${fill ? fillLine(fill) : ""}
|
||||
<form method="get" action="${here}">
|
||||
<p>${nav(pageN - 1, "← prev")}
|
||||
<label>page <input type="number" name="page" min="1" value="${Number.isNaN(pageN) ? 1 : pageN}"></label>
|
||||
<button type="submit">go</button>
|
||||
${nav(pageN + 1, "next →")}</p>
|
||||
</form>
|
||||
${notice}${list}
|
||||
</body></html>`;
|
||||
return new Response(body, { headers: { "content-type": "text/html;charset=utf-8" } });
|
||||
}
|
||||
|
||||
/** home page: the connect link (webapp's cookie form, diigo-prefilled) +
|
||||
* the wire step for an already-minted id + the dump form. `home` renders
|
||||
* the error path too, so it takes env for the connect link. Notices (the
|
||||
* inert-GET explainer, probe failures) log at info — exceptional errors
|
||||
* log at error in their own handlers. */
|
||||
async function home(env: Env, opts: { error?: string } | null, data: string | null, cacheId?: string): Promise<Response> {
|
||||
if (opts?.error) {
|
||||
console.log({ event: "notice", page: "home", text: opts.error });
|
||||
}
|
||||
const cacheState = cacheId
|
||||
? `<p>cache id, fingerprint <code>${esc(await nick(cacheId))}</code></p>`
|
||||
: `<p>no cache id wired yet — use the create flow below (or paste one).</p>`;
|
||||
const dumpForm = `<form method="post" action="/">
|
||||
${cacheId ? `<input type="hidden" name="cacheId" value="${esc(cacheId)}">` : `<p><label>petname <input autocomplete="username" size="24"></label>
|
||||
<label>cache id <input type="password" name="cacheId" autocomplete="current-password" size="24"></label></p>`}
|
||||
<p><label>page <input type="number" name="page" min="1"></label> <button type="submit">dump</button></p>
|
||||
</form>`;
|
||||
const result = data
|
||||
? `<pre readonly style="white-space:pre-wrap;border:1px solid #ccc;padding:1rem;max-height:60vh;overflow:auto">${escapeHtml(data)}</pre>`
|
||||
: opts && opts.error
|
||||
? `<p><em>${escapeHtml(opts.error)}</em></p>`
|
||||
: "";
|
||||
return new Response(
|
||||
`<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>diigo cache</title></head>
|
||||
<body>
|
||||
<h1>diigo cache</h1>
|
||||
${cacheState}
|
||||
<h2>create (two steps)</h2>
|
||||
<ol>
|
||||
<li><a href="/_connect">mint the diigo session at webapp</a> — webapp's
|
||||
own mint form (diigo-prefilled); paste the Cookie header there. The
|
||||
cookie transits this worker only as an opaque relay into webapp's DO;
|
||||
nobody here opens it. Mint lands you on the wire step, id pre-filled.</li>
|
||||
<li>wire the id into a cache (mode: public|private):</li>
|
||||
</ol>
|
||||
<form method="post" action="/_wire">
|
||||
<p><label>petname <input autocomplete="username" size="24"></label>
|
||||
<label>webapp id <input type="password" name="webappId" size="24" autocomplete="current-password"></label>
|
||||
<label>mode <select name="mode"><option value="private">private</option><option value="public">public (serves /public/<your-diigo-username>)</option></select></label></p>
|
||||
<p><button type="submit">wire</button></p>
|
||||
</form>
|
||||
<p>the ids this mints are for <b>you</b>: copy them somewhere you control (password manager)</p>
|
||||
<p><a href="/cache/">open a cache</a> — fill it, watch progress (your password manager can fill in the cache id)</p>
|
||||
${dumpForm}
|
||||
${result}
|
||||
</body></html>`,
|
||||
{ headers: { "content-type": "text/html;charset=utf-8" } },
|
||||
);
|
||||
}
|
||||
|
||||
/** a short display name for a bearer id: a prefix of its swissHash
|
||||
* (identity without authority), so labels and pages never show any
|
||||
* glyphs of the key itself */
|
||||
async function nick(id: string): Promise<string> {
|
||||
return (await shashKey(id)).slice(0, 8);
|
||||
}
|
||||
|
||||
function esc(s: string): string {
|
||||
return s
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """);
|
||||
}
|
||||
|
||||
const escapeHtml = esc;
|
||||
@@ -1,74 +0,0 @@
|
||||
/**
|
||||
* @file diigo interact_api items: the field-reading helpers (pure, so
|
||||
* tests can feed them rows shaped like diigo's).
|
||||
*/
|
||||
|
||||
/** one diigo item exactly as the interact_api returned it */
|
||||
export type Item = Record<string, unknown>;
|
||||
|
||||
/** the fields stored per item (the raw row rides in `json`) */
|
||||
export type ItemRow = {
|
||||
itemId: string;
|
||||
url: string;
|
||||
title: string;
|
||||
private: boolean;
|
||||
/** the raw dump row, JSON-encoded */
|
||||
json: string;
|
||||
updated: string;
|
||||
};
|
||||
|
||||
/** diigo's id for a bookmark (`link_id`), as text; "" when absent */
|
||||
function linkIdOf(it: Item): string {
|
||||
return typeof it.link_id === "number" || (typeof it.link_id === "string" && it.link_id !== "")
|
||||
? String(it.link_id)
|
||||
: "";
|
||||
}
|
||||
|
||||
/**
|
||||
* normalize one page of interact_api items into storable rows. Items
|
||||
* that can't be stored (no url, no link_id) are logged and skipped —
|
||||
* never merged under a made-up key. Logs name the fields present, not
|
||||
* their values (items may be private).
|
||||
*/
|
||||
export function toRows(items: Item[], log: Pick<Console, "warn">): ItemRow[] {
|
||||
const rows: ItemRow[] = [];
|
||||
for (const it of items) {
|
||||
const itemId = linkIdOf(it);
|
||||
const url = typeof it.url === "string" ? it.url : "";
|
||||
if (!itemId || !url) {
|
||||
log.warn({ event: "item-skip", reason: !itemId ? "no link_id" : "no url", fields: Object.keys(it) });
|
||||
continue;
|
||||
}
|
||||
rows.push({
|
||||
itemId,
|
||||
url,
|
||||
title: String(it.title ?? url),
|
||||
private: it.private !== undefined ? Boolean(it.private) : String(it.shared) !== "yes",
|
||||
json: JSON.stringify(it),
|
||||
updated: String(it.updated_at ?? it.created_at ?? ""),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** the diigo username an item belongs to (`u_name`; not `first_by`,
|
||||
* who may be whoever bookmarked the URL first), or "" when the item
|
||||
* carries none in the expected shape */
|
||||
export function usernameOf(item: Item | undefined): string {
|
||||
const username = typeof item?.u_name === "string" ? item.u_name : "";
|
||||
return /^[A-Za-z0-9_-]{1,64}$/.test(username) ? username : "";
|
||||
}
|
||||
|
||||
/** the public cache's filter: shared rows only. Applied before etching,
|
||||
* so private rows never reach public storage. */
|
||||
export function publicOnly(rows: ItemRow[]): ItemRow[] {
|
||||
return rows.filter((r) => !r.private);
|
||||
}
|
||||
|
||||
/** when diigo last updated the item, as `Date#toISOString()`, or "" when
|
||||
* it carries no usable `updated_at` (diigo sends epoch *seconds*) */
|
||||
export function updatedISO(item: Item): string {
|
||||
const secs = item.updated_at;
|
||||
if (typeof secs !== "number" || !Number.isFinite(secs)) return "";
|
||||
return new Date(secs * 1000).toISOString();
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/** @file the password-manager save, run in the browser (embedded via `pmSave.toString()`). */
|
||||
|
||||
/** the browser powers pmSave uses */
|
||||
export type PmPowers = {
|
||||
petname: { value: string };
|
||||
credentials?: { store(credential: unknown): Promise<unknown> };
|
||||
PasswordCredential?: new (init: { id: string; password: string }) => unknown;
|
||||
log: Pick<Console, "info" | "warn" | "error">;
|
||||
};
|
||||
|
||||
/** the button pmSave reports on */
|
||||
export type PmButton = { textContent: string | null; disabled: boolean };
|
||||
|
||||
/**
|
||||
* gesture-gated save of `value` under the holder's petname (the PM
|
||||
* username). Ids reach the browser's storage only this way (or by copy),
|
||||
* never localStorage/IndexedDB, which are ambient and XSS-reachable.
|
||||
*
|
||||
* Pages embed it with `pmSave.toString()`, so it must be self-contained:
|
||||
* no imports, no closures, no inner named functions (wrangler's keepNames
|
||||
* would wrap those in an `__name` helper the browser lacks). Its powers
|
||||
* (petname field, credential store, console) are passed in, so tests can
|
||||
* stand in for the browser.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/store
|
||||
*/
|
||||
export function pmSave(btn: PmButton, value: string, powers: PmPowers): Promise<void> {
|
||||
const label = powers.petname.value.trim();
|
||||
if (!label) {
|
||||
btn.textContent = "give it a petname first";
|
||||
return Promise.resolve();
|
||||
}
|
||||
btn.disabled = true;
|
||||
if (!powers.PasswordCredential || !powers.credentials) {
|
||||
powers.log.warn({ event: "pm-save", outcome: "unsupported", detail: "no PasswordCredential / navigator.credentials" });
|
||||
btn.textContent = "browser has no credential store — copy instead";
|
||||
btn.disabled = false;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return powers.credentials
|
||||
.store(new powers.PasswordCredential({ id: label, password: value }))
|
||||
.then(() => {
|
||||
// store() resolves with undefined per spec, whether the holder
|
||||
// accepted the browser's prompt or not (or no prompt showed):
|
||||
// we can only say it was offered — the PM's own UI is the truth
|
||||
powers.log.info({ event: "pm-save", outcome: "offered", label });
|
||||
btn.textContent = "offered to the password manager ✓ (see its prompt)";
|
||||
btn.disabled = false;
|
||||
})
|
||||
.catch((err) => {
|
||||
powers.log.error({ event: "pm-save", error: String(err) });
|
||||
btn.textContent = "save failed — copy instead";
|
||||
btn.disabled = false;
|
||||
});
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
/**
|
||||
* @file the public page's filters: date windows and search (goal 1d, **not
|
||||
* yet implemented**; the design is the skipped specs in tests/query.test.ts).
|
||||
*/
|
||||
|
||||
import type { Item } from "./items.js";
|
||||
|
||||
/**
|
||||
* diigo fetches one request may spend (cache hits are free); under the
|
||||
* Workers free plan's 50 external subrequests per invocation
|
||||
*
|
||||
* @see https://developers.cloudflare.com/workers/platform/limits/
|
||||
*/
|
||||
export const FETCH_BUDGET = 40;
|
||||
|
||||
/**
|
||||
* a filter as devs write it (`{ days: 7, q: "#weekly" }`); URL params map
|
||||
* onto these fields one-to-one (strings, with "" meaning absent). Dates
|
||||
* are `yyyy-mm-dd` (gmail's `yyyy/mm/dd` too); periods are `2025`,
|
||||
* `2025-03`, `2025-Q1`, or ISO week `2025-W01`. Time is UTC throughout;
|
||||
* ISO weeks start Monday, keeping a weekend together.
|
||||
*/
|
||||
export type FilterSpec = {
|
||||
/** the last N days, counted back from now (1–3650) */
|
||||
days?: number | string;
|
||||
/** inclusive lower bound, from 00:00Z */
|
||||
after?: string;
|
||||
/** exclusive upper bound, at 00:00Z */
|
||||
before?: string;
|
||||
/** a named period: shorthand for its after/before pair */
|
||||
in?: string;
|
||||
/** which date the window, the listed date, and the sort use */
|
||||
by?: "updated" | "created" | "";
|
||||
/** words, phrases, tags, and operators */
|
||||
q?: string;
|
||||
};
|
||||
|
||||
/** one search term; `negated` for a leading `-` */
|
||||
export type Term = { text: string; negated: boolean };
|
||||
|
||||
/** a parsed filter; an empty one (no window, no terms) filters nothing */
|
||||
export type Query = {
|
||||
/** which date the window, the listed date, and the sort use (default
|
||||
* `updated`, diigo's own order) */
|
||||
by: "updated" | "created";
|
||||
/** inclusive lower bound */
|
||||
after?: Date;
|
||||
/** exclusive upper bound */
|
||||
before?: Date;
|
||||
/** words and phrases: each must appear in title, description, or url */
|
||||
words: Term[];
|
||||
/** tags: exact, case-insensitive match against the item's tags */
|
||||
tags: Term[];
|
||||
};
|
||||
|
||||
/** a refused filter: the message is safe to show and log */
|
||||
export type QueryError = { error: string };
|
||||
|
||||
/**
|
||||
* resolve a filter: fields and `q` operators combine; a bound given twice
|
||||
* (by fields, operators, or both) is refused, as is an empty window.
|
||||
*
|
||||
* `q` takes the operators large audiences know: gmail's `after:`,
|
||||
* `before:`, `newer_than:7d`; Slack's `during:` (alias `in:`); GitHub's
|
||||
* `created:`/`updated:` with a period; plus words, `"phrases"`,
|
||||
* `#tag`/`tag:tag`, and `-` negation. Every window is half-open: `after`
|
||||
* inclusive from 00:00Z, `before` exclusive at 00:00Z (so no inclusive
|
||||
* GitHub `a..b` ranges).
|
||||
*
|
||||
* @see https://mailmeteor.com/blog/search-gmail-by-date
|
||||
* @see https://slack.com/help/articles/202528808
|
||||
* @see https://docs.github.com/en/search-github/searching-on-github/searching-for-repositories
|
||||
*
|
||||
* @param now the clock `days`/`newer_than` count back from (passed in,
|
||||
* not read ambiently, so tests pin it)
|
||||
*/
|
||||
export function toQuery(spec: FilterSpec, now: Date): Query | QueryError {
|
||||
void spec;
|
||||
void now;
|
||||
throw new Error("toQuery: not implemented (goal 1d)");
|
||||
}
|
||||
|
||||
/** {@link toQuery} over the public page's URL params */
|
||||
export function parseQuery(params: URLSearchParams, now: Date): Query | QueryError {
|
||||
void params;
|
||||
void now;
|
||||
throw new Error("parseQuery: not implemented (goal 1d)");
|
||||
}
|
||||
|
||||
/** does `item` fall in the window and satisfy every term? */
|
||||
export function matches(item: Item, query: Query): boolean {
|
||||
void item;
|
||||
void query;
|
||||
throw new Error("matches: not implemented (goal 1d)");
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
/** @file cached diigo items as RSS 2.0, in the shape of diigo's RSS export. */
|
||||
|
||||
import type { Item } from "./items.js";
|
||||
|
||||
/** characters XML 1.0 forbids (the C0 controls but tab, LF, CR);
|
||||
* diigo's export carries some raw, so strict parsers reject it */
|
||||
const XML_FORBIDDEN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
|
||||
|
||||
/** text as one or more CDATA sections: forbidden characters dropped,
|
||||
* a literal `]]>` split across two sections */
|
||||
function cdata(text: string): string {
|
||||
return `<![CDATA[${text.replace(XML_FORBIDDEN, "").replaceAll("]]>", "]]]]><![CDATA[>")}]]>`;
|
||||
}
|
||||
|
||||
const str = (v: unknown): string => (typeof v === "string" ? v : "");
|
||||
const list = (v: unknown): Record<string, unknown>[] => (Array.isArray(v) ? (v as Record<string, unknown>[]) : []);
|
||||
|
||||
/**
|
||||
* the packed description diigo's export uses:
|
||||
* `Tags:a,b;Description:…;Annotations and Sticky notes:…` — tags
|
||||
* comma-separated (`no_tag` when none), then each highlight as
|
||||
* `Highlight:<text>\n` followed by its sticky notes, one
|
||||
* `Sticky notes:<text>\n` each (notes may span lines). A diigo *note*
|
||||
* item's body (`note_content`) comes first, as a `Highlight:` line.
|
||||
*/
|
||||
export function itemDescription(item: Item): string {
|
||||
const tags = str(item.tags) || "no_tag";
|
||||
const body = str(item.note_content) ? `Highlight:${str(item.note_content)}\n` : "";
|
||||
const notes = list(item.annotations)
|
||||
.map((a) => `Highlight:${str(a.content)}\n${list(a.stickyNotes).map((n) => `Sticky notes:${str(n.content)}\n`).join("")}`)
|
||||
.join("");
|
||||
return `Tags:${tags};Description:${str(item.description)};Annotations and Sticky notes:${body}${notes}`;
|
||||
}
|
||||
|
||||
/** one `<item>`: title, link, packed description. The title is whole
|
||||
* (diigo's export cuts titles at 255 characters). */
|
||||
export function rssItem(item: Item): string {
|
||||
return `<item><title>${cdata(str(item.title))}</title><link>${cdata(str(item.url))}</link><description>${cdata(itemDescription(item))}</description></item>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* a whole feed
|
||||
*
|
||||
* @param channel `pubDate` in RFC 822 form is the caller's to supply
|
||||
* (no clock here)
|
||||
*/
|
||||
export function toRss(items: Item[], channel: { title: string; pubDate: string }): string {
|
||||
return `<?xml version="1.0"?>
|
||||
<rss version="2.0">
|
||||
<channel>
|
||||
<title>${cdata(channel.title)}</title>
|
||||
<link></link>
|
||||
<pubDate>${channel.pubDate}</pubDate>
|
||||
<lastBuildDate>${channel.pubDate}</lastBuildDate>
|
||||
${items.map(rssItem).join("\n")}
|
||||
</channel>
|
||||
</rss>
|
||||
`;
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
/**
|
||||
* named statements from a .sql file: each `-- name:` line starts one,
|
||||
* running to the next (a trailing `;` dropped). As `sqlStatements` in
|
||||
* finquick's brcal/src/gcbook.js.
|
||||
*/
|
||||
export function sqlStatements(text: string): Record<string, string> {
|
||||
const byName: Record<string, string> = {};
|
||||
const chop = (lo: number, hi: number) => text.substring(lo, hi).replace(/;\s*$/, "").trim();
|
||||
let pos = 0;
|
||||
let name: string | undefined;
|
||||
for (const m of text.matchAll(/^-- (?<name>[^:\n]+):\n/gm)) {
|
||||
if (name) byName[name] = chop(pos, m.index);
|
||||
pos = m.index + m[0].length;
|
||||
name = m.groups?.name;
|
||||
}
|
||||
if (name) byName[name] = chop(pos, text.length);
|
||||
return byName;
|
||||
}
|
||||
Vendored
-5
@@ -1,5 +0,0 @@
|
||||
/** .sql files import as their text (wrangler.jsonc "rules": Text) */
|
||||
declare module "*.sql" {
|
||||
const text: string;
|
||||
export default text;
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
/** @file a cache DO's SQL storage as two facets: a reader and a writer. */
|
||||
|
||||
import readText from "./cache-read.sql";
|
||||
import writeText from "./cache-write.sql";
|
||||
import type { ItemRow } from "./items.js";
|
||||
import { sqlStatements } from "./sql-statements.js";
|
||||
|
||||
const READ = sqlStatements(readText);
|
||||
const WRITE = sqlStatements(writeText);
|
||||
for (const [name, statement] of Object.entries(READ)) {
|
||||
if (!/^(select|with)\b/i.test(statement)) throw new Error(`cache-read.sql: ${name} is not a select`);
|
||||
}
|
||||
|
||||
/** the SQL surface the facets need (a DO's `ctx.storage.sql`) */
|
||||
type Sql = Pick<SqlStorage, "exec">;
|
||||
|
||||
/** one cached page, raw: `items` are the dump rows (JSON strings) */
|
||||
export type StoredPage = { total: number; items: string[]; etchedAt: string };
|
||||
|
||||
/**
|
||||
* read-only access to a cache's pages and items: runs only the statements
|
||||
* in cache-read.sql (all `select`s, checked when the module loads), so
|
||||
* whoever holds only a reader cannot change storage
|
||||
*/
|
||||
export function makeReader(sql: Sql) {
|
||||
const run = <T extends Record<string, SqlStorageValue>>(name: string, ...params: SqlStorageValue[]): T[] =>
|
||||
sql.exec<T>(READ[name], ...params).toArray();
|
||||
return Object.freeze({
|
||||
/** a cached page in its fetch-time order, or null if not cached at this size */
|
||||
page(pageNum: number, count: number): StoredPage | null {
|
||||
const [header] = run<{ total: number | null; etched_at: string }>("pageHeader", pageNum, count);
|
||||
if (!header) return null;
|
||||
const rows = run<{ json: string }>("pageItems", pageNum);
|
||||
return { total: header.total ?? -1, items: rows.map((r) => r.json), etchedAt: header.etched_at };
|
||||
},
|
||||
/** diigo's total, from the most recently cached page that had one */
|
||||
knownTotal(): number | null {
|
||||
return run<{ total: number }>("knownTotal")[0]?.total ?? null;
|
||||
},
|
||||
/** the deepest cached page holding an item updated at or after `cutoff` (epoch seconds) */
|
||||
deepestPageSince(cutoff: number): number | null {
|
||||
return run<{ last: number | null }>("deepestPageSince", cutoff)[0]?.last ?? null;
|
||||
},
|
||||
/** how many cached pages are numbered `pageNum` or lower */
|
||||
pagesThrough(pageNum: number): number {
|
||||
return Number(run<{ n: number }>("pagesThrough", pageNum)[0]?.n ?? 0);
|
||||
},
|
||||
});
|
||||
}
|
||||
export type Reader = ReturnType<typeof makeReader>;
|
||||
|
||||
/** the schema version storage is at (kv key "schema") */
|
||||
export const SCHEMA_VERSION = 2;
|
||||
|
||||
/** write access to a cache's pages and items (the statements in
|
||||
* cache-write.sql), each change one transaction */
|
||||
export function makeWriter(storage: {
|
||||
sql: Sql;
|
||||
kv: Pick<SyncKvStorage, "get" | "put">;
|
||||
transactionSync<T>(fn: () => T): T;
|
||||
}) {
|
||||
const run = (name: string, ...params: SqlStorageValue[]) => {
|
||||
storage.sql.exec(WRITE[name], ...params);
|
||||
};
|
||||
return Object.freeze({
|
||||
/** create tables, and migrate older storage; returns the version
|
||||
* migrated from (= SCHEMA_VERSION when nothing was to do) */
|
||||
migrate(): number {
|
||||
run("schemaV1");
|
||||
const version = storage.kv.get<number>("schema") ?? 1;
|
||||
if (version < 2) {
|
||||
// V1 sent our 1-based page number as diigo's 0-based page_num,
|
||||
// so a stored "page n" is really page n+1
|
||||
storage.transactionSync(() => {
|
||||
run("renumberV2");
|
||||
storage.kv.put("schema", SCHEMA_VERSION);
|
||||
});
|
||||
}
|
||||
return version;
|
||||
},
|
||||
/** store a fetched page: upsert its items, record their order */
|
||||
etch(pageNum: number, count: number, total: number, rows: ItemRow[], at: string): void {
|
||||
storage.transactionSync(() => {
|
||||
run("clearPageMembers", pageNum);
|
||||
rows.forEach((r, i) => {
|
||||
run("upsertItem", r.itemId, r.url, r.title, r.private ? 1 : 0, r.json, r.updated);
|
||||
run("insertPageMember", pageNum, i + 1, r.itemId);
|
||||
});
|
||||
run("upsertPage", pageNum, count, total, at);
|
||||
});
|
||||
},
|
||||
/** drop pages numbered `pageNum` or lower (their items stay) */
|
||||
dropPagesThrough(pageNum: number): void {
|
||||
storage.transactionSync(() => {
|
||||
run("dropPageMembersThrough", pageNum);
|
||||
run("dropPagesThrough", pageNum);
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
export type Writer = ReturnType<typeof makeWriter>;
|
||||
@@ -1,192 +0,0 @@
|
||||
/** @file webkeys: URL-borne bearer keys, YURL32-encoded; see {@link toWebkey}. */
|
||||
|
||||
/** the YURL32 alphabet: `a–z` then `2–7` (32 glyphs, 5 bits each) */
|
||||
const YURL32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567" as const;
|
||||
|
||||
/** encode bytes as YURL32 (`a–z2–7`, 5 bits/char; no padding, the tail
|
||||
* byte's leftover bits shift-left, as `org.waterken.uri.Base32.encode`
|
||||
* does) */
|
||||
export function yurl32(bytes: Uint8Array): string {
|
||||
let out = "";
|
||||
let buffer = 0;
|
||||
let bits = 0;
|
||||
for (const byte of bytes) {
|
||||
buffer = (buffer << 8) | byte;
|
||||
bits += 8;
|
||||
while (bits >= 5) {
|
||||
out += YURL32_ALPHABET[(buffer >>> (bits - 5)) & 31];
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
if (bits > 0) {
|
||||
out += YURL32_ALPHABET[(buffer << (5 - bits)) & 31];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** decode YURL32 back to bytes (inverse of {@link yurl32}); throws on
|
||||
* any character outside the alphabet — a webkey is either a webkey or
|
||||
* it is not */
|
||||
export function unyurl32(text: string): Uint8Array {
|
||||
let buffer = 0;
|
||||
let bits = 0;
|
||||
const out: number[] = [];
|
||||
for (const ch of text) {
|
||||
const v = YURL32_ALPHABET.indexOf(ch);
|
||||
if (v < 0) throw new Error(`not a webkey: ${JSON.stringify(ch)} is not YURL32`);
|
||||
buffer = (buffer << 5) | v;
|
||||
bits += 5;
|
||||
if (bits >= 8) {
|
||||
out.push((buffer >>> (bits - 8)) & 0xff);
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
// leftover bits (<8) are the encoder's zero-padding: validate, don't
|
||||
// carry them
|
||||
if (bits > 0 && (buffer & ((1 << bits) - 1)) !== 0) {
|
||||
throw new Error("not a webkey: non-zero tail bits");
|
||||
}
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
/** parse a hexadecimal string to raw bytes */
|
||||
export function hexToBytes(hex: string): Uint8Array {
|
||||
const trimmed = hex.trim();
|
||||
if (trimmed.length % 2 !== 0) throw new Error("invalid hex length");
|
||||
const bytes = new Uint8Array(trimmed.length / 2);
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
const val = Number.parseInt(trimmed.slice(i * 2, i * 2 + 2), 16);
|
||||
if (Number.isNaN(val)) throw new Error(`invalid hex byte at offset ${i * 2}`);
|
||||
bytes[i] = val;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** encode raw bytes to a lowercase hexadecimal string */
|
||||
export function bytesToHex(bytes: Uint8Array): string {
|
||||
let hex = "";
|
||||
for (const b of bytes) {
|
||||
hex += b.toString(16).padStart(2, "0");
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
export const BITS_PER_GLYPH = 5;
|
||||
|
||||
/** chars needed for n bits in YURL32 */
|
||||
export function glyphsFor(bits: number): number {
|
||||
return Math.ceil(bits / BITS_PER_GLYPH);
|
||||
}
|
||||
|
||||
/** YURL32 glyphs → bytes recoverable via {@link unyurl32} */
|
||||
export function bytesInGlyphs(glyphs: number): number {
|
||||
return Math.floor((glyphs * BITS_PER_GLYPH) / 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural type for a Cloudflare Worker unique ID (such as `DurableObjectId`),
|
||||
* matching `id.toString()` which returns the 64-hex string.
|
||||
*/
|
||||
export interface DurableObjectIdLike {
|
||||
toString(): string;
|
||||
equals?(other: unknown): boolean;
|
||||
readonly name?: string;
|
||||
}
|
||||
|
||||
/** A Worker unique ID input: a `DurableObjectId`, 64-char hex string, or raw bytes. */
|
||||
export type WorkerUniqueId = DurableObjectIdLike | Uint8Array;
|
||||
|
||||
/**
|
||||
* Convert a Worker unique ID (or raw bytes) to a YURL32 webkey string.
|
||||
*
|
||||
* A webkey separates secret from address. The secret bits are supplied by
|
||||
* the caller (a `DurableObjectId` from `ns.newUniqueId()`, or raw bytes):
|
||||
* these functions are pure, with no ambient RNG; the caller holds the
|
||||
* minting authority. The encoding is YURL32: lowercase `a–z` + `2–7`,
|
||||
* 5 bits per glyph, URL-safe by construction. A 256-bit `DurableObjectId`
|
||||
* (64 hex characters) becomes 52 glyphs; {@link idFromWebkey} decodes it
|
||||
* back for `ns.idFromString()`.
|
||||
*
|
||||
* Provenance: Tyler Close's web-key (IEEE W2SP 2008) and the Waterken code
|
||||
* in `kpreid/e-on-java` (YURL32 = `org.waterken.uri.Base32`); the design
|
||||
* abstract is docs/webkeys.md.
|
||||
*
|
||||
* @see https://waterken.sourceforge.net/web-key/
|
||||
*
|
||||
* @param id A `DurableObjectId` (from `ns.newUniqueId()`), a 64-char hex ID,
|
||||
* or raw bytes (`Uint8Array`).
|
||||
* @returns A YURL32 webkey string (52 glyphs for 256-bit `DurableObjectId`,
|
||||
* 26 glyphs for 128-bit raw bytes).
|
||||
*/
|
||||
export function toWebkey(id: WorkerUniqueId | string): string {
|
||||
if (id instanceof Uint8Array) {
|
||||
return yurl32(id);
|
||||
}
|
||||
const str = typeof id === "string" ? id.trim() : id.toString();
|
||||
if (/^[0-9a-fA-F]{64}$/.test(str)) {
|
||||
return yurl32(hexToBytes(str));
|
||||
}
|
||||
if (isWebkey(str)) {
|
||||
return str;
|
||||
}
|
||||
throw new Error("cannot convert ID to webkey: unrecognized format");
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a YURL32 webkey string back to the 64-character hex ID string
|
||||
* expected by `DurableObjectNamespace.idFromString(hex)`.
|
||||
*
|
||||
* If the input is already a 64-character hex ID, it is validated and returned
|
||||
* in lowercase for backwards compatibility.
|
||||
*/
|
||||
export function idFromWebkey(webkey: string): string {
|
||||
const trimmed = webkey.trim();
|
||||
if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
|
||||
return trimmed.toLowerCase();
|
||||
}
|
||||
const bytes = unyurl32(trimmed);
|
||||
if (bytes.length !== 32) {
|
||||
throw new Error(
|
||||
`expected 32 bytes (256 bits) for Worker unique ID, got ${bytes.length}`,
|
||||
);
|
||||
}
|
||||
return bytesToHex(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is `text` a well-formed webkey of the expected size?
|
||||
*
|
||||
* When `bits` is omitted, accepts standard 256-bit Worker unique ID webkeys
|
||||
* (52 glyphs), 128-bit webkeys (26 glyphs), or 64-bit webkeys (13 glyphs).
|
||||
*/
|
||||
export function isWebkey(text: string, bits?: number): boolean {
|
||||
if (bits !== undefined) {
|
||||
if (text.length !== glyphsFor(bits)) return false;
|
||||
try {
|
||||
return unyurl32(text).length === Math.floor(bits / 8);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (text.length === 52 || text.length === 26 || text.length === 13) {
|
||||
try {
|
||||
const b = unyurl32(text);
|
||||
return b.length === 32 || b.length === 16 || b.length === 8;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The identity-without-authority twin (the swissHash discipline):
|
||||
* SHA-256 hash of the webkey, YURL32-encoded (52 glyphs).
|
||||
*
|
||||
* Safe for logs/metrics/joins; never accepted as a credential.
|
||||
*/
|
||||
export async function shashKey(key: string | WorkerUniqueId): Promise<string> {
|
||||
const text = typeof key === "string" ? key : toWebkey(key);
|
||||
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
||||
return yurl32(new Uint8Array(digest));
|
||||
}
|
||||
@@ -1,435 +0,0 @@
|
||||
import { env } from "cloudflare:workers";
|
||||
import { evictDurableObject, runInDurableObject } from "cloudflare:test";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import worker from "../src/index.js";
|
||||
import { idFromWebkey, toWebkey } from "../src/webkeys.js";
|
||||
import { FETCH_BUDGET } from "../src/query.js";
|
||||
import { PAGE_SIZE } from "../src/cache.js";
|
||||
|
||||
// matches tests/fake-webapp.js: 30 items, every third private
|
||||
const WEBAPP_ID = "fake-webapp-id";
|
||||
|
||||
type TestEnv = {
|
||||
CACHE_DO: DurableObjectNamespace<import("../src/index.js").DiigoCache>;
|
||||
PUBLIC_DO: DurableObjectNamespace<import("../src/index.js").PublicCache>;
|
||||
CLOCKED_DO: DurableObjectNamespace<import("./test-worker.js").FixedClockCache>;
|
||||
WEBAPP: { calls(): Promise<number> };
|
||||
};
|
||||
const testEnv = env as unknown as TestEnv;
|
||||
|
||||
const parse = (items: string[]) => items.map((j) => JSON.parse(j) as Record<string, unknown>);
|
||||
|
||||
describe("PublicCache", () => {
|
||||
it("on a miss asks the webapp and keeps only shared items; a hit makes no call", async () => {
|
||||
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
|
||||
const before = await testEnv.WEBAPP.calls();
|
||||
const miss = await stub.page(1, 24);
|
||||
expect(miss.cached).toBe(false);
|
||||
expect(miss.total).toBe(250);
|
||||
// diigo page 1 = items 1..24, of which 8 are private
|
||||
expect(parse(miss.items).map((i) => i.private)).toEqual(Array(16).fill(false));
|
||||
const afterMiss = await testEnv.WEBAPP.calls();
|
||||
expect(afterMiss).toBeGreaterThan(before);
|
||||
|
||||
const hit = await stub.page(1, 24);
|
||||
expect(hit.cached).toBe(true);
|
||||
expect(hit.items).toEqual(miss.items);
|
||||
expect(await testEnv.WEBAPP.calls()).toBe(afterMiss);
|
||||
});
|
||||
|
||||
it("logs each page read as a hit or a miss (fetched vs kept), without the cache id", async () => {
|
||||
const spy = vi.spyOn(console, "log");
|
||||
try {
|
||||
const id = testEnv.PUBLIC_DO.newUniqueId();
|
||||
const stub = testEnv.PUBLIC_DO.get(id);
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
await stub.page(1, 24);
|
||||
await stub.page(1, 24);
|
||||
const cacheLogs = spy.mock.calls.map((c) => c[0]).filter((e) => e?.event === "cache");
|
||||
expect(cacheLogs).toEqual([
|
||||
{ event: "cache", kind: "public", page: 1, outcome: "miss", fetched: 24, kept: 16 },
|
||||
{ event: "cache", kind: "public", page: 1, outcome: "hit", items: 16 },
|
||||
]);
|
||||
expect(JSON.stringify(spy.mock.calls)).not.toContain(id.toString());
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("stores no private rows at all", async () => {
|
||||
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
await stub.page(1, 24);
|
||||
await stub.page(2, 24);
|
||||
await runInDurableObject(stub, (_obj, state) => {
|
||||
const rows = state.storage.sql.exec<{ n: number }>("select count(*) as n from items where private = 1").toArray();
|
||||
expect(rows[0].n).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("page size", () => {
|
||||
it("refuses, loudly, a short page that isn't the last (diigo capping the size would skip items)", async () => {
|
||||
const spy = vi.spyOn(console, "error");
|
||||
try {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: "fake-capped-webapp" });
|
||||
// settle the RPC promise ourselves: expect().rejects on a DO stub's
|
||||
// promise leaves the rejection unhandled
|
||||
const failure = () => stub.page(1, PAGE_SIZE).then(() => null, (e: unknown) => String(e));
|
||||
expect(await failure()).toMatch(/returned 64 items for page 1 of 3 \(asked for 100\), then 64 for page 2/);
|
||||
expect(spy.mock.calls.map((c) => c[0]).filter((e) => e?.outcome === "short-page")).toHaveLength(1);
|
||||
// nothing was stored: asking again refuses again
|
||||
expect(await failure()).toMatch(/page size not honored/);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("a short page whose next page is empty is the real end: an overstated total is noted, not refused", async () => {
|
||||
const spy = vi.spyOn(console, "log");
|
||||
try {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: "fake-overstated-webapp" });
|
||||
// 250 items claimed as 310: page 3 holds the last 50, "of 4"
|
||||
const page = await stub.page(3, PAGE_SIZE);
|
||||
expect(page.items).toHaveLength(50);
|
||||
const notes = spy.mock.calls.map((c) => c[0]).filter((e) => e?.outcome === "total-overstated");
|
||||
expect(notes).toEqual([expect.objectContaining({ page: 3, total: 310, actual: 250 })]);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("the last page may be short", async () => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
expect((await stub.page(3, PAGE_SIZE)).items).toHaveLength(250 - 2 * PAGE_SIZE);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pacing", () => {
|
||||
it("paces diigo calls only: a cache hit doesn't wait", async () => {
|
||||
const stub = testEnv.CLOCKED_DO.get(testEnv.CLOCKED_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
await stub.page(1, PAGE_SIZE);
|
||||
const afterMiss = (await stub.sleeps()).length;
|
||||
expect(afterMiss).toBeGreaterThan(0);
|
||||
for (let i = 0; i < 3; i += 1) expect((await stub.page(1, PAGE_SIZE)).cached).toBe(true);
|
||||
expect(await stub.sleeps()).toHaveLength(afterMiss);
|
||||
});
|
||||
});
|
||||
|
||||
describe("page numbering (schema v2)", () => {
|
||||
it("asks diigo for page_num n-1: page 1 is the newest page", async () => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
const first = (await stub.page(1, PAGE_SIZE)).items.map((j) => (JSON.parse(j) as { title: string }).title);
|
||||
expect(first[0]).toBe("bookmark 1");
|
||||
});
|
||||
|
||||
it("migrates v1 storage: a stored 'page n' was really page n+1, so it is renumbered, not refetched", async () => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
// the shape v1 left: a page 1 holding what diigo's page_num=1
|
||||
// returned (really page 2), and no schema marker; then a fresh
|
||||
// activation, whose constructor migrates
|
||||
await runInDurableObject(stub, (_obj, state) => {
|
||||
const sql = state.storage.sql;
|
||||
sql.exec("insert into items values ('a', 'https://a.example/', 'old page one, first', 0, '{\"title\":\"A\"}', '1')");
|
||||
sql.exec("insert into items values ('b', 'https://b.example/', 'old page one, second', 0, '{\"title\":\"B\"}', '1')");
|
||||
sql.exec("insert into pages values (1, 100, 250, '2026-10-07T00:00:00.000Z')");
|
||||
sql.exec("insert into page_members values (1, 1, 'a'), (1, 2, 'b')");
|
||||
state.storage.kv.delete("schema");
|
||||
});
|
||||
await evictDurableObject(stub);
|
||||
const before = await testEnv.WEBAPP.calls();
|
||||
const two = await stub.page(2, PAGE_SIZE);
|
||||
expect(two.cached).toBe(true);
|
||||
expect(two.items.map((j) => (JSON.parse(j) as { title: string }).title)).toEqual(["A", "B"]);
|
||||
expect(await testEnv.WEBAPP.calls()).toBe(before);
|
||||
// page 1 was never fetched under v1: now it is a miss
|
||||
expect((await stub.page(1, PAGE_SIZE)).cached).toBe(false);
|
||||
await runInDurableObject(stub, (_obj, state) => {
|
||||
expect(state.storage.kv.get("schema")).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("invalidateRecent", () => {
|
||||
it("drops the pages holding anything updated in the last N days, and only those", async () => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
// deep_dee: one bookmark a day, newest first; page 1 = days 0–99,
|
||||
// page 2 = days 100–199, page 3 = days 200–299
|
||||
await stub.setup({ webappId: "fake-deep-webapp" });
|
||||
for (const n of [1, 2, 3]) await stub.page(n, PAGE_SIZE);
|
||||
expect(await stub.invalidateRecent(150)).toEqual({ pages: 2 });
|
||||
expect((await stub.page(3, PAGE_SIZE)).cached).toBe(true);
|
||||
expect((await stub.page(2, PAGE_SIZE)).cached).toBe(false);
|
||||
expect((await stub.page(1, PAGE_SIZE)).cached).toBe(false);
|
||||
});
|
||||
|
||||
it("drops nothing when nothing cached is that recent, and refuses a bad day count", async () => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID }); // the plain account's dates are in 2023
|
||||
await stub.page(1, PAGE_SIZE);
|
||||
expect(await stub.invalidateRecent(7)).toEqual({ pages: 0 });
|
||||
expect((await stub.page(1, PAGE_SIZE)).cached).toBe(true);
|
||||
const refused = await stub.invalidateRecent(0).then(() => "", (e: unknown) => String(e));
|
||||
expect(refused).toMatch(/days/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("eviction", () => {
|
||||
it("a cache miss leaves no undisposed RPC stubs to block eviction", async () => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
await stub.page(1, 24);
|
||||
await evictDurableObject(stub);
|
||||
expect((await stub.page(1, 24)).cached).toBe(true);
|
||||
}, 3000);
|
||||
});
|
||||
|
||||
describe("DiigoCache", () => {
|
||||
it("keeps every item of a page, each under its own link_id", async () => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
const page = await stub.page(1, 24);
|
||||
const ids = parse(page.items).map((i) => i.link_id);
|
||||
expect(ids).toHaveLength(24);
|
||||
expect(new Set(ids).size).toBe(24);
|
||||
expect(parse(page.items).filter((i) => i.private)).toHaveLength(8);
|
||||
});
|
||||
});
|
||||
|
||||
describe("page replay order", () => {
|
||||
it("a hit replays diigo's fetch-time order (page_members), not a column sort", async () => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId: WEBAPP_ID });
|
||||
const titles = (items: string[]) => parse(items).map((i) => i.title);
|
||||
const expected = Array.from({ length: 24 }, (_, k) => `bookmark ${k + 1}`);
|
||||
|
||||
const miss = await stub.page(1, 24);
|
||||
expect(titles(miss.items)).toEqual(expected);
|
||||
// page 2's etch upserts other rows; page 1's replay must not shift
|
||||
await stub.page(2, 24);
|
||||
const hit = await stub.page(1, 24);
|
||||
expect(hit.cached).toBe(true);
|
||||
expect(titles(hit.items)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("worker routes", () => {
|
||||
const call = (path: string, init?: RequestInit) =>
|
||||
worker.fetch(new Request(`https://diigo-cache.test${path}`, init), env as never);
|
||||
|
||||
it("the public page only reads: an unfetched page says so; the owner's fill makes it appear", async () => {
|
||||
const wired = await call("/_wire", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ webappId: WEBAPP_ID, mode: "public" }),
|
||||
});
|
||||
expect(wired.status).toBe(200);
|
||||
const { username, publicId } = (await wired.json()) as { username: string; publicId: string };
|
||||
expect(username).toBe("alice_99");
|
||||
|
||||
// page 2 was never fetched: the public page can't fetch it
|
||||
const before = await testEnv.WEBAPP.calls();
|
||||
const unfetched = await (await call(`/public/${username}?page=2`)).text();
|
||||
expect(unfetched).toContain('<form method="get"');
|
||||
expect(unfetched).toContain("<strong>not fetched yet</strong>");
|
||||
expect(await testEnv.WEBAPP.calls()).toBe(before);
|
||||
|
||||
// the owner's side stores it (here, directly on the public cache)
|
||||
const pub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
|
||||
await pub.page(2, PAGE_SIZE);
|
||||
const html = await (await call(`/public/${username}?page=2`)).text();
|
||||
expect(html).toMatch(/<strong>stored \d{4}-\d\d-\d\dT[\d:.]+Z<\/strong>/);
|
||||
// PAGE_SIZE 100: page 2 is bookmarks 101..200
|
||||
expect(html).toContain(">bookmark 130<");
|
||||
// the date comes first, in toISOString() form
|
||||
expect(html).toMatch(/<li><time datetime="\d{4}-\d\d-\d\dT[\d:.]+Z">[^<]+<\/time> <a /);
|
||||
expect(html).not.toContain(">bookmark 129<"); // private (129 % 3 === 0)
|
||||
|
||||
const json = (await (
|
||||
await call(`/public/${username}?page=2`, { headers: { accept: "application/json" } })
|
||||
).json()) as { pages: number; stored: boolean; items: unknown[] };
|
||||
expect(json.pages).toBe(3);
|
||||
expect(json.stored).toBe(true);
|
||||
expect(json.items).toHaveLength(67); // 101..200 minus its 33 multiples of 3
|
||||
});
|
||||
|
||||
it("publishes a private cache later, without the cache id in the URL", async () => {
|
||||
const cacheId = toWebkey(testEnv.CACHE_DO.newUniqueId());
|
||||
const res = await call("/_publish", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ cacheId }),
|
||||
});
|
||||
// never wired: refused, not crashed
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
/** `yyyy-Www` for the ISO 8601 week holding `d` (UTC) */
|
||||
function isoWeek(d: Date): string {
|
||||
const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
||||
const day = t.getUTCDay() || 7;
|
||||
t.setUTCDate(t.getUTCDate() + 4 - day); // the week's Thursday names its year
|
||||
const year = t.getUTCFullYear();
|
||||
const week = Math.ceil(((t.getTime() - Date.UTC(year, 0, 1)) / 86400000 + 1) / 7);
|
||||
return `${year}-W${String(week).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
describe.skip("public page filters (goal 1d)", () => {
|
||||
// the fake's dated account: "dated n" updated n-1 days + 1h ago;
|
||||
// #weekly on every 7th; every 10th private; every 5th created 100
|
||||
// days before it was updated
|
||||
const call = (path: string, init?: RequestInit) =>
|
||||
worker.fetch(new Request(`https://diigo-cache.test${path}`, init), env as never);
|
||||
const wireDated = async () => {
|
||||
const res = await call("/_wire", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ webappId: "fake-dated-webapp", mode: "public" }),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
return "/public/dated_dan";
|
||||
};
|
||||
const titlesIn = (html: string) => [...html.matchAll(/>(dated \d+)<\/a>/g)].map((m) => m[1]);
|
||||
const dated = (...ns: number[]) => ns.map((n) => `dated ${n}`);
|
||||
|
||||
it("?days=7 lists the last week, walking only the diigo pages it needs", async () => {
|
||||
const page = await wireDated();
|
||||
const before = await testEnv.WEBAPP.calls();
|
||||
const html = await (await call(`${page}?days=7`)).text();
|
||||
expect(titlesIn(html)).toEqual(dated(1, 2, 3, 4, 5, 6, 7));
|
||||
expect((await testEnv.WEBAPP.calls()) - before).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("?by=created windows, lists, and dates by when it was bookmarked", async () => {
|
||||
const page = await wireDated();
|
||||
const html = await (await call(`${page}?days=7&by=created`)).text();
|
||||
// 5 was updated this week but bookmarked 100 days earlier
|
||||
expect(titlesIn(html)).toEqual(dated(1, 2, 3, 4, 6, 7));
|
||||
const updated = await (await call(`${page}?days=7`)).text();
|
||||
expect(titlesIn(updated)).toContain("dated 5");
|
||||
});
|
||||
|
||||
it("?by=created over a longer window sorts by created, newest first", async () => {
|
||||
const page = await wireDated();
|
||||
const html = await (await call(`${page}?days=150&by=created&q=${encodeURIComponent("#weekly")}`)).text();
|
||||
// weekly: 7,14,21,28,35,42,49,56; 35 was created ~134 days ago
|
||||
// (100 days before its update), so it sorts after 56 (~55 days)
|
||||
expect(titlesIn(html)).toEqual(dated(7, 14, 21, 28, 42, 49, 56, 35));
|
||||
});
|
||||
|
||||
it("?days=300 pages the matches PAGE_SIZE at a time; links keep the filter", async () => {
|
||||
const res = await call("/_wire", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ webappId: "fake-deep-webapp", mode: "public" }),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const page = "/public/deep_dee";
|
||||
// deep_dee: one a day; days=300 holds 1..300, minus every 10th (private)
|
||||
const want = Array.from({ length: 300 }, (_, k) => k + 1).filter((n) => n % 10 !== 0);
|
||||
const first = await (await call(`${page}?days=300`)).text();
|
||||
expect(titlesIn(first)).toEqual(dated(...want.slice(0, PAGE_SIZE)));
|
||||
expect(first).toContain(`href="${page}?days=300&page=2"`);
|
||||
const second = await (await call(`${page}?days=300&page=2`)).text();
|
||||
expect(titlesIn(second)).toEqual(dated(...want.slice(PAGE_SIZE, 2 * PAGE_SIZE)));
|
||||
const third = await (await call(`${page}?days=300&page=3`)).text();
|
||||
expect(titlesIn(third)).toEqual(dated(...want.slice(2 * PAGE_SIZE)));
|
||||
});
|
||||
|
||||
it("?after=&before= selects a date range", async () => {
|
||||
const page = await wireDated();
|
||||
const day = (n: number) => new Date(Date.now() - (n - 1) * 24 * 60 * 60 * 1000 - 60 * 60 * 1000).toISOString().slice(0, 10);
|
||||
// items are 24h apart, so each has its own UTC day: from dated 12's
|
||||
// day (inclusive) up to dated 9's day (exclusive); 10 is private
|
||||
const html = await (await call(`${page}?after=${day(12)}&before=${day(9)}`)).text();
|
||||
expect(titlesIn(html)).toEqual(dated(11, 12));
|
||||
});
|
||||
|
||||
it("?q=#weekly&days=60 filters by tag; private items stay out", async () => {
|
||||
const page = await wireDated();
|
||||
const html = await (await call(`${page}?days=60&q=${encodeURIComponent("#weekly")}`)).text();
|
||||
expect(titlesIn(html)).toEqual(dated(7, 14, 21, 28, 35, 42, 49, 56));
|
||||
});
|
||||
|
||||
it("?q= alone searches all time", async () => {
|
||||
const page = await wireDated();
|
||||
const html = await (await call(`${page}?q=fragments`)).text();
|
||||
expect(titlesIn(html)).toEqual(dated(7, 14, 21, 28, 35, 42, 49, 56));
|
||||
});
|
||||
|
||||
it("a request spends at most FETCH_BUDGET diigo fetches; incomplete results say so, and a reload continues", async () => {
|
||||
const res = await call("/_wire", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ webappId: "fake-deep-webapp", mode: "public" }),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
// deep_dee: 60 diigo pages of 100; a search matching nothing must walk them all
|
||||
const before = await testEnv.WEBAPP.calls();
|
||||
const first = await call("/public/deep_dee?q=nomatch", { headers: { accept: "application/json" } });
|
||||
expect(await first.json()).toMatchObject({ complete: false, items: [] });
|
||||
expect((await testEnv.WEBAPP.calls()) - before).toBeLessThanOrEqual(FETCH_BUDGET + 1);
|
||||
const html = await (await call("/public/deep_dee?q=nomatch")).text();
|
||||
expect(html).toMatch(/complete|no matches/);
|
||||
const again = await call("/public/deep_dee?q=nomatch", { headers: { accept: "application/json" } });
|
||||
expect(await again.json()).toMatchObject({ complete: true, items: [] });
|
||||
});
|
||||
|
||||
it("JSON answers carry the canonical filter, so devs see what was understood", async () => {
|
||||
const page = await wireDated();
|
||||
const res = await call(`${page}?days=7&q=${encodeURIComponent("#Weekly")}`, { headers: { accept: "application/json" } });
|
||||
expect(await res.json()).toMatchObject({
|
||||
filter: { by: "updated", tags: [{ text: "weekly", negated: false }] },
|
||||
complete: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("?in= an old week costs O(log pages) diigo fetches with by=updated, not a walk from page 1", async () => {
|
||||
const res = await call("/_wire", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ webappId: "fake-deep-webapp", mode: "public" }),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
// deep_dee: 6000 bookmarks, one a day, 60 diigo pages of 100; a week
|
||||
// ~14 years back sits near page 51 — a walk from page 1 would cost ~51
|
||||
const longAgo = new Date(Date.now() - 5100 * 24 * 60 * 60 * 1000);
|
||||
const week = isoWeek(longAgo);
|
||||
const before = await testEnv.WEBAPP.calls();
|
||||
const html = await (await call(`/public/deep_dee?in=${week}`)).text();
|
||||
// one a day; every 10th is private
|
||||
expect(titlesIn(html).length).toBeGreaterThanOrEqual(6);
|
||||
expect(titlesIn(html).length).toBeLessThanOrEqual(7);
|
||||
expect((await testEnv.WEBAPP.calls()) - before).toBeLessThanOrEqual(12);
|
||||
});
|
||||
|
||||
it("a malformed filter is a 400 with a message, not an empty list", async () => {
|
||||
const page = await wireDated();
|
||||
const res = await call(`${page}?days=7x`);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.text()).toMatch(/days/);
|
||||
});
|
||||
|
||||
it("the form offers the day presets, date inputs, and search, echoing the current filter", async () => {
|
||||
const page = await wireDated();
|
||||
const html = await (await call(`${page}?days=30&q=ocap`)).text();
|
||||
expect(html).toMatch(/<select name="days">/);
|
||||
expect(html).toMatch(/<select name="by">/);
|
||||
for (const n of [7, 30, 90, 365]) expect(html).toContain(`<option value="${n}"`);
|
||||
expect(html).toContain('<option value="30" selected>');
|
||||
expect(html).toMatch(/<input type="date" name="after"/);
|
||||
expect(html).toMatch(/<input type="date" name="before"/);
|
||||
expect(html).toMatch(/<input[^>]* name="q"[^>]* value="ocap"/);
|
||||
// times are UTC, and the page says so
|
||||
expect(html).toMatch(/UTC/);
|
||||
});
|
||||
});
|
||||
@@ -1,130 +0,0 @@
|
||||
/** @file a stand-in for webapp's `WebAppFactory`, serving diigo-shaped pages to tests. */
|
||||
import { RpcTarget, WorkerEntrypoint } from "cloudflare:workers";
|
||||
|
||||
const KNOWN_WEBAPP = "fake-webapp-id";
|
||||
const TOTAL = 250;
|
||||
/** the plain account, capped below PAGE_SIZE (as diigo caps at 100) */
|
||||
const CAPPED_WEBAPP = "fake-capped-webapp";
|
||||
const CAP = 64;
|
||||
/** the plain account, but its `total` claims 60 more items than it has
|
||||
* (hypothetical: what looked like this on 2026-10-07 was the 0-based
|
||||
* page_num, but the guard stays) */
|
||||
const OVERSTATED_WEBAPP = "fake-overstated-webapp";
|
||||
const OVERSTATEMENT = 60;
|
||||
|
||||
/** a second account, for date filters (goal 1d): 60 bookmarks, item n
|
||||
* updated n-1 days + 1 hour before the call, in diigo's updated-desc
|
||||
* order; tagged ocap, plus weekly every 7th; every 10th private; every
|
||||
* 5th an old bookmark edited recently (created 100 days before updated) */
|
||||
const DATED_WEBAPP = "fake-dated-webapp";
|
||||
const DATED_TOTAL = 60;
|
||||
/** the same shape, 6000 deep (~16 years, 60 pages of 100): for walk cost */
|
||||
const DEEP_WEBAPP = "fake-deep-webapp";
|
||||
const DEEP_TOTAL = 6000;
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
function datedItem(n, now, user = "dated_dan") {
|
||||
return {
|
||||
link_id: 5000 + n,
|
||||
url: `https://dated.example/${n}`,
|
||||
title: `dated ${n}`,
|
||||
description: n % 7 === 0 ? "a week of fragments" : "",
|
||||
private: n % 10 === 0,
|
||||
u_name: user,
|
||||
user_id: 777,
|
||||
tags: n % 7 === 0 ? "ocap,weekly" : "ocap",
|
||||
created_at: Math.floor((now - (n - 1) * 24 * HOUR - HOUR - (n % 5 === 0 ? 100 * 24 * HOUR : 0)) / 1000),
|
||||
updated_at: Math.floor((now - (n - 1) * 24 * HOUR - HOUR) / 1000),
|
||||
};
|
||||
}
|
||||
|
||||
/** item n (1-based, in diigo's order): diigo's field names, made-up
|
||||
* values. link_id and updated_at are scrambled (distinct; 7 and 11 are
|
||||
* coprime to 307, a prime above TOTAL), so neither column sorts back
|
||||
* into diigo's order — a
|
||||
* cache that replays by column rather than by fetch order is caught. */
|
||||
function item(n) {
|
||||
return {
|
||||
link_id: 1000 + ((n * 7) % 307),
|
||||
url: `https://example.com/${n}`,
|
||||
title: `bookmark ${n}`,
|
||||
description: "",
|
||||
private: n % 3 === 0,
|
||||
u_name: "alice_99",
|
||||
first_by: "someone-else",
|
||||
user_id: 4242,
|
||||
tags: "",
|
||||
created_at: 1700000000,
|
||||
updated_at: 1700001000 + ((n * 11) % 307),
|
||||
};
|
||||
}
|
||||
|
||||
let calls = 0;
|
||||
|
||||
class FakeGet extends RpcTarget {
|
||||
#path;
|
||||
#params;
|
||||
/** null (the plain account), "capped", "overstated", "dated", or "deep" */
|
||||
#dated;
|
||||
constructor(path, params, dated) {
|
||||
super();
|
||||
this.#path = path;
|
||||
this.#params = params;
|
||||
this.#dated = dated;
|
||||
}
|
||||
pathjoin(ref) {
|
||||
return new FakeGet(ref, this.#params, this.#dated);
|
||||
}
|
||||
query(params) {
|
||||
return new FakeGet(this.#path, { ...this.#params, ...params }, this.#dated);
|
||||
}
|
||||
async get() {
|
||||
calls += 1;
|
||||
if (this.#path !== "load_user_items") throw new Error(`fake webapp: no route ${this.#path}`);
|
||||
const count = Math.min(Number(this.#params.count), this.#dated === "capped" ? CAP : Infinity);
|
||||
const page = Number(this.#params.page_num);
|
||||
const dated = this.#dated === "dated" || this.#dated === "deep";
|
||||
const total = this.#dated === "deep" ? DEEP_TOTAL : dated ? DATED_TOTAL : TOTAL;
|
||||
const now = Date.now();
|
||||
const items = [];
|
||||
// diigo's page_num counts from 0 (observed 2026-10-07: page_num=1
|
||||
// skipped the newest page)
|
||||
for (let n = page * count + 1; n <= Math.min((page + 1) * count, total); n += 1) {
|
||||
items.push(dated ? datedItem(n, now, this.#dated === "deep" ? "deep_dee" : "dated_dan") : item(n));
|
||||
}
|
||||
// past the end, diigo answers no items and a total of 0 (observed
|
||||
// 2026-10-07: the page after the last reported total ≤ 100)
|
||||
if (items.length === 0) return JSON.stringify({ total: 0, items });
|
||||
return JSON.stringify({ total: this.#dated === "overstated" ? total + OVERSTATEMENT : total, items });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* webapp's `WebAppFactory` entrypoint, faked: an auxiliary worker (plain
|
||||
* JS; the vitest pool doesn't transform aux workers) serving
|
||||
* `load_user_items` pages for a few known webapp ids. Counts its diigo
|
||||
* calls, so tests can tell a cache hit (no call) from a miss.
|
||||
*/
|
||||
export class WebAppFactory extends WorkerEntrypoint {
|
||||
async at(id) {
|
||||
const kind = {
|
||||
[KNOWN_WEBAPP]: null,
|
||||
[CAPPED_WEBAPP]: "capped",
|
||||
[OVERSTATED_WEBAPP]: "overstated",
|
||||
[DATED_WEBAPP]: "dated",
|
||||
[DEEP_WEBAPP]: "deep",
|
||||
}[id];
|
||||
if (kind === undefined) throw new Error("fake webapp: unknown id");
|
||||
return new FakeGet("", {}, kind);
|
||||
}
|
||||
/** how many diigo calls so far (test hook) */
|
||||
async calls() {
|
||||
return calls;
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
fetch() {
|
||||
return new Response("fake webapp", { status: 404 });
|
||||
},
|
||||
};
|
||||
@@ -1,349 +0,0 @@
|
||||
import { env } from "cloudflare:workers";
|
||||
import { evictDurableObject, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import worker from "../src/index.js";
|
||||
import { newHttpBatchRpcSession } from "capnweb";
|
||||
import type { CacheApi } from "../src/api.js";
|
||||
import { idFromWebkey, toWebkey } from "../src/webkeys.js";
|
||||
import { FIXED_NOW } from "./test-worker.js";
|
||||
import { PAGE_SIZE } from "../src/cache.js";
|
||||
|
||||
// goal 1e (capsite checklist): a job that grabs every page. Fake
|
||||
// accounts: tests/fake-webapp.js ("fake-webapp-id": 250 items = 3 pages
|
||||
// of PAGE_SIZE 100, every 3rd private).
|
||||
|
||||
type TestEnv = {
|
||||
CACHE_DO: DurableObjectNamespace<import("../src/index.js").DiigoCache>;
|
||||
CLOCKED_DO: DurableObjectNamespace<import("./test-worker.js").FixedClockCache>;
|
||||
PUBLIC_DO: DurableObjectNamespace<import("../src/index.js").PublicCache>;
|
||||
WEBAPP: { calls(): Promise<number> };
|
||||
};
|
||||
const testEnv = env as unknown as TestEnv;
|
||||
|
||||
const wired = async (webappId = "fake-webapp-id") => {
|
||||
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
|
||||
await stub.setup({ webappId });
|
||||
return stub;
|
||||
};
|
||||
|
||||
/** run alarms until none is scheduled (bounded, so a runaway job fails) */
|
||||
const drain = async (stub: DurableObjectStub, max = 20) => {
|
||||
let ran = 0;
|
||||
while (ran < max && (await runDurableObjectAlarm(stub))) ran += 1;
|
||||
expect(ran).toBeLessThan(max);
|
||||
return ran;
|
||||
};
|
||||
|
||||
describe("fill job (goal 1e)", () => {
|
||||
it("fills every page; afterwards every page is a hit with no webapp call", async () => {
|
||||
const stub = await wired();
|
||||
const atStart = await testEnv.WEBAPP.calls();
|
||||
expect((await stub.startFill()).state).toBe("running");
|
||||
await drain(stub);
|
||||
const status = await stub.fillStatus();
|
||||
expect(status).toMatchObject({ state: "done", pages: 3, fetched: 3 });
|
||||
// one diigo call per page fetched (no extra page-1 fetch per miss)
|
||||
expect((await testEnv.WEBAPP.calls()) - atStart).toBe(3);
|
||||
|
||||
const before = await testEnv.WEBAPP.calls();
|
||||
for (const n of [1, 2, 3]) expect((await stub.page(n, PAGE_SIZE)).cached).toBe(true);
|
||||
expect(await testEnv.WEBAPP.calls()).toBe(before);
|
||||
});
|
||||
|
||||
it("advances pagesPerStep pages per alarm, with progress readable between steps", async () => {
|
||||
const stub = await wired();
|
||||
await stub.startFill({ pagesPerStep: 1 });
|
||||
expect(await runDurableObjectAlarm(stub)).toBe(true);
|
||||
expect(await stub.fillStatus()).toMatchObject({ state: "running", nextPage: 2, pages: 3 });
|
||||
await drain(stub);
|
||||
expect((await stub.fillStatus())?.state).toBe("done");
|
||||
});
|
||||
|
||||
it("survives eviction: progress is in storage, not memory", async () => {
|
||||
const stub = await wired();
|
||||
await stub.startFill({ pagesPerStep: 1 });
|
||||
await runDurableObjectAlarm(stub);
|
||||
await evictDurableObject(stub);
|
||||
expect(await stub.fillStatus()).toMatchObject({ state: "running", nextPage: 2 });
|
||||
await drain(stub);
|
||||
expect((await stub.fillStatus())?.state).toBe("done");
|
||||
});
|
||||
|
||||
it("starting again while running rejoins the same job", async () => {
|
||||
const stub = await wired();
|
||||
const first = await stub.startFill({ pagesPerStep: 1 });
|
||||
await runDurableObjectAlarm(stub);
|
||||
const again = await stub.startFill({ pagesPerStep: 1 });
|
||||
expect(again.startedAt).toBe(first.startedAt);
|
||||
expect(again.nextPage).toBe(2);
|
||||
});
|
||||
|
||||
it("skips pages already cached", async () => {
|
||||
const stub = await wired();
|
||||
await stub.page(1, PAGE_SIZE);
|
||||
await stub.startFill();
|
||||
await drain(stub);
|
||||
expect(await stub.fillStatus()).toMatchObject({ state: "done", fetched: 2 });
|
||||
});
|
||||
|
||||
it("stops when asked; cached pages stay", async () => {
|
||||
const stub = await wired();
|
||||
await stub.startFill({ pagesPerStep: 1 });
|
||||
await runDurableObjectAlarm(stub);
|
||||
expect((await stub.stopFill()).state).toBe("stopped");
|
||||
expect(await runDurableObjectAlarm(stub)).toBe(false);
|
||||
expect((await stub.page(1, PAGE_SIZE)).cached).toBe(true);
|
||||
});
|
||||
|
||||
it("a webapp failure fails the job loudly, once: status says why, the log too", async () => {
|
||||
const spy = vi.spyOn(console, "error");
|
||||
try {
|
||||
const stub = await wired("no-such-webapp");
|
||||
await stub.startFill();
|
||||
await drain(stub);
|
||||
const status = await stub.fillStatus();
|
||||
expect(status?.state).toBe("failed");
|
||||
expect(status?.error).toMatch(/unknown id/);
|
||||
expect(spy.mock.calls.map((c) => c[0]).filter((e) => e?.event === "fill")).not.toHaveLength(0);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("reads time only through its clock: a fixed clock pins the timestamps and the alarm", async () => {
|
||||
const stub = testEnv.CLOCKED_DO.get(testEnv.CLOCKED_DO.newUniqueId());
|
||||
await stub.setup({ webappId: "fake-webapp-id" });
|
||||
const at = new Date(FIXED_NOW).toISOString();
|
||||
expect(await stub.startFill()).toMatchObject({ startedAt: at, updatedAt: at });
|
||||
await runInDurableObject(stub, async (_obj, state) => {
|
||||
expect(await state.storage.getAlarm()).toBe(FIXED_NOW + 1000);
|
||||
});
|
||||
await drain(stub);
|
||||
expect(await stub.fillStatus()).toMatchObject({ state: "done", updatedAt: at });
|
||||
});
|
||||
|
||||
it("a capped page size fails the fill with the reason, instead of skipping items", async () => {
|
||||
const stub = await wired("fake-capped-webapp");
|
||||
await stub.startFill();
|
||||
await drain(stub);
|
||||
const status = await stub.fillStatus();
|
||||
expect(status?.state).toBe("failed");
|
||||
expect(status?.error).toMatch(/page size not honored/);
|
||||
});
|
||||
|
||||
it("fills to the real end if a total overstates the items", async () => {
|
||||
const stub = await wired("fake-overstated-webapp");
|
||||
await stub.startFill();
|
||||
await drain(stub);
|
||||
// 250 items claimed as 310: the walk reaches page 4 (empty, total 0)
|
||||
// and ends there; the count is the last page with items, not 4, and
|
||||
// not the empty page's ceil(0/100) = 1
|
||||
const status = await stub.fillStatus();
|
||||
expect(status).toMatchObject({ state: "done", nextPage: 4, pages: 3 });
|
||||
expect((await stub.page(3, PAGE_SIZE)).items).toHaveLength(50);
|
||||
});
|
||||
|
||||
it("a job saved under the old page numbering fails instead of resuming", async () => {
|
||||
const stub = await wired();
|
||||
await runInDurableObject(stub, async (_obj, state) => {
|
||||
const at = new Date().toISOString();
|
||||
await state.storage.put("fill", { state: "running", nextPage: 40, pages: 168, fetched: 39, pageSize: 100, startedAt: at, updatedAt: at });
|
||||
await state.storage.setAlarm(Date.now() + 60_000);
|
||||
});
|
||||
await drain(stub);
|
||||
expect((await stub.fillStatus())?.error).toMatch(/page numbering changed/);
|
||||
expect(await stub.startFill()).toMatchObject({ state: "running", nextPage: 1, numbering: 2 });
|
||||
});
|
||||
|
||||
it("a job saved under another page size fails instead of resuming; a new start replaces it", async () => {
|
||||
const stub = await wired();
|
||||
// the shape a 24-per-page job left in storage (no pageSize field)
|
||||
await runInDurableObject(stub, async (_obj, state) => {
|
||||
const at = new Date().toISOString();
|
||||
await state.storage.put("fill", { state: "running", nextPage: 25, pages: 698, fetched: 23, startedAt: at, updatedAt: at });
|
||||
await state.storage.setAlarm(Date.now() + 60_000);
|
||||
});
|
||||
await drain(stub);
|
||||
const stale = await stub.fillStatus();
|
||||
expect(stale?.state).toBe("failed");
|
||||
expect(stale?.error).toMatch(/page size changed \(from 24 to 100\)/);
|
||||
expect(await stub.startFill()).toMatchObject({ state: "running", nextPage: 1, pageSize: PAGE_SIZE });
|
||||
});
|
||||
|
||||
it("a public cache's fill stores no private rows", async () => {
|
||||
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
|
||||
await stub.setup({ webappId: "fake-webapp-id" });
|
||||
await stub.startFill();
|
||||
await drain(stub);
|
||||
await runInDurableObject(stub, (_obj, state) => {
|
||||
const rows = state.storage.sql.exec<{ n: number }>("select count(*) as n from items where private = 1").toArray();
|
||||
expect(rows[0].n).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("fill via webkey and Cap'n Web (goal 1e)", () => {
|
||||
const ORIGIN = "https://diigo-cache.test";
|
||||
const call = (path: string, init?: RequestInit) => worker.fetch(new Request(`${ORIGIN}${path}`, init), env as never);
|
||||
|
||||
/** a Cap'n Web batch session whose fetch goes to the worker; counts round trips */
|
||||
const session = () => {
|
||||
const trips = { n: 0 };
|
||||
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
|
||||
trips.n += 1;
|
||||
return worker.fetch(new Request(input as RequestInfo, init), env as never);
|
||||
});
|
||||
const api = newHttpBatchRpcSession<CacheApi>(`${ORIGIN}/api`);
|
||||
return { api, trips, done: () => fetchSpy.mockRestore() };
|
||||
};
|
||||
|
||||
const wireJson = async (mode: "private" | "public") => {
|
||||
const res = await call("/_wire", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ webappId: "fake-webapp-id", mode }),
|
||||
});
|
||||
return (await res.json()) as { cacheId: string; username?: string; publicId?: string };
|
||||
};
|
||||
|
||||
it("trading the key and starting the fill pipeline into one round trip", async () => {
|
||||
const { cacheId } = await wireJson("private");
|
||||
const { api, trips, done } = session();
|
||||
try {
|
||||
const status = await api.cache(cacheId).startFill();
|
||||
expect(status).toMatchObject({ state: "running" });
|
||||
expect(trips.n).toBe(1);
|
||||
} finally {
|
||||
done();
|
||||
}
|
||||
});
|
||||
|
||||
it("the capability is a facet: fill and status, never the DO's wiring", async () => {
|
||||
const { cacheId } = await wireJson("private");
|
||||
const { api, done } = session();
|
||||
try {
|
||||
const cap = api.cache(cacheId) as unknown as Record<string, () => Promise<unknown>>;
|
||||
await expect(cap.setup()).rejects.toThrow();
|
||||
} finally {
|
||||
done();
|
||||
}
|
||||
});
|
||||
|
||||
it("unknown and malformed keys get one refusal that never echoes the key", async () => {
|
||||
const unknown = toWebkey(testEnv.CACHE_DO.newUniqueId());
|
||||
for (const key of [unknown, "not-a-key", unknown.slice(0, 26)]) {
|
||||
const { api, done } = session();
|
||||
try {
|
||||
const err = await api.cache(key).fillStatus().then(() => null, (e: unknown) => e);
|
||||
expect(String(err)).toMatch(/no such cache/);
|
||||
expect(String(err)).not.toContain(key);
|
||||
} finally {
|
||||
done();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("publicCache() reaches the public companion's fill; refused when never published", async () => {
|
||||
const pub = await wireJson("public");
|
||||
const s1 = session();
|
||||
try {
|
||||
expect(await s1.api.cache(pub.cacheId).hasPublic()).toBe(true);
|
||||
} finally {
|
||||
s1.done();
|
||||
}
|
||||
const s2 = session();
|
||||
try {
|
||||
expect(await s2.api.cache(pub.cacheId).publicCache().startFill()).toMatchObject({ state: "running" });
|
||||
} finally {
|
||||
s2.done();
|
||||
}
|
||||
const s3 = session();
|
||||
try {
|
||||
expect(await s3.api.cache(pub.cacheId).publicCache().stopFill()).toMatchObject({ state: "stopped" });
|
||||
} finally {
|
||||
s3.done();
|
||||
}
|
||||
const priv = await wireJson("private");
|
||||
const s4 = session();
|
||||
try {
|
||||
expect(await s4.api.cache(priv.cacheId).hasPublic()).toBe(false);
|
||||
} finally {
|
||||
s4.done();
|
||||
}
|
||||
// a batch session ends after its round trip: a fresh one per await
|
||||
const s5 = session();
|
||||
try {
|
||||
await expect(s5.api.cache(priv.cacheId).publicCache().fillStatus()).rejects.toThrow(/no public cache/);
|
||||
} finally {
|
||||
s5.done();
|
||||
}
|
||||
});
|
||||
|
||||
it("the webkey page is a skeleton: the same for every key, which it reads from the fragment", async () => {
|
||||
const res = await call("/cache/");
|
||||
expect(res.status).toBe(200);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("location.hash");
|
||||
expect(html).toContain('from "/_capnweb.js"');
|
||||
expect(html).toContain('newHttpBatchRpcSession("/api")');
|
||||
expect(html).toContain('<meta name="referrer" content="no-referrer">');
|
||||
});
|
||||
|
||||
it("without a fragment, the webkey page is a login form a password manager can fill, which posts nothing", async () => {
|
||||
const html = await (await call("/cache/")).text();
|
||||
const form = html.match(/<form id="login"[^]*?<\/form>/)?.[0] ?? "";
|
||||
expect(form).toMatch(/<input[^>]* autocomplete="username"/);
|
||||
expect(form).toMatch(/<input[^>]* type="password"[^>]* autocomplete="current-password"/);
|
||||
// no name attributes: a native submit carries no key anywhere
|
||||
expect(form).not.toMatch(/\bname=/);
|
||||
expect(form).not.toMatch(/\baction=/);
|
||||
expect(html).toContain("event.preventDefault()");
|
||||
});
|
||||
|
||||
it("the capability can invalidate recent pages; the page offers it for each cache", async () => {
|
||||
const { cacheId } = await wireJson("private");
|
||||
const { api, done } = session();
|
||||
try {
|
||||
expect(await api.cache(cacheId).invalidateRecent(7)).toEqual({ pages: 0 });
|
||||
} finally {
|
||||
done();
|
||||
}
|
||||
const html = await (await call("/cache/")).text();
|
||||
expect(html).toContain('id="private-days"');
|
||||
expect(html).toContain('data-action="invalidate"');
|
||||
expect(html).toContain("invalidateRecent(days)");
|
||||
});
|
||||
|
||||
it("serves capnweb's browser build itself (no third-party script beside the key)", async () => {
|
||||
const res = await call("/_capnweb.js");
|
||||
expect(res.headers.get("content-type")).toMatch(/javascript/);
|
||||
expect(await res.text()).toMatch(/export \{[^}]*newHttpBatchRpcSession/);
|
||||
});
|
||||
|
||||
it("the created page links its webkey (key in the fragment); no cache id rides a form to /_fill", async () => {
|
||||
const res = await call("/_wire", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ webappId: "fake-webapp-id", mode: "private" }),
|
||||
});
|
||||
const html = await res.text();
|
||||
expect(html).toMatch(/<a href="\/cache\/#[a-z2-7]{52}">/);
|
||||
expect(html).not.toContain("/_fill");
|
||||
expect((await call("/_fill", { method: "POST" })).status).toBe(404);
|
||||
});
|
||||
|
||||
it("the public page shows a fill's progress", async () => {
|
||||
const { cacheId, username, publicId } = (await wireJson("public")) as { cacheId: string; username: string; publicId: string };
|
||||
const { api, done } = session();
|
||||
try {
|
||||
await api.cache(cacheId).publicCache().startFill({ pagesPerStep: 1 });
|
||||
} finally {
|
||||
done();
|
||||
}
|
||||
// one step of the job: page 1 stored, so the page count is known
|
||||
const pub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
|
||||
await runDurableObjectAlarm(pub);
|
||||
const html = await (await call(`/public/${username}`)).text();
|
||||
expect(html).toMatch(/fill(ed|ing)[^<]*\d+ of \d+ pages/);
|
||||
});
|
||||
});
|
||||
@@ -1,83 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { publicOnly, toRows, updatedISO, usernameOf } from "../src/items.js";
|
||||
import type { Item } from "../src/items.js";
|
||||
|
||||
/** a load_user_items row: diigo's actual field names (observed
|
||||
* 2026-10-07), made-up values */
|
||||
function diigoItem(linkId: number, url: string): Item {
|
||||
return {
|
||||
link_id: linkId,
|
||||
url,
|
||||
title: `title ${linkId}`,
|
||||
description: "",
|
||||
private: false,
|
||||
u_name: "alice_99",
|
||||
first_by: "bob-the-first",
|
||||
user_id: 4242,
|
||||
real_name: "Alice A.",
|
||||
tags: "",
|
||||
created_at: 1700000000,
|
||||
updated_at: 1700000100 + linkId,
|
||||
annotations: [],
|
||||
comments: [],
|
||||
};
|
||||
}
|
||||
|
||||
function makeLog() {
|
||||
const entries: { level: string; args: unknown[] }[] = [];
|
||||
const at = (level: string) => (...args: unknown[]) => entries.push({ level, args });
|
||||
return { log: { warn: at("warn") }, entries };
|
||||
}
|
||||
|
||||
describe("toRows", () => {
|
||||
it("keys each item on diigo's link_id, so a page of distinct items stays distinct", () => {
|
||||
const { log } = makeLog();
|
||||
const rows = toRows([diigoItem(11, "https://a.example/"), diigoItem(12, "https://b.example/")], log);
|
||||
expect(rows.map((r) => r.itemId)).toEqual(["11", "12"]);
|
||||
});
|
||||
|
||||
it("logs, rather than silently drops or merges, items it cannot key", () => {
|
||||
const { log, entries } = makeLog();
|
||||
const noId = diigoItem(13, "https://c.example/");
|
||||
delete noId.link_id;
|
||||
const noUrl = diigoItem(14, "");
|
||||
const rows = toRows([noId, noUrl, diigoItem(15, "https://d.example/")], log);
|
||||
expect(rows.map((r) => r.itemId)).toEqual(["15"]);
|
||||
expect(entries.map((e) => e.level)).toEqual(["warn", "warn"]);
|
||||
// diagnostics name the fields present, never their values
|
||||
expect(JSON.stringify(entries)).not.toContain("https://c.example/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("usernameOf", () => {
|
||||
it("reads the owner's username from diigo's u_name", () => {
|
||||
expect(usernameOf(diigoItem(1, "https://a.example/"))).toBe("alice_99");
|
||||
});
|
||||
|
||||
it("answers empty for an item without one", () => {
|
||||
expect(usernameOf(undefined)).toBe("");
|
||||
expect(usernameOf({ u_name: "has spaces" })).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("publicOnly", () => {
|
||||
it("keeps shared rows and drops private ones, before anything is stored", () => {
|
||||
const { log } = makeLog();
|
||||
const shared = diigoItem(21, "https://shared.example/");
|
||||
const secret = { ...diigoItem(22, "https://secret.example/"), private: true };
|
||||
const rows = publicOnly(toRows([shared, secret], log));
|
||||
expect(rows.map((r) => r.itemId)).toEqual(["21"]);
|
||||
expect(JSON.stringify(rows)).not.toContain("secret.example");
|
||||
});
|
||||
});
|
||||
|
||||
describe("updatedISO", () => {
|
||||
it("reads diigo's updated_at as epoch seconds", () => {
|
||||
expect(updatedISO({ updated_at: 1700000000 })).toBe("2023-11-14T22:13:20.000Z");
|
||||
});
|
||||
|
||||
it("answers empty when there is no usable date", () => {
|
||||
expect(updatedISO({})).toBe("");
|
||||
expect(updatedISO({ updated_at: "yesterday" })).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { pmSave } from "../src/pm-save.js";
|
||||
import type { PmPowers } from "../src/pm-save.js";
|
||||
|
||||
/** a fake console that records what was logged, by level */
|
||||
function makeLog() {
|
||||
const entries: { level: string; args: unknown[] }[] = [];
|
||||
const at = (level: string) => (...args: unknown[]) => entries.push({ level, args });
|
||||
return { log: { info: at("info"), warn: at("warn"), error: at("error") }, entries };
|
||||
}
|
||||
|
||||
class FakeCredential {
|
||||
constructor(readonly init: { id: string; password: string }) {}
|
||||
}
|
||||
|
||||
function setup(store: (c: unknown) => Promise<unknown>, petname = "my cache") {
|
||||
const { log, entries } = makeLog();
|
||||
const stored: unknown[] = [];
|
||||
const powers: PmPowers = {
|
||||
petname: { value: petname },
|
||||
credentials: { store: (c) => (stored.push(c), store(c)) },
|
||||
PasswordCredential: FakeCredential,
|
||||
log,
|
||||
};
|
||||
const btn = { textContent: "save to password manager", disabled: false };
|
||||
return { powers, btn, entries, stored };
|
||||
}
|
||||
|
||||
describe("pmSave", () => {
|
||||
it("stores under the petname, and reports a spec-conformant resolve (undefined) as offered, not failed", async () => {
|
||||
const { powers, btn, entries, stored } = setup(() => Promise.resolve(undefined));
|
||||
await pmSave(btn, "the-key", powers);
|
||||
expect(stored).toEqual([new FakeCredential({ id: "my cache", password: "the-key" })]);
|
||||
expect(btn.textContent).not.toMatch(/not saved|fail/);
|
||||
expect(btn.textContent).toMatch(/password manager/);
|
||||
expect(btn.disabled).toBe(false);
|
||||
expect(entries.map((e) => e.level)).toEqual(["info"]);
|
||||
});
|
||||
|
||||
it("logs, never silently, when the browser has no credential store", async () => {
|
||||
const { powers, btn, entries } = setup(() => Promise.resolve(undefined));
|
||||
delete powers.PasswordCredential;
|
||||
await pmSave(btn, "the-key", powers);
|
||||
expect(btn.textContent).toMatch(/no credential store/);
|
||||
expect(entries.map((e) => e.level)).toEqual(["warn"]);
|
||||
});
|
||||
|
||||
it("logs the error when the store rejects, without the key", async () => {
|
||||
const { powers, btn, entries } = setup(() => Promise.reject(new Error("NotAllowedError")));
|
||||
await pmSave(btn, "the-key", powers);
|
||||
expect(btn.textContent).toMatch(/save failed/);
|
||||
expect(entries.map((e) => e.level)).toEqual(["error"]);
|
||||
expect(JSON.stringify(entries)).not.toContain("the-key");
|
||||
});
|
||||
|
||||
it("asks for a petname rather than saving under an empty username", async () => {
|
||||
const { powers, btn, stored } = setup(() => Promise.resolve(undefined), " ");
|
||||
await pmSave(btn, "the-key", powers);
|
||||
expect(stored).toEqual([]);
|
||||
expect(btn.textContent).toMatch(/petname/);
|
||||
});
|
||||
});
|
||||
@@ -1,206 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { matches, parseQuery, toQuery } from "../src/query.js";
|
||||
import type { FilterSpec, Query, QueryError } from "../src/query.js";
|
||||
|
||||
// goal 1d (capsite checklist): the design as tests; unskip as it lands
|
||||
|
||||
const NOW = new Date("2026-10-07T12:00:00.000Z");
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
const fromUrl = (qs: string) => parseQuery(new URLSearchParams(qs), NOW);
|
||||
const ok = (q: Query | QueryError) => {
|
||||
if ("error" in q) throw new Error(`expected a query: ${q.error}`);
|
||||
return q;
|
||||
};
|
||||
const url = (qs: string) => ok(fromUrl(qs));
|
||||
const spec = (s: FilterSpec) => ok(toQuery(s, NOW));
|
||||
const refused = (q: Query | QueryError) => {
|
||||
expect(q).toHaveProperty("error");
|
||||
return (q as QueryError).error;
|
||||
};
|
||||
const day = (iso: string) => new Date(`${iso}T00:00:00.000Z`);
|
||||
const range = (q: Query) => [q.after?.toISOString().slice(0, 10), q.before?.toISOString().slice(0, 10)];
|
||||
|
||||
describe.skip("filters: one spec, two spellings (goal 1d)", () => {
|
||||
it("devs write { days: 7 }; URLs write ?days=7; same query", () => {
|
||||
expect(spec({ days: 7 })).toEqual(url("days=7"));
|
||||
expect(spec({ days: 7 }).after).toEqual(new Date(NOW.getTime() - 7 * DAY));
|
||||
});
|
||||
|
||||
it("an empty spec or URL filters nothing", () => {
|
||||
expect(spec({})).toEqual({ by: "updated", words: [], tags: [] });
|
||||
expect(url("")).toEqual({ by: "updated", words: [], tags: [] });
|
||||
});
|
||||
|
||||
it("empty URL fields mean absent (a GET form submits them all)", () => {
|
||||
expect(url("days=7&after=&before=&in=&by=&q=")).toEqual(url("days=7"));
|
||||
});
|
||||
|
||||
it("refuses a days value that isn't a whole number from 1 to 3650", () => {
|
||||
for (const bad of ["0", "-7", "7x", "1.5", "3651"]) expect(refused(fromUrl(`days=${bad}`))).toMatch(/days/);
|
||||
expect(refused(toQuery({ days: 0 }, NOW))).toMatch(/days/);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skip("windows: UTC, half-open (goal 1d)", () => {
|
||||
it("after/before are UTC days: after inclusive from 00:00Z, before exclusive", () => {
|
||||
expect(range(url("after=2026-01-01&before=2026-02-01"))).toEqual(["2026-01-01", "2026-02-01"]);
|
||||
expect(url("after=2026/01/01").after).toEqual(day("2026-01-01"));
|
||||
});
|
||||
|
||||
it("in= names a year, month, quarter, or ISO week", () => {
|
||||
expect(range(url("in=2025"))).toEqual(["2025-01-01", "2026-01-01"]);
|
||||
expect(range(url("in=2025-03"))).toEqual(["2025-03-01", "2025-04-01"]);
|
||||
expect(range(url("in=2025-12"))).toEqual(["2025-12-01", "2026-01-01"]);
|
||||
expect(range(url("in=2025-Q1"))).toEqual(["2025-01-01", "2025-04-01"]);
|
||||
expect(range(url("in=2025-Q4"))).toEqual(["2025-10-01", "2026-01-01"]);
|
||||
// ISO 8601: weeks start Monday; week 1 holds the year's first Thursday
|
||||
expect(range(url("in=2025-W01"))).toEqual(["2024-12-30", "2025-01-06"]);
|
||||
expect(range(url("in=2026-W53"))).toEqual(["2026-12-28", "2027-01-04"]);
|
||||
});
|
||||
|
||||
it("refuses malformed dates and periods", () => {
|
||||
expect(refused(fromUrl("after=2026-13-01"))).toMatch(/after/);
|
||||
expect(refused(fromUrl("before=yesterday"))).toMatch(/before/);
|
||||
// 2025 has 52 ISO weeks (it starts on a Wednesday, not a leap year)
|
||||
for (const bad of ["2025-13", "2025-Q5", "2025-W53", "2025-W00", "25", "2025-1"]) {
|
||||
expect(refused(fromUrl(`in=${bad}`))).toMatch(/in/);
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a bound given twice, and an empty window", () => {
|
||||
expect(refused(fromUrl("days=7&after=2026-01-01"))).toMatch(/days.*after|after.*days/);
|
||||
expect(refused(fromUrl("in=2025&days=7"))).toMatch(/in/);
|
||||
expect(refused(fromUrl("in=2025&before=2025-02-01"))).toMatch(/in/);
|
||||
expect(refused(fromUrl("after=2026-02-01&before=2026-02-01"))).toMatch(/after.*before|before.*after/);
|
||||
});
|
||||
|
||||
it("days combines with before", () => {
|
||||
const q = url("days=30&before=2026-10-01");
|
||||
expect(q.after).toEqual(new Date(NOW.getTime() - 30 * DAY));
|
||||
expect(q.before).toEqual(day("2026-10-01"));
|
||||
});
|
||||
|
||||
it("by=created or by=updated picks the date (default updated); anything else is refused", () => {
|
||||
expect(url("days=7").by).toBe("updated");
|
||||
expect(url("days=7&by=created").by).toBe("created");
|
||||
expect(refused(fromUrl("days=7&by=modified"))).toMatch(/by/);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skip("q: terms and operators (goal 1d)", () => {
|
||||
const q = (text: string) => url(`q=${encodeURIComponent(text)}`);
|
||||
|
||||
it("words, phrases, #tags, tag:, and - negation; case-insensitive", () => {
|
||||
const parsed = q('Foo bar -baz "exact phrase" #Weekly tag:ocap -#draft -tag:old');
|
||||
expect(parsed.words).toEqual([
|
||||
{ text: "foo", negated: false },
|
||||
{ text: "bar", negated: false },
|
||||
{ text: "baz", negated: true },
|
||||
{ text: "exact phrase", negated: false },
|
||||
]);
|
||||
expect(parsed.tags).toEqual([
|
||||
{ text: "weekly", negated: false },
|
||||
{ text: "ocap", negated: false },
|
||||
{ text: "draft", negated: true },
|
||||
{ text: "old", negated: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("gmail's after:/before:/newer_than: set the window", () => {
|
||||
expect(range(q("after:2026-01-01 before:2026/02/01"))).toEqual(["2026-01-01", "2026-02-01"]);
|
||||
expect(q("newer_than:7d").after).toEqual(new Date(NOW.getTime() - 7 * DAY));
|
||||
expect(q("newer_than:2w").after).toEqual(new Date(NOW.getTime() - 14 * DAY));
|
||||
// months and years are calendar steps back, in UTC
|
||||
expect(q("newer_than:1m").after).toEqual(new Date("2026-09-07T12:00:00.000Z"));
|
||||
expect(q("newer_than:1y").after).toEqual(new Date("2025-10-07T12:00:00.000Z"));
|
||||
});
|
||||
|
||||
it("Slack's during: (alias in:) names a period", () => {
|
||||
expect(range(q("during:2025-Q1"))).toEqual(["2025-01-01", "2025-04-01"]);
|
||||
expect(range(q("in:2025-W01"))).toEqual(["2024-12-30", "2025-01-06"]);
|
||||
});
|
||||
|
||||
it("GitHub-style created:/updated: name the date and the period at once", () => {
|
||||
const c = q("created:2025");
|
||||
expect(c.by).toBe("created");
|
||||
expect(range(c)).toEqual(["2025-01-01", "2026-01-01"]);
|
||||
expect(q("updated:2025-W03").by).toBe("updated");
|
||||
});
|
||||
|
||||
it("operators and fields combine, but a bound given twice is refused", () => {
|
||||
const both = url(`by=created&q=${encodeURIComponent("during:2025 #weekly")}`);
|
||||
expect(both.by).toBe("created");
|
||||
expect(both.tags).toEqual([{ text: "weekly", negated: false }]);
|
||||
expect(refused(fromUrl(`days=7&q=${encodeURIComponent("newer_than:30d")}`))).toMatch(/newer_than|days/);
|
||||
expect(refused(fromUrl(`by=updated&q=${encodeURIComponent("created:2025")}`))).toMatch(/by|created/);
|
||||
});
|
||||
|
||||
it("an unknown word:stuff is plain text (so urls work as words)", () => {
|
||||
expect(q("https://erights.org foo:bar").words).toEqual([
|
||||
{ text: "https://erights.org", negated: false },
|
||||
{ text: "foo:bar", negated: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("a malformed known operator is refused, not searched as text", () => {
|
||||
expect(refused(fromUrl(`q=${encodeURIComponent("newer_than:7x")}`))).toMatch(/newer_than/);
|
||||
expect(refused(fromUrl(`q=${encodeURIComponent("during:2025-Q5")}`))).toMatch(/during/);
|
||||
});
|
||||
});
|
||||
|
||||
/** an item updated at `iso`, diigo-shaped */
|
||||
const item = (iso: string, extra: Record<string, unknown> = {}) => ({
|
||||
updated_at: new Date(iso).getTime() / 1000,
|
||||
title: "",
|
||||
description: "",
|
||||
url: "https://example.com/",
|
||||
tags: "",
|
||||
...extra,
|
||||
});
|
||||
const query = (q: Partial<Query>): Query => ({ by: "updated", words: [], tags: [], ...q });
|
||||
|
||||
describe.skip("matches (goal 1d)", () => {
|
||||
it("the window is half-open: after inclusive, before exclusive", () => {
|
||||
const q = query({ after: day("2026-01-01"), before: day("2026-02-01") });
|
||||
expect(matches(item("2026-01-01T00:00:00.000Z"), q)).toBe(true);
|
||||
expect(matches(item("2025-12-31T23:59:59.000Z"), q)).toBe(false);
|
||||
expect(matches(item("2026-01-31T23:59:59.000Z"), q)).toBe(true);
|
||||
expect(matches(item("2026-02-01T00:00:00.000Z"), q)).toBe(false);
|
||||
});
|
||||
|
||||
it("by=created windows on created_at instead of updated_at", () => {
|
||||
const jan = { after: day("2026-01-01") };
|
||||
// an old bookmark, edited recently
|
||||
const edited = item("2026-01-05T00:00:00Z", { created_at: new Date("2025-06-01T00:00:00Z").getTime() / 1000 });
|
||||
expect(matches(edited, query({ ...jan, by: "updated" }))).toBe(true);
|
||||
expect(matches(edited, query({ ...jan, by: "created" }))).toBe(false);
|
||||
});
|
||||
|
||||
it("every word must appear in the title, description, or url (case-insensitive)", () => {
|
||||
const it1 = item("2026-01-05T00:00:00Z", { title: "Capability Patterns", url: "https://erights.org/x" });
|
||||
expect(matches(it1, query({ words: [{ text: "capability", negated: false }] }))).toBe(true);
|
||||
expect(matches(it1, query({ words: [{ text: "erights", negated: false }] }))).toBe(true);
|
||||
expect(
|
||||
matches(it1, query({ words: [{ text: "capability", negated: false }, { text: "missing", negated: false }] })),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("a negated word excludes", () => {
|
||||
const it1 = item("2026-01-05T00:00:00Z", { title: "Capability Patterns" });
|
||||
expect(matches(it1, query({ words: [{ text: "patterns", negated: true }] }))).toBe(false);
|
||||
});
|
||||
|
||||
it("a phrase matches only contiguously", () => {
|
||||
const it1 = item("2026-01-05T00:00:00Z", { description: "object capability patterns" });
|
||||
expect(matches(it1, query({ words: [{ text: "capability patterns", negated: false }] }))).toBe(true);
|
||||
expect(matches(it1, query({ words: [{ text: "patterns object", negated: false }] }))).toBe(false);
|
||||
});
|
||||
|
||||
it("a tag matches a whole comma-separated tag, case-insensitive; not a substring", () => {
|
||||
const it1 = item("2026-01-05T00:00:00Z", { tags: "ocap,Weekly-Notes,js" });
|
||||
expect(matches(it1, query({ tags: [{ text: "weekly-notes", negated: false }] }))).toBe(true);
|
||||
expect(matches(it1, query({ tags: [{ text: "weekly", negated: false }] }))).toBe(false);
|
||||
expect(matches(it1, query({ tags: [{ text: "js", negated: true }] }))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { itemDescription, rssItem, toRss } from "../src/rss.js";
|
||||
|
||||
// shaped like diigo's export (field layout observed 2026-10-07), made-up values
|
||||
|
||||
describe("itemDescription", () => {
|
||||
it("packs tags, description, and annotations the way diigo's export does", () => {
|
||||
expect(
|
||||
itemDescription({
|
||||
tags: "ocap,js",
|
||||
description: "a note",
|
||||
annotations: [
|
||||
{ content: "first highlight", stickyNotes: [] },
|
||||
{ content: "second", stickyNotes: [{ content: "a sticky\n\nwith lines" }, { content: "another" }] },
|
||||
],
|
||||
}),
|
||||
).toBe(
|
||||
"Tags:ocap,js;Description:a note;Annotations and Sticky notes:" +
|
||||
"Highlight:first highlight\n" +
|
||||
"Highlight:second\nSticky notes:a sticky\n\nwith lines\nSticky notes:another\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("renders a note item's body as a Highlight line, as diigo's export does", () => {
|
||||
expect(itemDescription({ type_name: "note", tags: "", description: "", note_content: "the note", annotations: [] })).toBe(
|
||||
"Tags:no_tag;Description:;Annotations and Sticky notes:Highlight:the note\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("says no_tag when there are no tags, and leaves empty parts empty", () => {
|
||||
expect(itemDescription({ tags: "", description: "", annotations: [] })).toBe(
|
||||
"Tags:no_tag;Description:;Annotations and Sticky notes:",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rssItem / toRss", () => {
|
||||
it("is well-formed even when diigo's text isn't: forbidden characters dropped, ]]> split", () => {
|
||||
const xml = rssItem({ title: "bad\u0003char", url: "https://a.example/", tags: "", description: "x]]>y" });
|
||||
expect(xml).not.toContain("\u0003");
|
||||
expect(xml).toContain("<title><![CDATA[badchar]]></title>");
|
||||
expect(xml).toContain("Description:x]]]]><![CDATA[>y;");
|
||||
});
|
||||
|
||||
it("keeps the whole title (diigo's export cuts at 255)", () => {
|
||||
const title = "t".repeat(300);
|
||||
expect(rssItem({ title, url: "u" })).toContain(title);
|
||||
});
|
||||
|
||||
it("wraps items in an RSS 2.0 channel, dated by the caller", () => {
|
||||
const feed = toRss([{ title: "a", url: "u" }], { title: "my items", pubDate: "Wed, 07 Oct 2026 12:00:00 +0000" });
|
||||
expect(feed).toMatch(/^<\?xml version="1.0"\?>\n<rss version="2.0">\n<channel>/);
|
||||
expect(feed).toContain("<pubDate>Wed, 07 Oct 2026 12:00:00 +0000</pubDate>");
|
||||
expect(feed).toContain("<item><title><![CDATA[a]]></title>");
|
||||
});
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sqlStatements } from "../src/sql-statements.js";
|
||||
|
||||
describe("sqlStatements", () => {
|
||||
it("splits a .sql file into named statements at each `-- name:` line, dropping the trailing ;", () => {
|
||||
const text = "-- first:\nselect 1;\n\n-- second:\nselect *\nfrom t\nwhere a = ?;\n";
|
||||
expect(sqlStatements(text)).toEqual({ first: "select 1", second: "select *\nfrom t\nwhere a = ?" });
|
||||
});
|
||||
|
||||
it("keeps a multi-statement entry whole (inner semicolons stay)", () => {
|
||||
expect(sqlStatements("-- both:\nupdate a set x = 1;\nupdate b set y = 2;\n")).toEqual({
|
||||
both: "update a set x = 1;\nupdate b set y = 2",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
/** @file the tests' main module: the real worker plus a fixed-clock cache. */
|
||||
import { DiigoCacheLogic } from "../src/cache.js";
|
||||
import type { CacheEnv } from "../src/cache.js";
|
||||
|
||||
export * from "../src/index.js";
|
||||
export { default } from "../src/index.js";
|
||||
|
||||
/** 2099-01-01T00:00:00Z: in the future, so an alarm set by this clock is
|
||||
* never due in real time — tests run it with runDurableObjectAlarm */
|
||||
export const FIXED_NOW = Date.UTC(2099, 0, 1, 0, 0, 0);
|
||||
|
||||
/** the private cache's logic on a fixed clock that records each sleep it
|
||||
* is asked for (bound as CLOCKED_DO in wrangler.tests.jsonc) */
|
||||
export class FixedClockCache extends DiigoCacheLogic {
|
||||
#sleeps: number[] = [];
|
||||
|
||||
constructor(ctx: DurableObjectState, env: CacheEnv) {
|
||||
const sleeps: number[] = [];
|
||||
super(ctx, env, {
|
||||
now: () => FIXED_NOW,
|
||||
sleep: async (ms) => {
|
||||
sleeps.push(ms);
|
||||
},
|
||||
});
|
||||
this.#sleeps = sleeps;
|
||||
}
|
||||
|
||||
/** the sleeps so far (test hook) */
|
||||
async sleeps(): Promise<number[]> {
|
||||
return [...this.#sleeps];
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"types": ["@cloudflare/vitest-plugin/types"],
|
||||
"allowJs": true
|
||||
},
|
||||
"include": ["./**/*", "../worker-configuration.d.ts"]
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
yurl32,
|
||||
unyurl32,
|
||||
hexToBytes,
|
||||
bytesToHex,
|
||||
glyphsFor,
|
||||
bytesInGlyphs,
|
||||
toWebkey,
|
||||
idFromWebkey,
|
||||
isWebkey,
|
||||
shashKey,
|
||||
type DurableObjectIdLike,
|
||||
} from "../src/webkeys.js";
|
||||
|
||||
// @ts-expect-error vite raw import
|
||||
import webkeysSource from "../src/webkeys.ts?raw";
|
||||
|
||||
const sampleHex = "ab9d14667a05453602b28218c3dc60995d890e49c1502ee1fffa2d0815b367ee";
|
||||
|
||||
/** mock a Cloudflare DurableObjectId */
|
||||
function mockDurableObjectId(hex = sampleHex): DurableObjectIdLike {
|
||||
return {
|
||||
toString: () => hex,
|
||||
equals: (other: unknown) =>
|
||||
typeof other === "object" &&
|
||||
other !== null &&
|
||||
"toString" in other &&
|
||||
(other as { toString(): string }).toString() === hex,
|
||||
};
|
||||
}
|
||||
|
||||
describe("yurl32 and hex codecs", () => {
|
||||
it("matches the paper's alphabet sample", () => {
|
||||
expect("mhbqcmmva5ja3").toMatch(/^[a-z2-7]{13}$/);
|
||||
});
|
||||
|
||||
it("encodes 5 bits per glyph", () => {
|
||||
expect(glyphsFor(64)).toBe(13);
|
||||
expect(glyphsFor(128)).toBe(26);
|
||||
expect(glyphsFor(160)).toBe(32);
|
||||
expect(glyphsFor(256)).toBe(52);
|
||||
expect(bytesInGlyphs(26)).toBe(16);
|
||||
expect(bytesInGlyphs(52)).toBe(32);
|
||||
});
|
||||
|
||||
it("round-trips hex bytes", () => {
|
||||
const bytes = hexToBytes(sampleHex);
|
||||
expect(bytes.length).toBe(32);
|
||||
expect(bytesToHex(bytes)).toBe(sampleHex);
|
||||
});
|
||||
|
||||
it("round-trips bytes through yurl32", () => {
|
||||
const bytes = hexToBytes(sampleHex);
|
||||
const encoded = yurl32(bytes);
|
||||
expect(encoded).toMatch(/^[a-z2-7]+$/);
|
||||
expect(encoded.length).toBe(52);
|
||||
expect(unyurl32(encoded)).toEqual(bytes);
|
||||
});
|
||||
|
||||
it("handles leftovers: 0xff encodes to '74'", () => {
|
||||
expect(yurl32(new Uint8Array([0xff]))).toBe("74");
|
||||
});
|
||||
|
||||
it("refuses garbage", () => {
|
||||
expect(() => unyurl32("0OIl")).toThrow(/not YURL32/);
|
||||
expect(() => unyurl32("AAAA-")).toThrow();
|
||||
expect(() => hexToBytes("abc")).toThrow(/invalid hex length/);
|
||||
expect(() => hexToBytes("zz")).toThrow(/invalid hex byte/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toWebkey and idFromWebkey (aligning with Worker unique ID)", () => {
|
||||
it("converts a DurableObjectId to a 52-glyph YURL32 webkey", () => {
|
||||
const doId = mockDurableObjectId();
|
||||
const webkey = toWebkey(doId);
|
||||
expect(webkey.length).toBe(52);
|
||||
expect(webkey).toMatch(/^[a-z2-7]{52}$/);
|
||||
expect(isWebkey(webkey)).toBe(true);
|
||||
});
|
||||
|
||||
it("round-trips DurableObjectId -> webkey -> hex string", () => {
|
||||
const doId = mockDurableObjectId();
|
||||
const webkey = toWebkey(doId);
|
||||
const hex = idFromWebkey(webkey);
|
||||
expect(hex).toBe(sampleHex);
|
||||
});
|
||||
|
||||
it("accepts a raw 64-char hex string as input to toWebkey", () => {
|
||||
const webkey = toWebkey(sampleHex);
|
||||
expect(webkey.length).toBe(52);
|
||||
expect(idFromWebkey(webkey)).toBe(sampleHex);
|
||||
});
|
||||
|
||||
it("accepts an already-hex ID in idFromWebkey for backward compatibility", () => {
|
||||
expect(idFromWebkey(sampleHex)).toBe(sampleHex);
|
||||
expect(idFromWebkey(sampleHex.toUpperCase())).toBe(sampleHex);
|
||||
});
|
||||
|
||||
it("encodes raw 16-byte (128-bit) entropy directly", () => {
|
||||
const bytes = new Uint8Array(16).fill(42);
|
||||
const webkey = toWebkey(bytes);
|
||||
expect(webkey.length).toBe(26);
|
||||
expect(isWebkey(webkey)).toBe(true);
|
||||
expect(isWebkey(webkey, 128)).toBe(true);
|
||||
expect(unyurl32(webkey)).toEqual(bytes);
|
||||
});
|
||||
|
||||
it("refuses malformed or wrong-sized webkeys in idFromWebkey", () => {
|
||||
expect(() => idFromWebkey("short")).toThrow();
|
||||
// 26-char (128-bit) webkey is valid YURL32, but not a 256-bit Worker ID:
|
||||
const short128 = toWebkey(new Uint8Array(16));
|
||||
expect(() => idFromWebkey(short128)).toThrow(/expected 32 bytes/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shashKey (swissHash discipline)", () => {
|
||||
it("is one-way: identity, not authority", async () => {
|
||||
const doId = mockDurableObjectId();
|
||||
const h = await shashKey(doId);
|
||||
expect(h).toMatch(/^[a-z2-7]+$/);
|
||||
expect(h.length).toBe(52);
|
||||
expect(h).not.toBe(toWebkey(doId));
|
||||
});
|
||||
|
||||
it("is deterministic (joinable in logs)", async () => {
|
||||
const doId = mockDurableObjectId();
|
||||
expect(await shashKey(doId)).toBe(await shashKey(doId));
|
||||
});
|
||||
});
|
||||
|
||||
describe("no ambient authority in this module", () => {
|
||||
it("the module's functions take their effects as arguments", () => {
|
||||
// strip comments before inspecting executable code
|
||||
const code = webkeysSource.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
|
||||
expect(code.includes("getRandomValues")).toBe(false);
|
||||
expect(code.match(/crypto\.subtle/g)?.length ?? 0).toBe(1); // shashKey only
|
||||
});
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "preserve",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"lib": ["ES2022", "ESNext.Disposable"],
|
||||
"noEmit": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*", "worker-configuration.d.ts"]
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { defineProject } from "vitest/config";
|
||||
import { cloudflareTest } from "@cloudflare/vitest-plugin";
|
||||
|
||||
export default defineProject({
|
||||
plugins: [
|
||||
cloudflareTest({
|
||||
// the real worker + DOs; WEBAPP is a fake (aux workers must be JS)
|
||||
wrangler: { configPath: "./wrangler.tests.jsonc" },
|
||||
miniflare: {
|
||||
workers: [
|
||||
{
|
||||
name: "fake-webapp",
|
||||
modules: true,
|
||||
scriptPath: "./tests/fake-webapp.js",
|
||||
compatibilityDate: "2026-09-29",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
],
|
||||
test: {
|
||||
include: ["tests/**/*.test.ts"],
|
||||
},
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
"name": "diigo-cache",
|
||||
"main": "src/index.ts",
|
||||
"compatibility_date": "2026-09-29",
|
||||
"observability": { "enabled": true },
|
||||
// capnweb's browser build, served as text at /_capnweb.js (the worker
|
||||
// itself imports capnweb's workerd build as code)
|
||||
"rules": [{ "type": "Text", "globs": ["**/capnweb/dist/index.js", "**/*.sql"], "fallthrough": true }],
|
||||
"services": [
|
||||
{
|
||||
"binding": "WEBAPP",
|
||||
"service": "webapp",
|
||||
"entrypoint": "WebAppFactory"
|
||||
}
|
||||
],
|
||||
"durable_objects": {
|
||||
"bindings": [
|
||||
{ "name": "CACHE_DO", "class_name": "DiigoCache" },
|
||||
{ "name": "PUBLIC_DO", "class_name": "PublicCache" }
|
||||
]
|
||||
},
|
||||
"exports": {
|
||||
"DiigoCache": { "type": "durable-object", "storage": "sqlite" },
|
||||
"PublicCache": { "type": "durable-object", "storage": "sqlite" }
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
// the real worker (via tests/test-worker.ts, which adds a fixed-clock
|
||||
// cache), with WEBAPP bound to tests/fake-webapp.js (an aux worker
|
||||
// declared in vitest.config.ts)
|
||||
"name": "diigo-cache-tests",
|
||||
"main": "./tests/test-worker.ts",
|
||||
"compatibility_date": "2026-09-29",
|
||||
"rules": [{ "type": "Text", "globs": ["**/capnweb/dist/index.js", "**/*.sql"], "fallthrough": true }],
|
||||
"services": [
|
||||
{ "binding": "WEBAPP", "service": "fake-webapp", "entrypoint": "WebAppFactory" }
|
||||
],
|
||||
"durable_objects": {
|
||||
"bindings": [
|
||||
{ "name": "CACHE_DO", "class_name": "DiigoCache" },
|
||||
{ "name": "PUBLIC_DO", "class_name": "PublicCache" },
|
||||
{ "name": "CLOCKED_DO", "class_name": "FixedClockCache" }
|
||||
]
|
||||
},
|
||||
"exports": {
|
||||
"DiigoCache": { "type": "durable-object", "storage": "sqlite" },
|
||||
"PublicCache": { "type": "durable-object", "storage": "sqlite" },
|
||||
"FixedClockCache": { "type": "durable-object", "storage": "sqlite" }
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
# references to DOs in Discord messages
|
||||
|
||||
*In Smalltalk, JavaScript, and Unix sockets, a message can carry
|
||||
references the receiver can then send messages on. Discord messages
|
||||
can refer to messages, threads, channels, and servers, but not to our
|
||||
Durable Objects. This note works out how they could, after
|
||||
[@endo/chat](https://github.com/endojs/endo-but-for-bots/tree/llm/packages/chat).
|
||||
Written 2026-10-08.*
|
||||
|
||||
## webkeys in markdown: works, but discloses
|
||||
|
||||
The cheapest option is a [webkey](webkeys.md) as a markdown link,
|
||||
`[cookie store](https://webapp.example/store/#<key>)`. It gets the
|
||||
basics right: following it in a browser works, and the key sits in the
|
||||
fragment, so Discord's link-preview fetcher never sends it anywhere.
|
||||
|
||||
But the message body itself is the leak. Every reader of the channel
|
||||
now holds the capability, and so does Discord: its servers, its logs,
|
||||
its search index, its moderation tooling, and whoever reads those.
|
||||
That is fine for capabilities meant to be public (a public cache page)
|
||||
and wrong for anything like webapp's store id, where holding it means
|
||||
choosing whose session the cache uses.
|
||||
|
||||
## what @endo/chat does instead
|
||||
|
||||
In @endo/chat a message is not a string with secrets in it. Its parser
|
||||
(`message-parse.js`) splits `Here is @my-file for you` into
|
||||
|
||||
- `strings`: the text between references,
|
||||
- `edgeNames`: the names the *sender* put in the text (`my-file`),
|
||||
- `petNames`: the sender's own names for those references,
|
||||
|
||||
and the daemon delivers the references themselves beside the text,
|
||||
over CapTP. The receiver sees the edge name and **adopts** the
|
||||
reference under a petname of their own. Three things follow:
|
||||
|
||||
- **References never appear in text.** Only names do, and names are
|
||||
safe to show anyone.
|
||||
- **Names are per-person.** My `cookie-store` and your `alice's store`
|
||||
can be the same object, and neither name has authority by itself.
|
||||
- **Adopting is an act.** Receiving a message gives you the option to
|
||||
hold a reference, not the reference itself, until you choose a name
|
||||
for it.
|
||||
|
||||
## the endo-shaped version for Discord
|
||||
|
||||
A capsite bot (a Worker serving Discord's HTTP interactions endpoint)
|
||||
plays the daemon's part:
|
||||
|
||||
- **Petstores.** Each Discord user has a petstore DO: petname →
|
||||
DO reference. Minting files results there directly: webapp's mint
|
||||
could file the store id under `diigo cookie store` in Alice's
|
||||
petstore instead of handing it to her password manager.
|
||||
- **Sending.** A slash command, e.g.
|
||||
`/send to:@bob text:"here is @cookie-store"`. The bot parses the text
|
||||
like `parseMessage`, looks up each `@name` in the sender's petstore,
|
||||
posts the text (names only) to the channel, and files
|
||||
`{ discord message id → recipients, edgeName → reference }` in a
|
||||
mailbox DO.
|
||||
- **Adopting.** The posted message carries an **Adopt** button. On a
|
||||
click, Discord tells the bot who clicked (in a signed interaction);
|
||||
if they are a recipient, the bot answers with an *ephemeral* message,
|
||||
shown only to them, asking for a petname, then files the reference
|
||||
in *their* petstore.
|
||||
- **Using.** References are exercised through the bot by petname
|
||||
(`/call cookie-store set cookie …`, or a link to a page the bot
|
||||
serves). The reference stays inside our Workers.
|
||||
|
||||
### what this does and doesn't keep from Discord
|
||||
|
||||
Ephemeral replies hide content from other channel readers, but **not
|
||||
from Discord**: they still pass through its servers. So the design
|
||||
above never sends a reference through Discord at all, ephemeral or
|
||||
not; only petnames, edge names, and message ids cross it. Handing over
|
||||
a webkey in an ephemeral reply would be a weaker variant: hidden from
|
||||
the channel, still disclosed to the infrastructure.
|
||||
|
||||
What Discord *does* hold is identity: the bot believes Discord about
|
||||
who clicked **Adopt**. A compromised Discord account, or Discord
|
||||
itself, could therefore adopt references meant for that user. That is
|
||||
the same trust users already put in Discord for their messages, but it
|
||||
should be stated where references matter more than chat does.
|
||||
|
||||
## open questions
|
||||
|
||||
- **Durable references across RPC.** A petstore entry is a DO id plus
|
||||
enough to say what kind of thing it is (webapp instance, header
|
||||
store, cache). Getting from that back to a live RpcTarget is the
|
||||
marshalling-layer question from the cookie-rotation work
|
||||
(`docs/cookie-rotation-wiring.html` on the `webapp-cookie-rotation`
|
||||
branch).
|
||||
- **Petstore ids.** `idFromName(discordUserId)` is convenient but
|
||||
ambient: any worker with the namespace binding can recompute it.
|
||||
Acceptable if only the bot has the binding; otherwise mint with
|
||||
`newUniqueId` and keep the mapping in one place.
|
||||
- **Leaving Discord.** The same mailbox and petstore could back a web
|
||||
page or @endo/chat itself; Discord would then be one front end of
|
||||
several.
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
# webkeys
|
||||
|
||||
*A web-key is an https URL that carries a permission: an unguessable
|
||||
random secret embedded in the URL, bearer-style. From Tyler Close's
|
||||
[web-key: Mashing with permission](https://waterken.sourceforge.net/web-key/) paper (IEEE W2SP 2008) — also, the Waterken precursor code in the E-on-Java tree (`kpreid/e-on-java`). Written 2026-10-07 for [diigo-cache's id-in-URL problem](../capsite-checklist.md).*
|
||||
## why passwords fail and URLs can carry permission
|
||||
|
||||
Web URLs are the one global identifier, but they are only *supposed* to
|
||||
identify; permission is supposed to ride ambient credentials
|
||||
(username/password, cookies). Close's paper argues that split is the
|
||||
root of several ills: sharing means sharing credentials,
|
||||
representations must encode auth (breaking orthogonality), the Same
|
||||
Origin Policy exists to plug the resulting hole, and XSRF happens
|
||||
because "client authentication … does not establish which of the
|
||||
client's permissions the client intends to exercise".
|
||||
|
||||
The web-key fix: put the permission *in* the URL, as a random secret.
|
||||
Possession of the URL *is* the permission (bearer; no MAC, no
|
||||
signatures). The server stores the secret and only it can tell a
|
||||
web-key from garbage — so an attacker's search is online guesswork,
|
||||
never offline cracking.
|
||||
|
||||
## the five conventions (from the paper)
|
||||
|
||||
- **The key is a random bit string**, never algorithmically derived.
|
||||
The paper specs 64 bits: at ≤ 1M permissions and 1 request/ms, ~292
|
||||
years to have a 50% chance of guessing even one. (E's CapTP used
|
||||
160-bit swiss numbers; diigo-cache's DO ids are 256 bits.)
|
||||
- **YURL32 encoding**: lowercase `a–z` + `2–7`, 5 bits per char,
|
||||
URL-safe by construction. 64 bits → 13 chars; 128 → 26; 160 → 32;
|
||||
256 → 52.
|
||||
- **The key goes in the fragment.** The paper's examples:
|
||||
|
||||
https://www.example.com/app/#mhbqcmmva5ja3
|
||||
https://mail.example.com/user123/#mhbqcmmva5ja3
|
||||
|
||||
This placement is the paper's central move. RFC 2616 §14.36 requires
|
||||
browsers to omit the fragment from Referer; and fragments never
|
||||
reach the server at all. So the key leaks neither to other sites nor
|
||||
to server/proxy logs — and Close is candid that this exploits a
|
||||
quirk: HTTP's Referer behaves like a dynamically scoped language,
|
||||
and the fragment is the one slot its leak misses.
|
||||
- **Dereferencing is client-side (skeleton page + XHR)**: the server
|
||||
serves a skeleton page, identical for every web-key of that resource
|
||||
and cacheable forever; its JavaScript reads `document.location`,
|
||||
moves the key out of the fragment, and issues an XHR carrying the
|
||||
key (as a query param) to fetch the actual representation. Two round
|
||||
trips on first visit, one ever after.
|
||||
- **Identity without authority: the swissHash discipline** — E's hash
|
||||
chain (`swissBase → swissNum → swissHash`) shows how to log safely —
|
||||
the hash "represents the identity of the object without providing
|
||||
any authority" (`SwissTable.java:106-108`); the chain is one-way on
|
||||
the assumed infeasibility of the "archash". Failure messages leak
|
||||
"no more than a swissHash".
|
||||
- **Attenuation by minting, revocation by dropping**: a new key is
|
||||
minted to narrow a view (registered, not algorithmically derived —
|
||||
Amoeba's derivable sub-capabilities hid excess-grant bugs);
|
||||
revocation drops the table entry; later holders "resolve to broken".
|
||||
|
||||
## the precursor style: key in the path segment (E-on-Java tree)
|
||||
|
||||
Before the fragment form, Waterken's capabilities put the secret in a
|
||||
path segment: `captp://*vatID@searchpath/swissStr[#expirationDate]`
|
||||
(`EARL.java:37`), with the host authenticated by public-key
|
||||
fingerprint. The AMP web-calculus client POSTs to
|
||||
`cap + "?mid=" + mid` (`AMP.java:83`) — the mid is a 128-bit freshness
|
||||
nonce, not an authenticator. Fragments there carry non-secrets only
|
||||
(`#make`, `#expirationDate`). The 2008 paper moved the secret into the
|
||||
fragment and the pattern got its standard form.
|
||||
|
||||
## what this means for diigo-cache: a webkey example
|
||||
|
||||
https://diigo-cache.example.com/cache/#5y7kq2mhbqcmmva5ja3x9w2f4e
|
||||
|
||||
- `…/cache/` — the address, non-secret, fine in logs, identical for
|
||||
every cache (skeleton-cacheable)
|
||||
- the fragment — the 256-bit DO id, 52 YURL32 chars (`a–z2–7` only),
|
||||
minted by `newUniqueId()`, never derived from anything; all the
|
||||
authority, none of the log-trail
|
||||
- diigo-cache's ids are already webkeys in substance (bearer secrets);
|
||||
the cache page now follows the paper's form — `/cache/#<key>`, a
|
||||
skeleton page, its script passing the key to the server — with the
|
||||
XHR replaced by a [Cap'n Web](https://github.com/cloudflare/capnweb)
|
||||
call that takes the key *in-band*, as a method argument
|
||||
(`api.cache(key)`), returning a capability. The forms elsewhere still
|
||||
carry keys in **POST bodies** (same leak profile as the fragment). A
|
||||
hash of the id would
|
||||
stand in wherever log-correlation is wanted (the swissHash
|
||||
discipline; `shashKey`, whose prefix is also the on-screen
|
||||
fingerprint). The bug that prompted this note: a cache id briefly
|
||||
rode a *query string* (`/?cacheId=…`) — the leaky spot the pattern
|
||||
exists to prevent. It recurred once as a *path segment*
|
||||
(`/_publish/<cacheId>`); publish now takes the id in its POST body.
|
||||
|
||||
## where this came from
|
||||
|
||||
- [web-key: Mashing with permission](https://waterken.sourceforge.net/web-key/)
|
||||
— Close's paper (IEEE W2SP 2008); paper PDFs, reviewer comments, and
|
||||
the W2SP publication are linked from that page
|
||||
- the Waterken code in E-on-Java (`kpreid/e-on-java`):
|
||||
`net/vattp/data/EARL.java`, `net/captp/tables/SwissTable.java`,
|
||||
`org/waterken/url/amp/AMP.java`, `org/waterken/uri/Base32.java`,
|
||||
`org/erights/e/extern/persist/{SturdyRefMaker,SwissRetainer}.java`,
|
||||
`net/captp/jcomm/IdentityMgr.java`
|
||||
Generated
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1794890597,
|
||||
"narHash": "sha256-lME2lHoDHAaSHP3/okgiVoJ0icVEvsQH8LeU3We7tcc=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "04906337b6d53e8bb0eaf0470ae9f070a4d4eb55",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nixos",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
description = "A Counter in an Internet Computer canister, called over OCapN";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs }:
|
||||
let
|
||||
system = "x86_64-linux";
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
in
|
||||
{
|
||||
# dfx is not in nixpkgs; install it with dfxvm (see README).
|
||||
devShells.${system}.default = pkgs.mkShell {
|
||||
buildInputs = with pkgs; [
|
||||
zig_0_17
|
||||
nodejs_22
|
||||
wasm-tools
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
canisters:
|
||||
- name: counter
|
||||
build:
|
||||
steps:
|
||||
- type: script
|
||||
commands:
|
||||
- zig build canister
|
||||
- cp zig-out/bin/counter.wasm "$ICP_WASM_OUTPUT_PATH"
|
||||
|
||||
networks:
|
||||
- name: local
|
||||
mode: managed
|
||||
gateway:
|
||||
bind: 127.0.0.1
|
||||
port: 4960
|
||||
@@ -1,151 +0,0 @@
|
||||
---
|
||||
name: building-emdash-site
|
||||
description: Build the site-facing parts of an EmDash CMS project on Astro, including schema and seeds, content queries, Portable Text rendering, menus, taxonomies, widgets, and deployment configuration. Use for EmDash site and theme work; use creating-plugins instead when the task is plugin authoring alone.
|
||||
---
|
||||
|
||||
# Building an EmDash Site
|
||||
|
||||
EmDash is a CMS built on Astro. It stores schema in the database (not in code), serves content via live content collections, and provides a full admin UI at `/_emdash/admin`. Sites are standard Astro projects with the `emdash` integration.
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
These are the things that silently break sites. Know them before you start.
|
||||
|
||||
1. **Image fields are objects, not strings.** `post.data.featured_image` is `{ id, src, alt }`. Writing `<img src={post.data.featured_image} />` renders `[object Object]`. Use `<Image image={post.data.featured_image} />` from `"emdash/ui"`.
|
||||
|
||||
2. **`entry.id` vs `entry.data.id` are different things.** `entry.id` is the slug (use in URLs). `entry.data.id` is the database ULID (use for `getEntryTerms`, `Comments`, and other API calls that need the real ID). Mixing them up causes silent empty results.
|
||||
|
||||
3. **Taxonomy names must match the seed exactly.** If your seed defines `"name": "category"`, you must query `getTerm("category", slug)` -- not `"categories"`. Wrong name = empty results, no error.
|
||||
|
||||
4. **Register cache hints when Astro's cache is enabled.** Content queries return a `cacheHint`; pass it to `Astro.cache.set(cacheHint)`. Use `getSiteSettingsWithCacheHint()`, `getMenuWithCacheHint()`, `getTaxonomyTermsWithCacheHint()`, and `getWidgetAreaWithCacheHint()` when a cached route renders those values.
|
||||
|
||||
5. **No `getStaticPaths` for CMS content.** EmDash content is dynamic. Pages must be server-rendered (`output: "server"` in `astro.config.mjs`).
|
||||
|
||||
## File Structure
|
||||
|
||||
Every EmDash site has these key files:
|
||||
|
||||
```
|
||||
my-site/
|
||||
├── astro.config.mjs # Astro config with emdash() integration
|
||||
├── src/
|
||||
│ ├── live.config.ts # EmDash loader registration (boilerplate)
|
||||
│ ├── pages/ # Astro pages (all server-rendered)
|
||||
│ ├── layouts/ # Layout components
|
||||
│ └── components/ # Reusable components
|
||||
├── seed/
|
||||
│ └── seed.json # Schema + demo content
|
||||
├── emdash-env.d.ts # Generated types (from `emdash types`)
|
||||
└── package.json
|
||||
```
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Configure the project
|
||||
|
||||
Read **[references/configuration.md](references/configuration.md)** for `astro.config.mjs`, `live.config.ts`, deployment targets (Node vs Cloudflare), and type generation.
|
||||
|
||||
### 2. Design the schema
|
||||
|
||||
Read **[references/schema-and-seed.md](references/schema-and-seed.md)** for collection definitions, field types, taxonomies, menus, widget areas, sections, bylines, and the complete seed file format.
|
||||
|
||||
### 3. Build the pages
|
||||
|
||||
Read **[references/querying-and-rendering.md](references/querying-and-rendering.md)** for content queries, Portable Text rendering, the Image component, visual editing attributes, caching, and common page patterns (list, detail, taxonomy archive, RSS, search, 404).
|
||||
|
||||
### 4. Wire up site features
|
||||
|
||||
Read **[references/site-features.md](references/site-features.md)** for site settings, navigation menus, taxonomies, widget areas, search, SEO meta, comments, and page contributions.
|
||||
|
||||
### 5. Create the seed file
|
||||
|
||||
Write `seed/seed.json` with collections, fields, taxonomies, menus, widgets, and sample content.
|
||||
|
||||
### 6. Run and verify
|
||||
|
||||
```bash
|
||||
pnpm dev # Start the Astro dev server
|
||||
```
|
||||
|
||||
The runtime runs pending migrations on the first request and applies the bundled seed when the database is empty and setup has not been completed. The Astro integration generates `emdash-env.d.ts` when the server starts. The admin UI is at `http://localhost:4321/_emdash/admin`.
|
||||
|
||||
## Quick API Cheat Sheet
|
||||
|
||||
```typescript
|
||||
// Content (entries have .data.byline and .data.bylines eagerly loaded)
|
||||
import { getEmDashCollection, getEmDashEntry } from "emdash";
|
||||
const { entries, nextCursor, cacheHint } = await getEmDashCollection("posts", {
|
||||
limit: 10,
|
||||
cursor,
|
||||
orderBy: { published_at: "desc" },
|
||||
});
|
||||
const { entry: post, cacheHint } = await getEmDashEntry("posts", slug);
|
||||
|
||||
// Site features
|
||||
import {
|
||||
getSiteSettings,
|
||||
getSiteSettingsWithCacheHint,
|
||||
getMenu,
|
||||
getMenuWithCacheHint,
|
||||
getTaxonomyTerms,
|
||||
getTaxonomyTermsWithCacheHint,
|
||||
getTerm,
|
||||
getEntryTerms,
|
||||
getEntriesByTerm,
|
||||
getWidgetArea,
|
||||
getWidgetAreaWithCacheHint,
|
||||
search,
|
||||
getSection,
|
||||
getSeoMeta,
|
||||
} from "emdash";
|
||||
|
||||
// Bylines (standalone queries -- usually not needed since entries have bylines attached)
|
||||
import { getByline, getBylineBySlug } from "emdash";
|
||||
|
||||
// UI components
|
||||
import {
|
||||
PortableText,
|
||||
Blocks,
|
||||
defineBlockComponents,
|
||||
Image,
|
||||
WidgetArea,
|
||||
EmDashHead,
|
||||
EmDashBodyStart,
|
||||
EmDashBodyEnd,
|
||||
} from "emdash/ui";
|
||||
import { Comments, CommentForm } from "emdash/ui/comments";
|
||||
import LiveSearch from "emdash/ui/search";
|
||||
|
||||
// Page context (for plugin contributions)
|
||||
import { createPublicPageContext } from "emdash/page";
|
||||
```
|
||||
|
||||
## Plugins
|
||||
|
||||
EmDash supports plugins for extending the CMS with hooks, storage, settings, admin UI, API routes, and custom Portable Text block types. Consider a plugin when you need to:
|
||||
|
||||
- React to content lifecycle events (e.g., send a notification on publish, sync to an external service)
|
||||
- Add custom admin pages or dashboard widgets
|
||||
- Add reusable behavior or custom Portable Text types (e.g., embedded maps or code playgrounds)
|
||||
- Provide a reusable service (e.g., analytics, forms, comments via a third-party provider)
|
||||
|
||||
Plugins are registered in `astro.config.mjs`:
|
||||
|
||||
```javascript
|
||||
emdash({
|
||||
database: sqlite({ url: "file:./data.db" }),
|
||||
storage: local({ directory: "./uploads", baseUrl: "/_emdash/api/media/file" }),
|
||||
plugins: [myPlugin()],
|
||||
}),
|
||||
```
|
||||
|
||||
**To build a plugin, load the `creating-plugins` skill** (in `.agents/skills/creating-plugins/`). It covers plugin anatomy, hooks, storage, admin UI, API routes, Portable Text blocks, capabilities, and the full `definePlugin()` API.
|
||||
|
||||
## Reference Documents
|
||||
|
||||
| File | Contents |
|
||||
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------- |
|
||||
| [references/configuration.md](references/configuration.md) | Project setup, astro.config, live.config, deployment, types |
|
||||
| [references/schema-and-seed.md](references/schema-and-seed.md) | Collections, fields, taxonomies, menus, widgets, seed format |
|
||||
| [references/querying-and-rendering.md](references/querying-and-rendering.md) | Content APIs, PortableText, Image, caching, page patterns |
|
||||
| [references/site-features.md](references/site-features.md) | Settings, menus, widgets, search, SEO, comments, page contributions |
|
||||
@@ -1,234 +0,0 @@
|
||||
# Configuration
|
||||
|
||||
## astro.config.mjs
|
||||
|
||||
### Node.js (local development / self-hosted)
|
||||
|
||||
```javascript
|
||||
import node from "@astrojs/node";
|
||||
import react from "@astrojs/react";
|
||||
import { defineConfig } from "astro/config";
|
||||
import emdash, { local } from "emdash/astro";
|
||||
import { sqlite } from "emdash/db";
|
||||
|
||||
export default defineConfig({
|
||||
output: "server",
|
||||
adapter: node({ mode: "standalone" }),
|
||||
image: {
|
||||
layout: "constrained",
|
||||
responsiveStyles: true,
|
||||
},
|
||||
integrations: [
|
||||
react(),
|
||||
emdash({
|
||||
database: sqlite({ url: "file:./data.db" }),
|
||||
storage: local({
|
||||
directory: "./uploads",
|
||||
baseUrl: "/_emdash/api/media/file",
|
||||
}),
|
||||
}),
|
||||
],
|
||||
devToolbar: { enabled: false },
|
||||
});
|
||||
```
|
||||
|
||||
### Reverse proxy
|
||||
|
||||
When behind a TLS-terminating reverse proxy, `Astro.url` returns the internal address (e.g. `http://localhost:4321`) instead of the public one (`https://mysite.example.com`). This breaks passkeys, CSRF, OAuth, redirects, and more.
|
||||
|
||||
**Step 1:** Declare allowed public hosts via [`security.allowedDomains`](https://docs.astro.build/en/reference/configuration-reference/#securityalloweddomains) so Astro reconstructs the URL from `X-Forwarded-*` headers. In dev, add matching **`vite.server.allowedHosts`** or Vite rejects the proxy `Host`.
|
||||
|
||||
**Step 2:** If the reconstructed URL still disagrees with the browser (common with TLS termination), set **`siteUrl`**:
|
||||
|
||||
```javascript
|
||||
emdash({
|
||||
siteUrl: "https://mysite.example.com",
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
Or via environment variable (useful for container deployments):
|
||||
|
||||
```bash
|
||||
EMDASH_SITE_URL=https://mysite.example.com
|
||||
# or: SITE_URL=https://mysite.example.com
|
||||
```
|
||||
|
||||
`siteUrl` replaces `passkeyPublicOrigin` (which only fixed passkeys). It applies to passkeys, CSRF origin matching, OAuth redirects, login redirects, MCP discovery, snapshot exports, sitemap, robots.txt, and JSON-LD structured data.
|
||||
|
||||
With TLS terminated in front, **`astro dev --host 127.0.0.1`** (loopback) is usually enough: the proxy reaches the dev server locally while **`siteUrl`** matches the browser’s HTTPS origin -- without opening the Node port on the LAN.
|
||||
|
||||
### Cloudflare (D1 + R2)
|
||||
|
||||
```javascript
|
||||
import cloudflare from "@astrojs/cloudflare";
|
||||
import react from "@astrojs/react";
|
||||
import { d1, r2 } from "@emdash-cms/cloudflare";
|
||||
import { defineConfig } from "astro/config";
|
||||
import emdash from "emdash/astro";
|
||||
|
||||
export default defineConfig({
|
||||
output: "server",
|
||||
adapter: cloudflare(),
|
||||
image: {
|
||||
layout: "constrained",
|
||||
responsiveStyles: true,
|
||||
},
|
||||
integrations: [
|
||||
react(),
|
||||
emdash({
|
||||
database: d1({ binding: "DB", session: "auto" }),
|
||||
storage: r2({ binding: "MEDIA" }),
|
||||
}),
|
||||
],
|
||||
devToolbar: { enabled: false },
|
||||
});
|
||||
```
|
||||
|
||||
Requires a `wrangler.jsonc` with D1 and R2 bindings:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"name": "my-site",
|
||||
"main": "./src/worker.ts",
|
||||
"compatibility_date": "2026-02-24",
|
||||
"compatibility_flags": ["nodejs_compat"],
|
||||
"d1_databases": [
|
||||
{
|
||||
"binding": "DB",
|
||||
"database_name": "my-site",
|
||||
},
|
||||
],
|
||||
"r2_buckets": [
|
||||
{
|
||||
"binding": "MEDIA",
|
||||
"bucket_name": "my-site-media",
|
||||
},
|
||||
],
|
||||
"triggers": {
|
||||
"crons": ["* * * * *"],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Use the EmDash Worker entry point so scheduled publishing and maintenance run through the same deployment:
|
||||
|
||||
```typescript
|
||||
import handler, { createScheduledHandler, PluginBridge } from "@emdash-cms/cloudflare/worker";
|
||||
|
||||
export { PluginBridge };
|
||||
|
||||
export default {
|
||||
...handler,
|
||||
scheduled: createScheduledHandler(),
|
||||
} satisfies ExportedHandler;
|
||||
```
|
||||
|
||||
### Plugins
|
||||
|
||||
Register plugins in `astro.config.mjs`:
|
||||
|
||||
```javascript
|
||||
import auditLog from "@emdash-cms/plugin-audit-log";
|
||||
|
||||
emdash({
|
||||
database: sqlite({ url: "file:./data.db" }),
|
||||
storage: local({ directory: "./uploads", baseUrl: "/_emdash/api/media/file" }),
|
||||
plugins: [auditLog],
|
||||
}),
|
||||
```
|
||||
|
||||
## live.config.ts
|
||||
|
||||
Every EmDash site needs this file at `src/live.config.ts`. It's boilerplate -- the same in every project:
|
||||
|
||||
```typescript
|
||||
import { defineLiveCollection } from "astro:content";
|
||||
import { emdashLoader } from "emdash/runtime";
|
||||
|
||||
export const collections = {
|
||||
_emdash: defineLiveCollection({ loader: emdashLoader() }),
|
||||
};
|
||||
```
|
||||
|
||||
This registers EmDash's live content collections with Astro. All content types are served through the single `_emdash` collection -- you query specific types using `getEmDashCollection("posts")` etc.
|
||||
|
||||
## emdash-env.d.ts
|
||||
|
||||
Auto-generated at the project root when the dev server starts. Provides TypeScript types for your collections. This is the file your `tsconfig.json` includes.
|
||||
|
||||
```typescript
|
||||
/// <reference types="emdash/locals" />
|
||||
|
||||
import type { PortableTextBlock } from "emdash";
|
||||
|
||||
export interface Post {
|
||||
id: string;
|
||||
slug: string | null;
|
||||
status: string;
|
||||
title: string;
|
||||
featured_image?: {
|
||||
id: string;
|
||||
src?: string;
|
||||
alt?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
content?: PortableTextBlock[];
|
||||
excerpt?: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
publishedAt: Date | null;
|
||||
}
|
||||
|
||||
declare module "emdash" {
|
||||
interface EmDashCollections {
|
||||
posts: Post;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The dev server regenerates this file automatically when schema changes. You can also generate it manually:
|
||||
|
||||
## Type Generation
|
||||
|
||||
```bash
|
||||
# From local dev server (writes emdash-env.d.ts at project root)
|
||||
npx emdash types
|
||||
|
||||
# From remote instance
|
||||
npx emdash types --url https://my-site.pages.dev
|
||||
|
||||
# Custom output path
|
||||
npx emdash types --output src/types/cms.ts
|
||||
```
|
||||
|
||||
The CLI also writes `.emdash/schema.json` with the raw schema for tooling.
|
||||
|
||||
## package.json
|
||||
|
||||
Key dependencies for a Node.js site:
|
||||
|
||||
```json
|
||||
{
|
||||
"dependencies": {
|
||||
"astro": "^7.0.0",
|
||||
"emdash": "workspace:*",
|
||||
"@astrojs/node": "^11.0.0",
|
||||
"@astrojs/react": "^4.0.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For Cloudflare, replace `@astrojs/node` with `@astrojs/cloudflare` and add `@emdash-cms/cloudflare`.
|
||||
|
||||
## Dev Server
|
||||
|
||||
```bash
|
||||
pnpm dev # Start the Astro dev server
|
||||
npx emdash types # Refresh types from the running site
|
||||
```
|
||||
|
||||
The runtime runs pending migrations on the first request and applies the bundled seed when the database is empty and setup has not been completed. The Astro integration generates `emdash-env.d.ts` when the server starts. The admin UI is at `http://localhost:4321/_emdash/admin`. On first run, you'll go through setup to create an admin account.
|
||||
@@ -1,411 +0,0 @@
|
||||
# Querying and Rendering Content
|
||||
|
||||
## Content Queries
|
||||
|
||||
All query functions are imported from `"emdash"`.
|
||||
|
||||
### getEmDashCollection
|
||||
|
||||
Fetch multiple entries from a collection. Returns `{ entries, error, cacheHint, nextCursor }`.
|
||||
|
||||
```typescript
|
||||
import { getEmDashCollection } from "emdash";
|
||||
|
||||
// Basic
|
||||
const { entries: posts } = await getEmDashCollection("posts");
|
||||
|
||||
// With options
|
||||
const { entries: posts, cacheHint } = await getEmDashCollection("posts", {
|
||||
status: "published",
|
||||
limit: 10,
|
||||
orderBy: { published_at: "desc" },
|
||||
where: { category: "news" },
|
||||
});
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
- `status` -- filter by status (`"published"`, `"draft"`, etc.)
|
||||
- `limit` -- max entries
|
||||
- `cursor` -- opaque cursor for keyset pagination (pass `nextCursor` from a previous result)
|
||||
- `orderBy` -- `{ field: "asc" | "desc" }` (default: `{ created_at: "desc" }`)
|
||||
- `where` -- filter by field values or taxonomy terms. Supports arrays for OR: `{ category: ["news", "featured"] }`
|
||||
- `locale` -- filter by locale (when i18n is configured)
|
||||
|
||||
### getEmDashEntry
|
||||
|
||||
Fetch a single entry by slug. Returns `{ entry, error, isPreview, cacheHint }`.
|
||||
|
||||
```typescript
|
||||
import { getEmDashEntry } from "emdash";
|
||||
|
||||
const { entry: post, cacheHint } = await getEmDashEntry("posts", slug);
|
||||
|
||||
if (!post) {
|
||||
return Astro.redirect("/404");
|
||||
}
|
||||
```
|
||||
|
||||
### Entry Shape
|
||||
|
||||
```typescript
|
||||
interface ContentEntry<T> {
|
||||
id: string; // The slug (used in URLs)
|
||||
data: T; // All fields, including system fields
|
||||
edit: EditProxy; // Visual editing attributes (spread onto elements)
|
||||
}
|
||||
|
||||
// data includes system fields plus your custom fields:
|
||||
interface PostData {
|
||||
id: string; // Database ULID (use for taxonomy lookups, etc.)
|
||||
slug: string;
|
||||
status: string;
|
||||
title: string;
|
||||
featured_image?: {
|
||||
id: string;
|
||||
src?: string;
|
||||
alt?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
content?: PortableTextBlock[];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
publishedAt: Date | null;
|
||||
// Bylines (eagerly loaded)
|
||||
byline: BylineSummary | null; // Primary author
|
||||
bylines: ContentBylineCredit[]; // All credits (with roleLabel, source)
|
||||
// ... your custom fields
|
||||
}
|
||||
```
|
||||
|
||||
**Important:** `entry.id` is the slug (for URLs), `entry.data.id` is the database ULID (for API calls like `getEntryTerms`).
|
||||
|
||||
### Caching
|
||||
|
||||
Query results include a `cacheHint` for Astro's Route Caching:
|
||||
|
||||
```astro
|
||||
---
|
||||
const { entries: posts, cacheHint } = await getEmDashCollection("posts");
|
||||
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
|
||||
---
|
||||
```
|
||||
|
||||
When Astro's route cache is enabled, call `Astro.cache.set(cacheHint)` so publishing invalidates cached output.
|
||||
|
||||
## Rendering Portable Text
|
||||
|
||||
### PortableText component
|
||||
|
||||
```astro
|
||||
---
|
||||
import { PortableText } from "emdash/ui";
|
||||
---
|
||||
<PortableText value={post.data.content} />
|
||||
```
|
||||
|
||||
Renders standard blocks (paragraphs, headings, lists, blockquotes, code blocks, images) and inline marks (bold, italic, code, strikethrough, links).
|
||||
|
||||
### Custom block types
|
||||
|
||||
For custom Portable Text objects that belong inside a rich-text document, pass a `components` prop:
|
||||
|
||||
```astro
|
||||
---
|
||||
import { PortableText } from "emdash/ui";
|
||||
import Diagram from "./blocks/Diagram.astro";
|
||||
|
||||
const customTypes = {
|
||||
"publication.diagram": Diagram,
|
||||
};
|
||||
---
|
||||
<PortableText value={page.data.content} components={{ type: customTypes }} />
|
||||
```
|
||||
|
||||
Each custom component receives the block data as props.
|
||||
|
||||
## Rendering a blocks field
|
||||
|
||||
Use `Blocks` for an ordered composition stored in a `blocks` collection field. Map each generated `_type` to an Astro component at the call site.
|
||||
|
||||
```astro
|
||||
---
|
||||
import { Blocks, defineBlockComponents } from "emdash/ui";
|
||||
import type { PageLayoutBlock } from "../../emdash-env";
|
||||
import Hero from "../components/blocks/Hero.astro";
|
||||
import FeatureGrid from "../components/blocks/FeatureGrid.astro";
|
||||
|
||||
const components = defineBlockComponents<PageLayoutBlock>({
|
||||
hero: Hero,
|
||||
feature_grid: FeatureGrid,
|
||||
});
|
||||
---
|
||||
|
||||
<Blocks value={page.data.layout} components={components} />
|
||||
```
|
||||
|
||||
Each component receives `{ value, index, blockKey }`. The value retains `_version`, so a renderer can narrow old and active shapes. `Blocks` performs no database or network queries.
|
||||
|
||||
An unmapped type produces a visible development placeholder. In production it renders the optional `fallback` component or no output. Ship renderer support before activating a new breaking block version.
|
||||
|
||||
## Image Component
|
||||
|
||||
**Always use the EmDash Image component for CMS images.** Image fields are objects, not strings.
|
||||
|
||||
```astro
|
||||
---
|
||||
import { Image } from "emdash/ui";
|
||||
---
|
||||
|
||||
{/* Correct -- passes the image object */}
|
||||
<Image image={post.data.featured_image} />
|
||||
|
||||
{/* Also works with explicit props */}
|
||||
{post.data.featured_image?.src && (
|
||||
<img src={post.data.featured_image.src} alt={post.data.featured_image.alt || ""} />
|
||||
)}
|
||||
```
|
||||
|
||||
**Common mistake:**
|
||||
|
||||
```astro
|
||||
{/* WRONG -- image is an object, not a string */}
|
||||
<img src={post.data.featured_image} />
|
||||
```
|
||||
|
||||
## Visual Editing Attributes
|
||||
|
||||
Entries include `edit` attributes for inline editing. Spread them onto the element that displays the field:
|
||||
|
||||
```astro
|
||||
<h1 {...post.edit.title}>{post.data.title}</h1>
|
||||
<p {...post.edit.excerpt}>{post.data.excerpt}</p>
|
||||
<div {...post.edit.featured_image}>
|
||||
<Image image={post.data.featured_image} />
|
||||
</div>
|
||||
```
|
||||
|
||||
When an admin is logged in and views the site, these attributes enable click-to-edit functionality.
|
||||
|
||||
## Common Page Patterns
|
||||
|
||||
### List page (e.g., `/posts/index.astro`)
|
||||
|
||||
```astro
|
||||
---
|
||||
import { getEmDashCollection } from "emdash";
|
||||
import { Image } from "emdash/ui";
|
||||
import Base from "../../layouts/Base.astro";
|
||||
|
||||
const { entries: posts, cacheHint } = await getEmDashCollection("posts", {
|
||||
orderBy: { published_at: "desc" },
|
||||
limit: 20,
|
||||
});
|
||||
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
|
||||
---
|
||||
<Base title="Posts">
|
||||
{posts.map(post => (
|
||||
<article>
|
||||
{post.data.featured_image && <Image image={post.data.featured_image} />}
|
||||
<a href={`/posts/${post.id}`}>{post.data.title}</a>
|
||||
{post.data.excerpt && <p>{post.data.excerpt}</p>}
|
||||
</article>
|
||||
))}
|
||||
</Base>
|
||||
```
|
||||
|
||||
### Detail page (e.g., `/posts/[slug].astro`)
|
||||
|
||||
```astro
|
||||
---
|
||||
import { getEmDashEntry, getSeoMeta } from "emdash";
|
||||
import { Image, PortableText } from "emdash/ui";
|
||||
import Base from "../../layouts/Base.astro";
|
||||
|
||||
const { slug } = Astro.params;
|
||||
if (!slug) return Astro.redirect("/404");
|
||||
|
||||
const { entry: post, cacheHint } = await getEmDashEntry("posts", slug);
|
||||
if (!post) return Astro.redirect("/404");
|
||||
|
||||
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
|
||||
|
||||
const seo = getSeoMeta(post, {
|
||||
siteTitle: "My Blog",
|
||||
siteUrl: Astro.url.origin,
|
||||
path: `/posts/${slug}`,
|
||||
});
|
||||
|
||||
const tags = post.data.terms?.tag ?? [];
|
||||
---
|
||||
<Base title={seo.title} description={seo.description}>
|
||||
<article>
|
||||
{post.data.featured_image && (
|
||||
<div {...post.edit.featured_image}>
|
||||
<Image image={post.data.featured_image} />
|
||||
</div>
|
||||
)}
|
||||
<h1 {...post.edit.title}>{post.data.title}</h1>
|
||||
<PortableText value={post.data.content} />
|
||||
{tags.length > 0 && (
|
||||
<div>
|
||||
{tags.map(t => <a href={`/tag/${t.slug}`}>{t.label}</a>)}
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
</Base>
|
||||
```
|
||||
|
||||
### Taxonomy archive (e.g., `/category/[slug].astro`)
|
||||
|
||||
```astro
|
||||
---
|
||||
import { getTaxonomyTermsWithCacheHint, getEmDashCollection } from "emdash";
|
||||
import Base from "../../layouts/Base.astro";
|
||||
|
||||
const { slug } = Astro.params;
|
||||
const termsResult = await getTaxonomyTermsWithCacheHint("category", { includeCounts: false });
|
||||
const term = slug ? termsResult.data.find((item) => item.slug === slug) : null;
|
||||
if (!term) return Astro.redirect("/404");
|
||||
|
||||
const { entries: posts, cacheHint } = await getEmDashCollection("posts", {
|
||||
where: { category: term.slug },
|
||||
orderBy: { published_at: "desc" },
|
||||
limit: 20,
|
||||
});
|
||||
if (Astro.cache?.enabled) {
|
||||
Astro.cache.set(termsResult.cacheHint);
|
||||
Astro.cache.set(cacheHint);
|
||||
}
|
||||
---
|
||||
<Base title={`${term.label} posts`}>
|
||||
<h1>{term.label}</h1>
|
||||
{posts.map(post => (
|
||||
<a href={`/posts/${post.id}`}>{post.data.title}</a>
|
||||
))}
|
||||
</Base>
|
||||
```
|
||||
|
||||
### RSS feed (e.g., `/rss.xml.ts`)
|
||||
|
||||
```typescript
|
||||
import type { APIRoute } from "astro";
|
||||
import { getEmDashCollection } from "emdash";
|
||||
|
||||
const siteTitle = "My Site";
|
||||
|
||||
export const GET: APIRoute = async ({ url }) => {
|
||||
const siteUrl = url.origin;
|
||||
const { entries: posts } = await getEmDashCollection("posts", {
|
||||
orderBy: { published_at: "desc" },
|
||||
limit: 20,
|
||||
});
|
||||
|
||||
const items = posts
|
||||
.filter((p) => p.data.publishedAt)
|
||||
.map((post) => {
|
||||
const postUrl = `${siteUrl}/posts/${post.id}`;
|
||||
return ` <item>
|
||||
<title>${escapeXml(post.data.title)}</title>
|
||||
<link>${postUrl}</link>
|
||||
<guid isPermaLink="true">${postUrl}</guid>
|
||||
<pubDate>${post.data.publishedAt!.toUTCString()}</pubDate>
|
||||
<description>${escapeXml(post.data.excerpt || "")}</description>
|
||||
</item>`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
return new Response(
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
||||
<channel>
|
||||
<title>${escapeXml(siteTitle)}</title>
|
||||
<link>${siteUrl}</link>
|
||||
<atom:link href="${siteUrl}/rss.xml" rel="self" type="application/rss+xml"/>
|
||||
<language>en-us</language>
|
||||
<lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
|
||||
${items}
|
||||
</channel>
|
||||
</rss>`,
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/rss+xml; charset=utf-8",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
function escapeXml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
```
|
||||
|
||||
### 404 page (`/404.astro`)
|
||||
|
||||
```astro
|
||||
---
|
||||
import Base from "../layouts/Base.astro";
|
||||
---
|
||||
<Base title="Not Found">
|
||||
<h1>Page not found</h1>
|
||||
<p>The page you're looking for doesn't exist.</p>
|
||||
<a href="/">Go home</a>
|
||||
</Base>
|
||||
```
|
||||
|
||||
### Empty state
|
||||
|
||||
When a collection has no content, show a helpful empty state:
|
||||
|
||||
```astro
|
||||
{posts.length === 0 ? (
|
||||
<section>
|
||||
<h2>No posts yet</h2>
|
||||
<p>Create your first post in the admin panel.</p>
|
||||
<a href="/_emdash/admin/content/posts/new">Create a post</a>
|
||||
</section>
|
||||
) : (
|
||||
/* ... render posts ... */
|
||||
)}
|
||||
```
|
||||
|
||||
## Pagination
|
||||
|
||||
`getEmDashCollection` supports cursor-based keyset pagination. Pass `cursor` from a previous result's `nextCursor` to get the next page:
|
||||
|
||||
```astro
|
||||
---
|
||||
const cursor = Astro.url.searchParams.get("cursor") ?? undefined;
|
||||
const { entries, nextCursor, cacheHint } = await getEmDashCollection("posts", {
|
||||
limit: 10,
|
||||
cursor,
|
||||
orderBy: { published_at: "desc" },
|
||||
});
|
||||
Astro.cache.set(cacheHint);
|
||||
---
|
||||
{entries.map(post => (
|
||||
<a href={`/posts/${post.id}`}>{post.data.title}</a>
|
||||
))}
|
||||
{nextCursor && <a href={`?cursor=${nextCursor}`}>Next page</a>}
|
||||
```
|
||||
|
||||
`nextCursor` is `undefined` when there are no more results.
|
||||
|
||||
## Date Formatting
|
||||
|
||||
Dates come as `Date` objects. Use `toLocaleDateString` or `Intl.DateTimeFormat`:
|
||||
|
||||
```typescript
|
||||
const formatted = post.data.publishedAt?.toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
```
|
||||
@@ -1,529 +0,0 @@
|
||||
# Schema and Seed Files
|
||||
|
||||
The seed file (`seed/seed.json`) defines the site's entire schema and optional demo content. It's inlined into the build and applied automatically on the first request when the database is empty and the setup wizard hasn't been completed.
|
||||
|
||||
## Seed File Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://emdashcms.com/seed.schema.json",
|
||||
"version": "1",
|
||||
"meta": {
|
||||
"name": "My Site",
|
||||
"description": "A description of this site",
|
||||
"author": "Author Name"
|
||||
},
|
||||
"settings": { ... },
|
||||
"blockTypes": [ ... ],
|
||||
"collections": [ ... ],
|
||||
"taxonomies": [ ... ],
|
||||
"menus": [ ... ],
|
||||
"widgetAreas": [ ... ],
|
||||
"sections": [ ... ],
|
||||
"bylines": [ ... ],
|
||||
"content": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
## Collections
|
||||
|
||||
Collections define content types. Each collection becomes a database table (`ec_{slug}`).
|
||||
|
||||
```json
|
||||
{
|
||||
"slug": "posts",
|
||||
"label": "Posts",
|
||||
"labelSingular": "Post",
|
||||
"supports": ["drafts", "revisions", "search", "seo"],
|
||||
"commentsEnabled": true,
|
||||
"fields": [ ... ]
|
||||
}
|
||||
```
|
||||
|
||||
### Collection Supports
|
||||
|
||||
| Support | Description |
|
||||
| ------------ | ------------------------- |
|
||||
| `drafts` | Draft/published workflow |
|
||||
| `revisions` | Revision history |
|
||||
| `preview` | Signed draft previews |
|
||||
| `scheduling` | Scheduled publication |
|
||||
| `search` | Full-text search indexing |
|
||||
| `seo` | SEO meta fields in admin |
|
||||
|
||||
### Slug Rules
|
||||
|
||||
- Lowercase alphanumeric + underscores: `/^[a-z][a-z0-9_]*$/`
|
||||
- Max 63 characters
|
||||
- Cannot conflict with reserved slugs
|
||||
|
||||
## Field Types
|
||||
|
||||
| Type | Column type | Runtime shape | Notes |
|
||||
| -------------- | ----------- | ------------------------------------- | ---------------------------- |
|
||||
| `string` | TEXT | `string` | Single line text |
|
||||
| `text` | TEXT | `string` | Multi-line text (textarea) |
|
||||
| `url` | TEXT | `string` | URL input |
|
||||
| `number` | REAL | `number` | Floating point |
|
||||
| `integer` | INTEGER | `number` | Whole numbers |
|
||||
| `boolean` | INTEGER | `boolean` | Stored as 0/1 |
|
||||
| `datetime` | TEXT | `Date` | ISO 8601 string in DB |
|
||||
| `select` | TEXT | `string` | One configured option |
|
||||
| `multiSelect` | JSON | `string[]` | Configured option list |
|
||||
| `image` | TEXT | `{ id, src?, alt?, width?, height? }` | **Object, not a string** |
|
||||
| `file` | TEXT | `{ id, url?, filename?, ... }` | File reference |
|
||||
| `reference` | TEXT | `string` (ID) | Reference to another entry |
|
||||
| `slug` | TEXT | `string` | Slug input |
|
||||
| `repeater` | JSON | `object[]` | Repeated structured rows |
|
||||
| `portableText` | JSON | `PortableTextBlock[]` | Rich text as structured JSON |
|
||||
| `blocks` | JSON | `{ _type, _version, _key, ... }[]` | Ordered typed composition |
|
||||
| `json` | JSON | `unknown` | Arbitrary JSON data |
|
||||
|
||||
### Field Definition
|
||||
|
||||
```json
|
||||
{
|
||||
"slug": "title",
|
||||
"label": "Title",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"searchable": true
|
||||
}
|
||||
```
|
||||
|
||||
Fields can have:
|
||||
|
||||
- `slug` (required) -- field identifier
|
||||
- `label` (required) -- display label in admin
|
||||
- `type` (required) -- one of the types above
|
||||
- `required` -- validation
|
||||
- `searchable` -- include in full-text search index
|
||||
|
||||
### Common Field Patterns
|
||||
|
||||
**Blog post:**
|
||||
|
||||
```json
|
||||
"fields": [
|
||||
{ "slug": "title", "label": "Title", "type": "string", "required": true, "searchable": true },
|
||||
{ "slug": "featured_image", "label": "Featured Image", "type": "image" },
|
||||
{ "slug": "content", "label": "Content", "type": "portableText", "searchable": true },
|
||||
{ "slug": "excerpt", "label": "Excerpt", "type": "text" }
|
||||
]
|
||||
```
|
||||
|
||||
**Portfolio project:**
|
||||
|
||||
```json
|
||||
"fields": [
|
||||
{ "slug": "title", "label": "Title", "type": "string", "required": true, "searchable": true },
|
||||
{ "slug": "featured_image", "label": "Featured Image", "type": "image", "required": true },
|
||||
{ "slug": "client", "label": "Client", "type": "string" },
|
||||
{ "slug": "year", "label": "Year", "type": "string" },
|
||||
{ "slug": "summary", "label": "Summary", "type": "text", "searchable": true },
|
||||
{ "slug": "content", "label": "Content", "type": "portableText", "searchable": true },
|
||||
{ "slug": "gallery", "label": "Gallery", "type": "repeater", "validation": { "subFields": [{ "slug": "image", "label": "Image", "type": "image", "required": true }] } },
|
||||
{ "slug": "url", "label": "Project URL", "type": "url" }
|
||||
]
|
||||
```
|
||||
|
||||
**Page (minimal):**
|
||||
|
||||
```json
|
||||
"fields": [
|
||||
{ "slug": "title", "label": "Title", "type": "string", "required": true, "searchable": true },
|
||||
{ "slug": "content", "label": "Content", "type": "portableText", "searchable": true }
|
||||
]
|
||||
```
|
||||
|
||||
## Block types
|
||||
|
||||
Define `blockTypes` before collections that use a `blocks` field. Each type retains every numbered version and names one active version for new blocks.
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1",
|
||||
"blockTypes": [
|
||||
{
|
||||
"slug": "hero",
|
||||
"label": "Hero",
|
||||
"currentVersion": 1,
|
||||
"versions": [
|
||||
{
|
||||
"version": 1,
|
||||
"fields": [
|
||||
{ "slug": "heading", "label": "Heading", "type": "string", "required": true },
|
||||
{ "slug": "image", "label": "Image", "type": "image" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"collections": [
|
||||
{
|
||||
"slug": "pages",
|
||||
"label": "Pages",
|
||||
"fields": [
|
||||
{
|
||||
"slug": "layout",
|
||||
"label": "Layout",
|
||||
"type": "blocks",
|
||||
"validation": { "allowedTypes": ["hero"], "maxItems": 20 }
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Compatible changes amend the active version. A breaking change creates a new inactive version; deploy renderers for it before activation, then migrate stored blocks explicitly. Removing a type from `allowedTypes` moves it to the server-managed `retiredTypes` list.
|
||||
|
||||
Seeded block values include their type version and stable key:
|
||||
|
||||
```json
|
||||
{
|
||||
"_type": "hero",
|
||||
"_version": 1,
|
||||
"_key": "home-hero",
|
||||
"heading": "Build something useful"
|
||||
}
|
||||
```
|
||||
|
||||
Adding a required blocks field or a positive `minItems` rule to a populated collection is not an additive schema change. Backfill every existing entry before enforcing the requirement.
|
||||
|
||||
Block fields support scalar, text, selection, Portable Text, image, file, and repeater fields. References, JSON, slugs, nested blocks, custom widgets, indexes, uniqueness, and per-subfield localization are not supported inside block definitions.
|
||||
|
||||
## Taxonomies
|
||||
|
||||
Taxonomies are tag/category systems attached to collections.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "category",
|
||||
"label": "Categories",
|
||||
"labelSingular": "Category",
|
||||
"hierarchical": true,
|
||||
"collections": ["posts"],
|
||||
"terms": [
|
||||
{ "slug": "development", "label": "Development" },
|
||||
{ "slug": "design", "label": "Design" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `hierarchical: true` -- tree structure (like WordPress categories)
|
||||
- `hierarchical: false` -- flat list (like WordPress tags)
|
||||
- `collections` -- which collections this taxonomy applies to
|
||||
- `terms` -- pre-defined terms to create
|
||||
|
||||
## Menus
|
||||
|
||||
Navigation menus, managed from the admin UI.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "primary",
|
||||
"label": "Primary Navigation",
|
||||
"items": [
|
||||
{ "type": "custom", "label": "Home", "url": "/" },
|
||||
{ "type": "custom", "label": "About", "url": "/pages/about" },
|
||||
{ "type": "custom", "label": "Posts", "url": "/posts" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Menu item types:
|
||||
|
||||
- `custom` -- arbitrary URL
|
||||
- Content references are resolved at render time
|
||||
|
||||
## Widget Areas
|
||||
|
||||
Named regions where editors can add configurable widgets.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "sidebar",
|
||||
"label": "Sidebar",
|
||||
"description": "Widget area displayed on single post pages",
|
||||
"widgets": [
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:search",
|
||||
"title": "Search"
|
||||
},
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:categories",
|
||||
"title": "Categories"
|
||||
},
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:tags",
|
||||
"title": "Tags"
|
||||
},
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:recent-posts",
|
||||
"title": "Recent Posts",
|
||||
"settings": { "count": 5, "showDate": true }
|
||||
},
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:archives",
|
||||
"title": "Archives",
|
||||
"settings": { "type": "monthly", "limit": 6 }
|
||||
},
|
||||
{
|
||||
"type": "content",
|
||||
"title": "About",
|
||||
"content": [
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [{ "_type": "span", "text": "Some rich text content." }]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Widget types
|
||||
|
||||
| Type | Description | Key fields |
|
||||
| ----------- | ------------------------- | ------------------------- |
|
||||
| `content` | Rich text (Portable Text) | `content` |
|
||||
| `menu` | Navigation menu | `menuName` |
|
||||
| `component` | Core or custom component | `componentId`, `settings` |
|
||||
|
||||
### Core widget components
|
||||
|
||||
- `core:search` -- search form
|
||||
- `core:categories` -- category list with counts
|
||||
- `core:tags` -- tag cloud
|
||||
- `core:recent-posts` -- latest posts list
|
||||
- `core:archives` -- monthly archive links
|
||||
|
||||
## Sections (Reusable Blocks)
|
||||
|
||||
Reusable content blocks that editors can insert via `/section` slash command in the editor.
|
||||
|
||||
```json
|
||||
{
|
||||
"slug": "newsletter-signup",
|
||||
"title": "Newsletter Signup",
|
||||
"description": "A call-to-action block for newsletter subscriptions",
|
||||
"keywords": ["newsletter", "subscribe", "email", "cta"],
|
||||
"source": "theme",
|
||||
"content": [
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "h3",
|
||||
"children": [{ "_type": "span", "text": "Stay in the loop" }]
|
||||
},
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [{ "_type": "span", "text": "Get notified when new posts are published." }]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Bylines
|
||||
|
||||
Named author profiles, independent of user accounts.
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "byline-editorial",
|
||||
"slug": "emdash-editorial",
|
||||
"displayName": "EmDash Editorial"
|
||||
}
|
||||
```
|
||||
|
||||
Guest bylines:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "byline-guest",
|
||||
"slug": "guest-contributor",
|
||||
"displayName": "Guest Contributor",
|
||||
"isGuest": true
|
||||
}
|
||||
```
|
||||
|
||||
## Settings
|
||||
|
||||
Site-wide settings:
|
||||
|
||||
```json
|
||||
"settings": {
|
||||
"title": "My Blog",
|
||||
"tagline": "Thoughts on building for the web"
|
||||
}
|
||||
```
|
||||
|
||||
Available keys: `title`, `tagline`, `logo`, `favicon`, `social`, `timezone`, `dateFormat`.
|
||||
|
||||
## Content
|
||||
|
||||
Sample content organized by collection slug:
|
||||
|
||||
```json
|
||||
"content": {
|
||||
"posts": [
|
||||
{
|
||||
"id": "post-1",
|
||||
"slug": "hello-world",
|
||||
"status": "published",
|
||||
"data": {
|
||||
"title": "Hello World",
|
||||
"excerpt": "My first post.",
|
||||
"featured_image": {
|
||||
"$media": {
|
||||
"url": "https://images.unsplash.com/photo-xxx?w=1200&h=800&fit=crop",
|
||||
"alt": "Description of image",
|
||||
"filename": "hello-world.jpg"
|
||||
}
|
||||
},
|
||||
"content": [
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [{ "_type": "span", "text": "This is the body text." }]
|
||||
}
|
||||
]
|
||||
},
|
||||
"bylines": [
|
||||
{ "byline": "byline-editorial" }
|
||||
],
|
||||
"taxonomies": {
|
||||
"category": ["development"],
|
||||
"tag": ["webdev", "opinion"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"pages": [
|
||||
{
|
||||
"id": "about",
|
||||
"slug": "about",
|
||||
"status": "published",
|
||||
"data": {
|
||||
"title": "About",
|
||||
"content": [
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [{ "_type": "span", "text": "About this site." }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Media references in seed content
|
||||
|
||||
Use `$media` for image fields -- EmDash downloads and stores the image:
|
||||
|
||||
```json
|
||||
"featured_image": {
|
||||
"$media": {
|
||||
"url": "https://images.unsplash.com/photo-xxx?w=1200&h=800&fit=crop",
|
||||
"alt": "Description",
|
||||
"filename": "my-image.jpg"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For external images without downloading:
|
||||
|
||||
```json
|
||||
"featured_image": "https://images.unsplash.com/photo-xxx?w=1200"
|
||||
```
|
||||
|
||||
### Reference fields in seed content
|
||||
|
||||
Use `$ref:id` format to reference other entries:
|
||||
|
||||
```json
|
||||
"author": "$ref:byline-editorial"
|
||||
```
|
||||
|
||||
### Portable Text in seed content
|
||||
|
||||
Content fields of type `portableText` are arrays of blocks:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [{ "_type": "span", "text": "A paragraph." }]
|
||||
},
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "h2",
|
||||
"children": [{ "_type": "span", "text": "A heading" }]
|
||||
},
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "blockquote",
|
||||
"children": [{ "_type": "span", "text": "A quote." }]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Inline marks (bold, italic, links):
|
||||
|
||||
```json
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [
|
||||
{ "_type": "span", "text": "This is " },
|
||||
{ "_type": "span", "text": "bold", "marks": ["strong"] },
|
||||
{ "_type": "span", "text": " and " },
|
||||
{ "_type": "span", "text": "italic", "marks": ["em"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Block styles: `normal`, `h1`-`h6`, `blockquote`.
|
||||
|
||||
### Draft content
|
||||
|
||||
Set `"status": "draft"` to create unpublished content:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "post-draft",
|
||||
"slug": "work-in-progress",
|
||||
"status": "draft",
|
||||
"data": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
## Applying Seeds
|
||||
|
||||
The seed at `.emdash/seed.json`, `package.json#emdash.seed`, or `seed/seed.json` is inlined into the build and applied on the first request when the database is empty and the setup wizard hasn't been completed. Existing data is never overwritten.
|
||||
|
||||
Validation runs at apply time. Common errors caught:
|
||||
|
||||
- Image fields with raw URLs (should use `$media`)
|
||||
- Reference fields with raw IDs (should use `$ref:id`)
|
||||
- PortableText not an array or missing `_type`
|
||||
- Type mismatches (string vs number, etc.)
|
||||
|
||||
If the seed is invalid, the first request fails and the error is logged. Restart the dev server after fixing it.
|
||||
|
||||
## Exporting Seeds
|
||||
|
||||
```bash
|
||||
npx emdash export-seed # Schema only
|
||||
npx emdash export-seed --with-content # Schema + all content
|
||||
npx emdash export-seed --with-content=posts,pages # Specific collections
|
||||
```
|
||||
@@ -1,540 +0,0 @@
|
||||
# Site Features
|
||||
|
||||
## Site Settings
|
||||
|
||||
```typescript
|
||||
import { getSiteSettings, getSiteSettingsWithCacheHint, getSiteSetting } from "emdash";
|
||||
|
||||
// All settings
|
||||
const settings = await getSiteSettings();
|
||||
settings.title; // "My Site"
|
||||
settings.tagline; // "A description"
|
||||
settings.logo?.url; // Resolved media URL
|
||||
settings.favicon?.url;
|
||||
|
||||
// Single setting
|
||||
const title = await getSiteSetting("title");
|
||||
|
||||
// Cached route: register invalidation for settings changes
|
||||
const { data: cachedSettings, cacheHint } = await getSiteSettingsWithCacheHint();
|
||||
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
|
||||
```
|
||||
|
||||
Available keys: `title`, `tagline`, `logo`, `favicon`, `social`, `timezone`, `dateFormat`.
|
||||
|
||||
Use these instead of hard-coding site name, logo, etc.
|
||||
|
||||
## Navigation Menus
|
||||
|
||||
```typescript
|
||||
import { getMenu, getMenuWithCacheHint, getMenus } from "emdash";
|
||||
|
||||
// Fetch a named menu
|
||||
const menu = await getMenu("primary");
|
||||
|
||||
// List all menus
|
||||
const menus = await getMenus();
|
||||
|
||||
// Cached route
|
||||
const { data: primaryMenu, cacheHint } = await getMenuWithCacheHint("primary");
|
||||
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
|
||||
```
|
||||
|
||||
### Rendering a menu
|
||||
|
||||
```astro
|
||||
---
|
||||
import { getMenu } from "emdash";
|
||||
const primaryMenu = await getMenu("primary");
|
||||
---
|
||||
<nav>
|
||||
{primaryMenu?.items.map(item => (
|
||||
<a
|
||||
href={item.url}
|
||||
target={item.target}
|
||||
rel={item.target === "_blank" ? "noopener noreferrer" : undefined}
|
||||
>{item.label}</a>
|
||||
))}
|
||||
</nav>
|
||||
```
|
||||
|
||||
### Nested menus (dropdowns)
|
||||
|
||||
```astro
|
||||
{primaryMenu?.items.map(item => (
|
||||
<li>
|
||||
<a href={item.url}>{item.label}</a>
|
||||
{item.children.length > 0 && (
|
||||
<ul class="submenu">
|
||||
{item.children.map(child => (
|
||||
<li><a href={child.url}>{child.label}</a></li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
```
|
||||
|
||||
### MenuItem shape
|
||||
|
||||
```typescript
|
||||
interface MenuItem {
|
||||
id: string;
|
||||
label: string;
|
||||
url: string; // Resolved URL
|
||||
target?: string; // "_blank" etc.
|
||||
children: MenuItem[];
|
||||
}
|
||||
```
|
||||
|
||||
## Taxonomies
|
||||
|
||||
```typescript
|
||||
import {
|
||||
getTaxonomyTerms,
|
||||
getTaxonomyTermsWithCacheHint,
|
||||
getTerm,
|
||||
getEntryTerms,
|
||||
getEntriesByTerm,
|
||||
} from "emdash";
|
||||
|
||||
// All terms in a taxonomy (name must match your seed's "name" field exactly)
|
||||
const categories = await getTaxonomyTerms("category");
|
||||
const tags = await getTaxonomyTerms("tag");
|
||||
|
||||
// Cached taxonomy archive or facet
|
||||
const { data: cachedCategories, cacheHint } = await getTaxonomyTermsWithCacheHint("category", {
|
||||
includeCounts: false,
|
||||
});
|
||||
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
|
||||
|
||||
// Single term by slug
|
||||
const term = await getTerm("category", "news");
|
||||
// { id, name, slug, label, children, count }
|
||||
|
||||
// Terms for a specific entry (use data.id, not entry.id!)
|
||||
const postCategories = await getEntryTerms("posts", post.data.id, "category");
|
||||
const postTags = await getEntryTerms("posts", post.data.id, "tag");
|
||||
|
||||
// Entries with a specific term
|
||||
const newsPosts = await getEntriesByTerm("posts", "category", "news");
|
||||
```
|
||||
|
||||
**Important:** The taxonomy name argument must match exactly what your seed defines in `"name"`. The blog seed uses `"category"` and `"tag"` (singular). Using `"categories"` returns empty results with no error.
|
||||
|
||||
**Important:** `getEntryTerms` takes the database ULID (`post.data.id`), not the slug (`post.id`).
|
||||
|
||||
### Displaying post terms
|
||||
|
||||
```astro
|
||||
---
|
||||
const tags = post.data.terms?.tag ?? [];
|
||||
---
|
||||
{tags.map(t => (
|
||||
<a href={`/tag/${t.slug}`}>{t.label}</a>
|
||||
))}
|
||||
```
|
||||
|
||||
### Filtering by taxonomy
|
||||
|
||||
```astro
|
||||
---
|
||||
const { entries: posts } = await getEmDashCollection("posts", {
|
||||
where: { category: term.slug },
|
||||
orderBy: { published_at: "desc" },
|
||||
});
|
||||
---
|
||||
```
|
||||
|
||||
## Widget Areas
|
||||
|
||||
Render a named widget area:
|
||||
|
||||
```astro
|
||||
---
|
||||
import { WidgetArea } from "emdash/ui";
|
||||
---
|
||||
<aside>
|
||||
<WidgetArea name="sidebar" />
|
||||
</aside>
|
||||
```
|
||||
|
||||
`WidgetArea` registers its widget-area cache hint when Astro's route cache is enabled.
|
||||
|
||||
The `WidgetArea` component automatically renders all widgets in the area (search, categories, tags, recent posts, rich text, etc.) with appropriate HTML and CSS classes.
|
||||
|
||||
### Manual widget rendering
|
||||
|
||||
For more control, use the `getWidgetArea` function:
|
||||
|
||||
```astro
|
||||
---
|
||||
import { getWidgetArea } from "emdash";
|
||||
import { PortableText } from "emdash/ui";
|
||||
|
||||
const sidebar = await getWidgetArea("sidebar");
|
||||
---
|
||||
{sidebar?.widgets.map(widget => (
|
||||
<div class="widget">
|
||||
{widget.title && <h3>{widget.title}</h3>}
|
||||
{widget.type === "content" && widget.content && (
|
||||
<PortableText value={widget.content} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
```
|
||||
|
||||
## Search
|
||||
|
||||
### LiveSearch component (instant search)
|
||||
|
||||
```astro
|
||||
---
|
||||
import LiveSearch from "emdash/ui/search";
|
||||
---
|
||||
<LiveSearch
|
||||
placeholder="Search..."
|
||||
collections={["posts", "pages"]}
|
||||
/>
|
||||
```
|
||||
|
||||
Customizable CSS classes:
|
||||
|
||||
```astro
|
||||
<LiveSearch
|
||||
placeholder="Search..."
|
||||
class="site-search"
|
||||
inputClass="site-search-input"
|
||||
resultsClass="site-search-results"
|
||||
resultClass="site-search-result"
|
||||
collections={["posts", "pages"]}
|
||||
expandOnFocus={{ collapsed: "180px", expanded: "280px" }}
|
||||
/>
|
||||
```
|
||||
|
||||
Theme via CSS variables:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--emdash-search-bg: var(--color-bg);
|
||||
--emdash-search-text: var(--color-text);
|
||||
--emdash-search-muted: var(--color-muted);
|
||||
--emdash-search-border: var(--color-border);
|
||||
--emdash-search-hover: var(--color-surface);
|
||||
--emdash-search-highlight: var(--color-text);
|
||||
}
|
||||
```
|
||||
|
||||
### Programmatic search
|
||||
|
||||
```typescript
|
||||
import { search } from "emdash";
|
||||
|
||||
const results = await search("hello world", {
|
||||
collections: ["posts", "pages"],
|
||||
status: "published",
|
||||
limit: 20,
|
||||
});
|
||||
// { items: SearchResult[], nextCursor? }
|
||||
```
|
||||
|
||||
Each item has: `collection`, `id`, `title`, `slug`, `locale`, `snippet` (sanitized HTML with `<mark>` highlights), and `score`.
|
||||
|
||||
### Search page
|
||||
|
||||
```astro
|
||||
---
|
||||
import LiveSearch from "emdash/ui/search";
|
||||
import Base from "../layouts/Base.astro";
|
||||
|
||||
const query = Astro.url.searchParams.get("q") || "";
|
||||
---
|
||||
<Base title="Search">
|
||||
<h1>Search</h1>
|
||||
<LiveSearch
|
||||
placeholder="Search posts..."
|
||||
collections={["posts", "pages"]}
|
||||
/>
|
||||
</Base>
|
||||
```
|
||||
|
||||
### Keyboard shortcut
|
||||
|
||||
Add Cmd+K / Ctrl+K to focus search:
|
||||
|
||||
```html
|
||||
<script>
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === "k") {
|
||||
e.preventDefault();
|
||||
document.querySelector(".site-search-input")?.focus();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Search prerequisites
|
||||
|
||||
Search requires per-collection enablement:
|
||||
|
||||
1. In admin: Edit Content Type -> check "Search" in Features
|
||||
2. Mark fields as `"searchable": true` in the seed file
|
||||
3. Only searchable fields of searchable collections are indexed
|
||||
|
||||
## SEO Meta
|
||||
|
||||
> [!IMPORTANT]
|
||||
> On server-rendered content pages that fetch the entry with `getEmDashEntry()`
|
||||
> and render `<EmDashHead>`, EmDash automatically applies the SEO panel's
|
||||
> description, image, canonical URL, and noindex setting. The panel title
|
||||
> supplies the social and JSON-LD title contributions. The panel data uses the
|
||||
> entry query the page already runs, so it adds no additional query.
|
||||
>
|
||||
> `<EmDashHead>` cannot set the document `<title>`, so use `getSeoMeta()` for
|
||||
> the title. Prerendered pages, pages without `<EmDashHead>`, hand-rolled query
|
||||
> paths, and multi-entry collection results do not receive this overlay. Use
|
||||
> `getSeoMeta()` or the raw SEO data on those paths.
|
||||
|
||||
Use `getSeoMeta()` when the template needs to set `<title>` or the page does not
|
||||
receive the automatic overlay:
|
||||
|
||||
```typescript
|
||||
import { getSeoMeta } from "emdash";
|
||||
|
||||
const seo = getSeoMeta(post, {
|
||||
siteTitle: "My Blog",
|
||||
siteUrl: Astro.url.origin,
|
||||
path: `/posts/${slug}`,
|
||||
defaultOgImage: featuredImageUrl, // Optional fallback
|
||||
});
|
||||
```
|
||||
|
||||
Use in your layout's `<head>`:
|
||||
|
||||
```astro
|
||||
<title>{seo.title}</title>
|
||||
{seo.description && <meta name="description" content={seo.description} />}
|
||||
{seo.canonical && <link rel="canonical" href={seo.canonical} />}
|
||||
{seo.ogImage && <meta property="og:image" content={seo.ogImage} />}
|
||||
{seo.robots && <meta name="robots" content={seo.robots} />}
|
||||
```
|
||||
|
||||
### Custom title and description defaults
|
||||
|
||||
Pass computed fallbacks through `defaultTitle` and `defaultDescription`. Values
|
||||
set in the SEO panel take precedence over these defaults:
|
||||
|
||||
```ts
|
||||
import { getSeoMeta } from "emdash";
|
||||
|
||||
const seo = getSeoMeta(post, {
|
||||
defaultTitle: `${post.data.title}: A practical guide`,
|
||||
defaultDescription: `Read ${post.data.title} on My Blog.`,
|
||||
});
|
||||
```
|
||||
|
||||
## Comments
|
||||
|
||||
Built-in comments system:
|
||||
|
||||
```astro
|
||||
---
|
||||
import { Comments, CommentForm } from "emdash/ui/comments";
|
||||
---
|
||||
<Comments collection="posts" contentId={post.data.id} threaded />
|
||||
<CommentForm collection="posts" contentId={post.data.id} />
|
||||
```
|
||||
|
||||
Comments are enabled per-collection in the seed: `"commentsEnabled": true`.
|
||||
|
||||
## Page Contributions (Plugin Head/Body Injection)
|
||||
|
||||
Plugins can inject content into the `<head>` and `<body>` of pages. To support this, use the page contribution components:
|
||||
|
||||
```astro
|
||||
---
|
||||
import { EmDashHead, EmDashBodyStart, EmDashBodyEnd } from "emdash/ui";
|
||||
import { createPublicPageContext } from "emdash/page";
|
||||
|
||||
const pageCtx = createPublicPageContext({
|
||||
Astro,
|
||||
kind: content ? "content" : "custom",
|
||||
pageType: "article",
|
||||
title: fullTitle,
|
||||
pageTitle: post.data.title,
|
||||
description,
|
||||
canonical,
|
||||
image,
|
||||
content: { collection: "posts", id: post.data.id, slug },
|
||||
});
|
||||
---
|
||||
<html>
|
||||
<head>
|
||||
<!-- your meta tags -->
|
||||
<EmDashHead page={pageCtx} />
|
||||
</head>
|
||||
<body>
|
||||
<EmDashBodyStart page={pageCtx} />
|
||||
<!-- your content -->
|
||||
<EmDashBodyEnd page={pageCtx} />
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
This enables plugins (analytics, tracking pixels, structured data, etc.) to contribute to any page.
|
||||
|
||||
## Bylines
|
||||
|
||||
Bylines are author profiles, independent of user accounts. They support guest authors and multi-author attribution with role labels.
|
||||
|
||||
### Eagerly loaded on entries
|
||||
|
||||
Bylines are automatically attached to every entry by the query layer:
|
||||
|
||||
```astro
|
||||
{/* Primary author */}
|
||||
{post.data.byline && (
|
||||
<span>{post.data.byline.displayName}</span>
|
||||
)}
|
||||
|
||||
{/* All credits (includes roleLabel for co-authors, guest essays, etc.) */}
|
||||
{post.data.bylines?.map(credit => (
|
||||
<span>
|
||||
{credit.byline.displayName}
|
||||
{credit.roleLabel && <em> ({credit.roleLabel})</em>}
|
||||
</span>
|
||||
))}
|
||||
```
|
||||
|
||||
- `entry.data.byline` -- primary `BylineSummary` or `null`
|
||||
- `entry.data.bylines` -- array of `ContentBylineCredit` (each has `.byline`, `.roleLabel`, `.source`)
|
||||
|
||||
### Standalone query functions
|
||||
|
||||
```typescript
|
||||
import { getByline, getBylineBySlug } from "emdash";
|
||||
|
||||
// Look up a specific byline
|
||||
const byline = await getBylineBySlug("jane-doe");
|
||||
```
|
||||
|
||||
### BylineSummary shape
|
||||
|
||||
```typescript
|
||||
interface BylineSummary {
|
||||
id: string;
|
||||
slug: string;
|
||||
displayName: string;
|
||||
bio: string | null;
|
||||
avatarMediaId: string | null;
|
||||
websiteUrl: string | null;
|
||||
isGuest: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### ContentBylineCredit shape
|
||||
|
||||
```typescript
|
||||
interface ContentBylineCredit {
|
||||
byline: BylineSummary;
|
||||
sortOrder: number;
|
||||
roleLabel: string | null; // e.g., "Guest essay", "Photographer"
|
||||
source?: "explicit" | "inferred"; // "inferred" = fallback from author_id
|
||||
}
|
||||
```
|
||||
|
||||
## Dark Mode Pattern
|
||||
|
||||
Cookie-based theme switching (no flash on load):
|
||||
|
||||
```html
|
||||
<!-- In <head>, before styles load -->
|
||||
<script is:inline>
|
||||
(function () {
|
||||
var c = document.cookie;
|
||||
var i = c.indexOf("theme=");
|
||||
var theme = i >= 0 ? c.slice(i + 6).split(";")[0] : null;
|
||||
if (theme === "dark" || theme === "light") {
|
||||
document.documentElement.classList.add(theme);
|
||||
} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
|
||||
document.documentElement.classList.add("dark");
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
```
|
||||
|
||||
Then use CSS variables that change based on `.dark` class:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--color-bg: #ffffff;
|
||||
--color-text: #1a1a1a;
|
||||
}
|
||||
:root.dark {
|
||||
--color-bg: #0d0d0d;
|
||||
--color-text: #ededed;
|
||||
}
|
||||
```
|
||||
|
||||
## Layout Pattern
|
||||
|
||||
A typical base layout:
|
||||
|
||||
```astro
|
||||
---
|
||||
import { getMenu, getEmDashCollection } from "emdash";
|
||||
import { WidgetArea, EmDashHead, EmDashBodyStart, EmDashBodyEnd } from "emdash/ui";
|
||||
import { createPublicPageContext } from "emdash/page";
|
||||
import LiveSearch from "emdash/ui/search";
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
description?: string | null;
|
||||
image?: string | null;
|
||||
content?: { collection: string; id: string; slug?: string | null };
|
||||
}
|
||||
|
||||
const { title, pageTitle, description, image, content } = Astro.props;
|
||||
const menu = await getMenu("primary");
|
||||
|
||||
const pageCtx = createPublicPageContext({
|
||||
Astro,
|
||||
kind: content ? "content" : "custom",
|
||||
pageType: "website",
|
||||
title,
|
||||
pageTitle: pageTitle ?? title,
|
||||
description,
|
||||
image,
|
||||
content,
|
||||
});
|
||||
---
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>{title}</title>
|
||||
{description && <meta name="description" content={description} />}
|
||||
<EmDashHead page={pageCtx} />
|
||||
</head>
|
||||
<body>
|
||||
<EmDashBodyStart page={pageCtx} />
|
||||
<header>
|
||||
<nav>
|
||||
<a href="/">My Site</a>
|
||||
<LiveSearch placeholder="Search..." collections={["posts", "pages"]} />
|
||||
{menu?.items.map(item => (
|
||||
<a href={item.url}>{item.label}</a>
|
||||
))}
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
<slot />
|
||||
</main>
|
||||
<footer>
|
||||
<WidgetArea name="footer" />
|
||||
</footer>
|
||||
<EmDashBodyEnd page={pageCtx} />
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
@@ -1,134 +0,0 @@
|
||||
---
|
||||
name: creating-plugins
|
||||
description: Create EmDash CMS plugins with sandboxed hooks, routes, storage, content and media APIs, MCP tools, and declarative admin UI, or native React and Astro extensions. Use when scaffolding or implementing an EmDash plugin.
|
||||
---
|
||||
|
||||
# Creating EmDash plugins
|
||||
|
||||
Build against the API that reaches the intended execution mode. Source types and production-boundary tests take precedence over examples in this skill when they disagree.
|
||||
|
||||
## Choose a format
|
||||
|
||||
| Format | Runtime source | Admin UI | Distribution |
|
||||
| --------- | --------------------------------------------------- | --------------------------------------------------------- | ---------------------------- |
|
||||
| Sandboxed | `src/plugin.ts` default-exports a `SandboxedPlugin` | Block Kit pages, widgets, saved-entry panels, and actions | Plugin CLI and registry |
|
||||
| Native | `definePlugin()` / `createPlugin()` | React, Block Kit, and Astro components | Trusted site dependency only |
|
||||
|
||||
Use a sandboxed plugin unless the feature needs host-process access, React admin code, Astro rendering components, raw page fragments, or custom Portable Text block definitions. Native plugins run with the site's authority and cannot be installed from the registry.
|
||||
|
||||
## Scaffold a sandboxed plugin
|
||||
|
||||
```sh
|
||||
pnpm dlx @emdash-cms/plugin-cli init my-plugin
|
||||
cd my-plugin
|
||||
pnpm install
|
||||
pnpm run test
|
||||
```
|
||||
|
||||
The manifest is the identity and trust contract. Runtime hooks and routes live in `src/plugin.ts`; the CLI generates descriptors, manifests, and bundles. Do not create a separate descriptor factory or `sandbox-entry.ts`.
|
||||
|
||||
```typescript title="src/plugin.ts"
|
||||
import type { SandboxedPlugin } from "emdash/plugin";
|
||||
|
||||
const plugin: SandboxedPlugin = {
|
||||
hooks: {
|
||||
"content:afterSave": async (event, ctx) => {
|
||||
ctx.log.info("Content saved", { id: event.content.id });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default plugin;
|
||||
```
|
||||
|
||||
Import authoring types from `emdash/plugin` with `import type`. Value imports are limited to lightweight helpers such as `pluginRoute()` and `pluginResponse()`, which the CLI bundles. Sandboxed runtime code can use Web APIs but not Node.js built-ins.
|
||||
|
||||
## Declare access
|
||||
|
||||
Declare every host API in `emdash-plugin.jsonc`. Adding authority, exposing a route publicly, or adding MCP tools requires renewed administrator approval.
|
||||
|
||||
| Capability | Grants |
|
||||
| -------------------------------- | -------------------------------------------------------------------------- |
|
||||
| `schema:read` | Public collection and field definitions |
|
||||
| `admin.editor-draft:read` | Selected unsaved field values after an explicit editor interaction |
|
||||
| `admin.editor-draft:patch` | Host-validated unsaved field changes proposed for editor review |
|
||||
| `content:read` | Content identity, translations, and published public URLs |
|
||||
| `content:revisions:read` | Retained revision data; implies content read |
|
||||
| `content:write` | Create, update, delete, and translation creation; implies read |
|
||||
| `content:publish` | Revision-fenced publish, unpublish, schedule, and unschedule; implies read |
|
||||
| `content:restore` | Revision-fenced reads and restoration of trashed content |
|
||||
| `hooks.content-policy:register` | Pre-publish, pre-schedule, and pre-unpublish policy hooks |
|
||||
| `taxonomies:read` | Taxonomy definitions, terms, and entry assignments |
|
||||
| `taxonomies:write` | Term creation and assignment deltas; implies read |
|
||||
| `redirects:read` | Versioned redirect inspection |
|
||||
| `redirects:write` | Versioned redirect creation, update, and deletion; implies read |
|
||||
| `comments:read` | Stored non-trashed comments and their personal data |
|
||||
| `comments:moderate` | Expected-status moderation; implies read |
|
||||
| `media:read` | Ready-media metadata and authenticated asset URLs |
|
||||
| `media:bytes:read` | Bounded media bytes and content hashes |
|
||||
| `media:metadata:write` | Alt text, caption, and focal-point updates |
|
||||
| `media:write` | Upload and delete; implies media read |
|
||||
| `network:request` | `ctx.http.fetch()` restricted to `allowedHosts` |
|
||||
| `network:request:unrestricted` | `ctx.http.fetch()` without a host list |
|
||||
| `users:read` | User directory lookup; also required by comment hooks |
|
||||
| `email:send` | Email delivery when a transport is configured |
|
||||
| `hooks.email-transport:register` | Exclusive `email:deliver` hook |
|
||||
| `hooks.email-events:register` | Email before/after hooks |
|
||||
| `hooks.page-fragments:register` | Trusted-only page fragments; excluded from sandbox registration |
|
||||
|
||||
Settings, KV, declared storage, logging, and cron scheduling are plugin-scoped and need no capability. Use `ctx.settings` for user configuration, `ctx.kv` for internal key-value state, and declared `ctx.storage.<collection>` for queryable records.
|
||||
|
||||
Read the focused reference for the API being used:
|
||||
|
||||
- [Content, schema, translations, and publication](./references/content.md)
|
||||
- [Taxonomies and redirects](./references/taxonomies-and-redirects.md)
|
||||
- [Comments](./references/comments.md)
|
||||
- [Media](./references/media.md)
|
||||
- [Storage, KV, and encrypted settings](./references/storage.md)
|
||||
|
||||
## Routes, HTTP, and MCP
|
||||
|
||||
Routes are private by default and require authentication, their declared RBAC permission, token scope or CSRF as appropriate. Public routes are internet-facing and require explicit install consent.
|
||||
|
||||
Undeclared routes keep the legacy JSON/query envelope. Declare methods and body modes for host-enforced parsing. Use `pluginResponse()` only on a route that declares a raw response. Outbound `ctx.http.fetch()` responses and declared route bodies are buffered and bounded.
|
||||
|
||||
MCP tools reference private JSON routes with explicit permissions and Zod input schemas. Mark difficult-to-reverse operations `destructive: true`. Read [API routes and MCP tools](./references/api-routes.md).
|
||||
|
||||
## Hooks
|
||||
|
||||
Sandboxed hooks enter the same priority, dependency, timeout, error-policy, enablement, exclusive-provider, and capability pipeline as trusted hooks. Publication policy hooks identify action origin and actor without granting publication authority. Comment moderation invoked through `ctx.comments` reports plugin origin and runs the normal after-hook once. Read [Hooks](./references/hooks.md).
|
||||
|
||||
## Declarative admin UI
|
||||
|
||||
Sandboxed pages and widgets return validated Block Kit. Structured links use host-resolved targets; `routeCtx.ui` carries host-attested locale, direction, and surface. External images require matching network authority.
|
||||
|
||||
Saved-entry panels and actions point to private routes. Ordinary panel load receives only host-reloaded saved identity and version. Add `admin.editor-draft:read` or `admin.editor-draft:patch` plus extension-level collection and field selectors when an explicit interaction must receive selected unsaved fields or propose an atomic whole-field patch. Patch does not imply read. The host previews accepted patches, marks the form dirty, and never saves them automatically. Read saved content through capability-gated `ctx.content`.
|
||||
|
||||
Declarative field widgets currently compose supported Block Kit elements into a JSON value. Custom Portable Text blocks and Astro render components remain native-only. Read [Admin UI](./references/admin-ui.md), [Block Kit](./references/block-kit.md), and [Portable Text blocks](./references/portable-text-blocks.md).
|
||||
|
||||
## Runner parity
|
||||
|
||||
Cloudflare Worker Loader and Node/workerd execute the same bundle behind a plugin-scoped bridge. Both return buffered WHATWG responses from `ctx.http.fetch()` with binary bytes preserved and decoded request/response bodies limited to 8 MiB. Write against exported types, not extra methods found in one wrapper.
|
||||
|
||||
Read [Sandbox boundaries](./references/sandbox-boundaries.md) before designing around an API not listed here.
|
||||
|
||||
## Test the production boundary
|
||||
|
||||
Use `createPluginTestHost()` for fast hook, route, manifest, capability, KV, settings, and storage transport tests. Use `createPluginRuntimeTestHost()` when the test must exercise real content actions, plugin activation, media, comments, redirects, scheduling, restart, authorization, CSRF, caching, Block Kit validation, or saved-entry extensions.
|
||||
|
||||
Runtime fixtures establish state without firing hooks. Runtime actions call production boundaries; inspectors read observable state. Queue outbound HTTP responses with `host.http.respond()` and inspect requests with `host.http.requests()`. Dispose every host after use. Add Node/workerd parity only for runner-sensitive behavior.
|
||||
|
||||
## References
|
||||
|
||||
- [Content, schema, translations, and publication](./references/content.md)
|
||||
- [Taxonomies and redirects](./references/taxonomies-and-redirects.md)
|
||||
- [Comments](./references/comments.md)
|
||||
- [Media](./references/media.md)
|
||||
- [Hooks](./references/hooks.md)
|
||||
- [Storage, KV, and encrypted settings](./references/storage.md)
|
||||
- [Admin UI and field widgets](./references/admin-ui.md)
|
||||
- [API routes and MCP tools](./references/api-routes.md)
|
||||
- [Block Kit](./references/block-kit.md)
|
||||
- [Portable Text blocks](./references/portable-text-blocks.md)
|
||||
- [Sandbox boundaries](./references/sandbox-boundaries.md)
|
||||
- [Publishing](./references/publishing.md)
|
||||
@@ -1,211 +0,0 @@
|
||||
# Admin UI and field widgets
|
||||
|
||||
Sandboxed plugins return declarative Block Kit from a private route. Native plugins may instead ship React components. Keep these paths separate: sandboxed plugin JavaScript never runs in the browser.
|
||||
|
||||
## Sandboxed pages and dashboard widgets
|
||||
|
||||
Declare navigation and widget cards in `emdash-plugin.jsonc`:
|
||||
|
||||
```jsonc title="emdash-plugin.jsonc"
|
||||
{
|
||||
"admin": {
|
||||
"pages": [
|
||||
{ "path": "/settings", "label": "Settings", "icon": "settings" },
|
||||
{ "path": "/reports", "label": "Reports", "icon": "chart" },
|
||||
],
|
||||
"widgets": [{ "id": "status", "title": "Plugin status", "size": "half" }],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Pages mount at `/_emdash/admin/plugins/<plugin-id>/<path>`. Widget sizes are `full`, `half`, and `third`.
|
||||
|
||||
Any sandboxed plugin that declares a page or widget must define an `admin` route. The admin sends a `page_load`, `block_action`, or `form_submit` interaction as `routeCtx.input`:
|
||||
|
||||
```typescript title="src/plugin.ts"
|
||||
import type { SandboxedPlugin } from "emdash/plugin";
|
||||
import type { BlockResponse } from "@emdash-cms/blocks";
|
||||
import { z } from "zod";
|
||||
|
||||
const interactionSchema = z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("page_load"), page: z.string() }),
|
||||
z.object({
|
||||
type: z.literal("block_action"),
|
||||
action_id: z.string(),
|
||||
block_id: z.string().optional(),
|
||||
value: z.unknown().optional(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("form_submit"),
|
||||
action_id: z.string(),
|
||||
block_id: z.string().optional(),
|
||||
values: z.object({ enabled: z.boolean() }),
|
||||
}),
|
||||
]);
|
||||
|
||||
function settingsForm(enabled: boolean): BlockResponse {
|
||||
return {
|
||||
blocks: [
|
||||
{ type: "header", text: "Settings" },
|
||||
{
|
||||
type: "form",
|
||||
block_id: "settings",
|
||||
fields: [
|
||||
{ type: "toggle", action_id: "enabled", label: "Enabled", initial_value: enabled },
|
||||
],
|
||||
submit: { action_id: "save", label: "Save" },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const plugin: SandboxedPlugin = {
|
||||
routes: {
|
||||
admin: {
|
||||
permission: "plugins:manage",
|
||||
handler: async (routeCtx, ctx) => {
|
||||
const parsed = interactionSchema.safeParse(routeCtx.input);
|
||||
if (!parsed.success) return { blocks: [] };
|
||||
const interaction = parsed.data;
|
||||
if (interaction.type === "form_submit" && interaction.action_id === "save") {
|
||||
await ctx.settings.set("enabled", interaction.values.enabled === true);
|
||||
return {
|
||||
...settingsForm(interaction.values.enabled === true),
|
||||
toast: { type: "success", message: "Settings saved" },
|
||||
};
|
||||
}
|
||||
|
||||
const enabled = (await ctx.settings.get<boolean>("enabled")) ?? false;
|
||||
return settingsForm(enabled);
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default plugin;
|
||||
```
|
||||
|
||||
Validate interactions before production side effects; `routeCtx.input` is `unknown`. Read [Block Kit](./block-kit.md) for exact interaction, block, and element shapes.
|
||||
|
||||
The plugin CLI preserves `admin.settingsSchema` in the registry manifest and generated descriptor, so the host can generate a settings form. Both sandbox bridges route `ctx.settings` through the same options records as that form. Read a generated setting with `ctx.settings.get("<key>")`; writes, deletes, list operations, and revision-based operations use the same namespace on Cloudflare and Node/workerd.
|
||||
|
||||
The `secret` settings field is write-only in the admin response and encrypted before persistence. The site must provide `EMDASH_ENCRYPTION_KEY`; missing, wrong, or tampered key material fails closed. Keep the encryption-key list with database backups. Existing `ctx.kv.get("settings:<key>")` reads remain compatible throughout EmDash 1.x.
|
||||
|
||||
## Sandboxed saved-entry extensions
|
||||
|
||||
Declare saved-entry panels and actions in `emdash-plugin.jsonc`:
|
||||
|
||||
```jsonc title="emdash-plugin.jsonc"
|
||||
{
|
||||
"admin": {
|
||||
"editorPanels": [
|
||||
{
|
||||
"id": "health",
|
||||
"title": "Content health",
|
||||
"route": "editor/health",
|
||||
"collections": ["posts"],
|
||||
"draft": {
|
||||
"read": { "translatable": true },
|
||||
"patch": { "fields": ["title", "excerpt"] },
|
||||
},
|
||||
},
|
||||
],
|
||||
"editorActions": [
|
||||
{
|
||||
"id": "repair",
|
||||
"label": "Repair metadata",
|
||||
"route": "editor/repair",
|
||||
"placement": "overflow",
|
||||
"style": "danger",
|
||||
"confirm": {
|
||||
"title": "Repair?",
|
||||
"text": "This changes the saved entry.",
|
||||
"confirm": "Repair",
|
||||
"deny": "Cancel",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Every referenced route must be private. EmDash reloads the saved entry and checks ownership plus the route permission before invoking it. `routeCtx.ui.entry` contains only the canonical collection, ID, locale, and version.
|
||||
|
||||
Panels start collapsed. `panel_load` never includes draft values. After an explicit `block_action`, `form_submit`, or `editor_action`, `admin.editor-draft:read` can attach only the fields selected by the extension's `draft.read` declaration. `fields` selects explicit slugs and `translatable: true` selects current schema fields marked translatable. Draft declarations require explicit collection scope.
|
||||
|
||||
`admin.editor-draft:patch` permits a separate `draft.patch` field selector and does not imply read. Return `patch: { type: "editor-draft-patch", operations }` with whole-field `set` or `clear` operations. The host rejects the complete patch on an unknown, forbidden, invalid, unsupported, oversized, or stale operation. Accepted patches receive a host-rendered preview, update the form atomically, mark it dirty, and remain unsaved. A response may contain a toast and one terminal effect: patch, refresh, or navigation.
|
||||
|
||||
Use `createPluginRuntimeTestHost().admin` to exercise this boundary. `captureEditorDraft()` creates a saved-entry draft request, the existing panel/action helpers invoke the production route, and `applyEditorDraftPatch()` applies only a current response through the host validator.
|
||||
|
||||
## Sandboxed declarative field widgets
|
||||
|
||||
Core and the admin contain a declarative field-widget path. Declare the widget in the registry manifest:
|
||||
|
||||
```jsonc title="emdash-plugin.jsonc"
|
||||
{
|
||||
"admin": {
|
||||
"fieldWidgets": [
|
||||
{
|
||||
"name": "event-picker",
|
||||
"label": "Event",
|
||||
"fieldTypes": ["json"],
|
||||
"elements": [
|
||||
{ "type": "text_input", "action_id": "eventId", "label": "Event ID" },
|
||||
{ "type": "toggle", "action_id": "featured", "label": "Featured" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
A schema field selects it with `widget: "pluginId:widgetName"`. The editor stores an object keyed by each element's `action_id`. Use a `json` field for this object. The manifest schema accepts other compatible field types, but the repository has no end-to-end test proving that the composed object saves through them.
|
||||
|
||||
The current field-widget renderer supports:
|
||||
|
||||
- `text_input`
|
||||
- `number_input`
|
||||
- `toggle`
|
||||
- `select`
|
||||
- `media_picker`
|
||||
|
||||
Other Block Kit element types display an unsupported-element message in this surface.
|
||||
|
||||
`emdash-plugin.jsonc` accepts `admin.fieldWidgets`, and the plugin CLI carries the definitions through the bundle manifest and generated descriptor for registry installation. The artifact round-trip is covered by plugin CLI, shared manifest, and plugin-test tests. The browser E2E fixture still tests a native React color picker rather than a registry-installed declarative widget, so verify the real editor render and value persistence for the chosen elements.
|
||||
|
||||
The sandbox admin route receives `routeCtx.ui` with the host-attested admin locale, text direction, and surface. Use it to select localized text in a runtime Block Kit response. Labels in manifest metadata remain static strings; registry plugins do not hand translation catalogs to the host.
|
||||
|
||||
## Native React pages, widgets, and fields
|
||||
|
||||
Native plugins may set `admin.entry` and export React components:
|
||||
|
||||
```typescript title="src/admin.tsx"
|
||||
export const pages = {
|
||||
"/settings": SettingsPage,
|
||||
};
|
||||
|
||||
export const widgets = {
|
||||
status: StatusWidget,
|
||||
};
|
||||
|
||||
export const fields = {
|
||||
picker: ColorPickerField,
|
||||
};
|
||||
```
|
||||
|
||||
The plugin definition points to the entry and declares its surfaces:
|
||||
|
||||
```typescript
|
||||
definePlugin({
|
||||
id: "color",
|
||||
version: "1.0.0",
|
||||
admin: {
|
||||
entry: "@my-org/plugin-color/admin",
|
||||
pages: [{ path: "/settings", label: "Settings" }],
|
||||
widgets: [{ id: "status", title: "Status", size: "half" }],
|
||||
fieldWidgets: [{ name: "picker", label: "Color picker", fieldTypes: ["string"] }],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Native admin code must follow the repository's Kumo, localization, accessibility, and RTL rules. It runs with the site's authority and is not registry-installable.
|
||||
@@ -1,245 +0,0 @@
|
||||
# API routes and MCP tools
|
||||
|
||||
Sandboxed plugin routes are mounted at `/_emdash/api/plugins/<slug>/<route-name>`. Define them in the typed default export from `src/plugin.ts`.
|
||||
|
||||
## Define a route
|
||||
|
||||
```typescript title="src/plugin.ts"
|
||||
import type { SandboxedPlugin } from "emdash/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
const submissionInput = z.object({
|
||||
formId: z.string().min(1),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||
});
|
||||
|
||||
const plugin: SandboxedPlugin = {
|
||||
routes: {
|
||||
submissions: {
|
||||
permission: "content:read",
|
||||
handler: async (routeCtx, ctx) => {
|
||||
const parsed = submissionInput.safeParse(routeCtx.input);
|
||||
if (!parsed.success) return { ok: false, error: "INVALID_INPUT" };
|
||||
|
||||
const result = await ctx.storage.submissions.query({
|
||||
where: { formId: parsed.data.formId },
|
||||
limit: parsed.data.limit,
|
||||
});
|
||||
return { ok: true, ...result };
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default plugin;
|
||||
```
|
||||
|
||||
The handler receives two arguments:
|
||||
|
||||
```typescript
|
||||
interface SandboxedRouteContext {
|
||||
input: unknown;
|
||||
request: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers: Record<string, string>;
|
||||
};
|
||||
requestMeta?: {
|
||||
ip: string | null;
|
||||
userAgent: string | null;
|
||||
referer: string | null;
|
||||
geo: { country: string | null; region: string | null; city: string | null } | null;
|
||||
};
|
||||
user?: UserInfo;
|
||||
}
|
||||
```
|
||||
|
||||
`routeCtx.request` is a serialized record in both sandbox runners, not a WHATWG `Request`. Header keys are lowercased. Read parsed request data from `routeCtx.input`; the body has already been consumed by the host.
|
||||
|
||||
The published authoring type currently declares `requestMeta` as `unknown`, although both runners send the normalized shape shown above. Narrow it before reading fields when TypeScript cannot infer the shape.
|
||||
|
||||
## Input sources and validation
|
||||
|
||||
Undeclared routes keep the original input contract: the host parses JSON for `POST`, `PUT`, and
|
||||
`PATCH`, and parses the query string for `GET`, `HEAD`, and `DELETE`. Repeated query keys become
|
||||
arrays. Validate the resulting `unknown` value inside the handler.
|
||||
|
||||
Declare `request.body` as `none`, `json`, `text`, `bytes`, or `form-data` to select a parser. Bodies
|
||||
are buffered with a 1 MiB default maximum; `maxBytes` can raise the limit to 8 MiB. Use
|
||||
`pluginRoute()` from `emdash/plugin` to infer `PluginRouteQuery`, `string`, `Uint8Array`, or
|
||||
`PluginFormData` from the mode. JSON remains `unknown` for validation.
|
||||
|
||||
Form data accepts multipart and URL-encoded requests. The multipart limits are 100 parts, 1 MiB per
|
||||
part, and 255 UTF-8 bytes for a safe filename. The total request must also fit the route body limit.
|
||||
|
||||
Declare request header names explicitly in `request.headers`. Only those safe headers reach the
|
||||
handler. Credentials, cookies, Cloudflare Access headers, proxy authorization, `Set-Cookie`, and
|
||||
the EmDash CSRF header cannot be declared and never cross the sandbox boundary.
|
||||
|
||||
The plugin CLI probe currently does not retain a route entry's `input` schema, so do not rely on route-level Zod validation for a built sandboxed plugin. An MCP tool still requires its own Zod input schema.
|
||||
|
||||
## Authentication, permission, and CSRF
|
||||
|
||||
Routes are private unless they set `public: true`.
|
||||
|
||||
A private route requires:
|
||||
|
||||
- an authenticated session, or a token with the `admin` scope;
|
||||
- the route's declared EmDash RBAC `permission`, defaulting to `plugins:manage`;
|
||||
- `X-EmDash-Request: 1` for cookie-authenticated calls, for every HTTP method.
|
||||
|
||||
The host resolves these checks before invoking the plugin. `routeCtx.user` then contains the authenticated caller for a user-bound request:
|
||||
|
||||
```typescript
|
||||
interface UserInfo {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
role: number;
|
||||
createdAt: string;
|
||||
}
|
||||
```
|
||||
|
||||
Caller identity is not gated by `users:read`; it identifies the current authorized caller. `ctx.users` is a directory lookup and does require `users:read`. `routeCtx.user` is absent on public routes and on machine-token calls without a bound user.
|
||||
|
||||
A public route skips authentication, permission, and token-scope checks. It is internet-facing, so validate input, check the intended HTTP method, and verify webhook signatures or shared tokens where applicable.
|
||||
|
||||
Public exposure is reviewed during installation. Adding a public route or changing a private route
|
||||
to public requires approval again on update.
|
||||
|
||||
## HTTP methods
|
||||
|
||||
The route name selects one handler. Declare `methods` to have the host reject other methods with
|
||||
`405 Method Not Allowed` and an `Allow` header before the handler runs:
|
||||
|
||||
```typescript
|
||||
methods: ["POST"],
|
||||
handler: async (routeCtx, ctx) => {
|
||||
// Validate input, then mutate.
|
||||
},
|
||||
```
|
||||
|
||||
Routes without `methods` remain method-agnostic. Check the method inside legacy handlers that mutate
|
||||
state, or add a declaration.
|
||||
|
||||
## Results and errors
|
||||
|
||||
Return a JSON-serializable value. The HTTP endpoint wraps it in EmDash's `{ success: true, data }` envelope.
|
||||
|
||||
Return a stable application-level error object for expected validation and domain failures. Throw only for unexpected failures, and keep exception messages free of credentials, personal data, paths, and stack traces.
|
||||
|
||||
Declare `response: "raw"` for unwrapped responses. The handler must return `pluginResponse()` from
|
||||
`emdash/plugin` with a text or `Uint8Array` body. Raw response bodies are buffered up to 8 MiB.
|
||||
The response header allowlist is `Accept-Ranges`, `Content-Disposition`, `Content-Encoding`,
|
||||
`Content-Language`, `Content-Range`, `Content-Type`, `ETag`, `Last-Modified`, `Location`, and
|
||||
`Retry-After`. The host removes other plugin-supplied headers, adds security headers, and applies the
|
||||
route-owned cache policy.
|
||||
|
||||
Raw routes cannot return active same-origin types, including HTML, JavaScript or ECMAScript, XHTML,
|
||||
SVG, XML, CSS, WebAssembly, `multipart/related`, and `multipart/x-mixed-replace`. A raw route also
|
||||
cannot back an MCP tool. Do not return or throw a WHATWG `Response`; it is not the portable response
|
||||
wire.
|
||||
|
||||
## Public caching
|
||||
|
||||
Core accepts `cacheControl` on a public route:
|
||||
|
||||
```typescript
|
||||
routes: {
|
||||
catalog: {
|
||||
public: true,
|
||||
cacheControl: "public, max-age=60, stale-while-revalidate=300",
|
||||
handler: async () => ({ items: [] }),
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
The value is applied only to successful public `GET` and `HEAD` responses. Private responses, errors, and other methods remain `private, no-store`. The plugin CLI carries `cacheControl` through the probe, bundle manifest, registry artifact, and generated descriptor.
|
||||
|
||||
## Request metadata
|
||||
|
||||
Both runners send the same normalized metadata:
|
||||
|
||||
- `ip`: a trusted client address when the platform or operator configured a trusted proxy header, otherwise `null`;
|
||||
- `userAgent`: the `User-Agent` value, otherwise `null`;
|
||||
- `referer`: the `Referer` value, otherwise `null`;
|
||||
- `geo`: Cloudflare country, region, and city when available, otherwise `null`.
|
||||
|
||||
Do not treat `userAgent`, `referer`, or geographic values as authenticated identity. Use `routeCtx.user` for the caller.
|
||||
|
||||
## Content reads
|
||||
|
||||
With `content:read`, both sandbox runners match the trusted read contract. `ctx.content.get()` and `ctx.content.list()` return content identity, slug, status, locale, data, created/updated/published/scheduled timestamps, and SEO metadata when enabled.
|
||||
|
||||
`list()` accepts `limit`, `cursor`, `where`, and `orderBy`. Field filters, status filters, ordering, and cursor pagination reach the host repository on both runners; they are not evaluated inside the plugin isolate. `getTranslations()` and `getPublicUrl()` use the same `content:read` authority. Collection discovery uses `ctx.schema` with `schema:read`. Read [Content, schema, translations, and publication](./content.md) for the complete contract.
|
||||
|
||||
## Publication actions
|
||||
|
||||
With `content:publish`, call `getVersioned()` before `publish()`, `unpublish()`, `schedule()`, or `unschedule()`, then pass the returned `_rev`. Each successful mutation returns the item and its next `_rev`. `content:restore` separately provides `getTrashedVersioned()` and `restore()` without granting ordinary content reads. These actions execute through the host runtime, including policy and after-hooks; a stale revision or recursive action rejects without changing the entry.
|
||||
|
||||
## Redirects
|
||||
|
||||
Declare `redirects:read` to list redirect rules with cursor pagination and read one rule with its opaque `_rev`. Declare `redirects:write` to create, update, or delete rules; it implies read access and authorizes the plugin to change where visitors are sent.
|
||||
|
||||
Pass `_rev` back unchanged for `update()` and `delete()`. A stale value fails with `CONFLICT`; re-read the current rule before retrying. The revision tracks redirect configuration, not visitor hit counting. Redirect writes use the host redirect handlers, including path-pattern, destination-parameter, duplicate-source, and terminal-status validation. Self-loop and multi-hop-loop validation runs when a rule is created or its source or destination changes. An enabled-only update can reactivate a pre-existing loop, which the Redirects page reports. Plugin input cannot set the host-owned `auto` marker.
|
||||
|
||||
## External HTTP responses
|
||||
|
||||
`ctx.http.fetch()` returns a buffered WHATWG `Response` in both sandbox runners. `ok`, `status`, `statusText`, `headers`, `url`, `redirected`, `text()`, `json()`, `arrayBuffer()`, `blob()`, and `clone()` use the standard Web API and preserve the same values across runners.
|
||||
|
||||
Request and response bodies are each limited to 8 MiB of decoded bytes. The bridge enforces the limit while reading the body rather than trusting `Content-Length`. Responses are buffered rather than streamed to plugin code.
|
||||
|
||||
## Expose a route as an MCP tool
|
||||
|
||||
MCP exposure is explicit. The following tool calls the private route as `<pluginId>__createEvent`:
|
||||
|
||||
```typescript title="src/plugin.ts"
|
||||
import type { SandboxedPlugin } from "emdash/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
const createEventInput = z.object({
|
||||
title: z.string().min(1),
|
||||
startsAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
const plugin: SandboxedPlugin = {
|
||||
routes: {
|
||||
"events/create": {
|
||||
permission: "content:create",
|
||||
handler: async (routeCtx) => {
|
||||
const parsed = createEventInput.safeParse(routeCtx.input);
|
||||
if (!parsed.success) return { ok: false, error: "INVALID_EVENT" };
|
||||
return { ok: true, id: crypto.randomUUID() };
|
||||
},
|
||||
},
|
||||
},
|
||||
mcp: {
|
||||
tools: {
|
||||
createEvent: {
|
||||
description: "Create a calendar event requested by the user.",
|
||||
route: "events/create",
|
||||
input: createEventInput,
|
||||
output: z.object({ ok: z.boolean(), id: z.string().optional() }),
|
||||
destructive: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default plugin;
|
||||
```
|
||||
|
||||
An MCP tool must:
|
||||
|
||||
- use a tool name containing only letters, digits, `_`, or `-`;
|
||||
- reference an existing private route;
|
||||
- reference a route with an explicit valid `permission`;
|
||||
- reference a JSON route, not a route with `response: "raw"`;
|
||||
- declare an input Zod schema;
|
||||
- set `destructive: true` for deletion, overwrite, publishing, charging, or another difficult-to-reverse action.
|
||||
|
||||
The optional output schema becomes structured MCP output. The bundle converts both schemas to JSON Schema.
|
||||
|
||||
Installation and updates show the exact MCP tools for consent. Adding a tool or changing a route from private to public requires fresh approval. After installation, an administrator separately enables plugin MCP tools. A caller then needs the route permission and either the `mcp:tools` scope or `mcp:tools:<pluginId>`.
|
||||
|
||||
The production core parser, shared plugin-types parser, plugin CLI artifact, and generated descriptor preserve MCP declarations and route permission/cache metadata. `@emdash-cms/plugin-test` exposes the parsed manifest so tests can assert that transport. Its `invokeRoute()` still bypasses the HTTP catch-all, so use the host for plugin execution and bridge behavior, not route authorization, response caching, MCP registration, or consent behavior.
|
||||
@@ -1,584 +0,0 @@
|
||||
# Block Kit
|
||||
|
||||
Declarative JSON UI for sandboxed plugin admin pages. The host renders blocks — no plugin JavaScript runs in the browser. Inspired by Slack's Block Kit but not identical — similar concepts and naming, different block/element types and capabilities.
|
||||
|
||||
Trusted plugins (declared in `astro.config.ts`) can ship custom React components instead. Block Kit is for runtime-installed sandboxed plugins.
|
||||
|
||||
Native plugins also use Block Kit elements for [Portable Text block editing fields](./portable-text-blocks.md). Plugin CLI and registry packages cannot register Portable Text block types.
|
||||
|
||||
## How It Works
|
||||
|
||||
1. User navigates to plugin admin page
|
||||
2. Admin sends `page_load` interaction to plugin's admin route
|
||||
3. Plugin returns `BlockResponse` with array of blocks
|
||||
4. Admin renders blocks using `BlockRenderer`
|
||||
5. User interacts (button click, form submit) → interaction sent back
|
||||
6. Plugin returns new blocks
|
||||
|
||||
```typescript
|
||||
import type { BlockInteraction } from "@emdash-cms/blocks";
|
||||
|
||||
routes: {
|
||||
admin: {
|
||||
handler: async (ctx) => {
|
||||
// EmDash parses the request body once and exposes it as ctx.input;
|
||||
// read it directly rather than ctx.request.json() (the body is consumed).
|
||||
// BlockInteraction is the discriminated union of page_load,
|
||||
// block_action, and form_submit payloads.
|
||||
const interaction = ctx.input as BlockInteraction;
|
||||
|
||||
if (interaction.type === "page_load") {
|
||||
return {
|
||||
blocks: [
|
||||
{ type: "header", text: "My Plugin Settings" },
|
||||
{
|
||||
type: "form",
|
||||
block_id: "settings",
|
||||
fields: [
|
||||
{ type: "text_input", action_id: "api_url", label: "API URL" },
|
||||
{ type: "toggle", action_id: "enabled", label: "Enabled", initial_value: true },
|
||||
],
|
||||
submit: { label: "Save", action_id: "save" },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (interaction.type === "form_submit" && interaction.action_id === "save") {
|
||||
await ctx.kv.set("settings", interaction.values);
|
||||
return {
|
||||
blocks: [/* updated blocks */],
|
||||
toast: { message: "Settings saved", type: "success" },
|
||||
};
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Block Types
|
||||
|
||||
| Type | Description |
|
||||
| ----------- | --------------------------------------------------- |
|
||||
| `header` | Large bold heading |
|
||||
| `section` | Text with optional accessory element |
|
||||
| `divider` | Horizontal rule |
|
||||
| `fields` | Two-column label/value grid |
|
||||
| `table` | Data table with formatting, sorting, pagination |
|
||||
| `actions` | Horizontal row of buttons and controls |
|
||||
| `stats` | Dashboard metric cards with trend indicators |
|
||||
| `form` | Input fields with conditional visibility and submit |
|
||||
| `image` | Block-level image with alt text and optional title |
|
||||
| `context` | Small muted help text |
|
||||
| `columns` | 2-3 column layout with nested blocks |
|
||||
| `chart` | Charts (timeseries line/bar, pie, custom ECharts) |
|
||||
| `code` | Syntax-highlighted code block |
|
||||
| `meter` | Progress/quota meter bar |
|
||||
| `banner` | Info, warning, or error inline messages |
|
||||
| `empty` | Empty state with optional command and actions |
|
||||
| `accordion` | Collapsible section containing nested blocks |
|
||||
|
||||
## Element Types
|
||||
|
||||
| Type | Description |
|
||||
| -------------- | --------------------------------------------------------- |
|
||||
| `button` | Action button with optional confirmation dialog |
|
||||
| `link` | Host-resolved navigation that does not dispatch an action |
|
||||
| `text_input` | Single-line or multiline text input |
|
||||
| `number_input` | Numeric input with min/max |
|
||||
| `select` | Dropdown select |
|
||||
| `toggle` | On/off switch |
|
||||
| `secret_input` | Masked input for API keys and tokens |
|
||||
| `checkbox` | Multi-select checkboxes |
|
||||
| `radio` | Single-select radio buttons |
|
||||
| `date_input` | Date picker |
|
||||
| `combobox` | Searchable dropdown select |
|
||||
| `repeater` | Array of records with scalar sub-fields |
|
||||
| `media_picker` | Media-library picker that stores the asset URL |
|
||||
|
||||
## Block Syntax
|
||||
|
||||
### Header
|
||||
|
||||
```json
|
||||
{ "type": "header", "text": "Settings" }
|
||||
```
|
||||
|
||||
### Section
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "section",
|
||||
"text": "Configure your plugin settings below.",
|
||||
"accessory": { "type": "button", "label": "Refresh", "action_id": "refresh" }
|
||||
}
|
||||
```
|
||||
|
||||
### Divider
|
||||
|
||||
```json
|
||||
{ "type": "divider" }
|
||||
```
|
||||
|
||||
### Fields
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "fields",
|
||||
"fields": [
|
||||
{ "label": "Status", "value": "Active" },
|
||||
{ "label": "Last Sync", "value": "2 hours ago" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Stats
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "stats",
|
||||
"items": [
|
||||
{ "label": "Total", "value": "1,234", "trend": "up", "description": "+12% vs last week" },
|
||||
{ "label": "Active", "value": "567" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `items` — the array key is `items`, not `stats`
|
||||
- `trend` — `"up"`, `"down"`, or `"neutral"`; renders an arrow icon next to the value
|
||||
- `description` — secondary line beneath the value, for context such as "+12% vs last week"
|
||||
|
||||
### Table
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "table",
|
||||
"columns": [
|
||||
{ "key": "name", "label": "Name" },
|
||||
{ "key": "status", "label": "Status" },
|
||||
{ "key": "date", "label": "Date" }
|
||||
],
|
||||
"rows": [{ "name": "Item 1", "status": "Active", "date": "2025-01-01" }],
|
||||
"page_action_id": "browse_items",
|
||||
"empty_text": "No items yet."
|
||||
}
|
||||
```
|
||||
|
||||
- `page_action_id` — required. The admin sends it as the `block_action` id when the user sorts a column or pages through results.
|
||||
- `empty_text` — shown in place of the table when `rows` is empty
|
||||
- `next_cursor` — set it to render a "Load more" control
|
||||
|
||||
### Actions
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "actions",
|
||||
"elements": [
|
||||
{ "type": "button", "label": "Save", "action_id": "save", "style": "primary" },
|
||||
{ "type": "button", "label": "Cancel", "action_id": "cancel" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Form
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "form",
|
||||
"block_id": "settings",
|
||||
"fields": [
|
||||
{ "type": "text_input", "action_id": "name", "label": "Name" },
|
||||
{ "type": "number_input", "action_id": "count", "label": "Count", "min": 0, "max": 100 },
|
||||
{
|
||||
"type": "select",
|
||||
"action_id": "theme",
|
||||
"label": "Theme",
|
||||
"options": [
|
||||
{ "label": "Light", "value": "light" },
|
||||
{ "label": "Dark", "value": "dark" }
|
||||
]
|
||||
},
|
||||
{ "type": "toggle", "action_id": "enabled", "label": "Enabled", "initial_value": true },
|
||||
{ "type": "secret_input", "action_id": "api_key", "label": "API Key" }
|
||||
],
|
||||
"submit": { "label": "Save", "action_id": "save_settings" }
|
||||
}
|
||||
```
|
||||
|
||||
### Columns
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "columns",
|
||||
"columns": [
|
||||
[
|
||||
{ "type": "header", "text": "Usage" },
|
||||
{ "type": "meter", "label": "Storage used", "value": 65 }
|
||||
],
|
||||
[
|
||||
{ "type": "header", "text": "Activity" },
|
||||
{ "type": "context", "text": "Last sync 2 hours ago" }
|
||||
]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `columns` — 2 or 3 columns, each one an array of blocks
|
||||
|
||||
### Chart (Timeseries)
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "chart",
|
||||
"config": {
|
||||
"chart_type": "timeseries",
|
||||
"series": [
|
||||
{
|
||||
"name": "Requests",
|
||||
"data": [
|
||||
[1709596800000, 42],
|
||||
[1709600400000, 67],
|
||||
[1709604000000, 53]
|
||||
],
|
||||
"color": "#086FFF"
|
||||
},
|
||||
{
|
||||
"name": "Errors",
|
||||
"data": [
|
||||
[1709596800000, 2],
|
||||
[1709600400000, 5],
|
||||
[1709604000000, 1]
|
||||
]
|
||||
}
|
||||
],
|
||||
"x_axis_name": "Time",
|
||||
"y_axis_name": "Count",
|
||||
"style": "line",
|
||||
"gradient": true,
|
||||
"height": 300
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `series[].data` — array of `[timestamp_ms, value]` tuples
|
||||
- `series[].color` — hex color (optional, auto-assigned from Kumo palette)
|
||||
- `style` — `"line"` (default) or `"bar"`
|
||||
- `gradient` — fill gradient beneath lines (default false)
|
||||
- `height` — chart height in pixels (default 350)
|
||||
|
||||
### Chart (Custom)
|
||||
|
||||
For pie charts, gauges, or any ECharts visualization:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "chart",
|
||||
"config": {
|
||||
"chart_type": "custom",
|
||||
"options": {
|
||||
"series": [
|
||||
{
|
||||
"type": "pie",
|
||||
"data": [
|
||||
{ "value": 335, "name": "Published" },
|
||||
{ "value": 234, "name": "Draft" },
|
||||
{ "value": 120, "name": "Scheduled" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"height": 300
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `options` — raw ECharts option object passed through to `chart.setOption()`
|
||||
|
||||
### Code
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "code",
|
||||
"code": "const greeting = \"Hello!\";\nconsole.log(greeting);",
|
||||
"language": "ts"
|
||||
}
|
||||
```
|
||||
|
||||
- `language` — `"ts"`, `"tsx"`, `"jsonc"`, `"bash"`, or `"css"` (defaults to `"ts"`)
|
||||
|
||||
### Meter
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "meter",
|
||||
"label": "Storage used",
|
||||
"value": 65,
|
||||
"custom_value": "6.5 GB / 10 GB"
|
||||
}
|
||||
```
|
||||
|
||||
- `value` — numeric value (default range 0-100)
|
||||
- `max` / `min` — custom range (defaults to 0-100)
|
||||
- `custom_value` — display string instead of percentage (e.g. "750 / 1,000")
|
||||
|
||||
### Banner
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "banner",
|
||||
"title": "API key invalid",
|
||||
"description": "Please check your API key in settings.",
|
||||
"variant": "error"
|
||||
}
|
||||
```
|
||||
|
||||
- `variant` — `"default"` (info, default), `"alert"` (warning), or `"error"`
|
||||
- At least one of `title` or `description` is required
|
||||
|
||||
### Empty
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "empty",
|
||||
"title": "No submissions",
|
||||
"description": "New submissions appear here.",
|
||||
"command_line": "pnpm run seed",
|
||||
"size": "base",
|
||||
"actions": [{ "type": "button", "action_id": "refresh", "label": "Refresh" }]
|
||||
}
|
||||
```
|
||||
|
||||
### Tabs
|
||||
|
||||
Use `tab` to group related blocks into labelled panels:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "tab",
|
||||
"panels": [
|
||||
{
|
||||
"label": "General",
|
||||
"blocks": [{ "type": "context", "text": "General settings" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Accordion
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "accordion",
|
||||
"label": "Advanced settings",
|
||||
"default_open": false,
|
||||
"blocks": [{ "type": "context", "text": "Settings visible when expanded" }]
|
||||
}
|
||||
```
|
||||
|
||||
## Repeater and media picker elements
|
||||
|
||||
`repeater` and `media_picker` are admin-authoring elements, not ordinary fields in a sandboxed admin-page `form`.
|
||||
|
||||
`repeater` captures an array of objects. Its nested fields are limited to `text_input`, `number_input`, `select`, and `toggle`:
|
||||
|
||||
```typescript
|
||||
{
|
||||
"type": "repeater",
|
||||
"action_id": "items",
|
||||
"label": "Questions",
|
||||
"item_label": "Question",
|
||||
"fields": [
|
||||
{ "type": "text_input", "action_id": "question", "label": "Question" },
|
||||
{ "type": "text_input", "action_id": "answer", "label": "Answer", "multiline": true }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`media_picker` opens the media library and stores the selected asset's URL string:
|
||||
|
||||
```typescript
|
||||
{
|
||||
"type": "media_picker",
|
||||
"action_id": "hero",
|
||||
"label": "Hero image",
|
||||
"mime_type_filter": "image/"
|
||||
}
|
||||
```
|
||||
|
||||
## Declarative field widgets
|
||||
|
||||
The admin field editor can render a plugin field widget from Block Kit elements. A schema field refers to `pluginId:widgetName`; a config-declared standard descriptor supplies `name`, `label`, compatible `fieldTypes`, and `elements`.
|
||||
|
||||
The field-widget renderer currently supports only these elements:
|
||||
|
||||
- `text_input`
|
||||
- `number_input`
|
||||
- `toggle`
|
||||
- `select`
|
||||
- `media_picker`
|
||||
|
||||
It stores an object keyed by each element's `action_id`. Use a `json` field for this composed value; other field types are accepted by the manifest schema but are not covered by an end-to-end save test. Other element types render an unsupported-element message.
|
||||
|
||||
`emdash-plugin.jsonc` accepts this field-widget definition, and the plugin CLI preserves it in the registry manifest and generated descriptor. The artifact transport is tested; the repository's browser E2E test still covers a native React field widget rather than a registry declarative widget. Verify the rendered editor and saved value for the selected elements.
|
||||
|
||||
## Conditional Fields
|
||||
|
||||
Show/hide fields based on other field values. Evaluated client-side, no round-trip.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "toggle",
|
||||
"action_id": "auth_enabled",
|
||||
"label": "Enable Authentication"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "secret_input",
|
||||
"action_id": "api_key",
|
||||
"label": "API Key",
|
||||
"condition": { "field": "auth_enabled", "eq": true }
|
||||
}
|
||||
```
|
||||
|
||||
## Builder Helpers
|
||||
|
||||
`@emdash-cms/blocks` provides TypeScript helpers:
|
||||
|
||||
```typescript
|
||||
import { blocks, elements } from "@emdash-cms/blocks";
|
||||
|
||||
const {
|
||||
header,
|
||||
form,
|
||||
section,
|
||||
stats,
|
||||
timeseriesChart,
|
||||
customChart,
|
||||
banner: bannerBlock,
|
||||
empty,
|
||||
accordion,
|
||||
} = blocks;
|
||||
const { textInput, toggle, select, button, repeater, mediaPicker } = elements;
|
||||
|
||||
return {
|
||||
blocks: [
|
||||
header("Settings"),
|
||||
form({
|
||||
blockId: "settings",
|
||||
fields: [
|
||||
textInput("site_title", "Site Title", { initialValue: "My Site" }),
|
||||
toggle("generate_sitemap", "Generate Sitemap", { initialValue: true }),
|
||||
select("robots", "Default Robots", [
|
||||
{ label: "Index, Follow", value: "index,follow" },
|
||||
{ label: "No Index", value: "noindex,follow" },
|
||||
]),
|
||||
],
|
||||
submit: { label: "Save", actionId: "save" },
|
||||
}),
|
||||
// Timeseries chart
|
||||
timeseriesChart({
|
||||
series: [
|
||||
{
|
||||
name: "Page Views",
|
||||
data: [
|
||||
[Date.now() - 3600000, 100],
|
||||
[Date.now(), 150],
|
||||
],
|
||||
},
|
||||
],
|
||||
yAxisName: "Views",
|
||||
gradient: true,
|
||||
}),
|
||||
// Pie chart via custom ECharts options
|
||||
customChart({
|
||||
options: {
|
||||
series: [
|
||||
{
|
||||
type: "pie",
|
||||
data: [
|
||||
{ value: 335, name: "Published" },
|
||||
{ value: 234, name: "Draft" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
## Button Confirmations
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "button",
|
||||
"label": "Delete All",
|
||||
"action_id": "delete_all",
|
||||
"style": "danger",
|
||||
"confirm": {
|
||||
"title": "Are you sure?",
|
||||
"text": "This cannot be undone.",
|
||||
"confirm": "Delete",
|
||||
"deny": "Cancel"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Saved-entry panels and actions
|
||||
|
||||
`admin.editorPanels` and `admin.editorActions` point to private plugin routes. Panel routes return Block Kit and receive `panel_load`, `block_action`, or `form_submit`. Action routes receive `editor_action` and return only these bounded fields:
|
||||
|
||||
```typescript
|
||||
{
|
||||
toast?: { message: string; type: "success" | "error" | "info" };
|
||||
refresh?: true;
|
||||
navigate?: LinkTarget;
|
||||
patch?: EditorDraftPatchEffect;
|
||||
}
|
||||
```
|
||||
|
||||
Use only one of `refresh`, `navigate`, or `patch`. Navigation uses the same structured target validator as `link` elements. A danger action declaration must include a confirmation dialog.
|
||||
|
||||
For both surfaces, `routeCtx.ui.entry` contains the host-reloaded collection, saved entry ID, content locale, and version. `routeCtx.ui.extensionId` identifies the manifest declaration. Ordinary panel load contains no draft. An explicit interaction includes selected unsaved fields only when the plugin has `admin.editor-draft:read` and the extension declares bounded `draft.read` access. `admin.editor-draft:patch` separately permits atomic whole-field `set` and `clear` proposals for fields in `draft.patch`; the host previews accepted changes without saving them.
|
||||
|
||||
## Links and admin locale
|
||||
|
||||
Use a structured link target instead of returning an admin URL:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "link",
|
||||
"label": "Edit article",
|
||||
"target": { "kind": "content", "collection": "posts", "id": "post-1", "locale": "ar" },
|
||||
"appearance": "primary"
|
||||
}
|
||||
```
|
||||
|
||||
Targets can identify saved content, a page declared by the same plugin, the plugin's generated settings page, or an absolute external HTTP, HTTPS, or `mailto:` URL. External links open in a new tab with `noopener noreferrer`. A link has no `action_id`; use a button when the interaction must call the plugin.
|
||||
|
||||
Every page and widget response is validated before rendering. Responses are limited to 256 KiB, 20 nested levels, 2,000 nodes, 1,000 items per array, and 64 KiB per string. Root-relative image URLs are accepted. External images require HTTPS and either `network:request` with the hostname in the plugin manifest's `allowedHosts`, or `network:request:unrestricted`.
|
||||
|
||||
The admin route receives host-attested UI context separately from the interaction:
|
||||
|
||||
```typescript
|
||||
const { locale, direction, surface } = routeCtx.ui ?? {
|
||||
locale: "en",
|
||||
direction: "ltr",
|
||||
surface: "admin-page",
|
||||
};
|
||||
```
|
||||
|
||||
The UI locale is the administrator's active locale. It is separate from the site's default content locale in `ctx.site.locale`. Runtime page labels can use it to select localized Block Kit text; manifest navigation labels remain static.
|
||||
|
||||
## Toast Responses
|
||||
|
||||
Return a `toast` alongside blocks to show a notification:
|
||||
|
||||
```typescript
|
||||
return {
|
||||
blocks: [/* ... */],
|
||||
toast: { message: "Settings saved", type: "success" }, // "success" | "error" | "info"
|
||||
};
|
||||
```
|
||||
@@ -1,13 +0,0 @@
|
||||
# Comment administration
|
||||
|
||||
Comment hooks and stored-comment administration have separate authority.
|
||||
|
||||
All comment hooks require `users:read` because their events contain author and request-derived information. `comments:read` separately exposes stored non-trashed comments through `ctx.comments.get()`, `list()`, and `count()`.
|
||||
|
||||
Comment reads include author name and email, body, pseudonymous IP hash, user agent, and moderation metadata. They do not expose the linked EmDash user-account ID. Treat this as personal-data access.
|
||||
|
||||
`comments:moderate` implies read and adds `ctx.comments.setStatus()`. Supply the status observed by the caller and move only between `approved`, `pending`, and `spam`. A stale status returns `COMMENT_STATUS_CONFLICT`; read again before deciding whether to retry.
|
||||
|
||||
A successful plugin transition identifies `{ source: "plugin", pluginId }`, runs `comment:afterModerate` once, preserves approval notifications, and rejects recursive moderation. The API does not hard-delete comments or replace statuses in bulk.
|
||||
|
||||
Use the runtime test host when a test must prove the personal-data shape, conflict behavior, notifications, hook origin, recursion fencing, or the real comment HTTP/runtime path.
|
||||
@@ -1,41 +0,0 @@
|
||||
# Content, schema, translations, and publication
|
||||
|
||||
Plugin content APIs are capability-gated and shared by native, Cloudflare Worker Loader, and Node/workerd execution.
|
||||
|
||||
## Discovery and reads
|
||||
|
||||
`schema:read` exposes `ctx.schema.listCollections()` and `getCollection()` for batched public collection and field definitions.
|
||||
|
||||
`content:read` exposes `ctx.content.get()`, `list()`, `getTranslations()`, and `getPublicUrl()`. Content results include identity, slug, status, locale, data, timestamps, author ID, translation group, live and draft revision pointers, and row version. Public URL resolution returns only published routable URLs, never previews.
|
||||
|
||||
`content:revisions:read` adds `listRevisions()` and `getRevision()`. Revision snapshots can retain field values removed later but omit revision-author identity.
|
||||
|
||||
## Writes and translations
|
||||
|
||||
`content:write` adds create, update, and delete. Create a translation with:
|
||||
|
||||
```typescript
|
||||
await ctx.content!.create("posts", data, { locale: "fr", translationOf: sourceId });
|
||||
```
|
||||
|
||||
The source must be an active entry in the same collection. The new row joins its translation group and inherits non-translatable fields, byline credits, and taxonomy assignments. Validation and save hooks run, with re-entrancy fencing for the creating plugin. A group permits one active row per locale.
|
||||
|
||||
Stable failures include `CONFLICT`, `NOT_FOUND`, `VALIDATION_ERROR`, and `SAVE_REJECTED`.
|
||||
|
||||
## Publication policy
|
||||
|
||||
`hooks.content-policy:register` enables `content:beforePublish`, `content:beforeSchedule`, and `content:beforeUnpublish` without granting content reads, writes, or publication actions. Return `{ cancel: true, reason }` to reject an action.
|
||||
|
||||
Events identify API, MCP, visual-editor, plugin, scheduler, and system origins. Authenticated human actions include actor identity and source. Scheduled publication runs the publish policy again; rejection unschedules the entry and records the bounded reason for administrators.
|
||||
|
||||
## Publication and restore actions
|
||||
|
||||
`content:publish` adds `getVersioned()`, `publish()`, `unpublish()`, `schedule()`, and `unschedule()`. Read first and pass the opaque `_rev` to every mutation. A successful action returns the next revision and runs the normal policy, synchronization, media-usage, cache-invalidation, and after-hook behavior.
|
||||
|
||||
`content:restore` separately adds `getTrashedVersioned()` and `restore()` without granting ordinary content reads. It does not grant permanent deletion.
|
||||
|
||||
Plugin actions report `{ source: "plugin", pluginId }`. Re-entering the same action for the same canonical entry from that plugin is rejected.
|
||||
|
||||
## Runtime tests
|
||||
|
||||
Use runtime fixtures for initial entries, translations, bylines, and taxonomy assignments. Use runtime actions for publication paths and inspectors for persisted state. Test stale revisions, policy rejection, duplicate locales, re-entrancy, restart, and cache invalidation when those behaviors matter.
|
||||
@@ -1,585 +0,0 @@
|
||||
# Hooks
|
||||
|
||||
Sandboxed plugins declare hooks in the typed default export from `src/plugin.ts`. The `SandboxedPlugin` type infers each event and return type from the hook name.
|
||||
|
||||
## Signature
|
||||
|
||||
```typescript
|
||||
async (event: EventType, ctx: PluginContext) => ReturnType;
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Simple handler or full config:
|
||||
|
||||
```typescript
|
||||
import type { SandboxedPlugin } from "emdash/plugin";
|
||||
|
||||
const plugin: SandboxedPlugin = {
|
||||
hooks: {
|
||||
"content:afterSave": {
|
||||
priority: 100,
|
||||
timeout: 5000,
|
||||
handler: async (event, ctx) => {
|
||||
ctx.log.info("Saved", { id: event.content.id });
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default plugin;
|
||||
```
|
||||
|
||||
The plugin CLI manifest retains `priority`, `timeout`, `dependencies`, `errorPolicy`, and `exclusive`. Registry-installed and config-managed sandbox hooks enter the shared host pipeline, so these settings apply consistently with trusted plugins.
|
||||
|
||||
Put capabilities in `emdash-plugin.jsonc`, not in `src/plugin.ts`. The host pipeline skips sandboxed and trusted hooks whose required capability is absent.
|
||||
|
||||
## Isolated sandbox support
|
||||
|
||||
The current isolated runtime dispatches these hooks to Cloudflare and Node/workerd sandbox instances through the shared host pipeline:
|
||||
|
||||
- `plugin:install`, `plugin:activate`, `plugin:deactivate`, and `plugin:uninstall`
|
||||
- `content:beforeSave`, `content:afterSave`, `content:beforeDelete`, and `content:afterDelete`
|
||||
- `content:beforePublish`, `content:beforeSchedule`, `content:beforeUnpublish`, `content:afterPublish`, `content:afterUnpublish`, `content:afterRestore`, `content:afterSchedule`, and `content:afterUnschedule`
|
||||
- `media:beforeUpload` and `media:afterUpload`
|
||||
- `email:beforeSend`, `email:deliver`, and `email:afterSend`
|
||||
- `comment:beforeCreate`, `comment:moderate`, `comment:afterCreate`, and `comment:afterModerate`
|
||||
- `cron`
|
||||
- `page:metadata`
|
||||
|
||||
`page:fragments` is the only declared hook excluded from sandbox registration. The plugin CLI accepts it and emits a trusted-only warning; the sandbox host proxy drops it before the hook pipeline is built.
|
||||
|
||||
## Lifecycle Hooks
|
||||
|
||||
### `plugin:install`
|
||||
|
||||
Runs once on first install. Use to seed defaults.
|
||||
|
||||
```typescript
|
||||
"plugin:install": async (_event, ctx) => {
|
||||
await ctx.settings.set("enabled", true);
|
||||
await ctx.storage.items!.put("default", { name: "Default" });
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{}`
|
||||
Returns: `void`
|
||||
|
||||
### `plugin:activate`
|
||||
|
||||
Runs when plugin is enabled (after install or re-enable).
|
||||
|
||||
```typescript
|
||||
"plugin:activate": async (_event, ctx) => {
|
||||
ctx.log.info("Activated");
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{}`
|
||||
Returns: `void`
|
||||
|
||||
### `plugin:deactivate`
|
||||
|
||||
Runs when plugin is disabled (not removed).
|
||||
|
||||
```typescript
|
||||
"plugin:deactivate": async (_event, ctx) => {
|
||||
ctx.log.info("Deactivated");
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{}`
|
||||
Returns: `void`
|
||||
|
||||
### `plugin:uninstall`
|
||||
|
||||
Runs when plugin is removed. Only delete data if `event.deleteData` is true.
|
||||
|
||||
```typescript
|
||||
"plugin:uninstall": async (event, ctx) => {
|
||||
if (event.deleteData) {
|
||||
const result = await ctx.storage.items!.query({ limit: 1000 });
|
||||
await ctx.storage.items!.deleteMany(result.items.map(i => i.id));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ deleteData: boolean }`
|
||||
Returns: `void`
|
||||
|
||||
## Content Hooks
|
||||
|
||||
### `content:beforeSave`
|
||||
|
||||
Runs before save. Return modified content, or void to keep it unchanged. To reject from the sandbox, return `{ __emdashSandboxHookResult: true, version: 1, error: { code: "SAVE_REJECTED", reason } }`. The reason must be 1–500 characters of plain text. EmDash identifies the plugin and shows the reason as text; invalid or unknown error results fail with a generic hook error. From the host process, throw `ContentSaveRejectedError` (exported from `emdash`) instead. Any other exception from either execution mode fails the save with a generic message.
|
||||
|
||||
```typescript
|
||||
"content:beforeSave": async (event, ctx) => {
|
||||
const { content } = event;
|
||||
if (!content.title) {
|
||||
return {
|
||||
__emdashSandboxHookResult: true,
|
||||
version: 1,
|
||||
error: { code: "SAVE_REJECTED", reason: "Add a title before saving." },
|
||||
};
|
||||
}
|
||||
|
||||
// Transform
|
||||
if (content.slug) {
|
||||
content.slug = content.slug.toLowerCase().replace(/\s+/g, "-");
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ content: Record<string, unknown>, collection: string, isNew: boolean, id?: string, actor?: { id: string, role: number } }`. Authenticated REST, visual editing, and MCP saves include a read-only actor snapshot; internal writes may omit it. On updates, `id` identifies the existing item. The actor snapshot does not identify the request origin, so a hook cannot distinguish REST, visual editing, MCP, or another authenticated path from this field alone.
|
||||
Returns: `Record<string, unknown> | SandboxHookErrorEnvelope | void`
|
||||
|
||||
### `content:afterSave`
|
||||
|
||||
Runs after successful save. Side effects only — logging, notifications, syncing.
|
||||
|
||||
```typescript
|
||||
"content:afterSave": async (event, ctx) => {
|
||||
const { content, collection, isNew } = event;
|
||||
ctx.log.info(`${isNew ? "Created" : "Updated"} ${collection}/${content.id}`);
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ content: Record<string, unknown>, collection: string, isNew: boolean, actor?: { id: string, role: number } }`. Authenticated saves include a read-only actor snapshot; internal writes may omit it.
|
||||
Returns: `void`
|
||||
|
||||
### `content:beforeDelete`
|
||||
|
||||
Runs before delete. Return `false` to cancel, `true` or void to allow.
|
||||
|
||||
```typescript
|
||||
"content:beforeDelete": async (event, ctx) => {
|
||||
if (event.collection === "pages" && event.id === "home") {
|
||||
ctx.log.warn("Cannot delete home page");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ id: string, collection: string }`
|
||||
Returns: `boolean | void`
|
||||
|
||||
### `content:afterDelete`
|
||||
|
||||
Runs after successful delete.
|
||||
|
||||
```typescript
|
||||
"content:afterDelete": async (event, ctx) => {
|
||||
ctx.log.info(`Deleted ${event.collection}/${event.id}`);
|
||||
await ctx.storage.cache!.delete(`${event.collection}:${event.id}`);
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ id: string, collection: string }`
|
||||
Returns: `void`
|
||||
|
||||
### Publication policy hooks
|
||||
|
||||
`content:beforePublish`, `content:beforeSchedule`, and `content:beforeUnpublish` require `hooks.content-policy:register`. This authority is independent of `content:read`, `content:write`, and publication actions.
|
||||
|
||||
Publish and schedule events expose the effective draft in `content.data` and the staged slug in `content.slug`. Unpublish events expose the currently live content that the action would remove.
|
||||
|
||||
Return `void` to allow the action or `{ cancel: true, reason }` to reject it. The reason must contain 1–500 plain-text characters. Invalid decisions and unexpected abort-policy errors stop the action with a generic failure. Explicit cancellations return `PUBLISH_REJECTED`, `SCHEDULE_REJECTED`, or `UNPUBLISH_REJECTED`.
|
||||
|
||||
```typescript
|
||||
"content:beforePublish": async (event) => {
|
||||
const data = event.content.data;
|
||||
const approvalStatus =
|
||||
typeof data === "object" && data !== null && "approval_status" in data
|
||||
? data.approval_status
|
||||
: undefined;
|
||||
if (approvalStatus !== "approved") {
|
||||
return { cancel: true, reason: "Approve this entry before publishing." };
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
Events contain `{ content, collection, origin, actor? }`; `content:beforeSchedule` also contains `scheduledAt`. Human origins are `api`, `mcp`, or `visual-editor` and include the same value in `actor.source`. The visual-editor origin requires the signed short-lived token from an authenticated toolbar render. Other origins are `plugin` (with `pluginId`), `scheduler`, and `system`.
|
||||
|
||||
Scheduled content runs `content:beforePublish` again when it becomes due. An explicit scheduler rejection unschedules the entry and lists its reason on the dashboard until the entry is rescheduled, published, deleted, or the record is dismissed. There is no `content:beforeUnschedule`, so an administrator can always cancel a future publication.
|
||||
|
||||
### `content:afterPublish`
|
||||
|
||||
Runs after content is published (promoted from draft to live). Side effects only.
|
||||
|
||||
```typescript
|
||||
"content:afterPublish": async (event, ctx) => {
|
||||
ctx.log.info(`Published ${event.collection}/${event.content.id}`);
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ content: Record<string, unknown>, collection: string }`
|
||||
Returns: `void`
|
||||
|
||||
### `content:afterUnpublish`
|
||||
|
||||
Runs after content is unpublished (reverted to draft). Side effects only.
|
||||
|
||||
```typescript
|
||||
"content:afterUnpublish": async (event, ctx) => {
|
||||
ctx.log.info(`Unpublished ${event.collection}/${event.content.id}`);
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ content: Record<string, unknown>, collection: string }`
|
||||
Returns: `void`
|
||||
|
||||
### `content:afterRestore`
|
||||
|
||||
Runs after trashed content is restored. Side effects only.
|
||||
|
||||
```typescript
|
||||
"content:afterRestore": async (event, ctx) => {
|
||||
ctx.log.info(`Restored ${event.collection}/${event.content.id}`);
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ content: Record<string, unknown>, collection: string }`
|
||||
Returns: `void`
|
||||
|
||||
### `content:afterSchedule`
|
||||
|
||||
Runs after content is scheduled for future publishing. Side effects only.
|
||||
|
||||
```typescript
|
||||
"content:afterSchedule": async (event, ctx) => {
|
||||
ctx.log.info(`Scheduled ${event.collection}/${event.content.id}`);
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ content: Record<string, unknown>, collection: string }`
|
||||
Returns: `void`
|
||||
|
||||
### `content:afterUnschedule`
|
||||
|
||||
Runs after scheduled content is unscheduled. Side effects only.
|
||||
|
||||
```typescript
|
||||
"content:afterUnschedule": async (event, ctx) => {
|
||||
ctx.log.info(`Unscheduled ${event.collection}/${event.content.id}`);
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ content: Record<string, unknown>, collection: string }`
|
||||
Returns: `void`
|
||||
|
||||
## Media Hooks
|
||||
|
||||
### `media:beforeUpload`
|
||||
|
||||
Runs before upload. Return modified file info, void to keep, or throw to cancel.
|
||||
|
||||
```typescript
|
||||
"media:beforeUpload": async (event, ctx) => {
|
||||
const { file } = event;
|
||||
|
||||
if (!file.type.startsWith("image/")) {
|
||||
throw new Error("Only images allowed");
|
||||
}
|
||||
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
throw new Error("Max 10MB");
|
||||
}
|
||||
|
||||
return { ...file, name: `${Date.now()}-${file.name}` };
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ file: { name: string, type: string, size: number } }`
|
||||
Returns: `{ name: string, type: string, size: number } | void`
|
||||
|
||||
### `media:afterUpload`
|
||||
|
||||
Runs after successful upload.
|
||||
|
||||
```typescript
|
||||
"media:afterUpload": async (event, ctx) => {
|
||||
ctx.log.info(`Uploaded ${event.media.filename}`, { id: event.media.id });
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ media: { id: string, filename: string, mimeType: string, size: number | null, url: string, createdAt: string } }`
|
||||
Returns: `void`
|
||||
|
||||
## Email Hooks
|
||||
|
||||
Email hooks require specific capabilities. Without the required capability, hooks are silently skipped.
|
||||
|
||||
### `email:beforeSend`
|
||||
|
||||
**Requires:** `hooks.email-events:register` capability.
|
||||
|
||||
Runs before email delivery. Return modified message, or `false` to cancel delivery. Handlers are chained — each receives the output of the previous one.
|
||||
|
||||
```typescript
|
||||
// emdash-plugin.jsonc: "capabilities": ["hooks.email-events:register"]
|
||||
"email:beforeSend": async (event) => {
|
||||
return { ...event.message, text: event.message.text + "\n\n-- Sent via EmDash" };
|
||||
},
|
||||
```
|
||||
|
||||
Event: `{ message: EmailMessage, source: string }`
|
||||
Returns: `EmailMessage | false`
|
||||
|
||||
### `email:deliver`
|
||||
|
||||
**Requires:** `hooks.email-transport:register` capability. **Exclusive hook** — exactly one provider is active.
|
||||
|
||||
Implements email transport (e.g. Resend, SMTP, SES). Selected by the admin in Settings > Email.
|
||||
|
||||
```typescript
|
||||
// emdash-plugin.jsonc declares hooks.email-transport:register and network:request,
|
||||
// with api.resend.com in allowedHosts.
|
||||
"email:deliver": {
|
||||
exclusive: true,
|
||||
handler: async ({ message }, ctx) => {
|
||||
const apiKey = await ctx.settings.get("apiKey");
|
||||
await ctx.http!.fetch("https://api.resend.com/emails", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
body: JSON.stringify({
|
||||
to: message.to,
|
||||
cc: message.cc,
|
||||
reply_to: message.replyTo,
|
||||
subject: message.subject,
|
||||
text: message.text,
|
||||
}),
|
||||
});
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
Event: `{ message: EmailMessage, source: string }`
|
||||
Returns: `void`
|
||||
|
||||
### `email:afterSend`
|
||||
|
||||
**Requires:** `hooks.email-events:register` capability.
|
||||
|
||||
Runs after successful delivery. Fire-and-forget — errors are logged but don't propagate.
|
||||
|
||||
```typescript
|
||||
// emdash-plugin.jsonc: "capabilities": ["hooks.email-events:register"]
|
||||
"email:afterSend": async (event, ctx) => {
|
||||
ctx.log.info(`Email sent to ${event.message.to}`, { source: event.source });
|
||||
},
|
||||
```
|
||||
|
||||
Event: `{ message: EmailMessage, source: string }`
|
||||
Returns: `void`
|
||||
|
||||
## Comment hooks
|
||||
|
||||
Comment hooks run for sandboxed and trusted plugins through the shared pipeline. All four require `users:read`. Their events include author email and request-derived information, so the pipeline skips the hook when the capability is absent.
|
||||
|
||||
### `comment:beforeCreate`
|
||||
|
||||
Runs before storage. Return a modified event to enrich the comment or its moderator-only metadata, return `false` to reject the comment, or return nothing to keep it unchanged.
|
||||
|
||||
```typescript
|
||||
"comment:beforeCreate": async (event) => {
|
||||
if (event.comment.body.includes("blocked phrase")) return false;
|
||||
return {
|
||||
...event,
|
||||
metadata: { ...event.metadata, reviewedBy: "rules-v1" },
|
||||
};
|
||||
},
|
||||
```
|
||||
|
||||
Event:
|
||||
|
||||
```typescript
|
||||
{
|
||||
comment: {
|
||||
collection: string;
|
||||
contentId: string;
|
||||
parentId: string | null;
|
||||
authorName: string;
|
||||
authorEmail: string;
|
||||
authorUserId: string | null;
|
||||
body: string;
|
||||
ipHash: string | null;
|
||||
userAgent: string | null;
|
||||
}
|
||||
metadata: Record<string, unknown>;
|
||||
}
|
||||
```
|
||||
|
||||
Returns: the event, `false`, or `void`.
|
||||
|
||||
### `comment:moderate`
|
||||
|
||||
The exclusive moderation provider decides the initial status after the enrichment pipeline.
|
||||
|
||||
```typescript
|
||||
"comment:moderate": {
|
||||
exclusive: true,
|
||||
handler: async (event) => ({
|
||||
status: event.priorApprovedCount > 0 ? "approved" : "pending",
|
||||
reason: "First-time authors require review",
|
||||
}),
|
||||
},
|
||||
```
|
||||
|
||||
The event contains `comment`, `metadata`, collection comment settings, and `priorApprovedCount`. Return `{ status: "approved" | "pending" | "spam", reason?: string }`.
|
||||
|
||||
### `comment:afterCreate`
|
||||
|
||||
Runs after the comment is stored. The event contains the stored comment, moderation metadata, the target content summary, and the content author when available. Use it for notifications and other side effects. Returns `void`.
|
||||
|
||||
### `comment:afterModerate`
|
||||
|
||||
Runs after an administrator or a plugin changes a comment's status. The event contains the stored comment, `previousStatus`, `newStatus`, the moderator's `{ id, name }`, and `origin`. Administrator changes use `{ source: "admin", userId }`; `ctx.comments.setStatus()` uses `{ source: "plugin", pluginId }`. A transition runs the hook once. Returns `void`.
|
||||
|
||||
## Cron Hook
|
||||
|
||||
### `cron`
|
||||
|
||||
Runs on a schedule. Configure schedules via `ctx.cron.schedule()` in `plugin:activate`.
|
||||
|
||||
```typescript
|
||||
hooks: {
|
||||
"plugin:activate": async (_event, ctx) => {
|
||||
await ctx.cron!.schedule("daily-cleanup", { schedule: "0 2 * * *" });
|
||||
},
|
||||
cron: async (event, ctx) => {
|
||||
if (event.name === "daily-cleanup") {
|
||||
// ... cleanup logic
|
||||
}
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
Event: `{ name: string, data?: Record<string, unknown> }`
|
||||
Returns: `void`
|
||||
|
||||
## Public Page Hooks
|
||||
|
||||
Public page hooks let plugins contribute to the rendered output of public site pages. Templates opt in to these contributions with `<EmDashHead>`, `<EmDashBodyStart>`, and `<EmDashBodyEnd>` components.
|
||||
|
||||
### `page:metadata`
|
||||
|
||||
Contributes typed metadata to `<head>` — meta tags, OG properties, canonical/alternate links, and JSON-LD. Works in both trusted and sandboxed modes.
|
||||
|
||||
Returns structured contributions that core validates, dedupes (first-wins), and renders. Plugins never emit raw HTML through this hook.
|
||||
|
||||
```typescript
|
||||
"page:metadata": async (event, ctx) => {
|
||||
if (event.page.kind !== "content") return null;
|
||||
|
||||
return [
|
||||
{ kind: "meta", name: "author", content: "My Blog" },
|
||||
{
|
||||
kind: "jsonld",
|
||||
id: `schema:${event.page.content?.collection}:${event.page.content?.id}`,
|
||||
graph: {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "BlogPosting",
|
||||
headline: event.page.pageTitle ?? event.page.title,
|
||||
description: event.page.description,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ page: PublicPageContext }`
|
||||
Returns: `PageMetadataContribution | PageMetadataContribution[] | null`
|
||||
|
||||
Contribution types:
|
||||
|
||||
- `{ kind: "meta", name: string, content: string, key?: string }` — `<meta name="..." content="...">`
|
||||
- `{ kind: "property", property: string, content: string, key?: string }` — `<meta property="..." content="...">` (OpenGraph)
|
||||
- `{ kind: "link", rel: "canonical" | "alternate", href: string, hreflang?: string, key?: string }` — `<link>` tag (HTTP/HTTPS URLs only)
|
||||
- `{ kind: "jsonld", id?: string, graph: object | object[] }` — `<script type="application/ld+json">`
|
||||
|
||||
Dedupe rules: first contribution wins per key. Canonical is singleton.
|
||||
|
||||
### `page:fragments` (trusted only)
|
||||
|
||||
Contributes raw HTML, scripts, or markup to `head`, `body:start`, or `body:end`. The sandbox authoring type and manifest schema accept the declaration, and the plugin CLI warns that it is trusted-only. The sandbox host proxy excludes the hook, so a registry-installed plugin never contributes these fragments.
|
||||
|
||||
```typescript
|
||||
"page:fragments": async (event, ctx) => {
|
||||
return [
|
||||
{
|
||||
kind: "external-script",
|
||||
placement: "head",
|
||||
src: "https://www.googletagmanager.com/gtm.js?id=GTM-XXXXX",
|
||||
async: true,
|
||||
},
|
||||
{
|
||||
kind: "html",
|
||||
placement: "body:start",
|
||||
html: '<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>',
|
||||
},
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Event: `{ page: PublicPageContext }`
|
||||
Returns: `PageFragmentContribution | PageFragmentContribution[] | null`
|
||||
|
||||
Contribution types:
|
||||
|
||||
- `{ kind: "external-script", placement, src, async?, defer?, attributes?, key? }`
|
||||
- `{ kind: "inline-script", placement, code, attributes?, key? }`
|
||||
- `{ kind: "html", placement, html, key? }`
|
||||
|
||||
Placements: `"head"`, `"body:start"`, `"body:end"`
|
||||
|
||||
## Execution Order
|
||||
|
||||
1. Lower `priority` values run first
|
||||
2. Equal priorities: plugin registration order
|
||||
3. `dependencies` forces a hook to wait for the named plugins regardless of priority
|
||||
|
||||
These ordering rules apply to sandboxed and trusted hooks in the shared host pipeline.
|
||||
|
||||
## Error Handling
|
||||
|
||||
- `errorPolicy: "abort"` (default) — pipeline stops, operation may fail
|
||||
- `errorPolicy: "continue"` — error logged, remaining hooks still run
|
||||
|
||||
These policies apply to sandboxed and trusted hooks in the shared host pipeline.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Hook | Trigger | Capability Required | Return |
|
||||
| ------------------------- | -------------------- | --------------------------------------------- | ------------------------------------------------------- |
|
||||
| `plugin:install` | First install | — | `void` |
|
||||
| `plugin:activate` | Plugin enabled | — | `void` |
|
||||
| `plugin:deactivate` | Plugin disabled | — | `void` |
|
||||
| `plugin:uninstall` | Plugin removed | — | `void` |
|
||||
| `content:beforeSave` | Before save | `content:write` | Modified content, `SandboxHookErrorEnvelope`, or `void` |
|
||||
| `content:afterSave` | After save | `content:read` | `void` |
|
||||
| `content:beforeDelete` | Before delete | `content:read` | `false` to cancel |
|
||||
| `content:afterDelete` | After delete | `content:read` | `void` |
|
||||
| `content:beforePublish` | Before publish | `hooks.content-policy:register` | `void` or cancellation |
|
||||
| `content:beforeSchedule` | Before schedule | `hooks.content-policy:register` | `void` or cancellation |
|
||||
| `content:beforeUnpublish` | Before unpublish | `hooks.content-policy:register` | `void` or cancellation |
|
||||
| `content:afterPublish` | After publish | `content:read` | `void` |
|
||||
| `content:afterUnpublish` | After unpublish | `content:read` | `void` |
|
||||
| `content:afterRestore` | After restore | `content:read` | `void` |
|
||||
| `content:afterSchedule` | After schedule | `content:read` | `void` |
|
||||
| `content:afterUnschedule` | After unschedule | `content:read` | `void` |
|
||||
| `media:beforeUpload` | Before upload | `media:write` | Modified file info or `void` |
|
||||
| `media:afterUpload` | After upload | `media:read` | `void` |
|
||||
| `email:beforeSend` | Before email send | `hooks.email-events:register` | Modified message or `false` |
|
||||
| `email:deliver` | Email delivery | `hooks.email-transport:register` | `void` (exclusive) |
|
||||
| `email:afterSend` | After email send | `hooks.email-events:register` | `void` |
|
||||
| `comment:beforeCreate` | Before comment save | `users:read` | Modified event, `false`, or `void` |
|
||||
| `comment:moderate` | Initial moderation | `users:read` | Moderation decision (exclusive) |
|
||||
| `comment:afterCreate` | After comment save | `users:read` | `void` |
|
||||
| `comment:afterModerate` | After status change | `users:read` | `void` |
|
||||
| `cron` | Scheduled task fires | — | `void` |
|
||||
| `page:metadata` | Page render | — | Metadata contributions |
|
||||
| `page:fragments` | Page render | `hooks.page-fragments:register` (native only) | Fragment contributions |
|
||||
@@ -1,25 +0,0 @@
|
||||
# Media access
|
||||
|
||||
Keep media authority as narrow as the plugin's behavior permits.
|
||||
|
||||
| Capability | Access |
|
||||
| ---------------------- | ---------------------------------------------------------- |
|
||||
| `media:read` | Ready-media metadata and authenticated ID-based asset URLs |
|
||||
| `media:bytes:read` | Bounded original bytes and content hashes |
|
||||
| `media:metadata:write` | Alt text, caption, and complete focal-point updates |
|
||||
| `media:write` | Upload and delete; implies `media:read` |
|
||||
|
||||
`media:read` metadata includes dimensions, alt text, caption, focal point, blurhash, dominant color, and folder ID. It excludes storage keys, author identity, content hashes, and bytes. Logged-out asset requests stop at authentication before the media lookup.
|
||||
|
||||
`ctx.media.readBytes(id, { maxBytes })` buffers from the configured storage adapter. The default limit is 10 MiB and callers cannot request more than 16 MiB. The host enforces the limit while consuming the stream rather than trusting stored size metadata.
|
||||
|
||||
`ctx.media.updateMetadata()` changes only alt text, caption, and a complete focal-point pair. It cannot upload, replace, move, or delete the underlying file.
|
||||
|
||||
With `media:write`, upload bytes through the bridge:
|
||||
|
||||
```typescript
|
||||
const bytes = await source.arrayBuffer();
|
||||
const uploaded = await ctx.media!.upload("report.pdf", "application/pdf", bytes);
|
||||
```
|
||||
|
||||
Both sandbox runners write through the configured media adapter and create a ready record. A sandbox does not follow a presigned upload URL directly.
|
||||
@@ -1,253 +0,0 @@
|
||||
# Portable Text Block Types
|
||||
|
||||
Plugin CLI and registry packages cannot define Portable Text block types. `emdash-plugin build` warns that `portableTextBlocks` require trusted mode and omits them from the sandboxed manifest. Site-side rendering also needs an Astro `componentsEntry`, which is loaded with the site at build time.
|
||||
|
||||
Core can forward declarative block metadata from a config-declared standard plugin descriptor, but that path does not make the definition portable through the registry and does not provide a site renderer. Treat custom Portable Text blocks as a native-plugin feature unless the site owns both the descriptor and the rendering components and has verified the complete editor-to-render path.
|
||||
|
||||
Plugins can add custom block types to the Portable Text editor. These appear in the slash command menu and can be inserted into any `portableText` field.
|
||||
|
||||
## Declaring Block Types
|
||||
|
||||
In `definePlugin()`, declare blocks under `admin.portableTextBlocks`:
|
||||
|
||||
```typescript
|
||||
admin: {
|
||||
portableTextBlocks: [
|
||||
{
|
||||
type: "youtube",
|
||||
label: "YouTube Video",
|
||||
icon: "video",
|
||||
placeholder: "Paste YouTube URL...",
|
||||
fields: [
|
||||
{ type: "text_input", action_id: "id", label: "YouTube URL" },
|
||||
{ type: "text_input", action_id: "title", label: "Title" },
|
||||
{ type: "text_input", action_id: "poster", label: "Poster Image URL" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "codepen",
|
||||
label: "CodePen",
|
||||
icon: "code",
|
||||
placeholder: "Paste CodePen URL...",
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Block Config Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------- | -------- | ----------------------------------------------- |
|
||||
| `type` | `string` | Block type name (used in PT `_type`). Required. |
|
||||
| `label` | `string` | Display name in slash command menu. Required. |
|
||||
| `icon` | `string` | Icon key. Optional. |
|
||||
| `description` | `string` | Description in slash command menu. Optional. |
|
||||
| `placeholder` | `string` | Input placeholder text. Optional. |
|
||||
| `fields` | `array` | Block Kit form fields for editing UI. Optional. |
|
||||
|
||||
### Icons
|
||||
|
||||
Named icons: `video`, `code`, `link`, `link-external`. Unknown or missing falls back to a generic cube icon.
|
||||
|
||||
### Fields
|
||||
|
||||
When `fields` is declared, the editor renders a Block Kit form for editing. When omitted, a simple URL input is shown.
|
||||
|
||||
Fields use Block Kit element syntax:
|
||||
|
||||
```typescript
|
||||
fields: [
|
||||
{
|
||||
type: "text_input",
|
||||
action_id: "id",
|
||||
label: "URL",
|
||||
placeholder: "https://...",
|
||||
},
|
||||
{ type: "text_input", action_id: "title", label: "Title" },
|
||||
{ type: "text_input", action_id: "poster", label: "Poster Image" },
|
||||
{ type: "number_input", action_id: "start", label: "Start Time (seconds)" },
|
||||
{ type: "toggle", action_id: "autoplay", label: "Autoplay" },
|
||||
{
|
||||
type: "select",
|
||||
action_id: "size",
|
||||
label: "Size",
|
||||
options: [
|
||||
{ label: "Small", value: "small" },
|
||||
{ label: "Medium", value: "medium" },
|
||||
{ label: "Large", value: "large" },
|
||||
],
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
See [Block Kit](./block-kit.md) for element shapes. The Portable Text editor additionally renders `repeater` and `media_picker` authoring elements. Do not assume every element accepted by the shared union renders in every Block Kit surface.
|
||||
|
||||
The `action_id` of each field becomes a key in the Portable Text block data. The field with `action_id: "id"` is treated as the primary identifier (typically the URL).
|
||||
|
||||
### Data Flow
|
||||
|
||||
1. User types `/` in the editor and selects a block type
|
||||
2. Modal opens with Block Kit form (or simple URL input if no fields)
|
||||
3. User fills in fields and submits
|
||||
4. Block is inserted with `_type` set to the block type and field values as properties
|
||||
5. Editing an existing block re-opens the modal pre-populated
|
||||
|
||||
Portable Text output:
|
||||
|
||||
```json
|
||||
{
|
||||
"_type": "youtube",
|
||||
"_key": "abc123",
|
||||
"id": "https://youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
"title": "Never Gonna Give You Up",
|
||||
"poster": "https://img.youtube.com/vi/dQw4w9WgXcQ/0.jpg"
|
||||
}
|
||||
```
|
||||
|
||||
## Site-Side Rendering
|
||||
|
||||
To render block types on the site, export Astro components from a `componentsEntry`.
|
||||
|
||||
### Component File
|
||||
|
||||
```typescript
|
||||
// src/astro/index.ts
|
||||
import YouTube from "./YouTube.astro";
|
||||
import CodePen from "./CodePen.astro";
|
||||
|
||||
// This export name is required
|
||||
export const blockComponents = {
|
||||
youtube: YouTube,
|
||||
codepen: CodePen,
|
||||
};
|
||||
```
|
||||
|
||||
### Astro Component
|
||||
|
||||
```astro
|
||||
---
|
||||
// src/astro/YouTube.astro
|
||||
const { id, title, poster } = Astro.props.node;
|
||||
|
||||
// Extract video ID from URL
|
||||
const videoId = id?.match(/(?:v=|youtu\.be\/)([^&]+)/)?.[1] ?? id;
|
||||
---
|
||||
|
||||
<div class="youtube-embed">
|
||||
<iframe
|
||||
src={`https://www.youtube-nocookie.com/embed/${videoId}`}
|
||||
title={title || "YouTube Video"}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
</div>
|
||||
```
|
||||
|
||||
Component receives `Astro.props.node` with the full block data.
|
||||
|
||||
### Plugin Descriptor
|
||||
|
||||
Set `componentsEntry` in the descriptor:
|
||||
|
||||
```typescript
|
||||
export function myPlugin(options = {}): PluginDescriptor {
|
||||
return {
|
||||
id: "my-plugin",
|
||||
entrypoint: "@my-org/my-plugin",
|
||||
componentsEntry: "@my-org/my-plugin/astro",
|
||||
version: "1.0.0",
|
||||
options,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Package Exports
|
||||
|
||||
Add the `./astro` export:
|
||||
|
||||
```json
|
||||
{
|
||||
"exports": {
|
||||
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
|
||||
"./admin": { "types": "./dist/admin.d.ts", "import": "./dist/admin.js" },
|
||||
"./astro": {
|
||||
"types": "./dist/astro/index.d.ts",
|
||||
"import": "./dist/astro/index.js"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Auto-Wiring
|
||||
|
||||
Plugin block components are automatically merged into `<PortableText>` on the site. Merge order:
|
||||
|
||||
1. EmDash defaults (lowest priority)
|
||||
2. Plugin block components
|
||||
3. User-provided components (highest priority)
|
||||
|
||||
Site authors don't need to import anything. User components take precedence over plugin defaults.
|
||||
|
||||
## Complete Example
|
||||
|
||||
```typescript
|
||||
// src/index.ts
|
||||
import { definePlugin } from "emdash";
|
||||
import type { PluginDescriptor } from "emdash";
|
||||
|
||||
export function embedsPlugin(options = {}): PluginDescriptor {
|
||||
return {
|
||||
id: "embeds",
|
||||
version: "1.0.0",
|
||||
entrypoint: "@my-org/plugin-embeds",
|
||||
componentsEntry: "@my-org/plugin-embeds/astro",
|
||||
options,
|
||||
};
|
||||
}
|
||||
|
||||
export function createPlugin() {
|
||||
return definePlugin({
|
||||
id: "embeds",
|
||||
version: "1.0.0",
|
||||
|
||||
admin: {
|
||||
portableTextBlocks: [
|
||||
{
|
||||
type: "youtube",
|
||||
label: "YouTube Video",
|
||||
icon: "video",
|
||||
placeholder: "Paste YouTube URL...",
|
||||
fields: [
|
||||
{ type: "text_input", action_id: "id", label: "YouTube URL" },
|
||||
{ type: "text_input", action_id: "title", label: "Title" },
|
||||
{
|
||||
type: "text_input",
|
||||
action_id: "poster",
|
||||
label: "Poster Image URL",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "linkPreview",
|
||||
label: "Link Preview",
|
||||
icon: "link-external",
|
||||
placeholder: "Paste any URL...",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export default createPlugin;
|
||||
```
|
||||
|
||||
```typescript
|
||||
// src/astro/index.ts
|
||||
import YouTube from "./YouTube.astro";
|
||||
import LinkPreview from "./LinkPreview.astro";
|
||||
|
||||
export const blockComponents = {
|
||||
youtube: YouTube,
|
||||
linkPreview: LinkPreview,
|
||||
};
|
||||
```
|
||||
@@ -1,101 +0,0 @@
|
||||
# Publishing sandboxed plugins
|
||||
|
||||
Use `@emdash-cms/plugin-cli` for registry publishing. The package profile and release records belong to the Atmosphere account named by `publisher` in `emdash-plugin.jsonc`.
|
||||
|
||||
## Required package metadata
|
||||
|
||||
Before publishing, require:
|
||||
|
||||
- `@emdash-cms/plugin-cli` installed in the plugin package;
|
||||
- a unique plugin `slug`;
|
||||
- a publisher DID or Atmosphere handle;
|
||||
- a version in `package.json` or `emdash-plugin.jsonc`;
|
||||
- a license, at least one author, and at least one security contact;
|
||||
- declared capabilities and allowed hosts that match the plugin implementation;
|
||||
- a canonical public GitHub `repo` for delegated releases.
|
||||
|
||||
Run validation from the plugin directory:
|
||||
|
||||
```sh
|
||||
pnpm exec emdash-plugin validate
|
||||
```
|
||||
|
||||
## Local publishing
|
||||
|
||||
Use local publishing when the maintainer starts the release from their computer:
|
||||
|
||||
```sh
|
||||
pnpm exec emdash-plugin login alice.example.com
|
||||
pnpm exec emdash-plugin publish
|
||||
```
|
||||
|
||||
`publish` builds and validates the bundle, uploads its files to the publisher's personal data server, and creates the package release record. Use `emdash-plugin bundle` to inspect a tarball without publishing it.
|
||||
|
||||
The success output uses the registry identifier `@<publisher-handle>/<slug>`, prints the eventual plugin-page URL, and provides `emdash-plugin info <handle> <slug> --version <version> --watch`. Before approval, `info` reads the labeler's current checks and does not return unapproved package metadata from the aggregator.
|
||||
|
||||
## Automated repository releases
|
||||
|
||||
Generate the shared workflow from one plugin package, not the monorepo root. Pass `--dir <plugin-directory>` when running the command from elsewhere:
|
||||
|
||||
```sh
|
||||
pnpm exec emdash-plugin release setup
|
||||
```
|
||||
|
||||
The command prepares the current signed package profile and writes `.github/workflows/emdash-release.yml` at the Git repository root. If the manifest omits `repo`, setup detects a GitHub `origin` remote and pre-fills the repository prompt. It does not push the file. The workflow is shared by all plugin packages in that repository and requires no Actions secret.
|
||||
|
||||
When `.changeset/config.json` exists at the repository root, interactive setup offers **Follow Changesets releases**. The generated workflow accepts the Changesets Action published-package JSON and publishes packages that also contain `emdash-plugin.jsonc`.
|
||||
|
||||
Connect Changesets Action v2 by exposing its outputs from the existing release job and calling the generated workflow:
|
||||
|
||||
```yaml
|
||||
jobs:
|
||||
release:
|
||||
# Keep the existing runner, permissions, and steps.
|
||||
outputs:
|
||||
published: ${{ steps.changesets.outputs.published }}
|
||||
published-packages: ${{ steps.changesets.outputs['published-packages'] }}
|
||||
|
||||
publish-emdash-plugins:
|
||||
needs: release
|
||||
if: needs.release.outputs.published == 'true'
|
||||
uses: ./.github/workflows/emdash-release.yml
|
||||
with:
|
||||
published-packages: ${{ needs.release.outputs['published-packages'] }}
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
```
|
||||
|
||||
For Changesets Action v1, set the normalized `published-packages` job output from `${{ steps.changesets.outputs.publishedPackages }}` instead. Private EmDash-only packages require both `privatePackages.version: true` and `privatePackages.tag: true`; add unrelated private packages to `ignore`.
|
||||
|
||||
Without Changesets, the generated workflow publishes tags in `<slug>@<version>` form:
|
||||
|
||||
```sh
|
||||
git tag gallery@1.2.3
|
||||
git push origin gallery@1.2.3
|
||||
```
|
||||
|
||||
The workflow runs `release prepare` through the exact plugin CLI version that generated it. The command finds exactly one `emdash-plugin.jsonc` whose slug matches the tag, requires the manifest version to match, builds that package, and writes its outputs for the provenance and release Actions. Duplicate slugs, missing packages, and version mismatches stop before attestation.
|
||||
|
||||
The first run uses GitHub OpenID Connect to request a repository connection. The service checks that the initiating package's signed profile names the same repository before creating the request. The publisher approves the repository, workflow file, ref scope, and environment in the release dashboard. A manual run requests approval the first time its branch is used; confirmation adds that scope without removing approved tags or branches.
|
||||
|
||||
Prepare another package without changing the workflow. Changesets users add it to a changeset; package-tag users push its tag:
|
||||
|
||||
```sh
|
||||
pnpm exec emdash-plugin profile setup --dir packages/comments
|
||||
git tag comments@1.0.0
|
||||
git push origin comments@1.0.0
|
||||
```
|
||||
|
||||
`profile setup` confirms that it published the profile, then prints `emdash-plugin publish` for a manual release and `emdash-plugin release setup` for GitHub Actions.
|
||||
|
||||
The later package reuses an approved repository scope only when its signed profile names that repository. Package approvals created by older workflows remain package-scoped until an unmatched package or ref is explicitly approved as a repository connection. Release confirmation remains package-specific: `escalation-only` requires approval when declared access increases, while `always` requires approval for every release.
|
||||
|
||||
## Verification boundaries
|
||||
|
||||
The release service verifies the GitHub repository and owner IDs, workflow, ref, environment, commit, run, runner, package profile, bundle checksum, manifest identity, declared access, and raw Sigstore provenance. It accepts artifacts only after the repository workflow and signed package profile both authorize the run.
|
||||
|
||||
Metadata moderation and release verification are separate. Registry moderation covers displayed package metadata and media. Installation independently verifies release records, bundle checksums, and declared access.
|
||||
|
||||
Use the public [Automated plugin releases](https://docs.emdashcms.com/plugins/creating-plugins/delegated-releases/) guide for the complete publisher journey and troubleshooting.
|
||||
@@ -1,43 +0,0 @@
|
||||
# Sandbox boundaries
|
||||
|
||||
Registry plugins run against a capability-gated host API, not the complete trusted EmDash runtime. Design within exported authoring types and do not infer an API from internal repositories or admin routes.
|
||||
|
||||
## Transport limits
|
||||
|
||||
- `ctx.http.fetch()` preserves binary requests and responses across both runners, but complete bodies are buffered and limited to 8 MiB of decoded bytes.
|
||||
- Declared plugin route bodies are buffered with a 1 MiB default and 8 MiB author maximum. Raw route responses are buffered to 8 MiB.
|
||||
- Media byte reads default to 10 MiB and cannot request more than 16 MiB.
|
||||
- Neither test host reproduces deployed CPU, memory, or subrequest limits.
|
||||
|
||||
## Trusted-only surfaces
|
||||
|
||||
- `page:fragments` is accepted by shared authoring types but excluded from sandbox registration. Use validated `page:metadata`; raw HTML, scripts, and styles require a trusted native plugin.
|
||||
- React admin code, Astro render components, build-time integrations, host bindings, Node built-ins, TCP sockets, and direct database access require trusted site code.
|
||||
- Custom Portable Text definitions and Astro renderers remain native-only. Registry packages can use the declarative admin surfaces that the CLI serializes.
|
||||
|
||||
## Content and schema limits
|
||||
|
||||
- Schema access is read-only. Plugins cannot create, alter, attach, or delete collection definitions through `ctx.schema`.
|
||||
- Content writes do not expose permanent deletion.
|
||||
- Publication policy hooks can reject publish, schedule, and unpublish, but cannot transform the action or restore content.
|
||||
- Publication and restore actions require separate capabilities and opaque revisions.
|
||||
- Public URL resolution never returns previews.
|
||||
|
||||
## Taxonomy, redirect, comment, and media limits
|
||||
|
||||
- Taxonomy writes cannot manage definitions, attachments, term updates or deletion, or replace all assignments.
|
||||
- Redirect writes cannot set host-owned fields and remain subject to host validation.
|
||||
- Comment administration excludes trashed comments and linked user-account IDs. It cannot hard-delete or bulk-replace statuses.
|
||||
- Media metadata writes cannot upload, replace, move, or delete files. Byte reads and content hashes require separate authority.
|
||||
|
||||
## Routes and admin UI
|
||||
|
||||
- `public: true` removes host authentication. It does not create a restricted public view; validate requests and return the minimum data.
|
||||
- Raw routes use `pluginResponse()`, an allowlisted set of representation/download/redirect headers, host-owned caching and security headers, and no active same-origin browser content. They cannot back MCP tools.
|
||||
- Credential, cookie, Cloudflare Access, proxy authorization, and EmDash CSRF headers never cross declared route-header boundaries.
|
||||
- Saved-entry panels and actions receive canonical saved identity and version. Ordinary panel load and typing never send unsaved state. An explicit interaction can receive only extension-selected draft fields with `admin.editor-draft:read`, and can propose an atomic whole-field patch with the independent `admin.editor-draft:patch` capability. The host validates and previews a patch but never saves it automatically. Use capability-gated APIs to read saved content.
|
||||
- `routeCtx.ui` carries host-attested admin locale, direction, and surface. Manifest labels remain static strings; the host does not consume plugin translation catalogs.
|
||||
|
||||
## Runner-only methods are not portable
|
||||
|
||||
Methods absent from public authoring types are not part of the registry contract even if one wrapper contains them. Write against `SandboxedPlugin` and exported context types, then test the feature through both bridges when behavior is runner-sensitive.
|
||||
@@ -1,213 +0,0 @@
|
||||
# Storage and KV
|
||||
|
||||
Sandboxed plugins have three plugin-scoped data APIs:
|
||||
|
||||
| API | Use |
|
||||
| -------------------------- | ------------------------------------------------------- |
|
||||
| `ctx.storage.<collection>` | Queryable records declared in `emdash-plugin.jsonc` |
|
||||
| `ctx.settings` | User-configurable settings, including encrypted secrets |
|
||||
| `ctx.kv` | Cursors, cached values, and other key-value state |
|
||||
|
||||
All three stores use the host database and are isolated by runtime plugin ID. None needs a capability.
|
||||
|
||||
## Declare storage collections
|
||||
|
||||
Declare every collection and query index in the manifest:
|
||||
|
||||
```jsonc title="emdash-plugin.jsonc"
|
||||
{
|
||||
"storage": {
|
||||
"submissions": {
|
||||
"indexes": ["formId", "status", "createdAt", ["formId", "createdAt"]],
|
||||
"uniqueIndexes": ["externalId"],
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
An undeclared collection is rejected by the sandbox bridge. Fields in `uniqueIndexes` are already queryable; do not repeat them in `indexes`.
|
||||
|
||||
## Collection operations
|
||||
|
||||
Every declared collection exposes this portable API in native, Cloudflare-sandboxed, and Node/workerd-sandboxed execution:
|
||||
|
||||
```typescript
|
||||
interface StorageCollection<T = unknown> {
|
||||
get(id: string): Promise<T | null>;
|
||||
put(id: string, data: T): Promise<void>;
|
||||
delete(id: string): Promise<boolean>;
|
||||
exists(id: string): Promise<boolean>;
|
||||
|
||||
getVersioned(id: string): Promise<{ value: T; revision: string } | null>;
|
||||
compareAndSet(
|
||||
id: string,
|
||||
expectedRevision: string | null,
|
||||
data: T,
|
||||
): Promise<{ applied: true; revision: string } | { applied: false }>;
|
||||
compareAndDelete(id: string, expectedRevision: string): Promise<{ applied: boolean }>;
|
||||
updateIf(id: string, args: UpdateIfArgs<T>): Promise<UpdateIfResult<T>>;
|
||||
|
||||
getMany(ids: string[]): Promise<Map<string, T>>;
|
||||
putMany(items: Array<{ id: string; data: T }>): Promise<void>;
|
||||
deleteMany(ids: string[]): Promise<number>;
|
||||
|
||||
query(options?: QueryOptions): Promise<{
|
||||
items: Array<{ id: string; data: T }>;
|
||||
cursor?: string;
|
||||
hasMore: boolean;
|
||||
}>;
|
||||
count(where?: WhereClause): Promise<number>;
|
||||
}
|
||||
```
|
||||
|
||||
The Node/workerd wrapper also contains content batch methods. They are not part of `StorageCollection`; storage batch methods in the interface above are portable across both runners.
|
||||
|
||||
## Basic and batch writes
|
||||
|
||||
```typescript
|
||||
const submissions = ctx.storage.submissions as StorageCollection<Submission>;
|
||||
|
||||
await submissions.put("sub_123", {
|
||||
formId: "contact",
|
||||
status: "pending",
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const item = await submissions.get("sub_123");
|
||||
const exists = await submissions.exists("sub_123");
|
||||
|
||||
const items = await submissions.getMany(["sub_123", "sub_456"]);
|
||||
await submissions.putMany([
|
||||
{ id: "sub_456", data: { formId: "contact", status: "pending" } },
|
||||
{ id: "sub_789", data: { formId: "sales", status: "pending" } },
|
||||
]);
|
||||
const deleted = await submissions.deleteMany(["sub_456", "sub_789"]);
|
||||
```
|
||||
|
||||
`getMany()` returns a `Map`, including after crossing either sandbox bridge.
|
||||
|
||||
## Revision-based compare and set
|
||||
|
||||
Use `getVersioned()`, `compareAndSet()`, and `compareAndDelete()` when concurrent requests may replace the same whole value.
|
||||
|
||||
```typescript
|
||||
const current = await submissions.getVersioned("sub_123");
|
||||
if (!current) throw new Error("Submission not found");
|
||||
|
||||
const result = await submissions.compareAndSet("sub_123", current.revision, {
|
||||
...current.value,
|
||||
status: "processing",
|
||||
});
|
||||
|
||||
if (!result.applied) {
|
||||
// Another request changed or deleted the value. Read it again before retrying.
|
||||
}
|
||||
```
|
||||
|
||||
The operations have these preconditions:
|
||||
|
||||
| Operation | Behavior |
|
||||
| ------------------------------------- | --------------------------------------------------------- |
|
||||
| `getVersioned(key)` | Returns `{ value, revision }`, or `null` only when absent |
|
||||
| `compareAndSet(key, null, value)` | Creates only when absent |
|
||||
| `compareAndSet(key, revision, value)` | Replaces only when the current revision matches |
|
||||
| `compareAndDelete(key, revision)` | Deletes only when the current revision matches |
|
||||
|
||||
A stored JSON `null` still returns a versioned envelope. Every successful write changes the revision, including an equal-value `put()` or `set()`. Revisions are opaque, key-specific values; pass them back unchanged.
|
||||
|
||||
Conflicts return `applied: false`. Invalid inputs, permission failures, unique-index violations, and database failures reject. After a conflict, re-read and recompute; keep retries bounded. A lost response can leave the write outcome unknown, so CAS is not an exactly-once mechanism for external side effects.
|
||||
|
||||
The versioned methods are also available on `ctx.kv`:
|
||||
|
||||
```typescript
|
||||
const current = await ctx.kv.getVersioned<number>("state:completed");
|
||||
const next = (current?.value ?? 0) + 1;
|
||||
const result = await ctx.kv.compareAndSet("state:completed", current?.revision ?? null, next);
|
||||
```
|
||||
|
||||
## Predicate-guarded updates
|
||||
|
||||
`updateIf()` changes fields of an existing document when its stored data matches a guard. The guard, field replacements, and integer deltas execute atomically for that record.
|
||||
|
||||
```typescript
|
||||
const result = await submissions.updateIf("sub_123", {
|
||||
where: { status: "pending", attempts: { lt: 3 } },
|
||||
set: { status: "processing", lastAttemptAt: new Date().toISOString() },
|
||||
delta: { attempts: { inc: 1 } },
|
||||
});
|
||||
|
||||
if (result.applied) {
|
||||
ctx.log.info("Claimed submission", { submission: result.data });
|
||||
}
|
||||
```
|
||||
|
||||
`updateIf()` returns `{ applied: false }` when the row is absent, the guard fails, the stored document is not an object, or integer arithmetic is unsafe. It never inserts.
|
||||
|
||||
Rules:
|
||||
|
||||
- `where` is required. An explicit `{}` means “match any existing row.”
|
||||
- `set` replaces supplied top-level fields and leaves other fields unchanged.
|
||||
- `delta` contains exactly one safe-integer `inc` or `dec` per field. Missing or `null` counters start at zero.
|
||||
- A field cannot appear in both `set` and `delta`.
|
||||
- At least one defined field must remain in `set` or `delta`.
|
||||
- Pair `dec: n` with a `gte: n` guard when the value must stay nonnegative.
|
||||
|
||||
Malformed arguments reject without writing. In native PostgreSQL execution, serialization failures and deadlocks throw `StorageSerializationError` with `code: "STORAGE_SERIALIZATION_FAILURE"` and `retryable: true`. Sandbox transports preserve the safe fields but do not guarantee `instanceof`; check `code` and `retryable`. Restart an entire explicit transaction before retrying it.
|
||||
|
||||
## Indexed queries
|
||||
|
||||
Only declared index fields can be filtered or ordered:
|
||||
|
||||
```typescript
|
||||
const result = await submissions.query({
|
||||
where: {
|
||||
formId: "contact",
|
||||
status: { in: ["pending", "processing"] },
|
||||
createdAt: { gte: "2026-01-01" },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
limit: 100,
|
||||
cursor,
|
||||
});
|
||||
```
|
||||
|
||||
Supported filters are exact values, `{ in: [...] }`, `{ startsWith: "..." }`, and range objects using `gt`, `gte`, `lt`, or `lte`. A range needs at least one defined bound.
|
||||
|
||||
`query()` defaults to 50 items and returns at most 100 per page. Follow `cursor` while `hasMore` is true. `count(where)` accepts the same indexed filters.
|
||||
|
||||
Composite index order determines useful query shapes. `['formId', 'createdAt']` supports filtering by `formId` and ordering by `createdAt`; it does not replace a standalone `createdAt` index for queries that omit `formId`.
|
||||
|
||||
## KV operations
|
||||
|
||||
KV supports unconditional, versioned, delete, and prefix-list operations:
|
||||
|
||||
```typescript
|
||||
interface KVAccess {
|
||||
get<T>(key: string): Promise<T | null>;
|
||||
set(key: string, value: unknown): Promise<void>;
|
||||
delete(key: string): Promise<boolean>;
|
||||
list(prefix?: string): Promise<Array<{ key: string; value: unknown }>>;
|
||||
getVersioned<T>(key: string): Promise<{ value: T; revision: string } | null>;
|
||||
compareAndSet(
|
||||
key: string,
|
||||
expectedRevision: string | null,
|
||||
value: unknown,
|
||||
): Promise<{ applied: true; revision: string } | { applied: false }>;
|
||||
compareAndDelete(key: string, expectedRevision: string): Promise<{ applied: boolean }>;
|
||||
}
|
||||
```
|
||||
|
||||
Use stable prefixes to keep internal KV keys discoverable:
|
||||
|
||||
```typescript
|
||||
await ctx.settings.set("webhookUrl", url);
|
||||
await ctx.kv.set("state:lastRun", new Date().toISOString());
|
||||
await ctx.kv.set("cache:summary", summary);
|
||||
const settings = await ctx.settings.list();
|
||||
```
|
||||
|
||||
The plugin CLI serializes `admin.settingsSchema`, and both sandbox bridges route `ctx.settings` through the same options records as the generated admin form. Values saved in that form are available through `ctx.settings.get("<key>")`. The complete settings API supports `set`, `delete`, `list`, `getVersioned`, `compareAndSet`, and `compareAndDelete`.
|
||||
|
||||
Fields declared as `secret` use a versioned AES-GCM envelope with the plugin ID and setting key as authenticated data. `EMDASH_ENCRYPTION_KEY` may contain a comma-separated rotation list: the first key encrypts new values and the envelope's `kid` selects a key for reads. Missing, wrong, and tampered keys fail closed without exposing plaintext. Existing plaintext secrets remain readable and become encrypted when saved again.
|
||||
|
||||
Keep the full encryption-key list with operational backups. Restoring the database without every key referenced by its encrypted settings leaves those values unreadable. `ctx.kv.get("settings:<key>")` remains a compatibility alias throughout EmDash 1.x; new plugins should use `ctx.settings`.
|
||||
@@ -1,19 +0,0 @@
|
||||
# Taxonomies and redirects
|
||||
|
||||
## Taxonomies
|
||||
|
||||
`taxonomies:read` exposes taxonomy definitions, terms, and entry assignments. `taxonomies:write` implies read and adds `createTerm()`, `addEntryTerms()`, and `removeEntryTerms()`.
|
||||
|
||||
Term assignment methods accept term row IDs or translation-group IDs, not slugs. Add and remove operations apply idempotent deltas rather than replacing the full set, so concurrent additions do not overwrite one another.
|
||||
|
||||
The host validates taxonomy attachment, entry and term ownership, configured locales, translation identity, and hierarchy. `createTerm()` rejects a parent for a flat taxonomy. Definition management, attachment changes, assignment replacement, term updates, and term deletion remain unavailable.
|
||||
|
||||
## Redirects
|
||||
|
||||
`redirects:read` exposes cursor-paged listing and versioned reads. `redirects:write` implies read and adds create, update, and delete.
|
||||
|
||||
Pass the opaque redirect `_rev` unchanged to update and delete. A stale revision returns `CONFLICT`; re-read before retrying. Redirect writes use the host's source-pattern, destination-parameter, duplicate-source, status, and loop validation. Plugin input cannot set host-owned fields such as the automatic-rule marker.
|
||||
|
||||
Changing redirect rules changes where visitors are sent, so request this capability only when the plugin owns that behavior.
|
||||
|
||||
For runtime tests, establish redirect state with fixtures, invoke the plugin through the real route/action boundary, and inspect persisted rules. Cover stale revisions and loop or destination validation when relevant.
|
||||
@@ -1,180 +0,0 @@
|
||||
# Editing Flow
|
||||
|
||||
How content editing works through the CLI. Covers Portable Text conversion, `_rev` tokens, and raw mode.
|
||||
|
||||
## Portable Text and Markdown
|
||||
|
||||
EmDash stores rich text as [Portable Text](https://portabletext.org/) (PT) — a structured JSON format. The CLI automatically converts between PT and markdown so you work with a familiar text format.
|
||||
|
||||
### Automatic Conversion
|
||||
|
||||
- **On read**: PT arrays in `portableText` fields are converted to markdown strings
|
||||
- **On write**: markdown strings in `portableText` fields are converted back to PT arrays
|
||||
- **Non-PT fields** (string, text, number, etc.) pass through unchanged
|
||||
|
||||
The CLI detects which fields need conversion by fetching the collection's field schema.
|
||||
|
||||
### Supported Markdown Syntax
|
||||
|
||||
Standard blocks (lossless round-trip):
|
||||
|
||||
| Markdown | PT block |
|
||||
| ---------------------------- | ------------------------------------------ |
|
||||
| `# Heading` through `######` | h1-h6 blocks |
|
||||
| Plain paragraph | normal block |
|
||||
| `> Quote` | blockquote |
|
||||
| `- item` / `* item` | bullet list (nesting via 2-space indent) |
|
||||
| `1. item` | numbered list (nesting via 2-space indent) |
|
||||
| ` ``` ```lang``` ` | code block with language |
|
||||
| `` | image block |
|
||||
|
||||
Inline marks:
|
||||
|
||||
| Markdown | PT mark |
|
||||
| ------------- | --------------- |
|
||||
| `**bold**` | `strong` |
|
||||
| `_italic_` | `em` |
|
||||
| `` `code` `` | `code` |
|
||||
| `~~strike~~` | `strikethrough` |
|
||||
| `[text](url)` | link annotation |
|
||||
|
||||
### Unknown Blocks (Opaque Fences)
|
||||
|
||||
Blocks the converter doesn't recognize (custom blocks, embeds, etc.) are serialized as HTML comments:
|
||||
|
||||
```markdown
|
||||
<!--ec:block {"_type":"callout","level":"warning","text":"Be careful"} -->
|
||||
```
|
||||
|
||||
These survive round-trips intact. You can see and move them, but editing the JSON risks corruption. On write, they're deserialized back to the original PT block.
|
||||
|
||||
### Raw Mode
|
||||
|
||||
Skip markdown conversion entirely to work with raw PT JSON:
|
||||
|
||||
```bash
|
||||
npx emdash content get posts 01ABC123 --raw
|
||||
```
|
||||
|
||||
Use raw mode when:
|
||||
|
||||
- You need exact control over PT structure
|
||||
- You're working with custom block types
|
||||
- You're copying PT between items without transformation
|
||||
|
||||
### Writing Content
|
||||
|
||||
When creating or updating content, each field is checked:
|
||||
|
||||
- `portableText` field + **string value** → converts markdown to PT before sending
|
||||
- `portableText` field + **array value** → sends as raw PT (no conversion)
|
||||
- Any other field type → sends as-is
|
||||
|
||||
```bash
|
||||
# Markdown string — converted to PT automatically
|
||||
npx emdash content create posts --data '{"title": "Hello", "body": "# Welcome\n\nThis is **bold**."}'
|
||||
|
||||
# Raw PT array — passed through as-is
|
||||
npx emdash content create posts --data '{"title": "Hello", "body": [{"_type": "block", "children": [{"_type": "span", "text": "Welcome"}]}]}'
|
||||
```
|
||||
|
||||
## Auto-Publishing
|
||||
|
||||
The CLI is designed for agents. It auto-publishes on `create` and `update` by default so agents get read-after-write consistency without managing the draft/publish lifecycle.
|
||||
|
||||
### How It Works
|
||||
|
||||
- **`create`** — creates the item, then publishes it. The returned item is in `published` status.
|
||||
- **`update`** — updates the item. If the collection uses revisions and the update created a draft revision, it auto-publishes to promote the draft to the content table. The returned item reflects the updated data.
|
||||
- **`get`** — returns the latest state. If a pending draft exists (e.g. someone edited in the admin UI but didn't publish), the draft data is returned instead of the published data. Use `--published` to see only published data.
|
||||
|
||||
Use `--draft` on create/update to skip auto-publishing.
|
||||
|
||||
### Why Auto-Publish?
|
||||
|
||||
EmDash collections can support draft revisions. When they do, `update` writes data to a draft revision instead of the content table. Without auto-publish, an agent would update, then `get` the item, and see stale published data — not the changes it just made. Auto-publish eliminates this confusion.
|
||||
|
||||
## Read-Before-Write
|
||||
|
||||
Updates use `_rev` tokens for optimistic concurrency — the same principle as a file editing tool that requires you to read a file before you can edit it. You must see what you're overwriting.
|
||||
|
||||
### The Analogy
|
||||
|
||||
Think of it like a filesystem edit tool:
|
||||
|
||||
1. You **read** the file to see its current contents
|
||||
2. You decide what to change
|
||||
3. You **write** with a reference to the version you read
|
||||
|
||||
If someone else changed the file between your read and your write, the write fails — you can't overwrite changes you haven't seen. The `_rev` token is your proof that you've seen the current state.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. `content get` returns the item with a `_rev` token in the output
|
||||
2. You pass that `_rev` back to `content update` via `--rev`
|
||||
3. The server checks: if the item has changed since your read, it returns **409 Conflict**
|
||||
4. A successful update returns a new `_rev` for subsequent edits
|
||||
|
||||
### What Is a `_rev` Token?
|
||||
|
||||
An opaque base64 string. Don't parse it — just pass it back.
|
||||
|
||||
### CLI Workflow
|
||||
|
||||
The CLI **requires** `--rev` on updates. The typical workflow:
|
||||
|
||||
```bash
|
||||
# 1. Read the item — note the _rev in the output
|
||||
npx emdash content get posts 01ABC123
|
||||
# Output includes: _rev: MToyMDI2LTAyLTE0...
|
||||
|
||||
# 2. Update with the _rev you received — auto-publishes by default
|
||||
npx emdash content update posts 01ABC123 \
|
||||
--rev MToyMDI2LTAyLTE0... \
|
||||
--data '{"title": "New Title"}'
|
||||
# Output shows updated item with new _rev
|
||||
```
|
||||
|
||||
If you try to update without `--rev`, the CLI rejects the command. This ensures you always know what you're overwriting.
|
||||
|
||||
### Conflict Handling
|
||||
|
||||
If someone else updated the item between your read and write:
|
||||
|
||||
```
|
||||
EmDashApiError: Content has been modified since last read (version conflict)
|
||||
status: 409
|
||||
code: CONFLICT
|
||||
```
|
||||
|
||||
Resolution: re-read with `get`, inspect the new state, then `update` with the fresh `_rev`.
|
||||
|
||||
### Locked Entries
|
||||
|
||||
A 409 does not always mean the item changed. If someone has the entry open in the admin, the write is refused with a different code:
|
||||
|
||||
```
|
||||
EmDashApiError: Ada is holding this entry
|
||||
status: 409
|
||||
code: ENTRY_LOCKED
|
||||
```
|
||||
|
||||
Re-reading does not clear this one. The item has not changed, so a fresh `_rev` produces the same refusal. Check `code` before you retry. Either wait, or pass `--override-lock` to write anyway. An editor releases the lock when they close the entry, and a lock left behind by a crashed tab lapses seven minutes after their last heartbeat.
|
||||
|
||||
Overriding does not take the lock. The editor keeps it and their next save is rejected as a version conflict, so wait unless you know they have gone.
|
||||
|
||||
`--override-lock` is accepted by `content update`, `content delete`, `content publish`, `content unpublish` and `content schedule`. Collections with edit locking switched off never return `ENTRY_LOCKED`.
|
||||
|
||||
### Which Operations Need `_rev`?
|
||||
|
||||
Only `update`. All other operations are either idempotent or non-destructive:
|
||||
|
||||
| Command | `--rev` needed? | Why |
|
||||
| ------------------- | --------------- | ------------------------ |
|
||||
| `content create` | No | Nothing exists yet |
|
||||
| `content update` | **Yes** | Overwrites existing data |
|
||||
| `content delete` | No | Soft delete, reversible |
|
||||
| `content publish` | No | Idempotent status change |
|
||||
| `content unpublish` | No | Idempotent status change |
|
||||
| `content schedule` | No | Only changes metadata |
|
||||
| `content restore` | No | Restores from trash |
|
||||
@@ -1,267 +0,0 @@
|
||||
---
|
||||
name: emdash-cli
|
||||
description: Use the EmDash CLI to inspect and manage an EmDash instance from the command line, including content, schema, media, taxonomies, menus, search, authentication, seeds, migrations, generated types, and whole-site export and import.
|
||||
---
|
||||
|
||||
# EmDash CLI
|
||||
|
||||
The EmDash CLI (`emdash`, with the short alias `em`) manages EmDash CMS instances. Commands fall into two categories:
|
||||
|
||||
- **Local commands** work with project files or a configured database: `init`, `doctor`, `seed`, `migrate`, `export-seed`, and `secrets`.
|
||||
- **Remote commands** talk to a running EmDash instance: `types`, `login`, `logout`, `whoami`, `content`, `schema`, `media`, `search`, `taxonomy`, `menu`, `site`, and `plugin`.
|
||||
|
||||
Run `npx emdash --help` and `npx emdash <command> --help` for the installed version's exact commands and flags. Resolve the current target with a read command before a destructive or bulk mutation; examples in this skill do not authorize changing an instance the user did not place in scope.
|
||||
|
||||
## Authentication
|
||||
|
||||
Remote commands resolve auth automatically:
|
||||
|
||||
1. `--token` flag
|
||||
2. `EMDASH_TOKEN` env var
|
||||
3. Stored credentials from `emdash login`
|
||||
4. Dev bypass (localhost only — no token needed)
|
||||
|
||||
For a localhost development server with the development bypass enabled, the client can authenticate automatically. For a remote instance, run `emdash login --url https://my-site.pages.dev` or provide a scoped token.
|
||||
|
||||
## Custom Headers & Reverse Proxies
|
||||
|
||||
Sites behind Cloudflare Access or other reverse proxies need auth headers on every request. The CLI supports this via `--header` flags and environment variables.
|
||||
|
||||
### Service tokens for automation
|
||||
|
||||
```bash
|
||||
# Provide sensitive headers through the environment in CI.
|
||||
export EMDASH_HEADERS="CF-Access-Client-Id: xxx
|
||||
CF-Access-Client-Secret: yyy"
|
||||
npx emdash whoami --url https://my-site.pages.dev
|
||||
```
|
||||
|
||||
`emdash login --header` persists custom headers to `~/.config/emdash/auth.json` for later commands. Prefer environment-provided headers in CI so a service secret is not written to the credential file or shell history.
|
||||
|
||||
### Cloudflare Access Browser Flow
|
||||
|
||||
If you don't have service tokens and `cloudflared` is installed, the CLI will automatically:
|
||||
|
||||
1. Detect when Access blocks the request
|
||||
2. Try to get a cached JWT via `cloudflared access token`
|
||||
3. Fall back to `cloudflared access login` for browser-based auth
|
||||
|
||||
This works for interactive use but isn't suitable for CI. Use service tokens for automation.
|
||||
|
||||
### Generic Reverse Proxy Auth
|
||||
|
||||
The `--header` flag works with any auth scheme:
|
||||
|
||||
```bash
|
||||
# Basic auth
|
||||
npx emdash login --url https://example.com -H "Authorization: Basic dXNlcjpwYXNz"
|
||||
|
||||
# Custom auth header
|
||||
npx emdash login --url https://example.com -H "X-API-Key: secret123"
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Database Setup
|
||||
|
||||
For normal site startup, use the project's package script. The first request runs pending migrations and applies the bundled seed when the database is empty and setup has not been completed. The Astro integration generates `emdash-env.d.ts` when the server starts.
|
||||
|
||||
```bash
|
||||
# Start the site with its package script
|
||||
pnpm dev
|
||||
|
||||
# Export an existing database as a seed file
|
||||
# (the runtime auto-discovers .emdash/seed.json on first boot;
|
||||
# `mkdir -p` because the directory may not exist yet)
|
||||
mkdir -p .emdash
|
||||
npx emdash export-seed > .emdash/seed.json
|
||||
npx emdash export-seed --with-content=all > .emdash/seed.json
|
||||
```
|
||||
|
||||
### Type Generation
|
||||
|
||||
```bash
|
||||
# Generate types from local dev server
|
||||
npx emdash types
|
||||
|
||||
# Generate from remote
|
||||
npx emdash types --url https://my-site.pages.dev
|
||||
|
||||
# Custom output path
|
||||
npx emdash types --output src/types/cms.ts
|
||||
```
|
||||
|
||||
Writes `.emdash/types.ts` (TypeScript interfaces) and `.emdash/schema.json`.
|
||||
|
||||
### Authentication
|
||||
|
||||
```bash
|
||||
# Login (OAuth Device Flow)
|
||||
npx emdash login --url https://my-site.pages.dev
|
||||
|
||||
# Check current user
|
||||
npx emdash whoami
|
||||
|
||||
# Logout
|
||||
npx emdash logout
|
||||
|
||||
# Generate an encryption key for deployment
|
||||
npx emdash secrets generate
|
||||
```
|
||||
|
||||
### Content CRUD
|
||||
|
||||
The CLI is designed for agents. Create and update auto-publish by default so agents get read-after-write consistency without managing drafts.
|
||||
|
||||
```bash
|
||||
# List content
|
||||
npx emdash content list posts
|
||||
npx emdash content list posts --status published --limit 10
|
||||
|
||||
# Get a single item (Portable Text fields converted to markdown)
|
||||
# Returns draft data if a pending draft exists
|
||||
npx emdash content get posts 01ABC123
|
||||
npx emdash content get posts 01ABC123 --raw # skip PT->markdown conversion
|
||||
npx emdash content get posts 01ABC123 --published # ignore pending drafts
|
||||
|
||||
# Create content (auto-publishes by default)
|
||||
npx emdash content create posts --data '{"title": "Hello", "body": "# World"}'
|
||||
npx emdash content create posts --file post.json --slug hello-world
|
||||
npx emdash content create posts --draft --data '...' # keep as draft
|
||||
cat post.json | npx emdash content create posts --stdin
|
||||
|
||||
# Update (requires --rev from a prior get, auto-publishes by default)
|
||||
npx emdash content update posts 01ABC123 --rev MToyMDI2... --data '{"title": "Updated"}'
|
||||
npx emdash content update posts 01ABC123 --rev MToyMDI2... --draft --data '...' # keep as draft
|
||||
|
||||
# Delete (soft delete)
|
||||
npx emdash content delete posts 01ABC123
|
||||
|
||||
# Lifecycle
|
||||
npx emdash content publish posts 01ABC123
|
||||
npx emdash content unpublish posts 01ABC123
|
||||
npx emdash content schedule posts 01ABC123 --at 2026-03-01T09:00:00Z
|
||||
npx emdash content restore posts 01ABC123
|
||||
```
|
||||
|
||||
### Schema Management
|
||||
|
||||
```bash
|
||||
# List collections
|
||||
npx emdash schema list
|
||||
|
||||
# Get collection with fields
|
||||
npx emdash schema get posts
|
||||
|
||||
# Create collection
|
||||
npx emdash schema create articles --label Articles --description "Blog articles"
|
||||
|
||||
# Delete a collection after inspecting it and confirming the target
|
||||
npx emdash schema get articles
|
||||
npx emdash schema delete articles
|
||||
|
||||
# Add field
|
||||
npx emdash schema add-field posts body --type portableText --label "Body Content"
|
||||
npx emdash schema add-field posts featured --type boolean --required
|
||||
|
||||
# Remove field
|
||||
npx emdash schema remove-field posts featured
|
||||
```
|
||||
|
||||
`schema add-field` supports the field types printed by `npx emdash schema add-field --help`. The full product schema supports additional field types that are not necessarily creatable through this command.
|
||||
|
||||
### Media
|
||||
|
||||
```bash
|
||||
# List media
|
||||
npx emdash media list
|
||||
npx emdash media list --mime image/png
|
||||
|
||||
# Upload
|
||||
npx emdash media upload ./photo.jpg --alt "A sunset" --caption "Bristol, 2026"
|
||||
|
||||
# Get / delete
|
||||
npx emdash media get 01MEDIA123
|
||||
npx emdash media delete 01MEDIA123
|
||||
```
|
||||
|
||||
### Search
|
||||
|
||||
```bash
|
||||
npx emdash search "hello world"
|
||||
npx emdash search "hello" --collection posts --limit 5
|
||||
```
|
||||
|
||||
### Taxonomies
|
||||
|
||||
```bash
|
||||
npx emdash taxonomy list
|
||||
npx emdash taxonomy terms categories
|
||||
npx emdash taxonomy add-term categories --name "Tech" --slug tech
|
||||
npx emdash taxonomy add-term categories --name "Frontend" --parent 01PARENT123
|
||||
```
|
||||
|
||||
### Menus
|
||||
|
||||
```bash
|
||||
npx emdash menu list
|
||||
npx emdash menu get primary
|
||||
```
|
||||
|
||||
### Site Export and Import
|
||||
|
||||
`emdash site` copies a whole site (content model, content, history, settings, and media, but no users or secrets) into a `.emdash` site package, and imports a package into an empty site. The token needs `admin`, which the `emdash login` token has, or the `transfer:export`, `transfer:analyze`, and `transfer:execute` scopes. An `INSUFFICIENT_SCOPE` error means the token has neither. A package holds every entry and the email addresses of authors and commenters: treat it like a database backup.
|
||||
|
||||
```bash
|
||||
# Export (re-run the same command to resume after an interruption)
|
||||
npx emdash site export --url https://old.example.com --output site.emdash
|
||||
npx emdash site export --url https://old.example.com --output site.emdash --no-comments
|
||||
|
||||
# Import, step 1: upload and analyze; prints the plan and its digest
|
||||
npx emdash site import site.emdash --url https://new.example.com --analyze
|
||||
npx emdash site import site.emdash --url https://new.example.com --analyze \
|
||||
--map-principal editor@example.com=editor@example.com --use-target-title
|
||||
|
||||
# Import, step 2: execute exactly the reviewed plan
|
||||
npx emdash site import site.emdash --url https://new.example.com --plan sha256:<hex> --confirm
|
||||
|
||||
# Follow up on an import by operation id
|
||||
npx emdash site import status <operation-id> --url https://new.example.com
|
||||
npx emdash site import resume <operation-id> [site.emdash] --url https://new.example.com
|
||||
npx emdash site import receipt <operation-id> --url https://new.example.com
|
||||
|
||||
# Stop an import, or lift the write block a failed or cancelled import leaves
|
||||
# (neither deletes what the import wrote; --yes skips the prompt)
|
||||
npx emdash site import cancel <operation-id> --url https://new.example.com
|
||||
npx emdash site import abandon <operation-id> --url https://new.example.com
|
||||
```
|
||||
|
||||
Show the user the plan (differences from the source site, warnings, blockers, principal mappings) and get their confirmation before running `--confirm`; it writes to the target site and blocks other writes there until it finishes. `site import` exits `2` when the plan has blockers, and `site import status` exits `1` for an import that failed, was cancelled or abandoned, or expired. Only cancel or abandon an import when the user asks: abandoning leaves partial data on the site, which then has to be reset before another import. `--map-principal` takes `<principal id or email>=<user id, email, or none>` and is repeatable; decision flags only work with `--analyze`, and each change produces a new plan digest. The public site is not hidden during an import, so the target should stay private until the command prints a receipt with `receiptDigestValid: true`.
|
||||
|
||||
## Drafts and Publishing
|
||||
|
||||
The CLI auto-publishes on `create` and `update` by default. This means:
|
||||
|
||||
- **`create`** creates the item and immediately publishes it
|
||||
- **`update`** updates the item and publishes if a draft revision was created
|
||||
- **`get`** returns draft data if a pending draft exists (e.g. from the admin UI)
|
||||
|
||||
Use `--draft` on create/update to skip auto-publishing. Use `--published` on get to ignore pending drafts.
|
||||
|
||||
Collections that support revisions store edits as draft revisions. The CLI handles this transparently — agents don't need to know whether a collection uses revisions or not.
|
||||
|
||||
## JSON Output
|
||||
|
||||
All remote commands support `--json` for machine-readable output. It's auto-enabled when stdout is piped. `emdash site` always writes progress to stderr, so stdout holds only the JSON result; errors are `{ "error": { "code", "message" } }`.
|
||||
|
||||
```bash
|
||||
# Pipe to jq
|
||||
npx emdash content list posts --json | jq '.items[].slug'
|
||||
|
||||
# Use in scripts
|
||||
ID=$(npx emdash content create posts --data '{"title":"Hello"}' --json | jq -r '.id')
|
||||
```
|
||||
|
||||
## Editing Flow
|
||||
|
||||
For details on how content editing works — Portable Text/markdown conversion, `_rev` tokens, and raw mode — see **[EDITING-FLOW.md](./EDITING-FLOW.md)**.
|
||||
@@ -1 +0,0 @@
|
||||
../.agents/skills
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"emdash-docs": {
|
||||
"type": "http",
|
||||
"url": "https://docs.emdashcms.com/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
node_modules
|
||||
dist
|
||||
.astro
|
||||
.emdash/migrations.json
|
||||
uploads
|
||||
data.db
|
||||
.wrangler
|
||||
|
||||
# Environment / Wrangler secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.dev.vars
|
||||
.dev.vars.*
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"emdash-docs": {
|
||||
"type": "http",
|
||||
"url": "https://docs.emdashcms.com/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
-8
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"servers": {
|
||||
"emdash-docs": {
|
||||
"type": "http",
|
||||
"url": "https://docs.emdashcms.com/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
This is an EmDash site -- a CMS built on Astro with a full admin UI.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
pnpm dev # Start the Astro dev server
|
||||
npx emdash types # Regenerate TypeScript types from a running site
|
||||
```
|
||||
|
||||
The admin UI is at `http://localhost:4321/_emdash/admin`.
|
||||
|
||||
## Key Files
|
||||
|
||||
| File | Purpose |
|
||||
| ------------------------ | ---------------------------------------------------------------------------------- |
|
||||
| `astro.config.mjs` | Astro config with `emdash()` integration, database, and storage |
|
||||
| `src/live.config.ts` | EmDash loader registration (boilerplate -- don't modify) |
|
||||
| `seed/seed.json` | Schema definition + demo content (collections, fields, taxonomies, menus, widgets) |
|
||||
| `emdash-env.d.ts` | Generated types for collections (auto-regenerated on dev server start) |
|
||||
| `src/layouts/Base.astro` | Base layout with EmDash wiring (menus, search, page contributions) |
|
||||
| `src/pages/` | Astro pages -- all server-rendered |
|
||||
|
||||
## Skills
|
||||
|
||||
Agent skills are in `.agents/skills/`. Load them when working on specific tasks:
|
||||
|
||||
- **building-emdash-site** -- Querying content, rendering Portable Text, schema design, seed files, site features (menus, widgets, search, SEO, comments, bylines). Start here.
|
||||
- **creating-plugins** -- Building EmDash plugins with hooks, storage, admin UI, API routes, and Portable Text block types.
|
||||
- **emdash-cli** -- CLI commands for content management, seeding, type generation, and visual editing flow.
|
||||
|
||||
## Documentation
|
||||
|
||||
The EmDash docs are available as an MCP server at `https://docs.emdashcms.com/mcp`. When you need to verify an API, hook, config option, field type, or pattern, call `search_docs` against the live documentation rather than relying on training-data recall. The docs reflect current behaviour; assumptions may not.
|
||||
|
||||
This template ships with `.mcp.json`, `.cursor/mcp.json`, and `.vscode/mcp.json` so Claude Code, Cursor, and VS Code auto-discover the docs server. Other tools (OpenCode, Windsurf, etc.) need a manual one-time setup -- see [docs.emdashcms.com/docs-mcp](https://docs.emdashcms.com/docs-mcp).
|
||||
|
||||
## Rules
|
||||
|
||||
- All content pages must be server-rendered (`output: "server"`). No `getStaticPaths()` for CMS content.
|
||||
- Image fields are objects (`{ src, alt }`), not strings. Use `<Image image={...} />` from `"emdash/ui"`.
|
||||
- `entry.id` is the slug (for URLs). `entry.data.id` is the database ULID (for API calls like `getEntryTerms`).
|
||||
- When Astro's cache is enabled, pass content-query hints to `Astro.cache.set(cacheHint)`. Use the `WithCacheHint` variants for site settings, menus, taxonomies, and widget areas rendered by cached routes.
|
||||
- Taxonomy names in queries must match the seed's `"name"` field exactly (e.g., `"category"` not `"categories"`).
|
||||
|
||||
## This Template
|
||||
|
||||
A blog with posts, pages, categories, tags, full-text search, and RSS. Designed for personal writing, technical writing, indie newsletters, and anything where the writing is the product. Editorial-tech aesthetic: confident sans-serif, restrained accent, real article structure with bylines and reading time.
|
||||
|
||||
## Pages
|
||||
|
||||
| Page | Path | What it shows |
|
||||
| ----------- | ------------------ | ------------------------------------------------------------------------------------------------------ |
|
||||
| Home | `/` | Featured post hero (large image + excerpt), latest posts grid |
|
||||
| All posts | `/posts` | Article count, full post list with excerpts and tag chips |
|
||||
| Post detail | `/posts/[slug]` | Featured image, title, body, left meta column (authors + date), right TOC + search + categories gutter |
|
||||
| Search | `/search` | Full-text search UI |
|
||||
| Page | `/pages/[slug]` | Static page content (Portable Text) |
|
||||
| Category | `/category/[slug]` | Posts filtered by category |
|
||||
| Tag | `/tag/[slug]` | Posts filtered by tag |
|
||||
| RSS | `/rss.xml` | Generated feed |
|
||||
|
||||
## Schema
|
||||
|
||||
- `posts` collection: `title`, `featured_image`, `content` (Portable Text), `excerpt` (text).
|
||||
- `pages` collection: `title`, `content` (Portable Text). Used for `/about` etc.
|
||||
- Taxonomies: `category`, `tag`.
|
||||
- Single `primary` menu (Home, About, Posts by default).
|
||||
|
||||
Site settings have `title` and `tagline` -- both render in the header / footer.
|
||||
|
||||
## Visual character
|
||||
|
||||
Single typeface: **Inter** on `--font-body`, used for everything including headings (`--font-heading` defaults to the body face; tighter letter-spacing on h1/h2). **JetBrains Mono** on `--font-mono` for inline code and code blocks. Body and headings share the same family; weight and size carry the hierarchy (`--font-weight-heading` 600, `--font-weight-display` 700 for h1/page titles).
|
||||
|
||||
The brand colour is `#0066cc` (`--color-brand`) -- used for links, the post-card title hover, and the search input focus ring. There's also a secondary text colour (`--color-text-secondary`) and a `--color-muted` for meta info. Don't add a second accent.
|
||||
|
||||
The article layout is the standout feature: a three-column reading view with a left meta column (author bylines, date), centred 680px body column, and a right gutter for search, table of contents, and categories. Don't flatten that into one column on desktop -- the layout signals "this is something to read".
|
||||
|
||||
## Customisation
|
||||
|
||||
Design tokens live in `src/styles/tokens.css` with their default values. To restyle the site, override tokens in `src/styles/theme.css` -- declarations there are unlayered, so they always beat the `@layer base` defaults. Don't edit `tokens.css` or `Base.astro` for visual changes.
|
||||
|
||||
Colours are defined with `light-dark(<light>, <dark>)`, so each token carries both modes. Overriding with a plain colour changes light and dark at once; use `light-dark()` in the override to keep them distinct. There is no separate dark palette to maintain.
|
||||
|
||||
Webfonts are configured in `astro.config.mjs` under `fonts:`. To swap the body face, change the `name:` for the entry bound to `cssVariable: "--font-body"`. Good alternatives: Geist, IBM Plex Sans, Söhne (if you have a licence), Public Sans. If you want a serif-bodied blog, swap to a humanist serif like Source Serif, Crimson Pro, or Lora -- but then also raise `--font-size-base` to `1.0625rem` for readability. To give headings their own face (or use a system font) without touching the font pipeline, override `--font-heading` or `--font-body` in `theme.css`.
|
||||
|
||||
CSS variables worth knowing (see `tokens.css` for the full list):
|
||||
|
||||
- `--color-brand`, `--color-brand-hover`, `--color-on-brand`, `--color-brand-ring`
|
||||
- `--color-bg`, `--color-bg-subtle`, `--color-surface`, `--color-text`, `--color-text-secondary`, `--color-muted`, `--color-border`, `--color-border-subtle`
|
||||
- `--font-body`, `--font-heading`, `--font-mono`
|
||||
- `--font-weight-heading` (600) / `--font-weight-display` (700) -- heading weights; lower them if you switch to a serif
|
||||
- `--tracking-tight` / `--tracking-snug` / `--tracking-wide` / `--tracking-wider` -- letter-spacing tokens used across headings and meta labels
|
||||
- `--content-width` (680px) -- article body column
|
||||
- `--wide-width` (1200px) -- max container
|
||||
- `--gutter-width` (200px) -- right sidebar (TOC) on article pages
|
||||
- `--meta-col-width` (180px) -- left meta column on article pages
|
||||
- `--avatar-size-{xs,sm,md,lg}` -- byline avatar sizes at different scales
|
||||
|
||||
## What not to do
|
||||
|
||||
- Don't add a second accent colour or coloured section backgrounds. The page should be black, white, and one blue.
|
||||
- Don't replace Inter with a display sans (Bebas, Anton, etc.). Headings rely on weight contrast, not novelty faces.
|
||||
- Don't collapse the article gutter on desktop -- it's part of the reading experience.
|
||||
- Don't use stock blog copy ("Welcome to my blog", "Stay tuned for more"). Write a real tagline that says what this blog is about.
|
||||
- Don't seed the home page with three identical placeholder posts. If you only have one real post, show one real post.
|
||||
- Comments are enabled on posts and rendered on the post detail page. Configure moderation before publishing the site, or remove `commentsEnabled` and the comments UI together.
|
||||
@@ -1,68 +0,0 @@
|
||||
# EmDash Blog Template (Cloudflare)
|
||||
|
||||
A clean, minimal blog built with [EmDash](https://github.com/emdash-cms/emdash) and deployed on Cloudflare Workers with D1 and R2.
|
||||
|
||||
[](https://deploy.workers.cloudflare.com/?url=https://github.com/emdash-cms/templates/tree/main/blog-cloudflare)
|
||||
|
||||

|
||||
|
||||
## What's Included
|
||||
|
||||
- Featured post hero on the homepage
|
||||
- Post archive with reading time estimates
|
||||
- Category and tag archives
|
||||
- Full-text search
|
||||
- RSS feed
|
||||
- SEO metadata and JSON-LD
|
||||
- Dark/light mode
|
||||
|
||||
## Pages
|
||||
|
||||
| Page | Route |
|
||||
|---|---|
|
||||
| Homepage | `/` |
|
||||
| All posts | `/posts` |
|
||||
| Single post | `/posts/:slug` |
|
||||
| Category archive | `/category/:slug` |
|
||||
| Tag archive | `/tag/:slug` |
|
||||
| Search | `/search` |
|
||||
| Static pages | `/pages/:slug` |
|
||||
| 404 | fallback |
|
||||
|
||||
## Screenshots
|
||||
|
||||
| | Desktop | Mobile |
|
||||
|---|---|---|
|
||||
| Light |  |  |
|
||||
| Dark |  |  |
|
||||
|
||||
## Infrastructure
|
||||
|
||||
- **Runtime:** Cloudflare Workers
|
||||
- **Database:** D1
|
||||
- **Storage:** R2
|
||||
- **Framework:** Astro with `@astrojs/cloudflare`
|
||||
|
||||
## Local Development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
Open http://localhost:4321/_emdash/admin and complete the setup wizard. EmDash runs database migrations and applies the blog seed during setup. The site is available at http://localhost:4321.
|
||||
|
||||
## Deploying
|
||||
|
||||
```bash
|
||||
pnpm wrangler login
|
||||
pnpm deploy
|
||||
```
|
||||
|
||||
The first deployment provisions the named D1 database and R2 bucket from `wrangler.jsonc`. See [Deploy to Cloudflare](https://docs.emdashcms.com/deployment/cloudflare/) for production setup, or use the deploy button above.
|
||||
|
||||
## See Also
|
||||
|
||||
- [Node.js variant](../blog) -- same template using SQLite and local file storage
|
||||
- [All templates](../)
|
||||
- [EmDash documentation](https://docs.emdashcms.com/)
|
||||
@@ -1,22 +0,0 @@
|
||||
import cloudflare from "@astrojs/cloudflare";
|
||||
import react from "@astrojs/react";
|
||||
import { d1, r2 } from "@emdash-cms/cloudflare";
|
||||
import { defineConfig } from "astro/config";
|
||||
import emdash from "emdash/astro";
|
||||
|
||||
export default defineConfig({
|
||||
output: "server",
|
||||
adapter: cloudflare(),
|
||||
image: {
|
||||
layout: "constrained",
|
||||
responsiveStyles: true,
|
||||
},
|
||||
integrations: [
|
||||
react(),
|
||||
emdash({
|
||||
database: d1({ binding: "DB", session: "auto" }),
|
||||
storage: r2({ binding: "MEDIA" }),
|
||||
}),
|
||||
],
|
||||
devToolbar: { enabled: false },
|
||||
});
|
||||
Vendored
-60
@@ -1,60 +0,0 @@
|
||||
// Generated by EmDash on dev server start
|
||||
// Do not edit manually
|
||||
|
||||
/// <reference types="emdash/locals" />
|
||||
|
||||
import type { BylineSummary, ContentBylineCredit, TaxonomyTerm, PortableTextBlock } from "emdash";
|
||||
|
||||
export interface Issue {
|
||||
id: string;
|
||||
slug: string | null;
|
||||
status: string;
|
||||
title: string;
|
||||
week: string;
|
||||
dek?: string;
|
||||
body?: PortableTextBlock[];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
publishedAt: Date | null;
|
||||
byline?: BylineSummary | null;
|
||||
bylines?: ContentBylineCredit[];
|
||||
terms?: Record<string, TaxonomyTerm[]>;
|
||||
}
|
||||
|
||||
export interface Page {
|
||||
id: string;
|
||||
slug: string | null;
|
||||
status: string;
|
||||
title: string;
|
||||
content?: PortableTextBlock[];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
publishedAt: Date | null;
|
||||
byline?: BylineSummary | null;
|
||||
bylines?: ContentBylineCredit[];
|
||||
terms?: Record<string, TaxonomyTerm[]>;
|
||||
}
|
||||
|
||||
export interface Post {
|
||||
id: string;
|
||||
slug: string | null;
|
||||
status: string;
|
||||
title: string;
|
||||
featured_image?: { id: string; src?: string; alt?: string; width?: number; height?: number; filename?: string; mimeType?: string; blurhash?: string; dominantColor?: string; focalX?: number; focalY?: number; provider?: string; previewUrl?: string; meta?: Record<string, unknown>; darkVariant?: { id: string; src?: string; alt?: string; width?: number; height?: number; filename?: string; mimeType?: string; blurhash?: string; dominantColor?: string; focalX?: number; focalY?: number; provider?: string; previewUrl?: string; meta?: Record<string, unknown> } };
|
||||
content?: PortableTextBlock[];
|
||||
excerpt?: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
publishedAt: Date | null;
|
||||
byline?: BylineSummary | null;
|
||||
bylines?: ContentBylineCredit[];
|
||||
terms?: Record<string, TaxonomyTerm[]>;
|
||||
}
|
||||
|
||||
declare module "emdash" {
|
||||
interface EmDashCollections {
|
||||
issues: Issue;
|
||||
pages: Page;
|
||||
posts: Post;
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
# potluck: a few weeks of issues, sketched
|
||||
|
||||
A dry run of the zine shape (an `issues` collection, ISO-week slugs, a
|
||||
`blocks` field of typed pieces) against real material: public
|
||||
bookmarks from the diigo public cache, by `created_at`, UTC weeks.
|
||||
Descriptions in quotes are Dan's own diigo descriptions. Everything
|
||||
marked *draft* is a guess at an editorial line, for Dan to rewrite or
|
||||
cut. Sources we don't read yet (social.coop, photos, GitHub, Zotero) are
|
||||
marked as empty plates, not invented.
|
||||
|
||||
Block types used: `note` (rich text), `bookmark` (url, title, comment),
|
||||
`cluster` (a heading over several bookmarks; maybe just a `note` +
|
||||
bookmarks), `plate` (an empty slot for a source not wired yet).
|
||||
|
||||
---
|
||||
|
||||
## 2026-W38 (Sep 14–20): moving into KDE
|
||||
|
||||
**note** *draft:* The workstation moved from MATE to KDE Plasma this
|
||||
week, and the bookmarks show it.
|
||||
|
||||
**cluster: the migration**
|
||||
- **bookmark** [Plasma / PowerDevil · GitLab](https://invent.kde.org/plasma/powerdevil):
|
||||
"wake up, bldbox! oh... MATE was configured to only lock screen, not
|
||||
suspend, on idle. nice: sovereign kde.org domain vs github"
|
||||
- **bookmark** [KDE Identity](https://identity.kde.org): "in addition to
|
||||
my Ubuntu account? hm."
|
||||
- **bookmark** [Plasma 6.7](https://kde.org/announcements/plasma/6/6.7.0/)
|
||||
- **bookmark** [Making Dolphin's compact view denser (r/kde)](https://www.reddit.com/r/kde/comments/16ylic8/comment/k39subf/)
|
||||
- **bookmark** [polkit Reference Manual](https://polkit.pages.freedesktop.org/polkit/polkit.8.html),
|
||||
[Desktop Services (GNU Guix manual)](https://guix.gnu.org/manual/1.5.0/en/html_node/Desktop-Services.html)
|
||||
|
||||
**cluster: AI and the web**
|
||||
- **bookmark** ['Doom Loop': OpenAI and Microsoft admit LLMs are destroying the web (404 Media)](https://www.404media.co/doom-loop-openai-and-microsoft-admits-llms-are-destroying-the-web-and-built-on-theft/)
|
||||
- **bookmark** [OpenAI agents involved in an attack on RubyGems (The Guardian)](https://www.theguardian.com/technology/2026/sep/11/openai-agents-rubygems-malicious-packages)
|
||||
(tagged `invasive-ai`)
|
||||
- **bookmark** [The Agent Development Lifecycle on Cloudflare](https://blog.cloudflare.com/agent-development-lifecycle/),
|
||||
[Artifacts: versioned storage that speaks Git](https://blog.cloudflare.com/artifacts-git-for-agents-beta/)
|
||||
|
||||
**bookmark** [Zotero 10](https://www.zotero.org/blog/zotero-10/)
|
||||
*draft:* (bib sync, #195, gets a new target.)
|
||||
|
||||
**bookmark** [The Message from Deep Space on Steam](https://store.steampowered.com/app/4080030/The_Message_from_Deep_Space/):
|
||||
"Kyle invited me to play. Fun!"
|
||||
|
||||
**plate** social.coop posts this week · **plate** photos
|
||||
|
||||
*Left on the table:* the Costco motor-oil story, Tampermonkey, the
|
||||
inotify sysctl, the KDE screenshot how-to, Geo Tracker,
|
||||
the Gemini exporter.
|
||||
|
||||
---
|
||||
|
||||
## 2026-W39 (Sep 21–27): repair, reuse, and TV night
|
||||
|
||||
**note** *draft:* Kansas City has a whole circular-economy scene I
|
||||
hadn't been paying attention to.
|
||||
|
||||
**cluster: fix it, don't toss it**
|
||||
- **bookmark** [Repair Cafes | Re.Use.Full](https://reusefull.org/repair-cafes/)
|
||||
- **bookmark** [Un-Dumpster Day | Re.Use.Full](https://reusefull.org/un-dumpster-day/)
|
||||
- **bookmark** [Amazon Basics wireless mouse](https://www.amazon.com/dp/B005EJH6Z4):
|
||||
"middle mouse button failed" *draft:* (a repair café candidate?)
|
||||
|
||||
**bookmark** [MATE: no 26.04 release; what is the future of Ubuntu MATE?](https://discourse.ubuntu.com/t/mate-no-26-04-release-how-does-that-affect-you-and-what-is-the-future-of-ubuntu-mate/83877)
|
||||
*draft:* (So last week's move was timely.)
|
||||
|
||||
**bookmark** [We taught sqlc to invalidate our caches (exe.dev)](https://blog.exe.dev/we-taught-sqlc-to-invalidate-our-caches)
|
||||
*draft:* (Relevant: potluck's own diigo cache can't invalidate yet.)
|
||||
|
||||
**cluster: family screens**
|
||||
- **bookmark** [Critical Role](https://critrole.com)
|
||||
- **bookmark** [Chad Powers (Wikipedia)](https://en.wikipedia.org/wiki/Chad_Powers):
|
||||
"spotter: LQ - see eli manning viral"
|
||||
|
||||
**plate** social.coop · **plate** photos
|
||||
|
||||
*Left on the table:* the Spotify playlist API reference, Evergy HVAC
|
||||
discounts.
|
||||
|
||||
---
|
||||
|
||||
## 2026-W40 (Sep 28–Oct 4): co-ops, protocols, and where to host
|
||||
|
||||
**note** *draft:* A week of reading about cooperatives and the
|
||||
protocols they might run on, and about owning your own bookmarks,
|
||||
which is what this zine is made of.
|
||||
|
||||
**cluster: cooperative economics**
|
||||
- **bookmark** [co/core: an AI cooperative](https://cocore.dev) and
|
||||
[How the co/core economy is shaped, and why](https://cocore.dev/blog/token-market-design)
|
||||
- **bookmark** [Designing for the Economy of Involvement in Co-ops (MEDLab, CU Boulder)](https://www.colorado.edu/lab/medlab/2023/03/27/designing-economy-involvement-co-ops-0)
|
||||
- **bookmark** [Transkribus](https://www.transkribus.org): run by a
|
||||
cooperative
|
||||
|
||||
**cluster: own your bookmarks, AT Protocol edition**
|
||||
- **bookmark** [kipclip: own your bookmarks, a Pinboard alternative on AT Protocol](https://kipclip.com):
|
||||
"does it do annotations / highlights?"
|
||||
- **bookmark** [Semble: make sense of the web, together](https://semble.so)
|
||||
- **bookmark** [Graze: custom feed builder for Bluesky](https://www.graze.social)
|
||||
- **bookmark** [AT Protocol account recovery](https://atproto.com/guides/account-recovery),
|
||||
[First steps of the PLC organization](https://blog.plcred.org/3mwlphq42d227)
|
||||
|
||||
**cluster: where to host**
|
||||
- **bookmark** [Hetzner Storage Box](https://www.hetzner.com/storage/storage-box/),
|
||||
[Infomaniak (Wikipedia)](https://en.wikipedia.org/wiki/Infomaniak),
|
||||
[Cloudron pricing](https://www.cloudron.io/pricing.html)
|
||||
- **bookmark** [NearlyFreeSpeech.NET turns 20](https://blog.nearlyfreespeech.net/2022/01/18/nearlyfreespeech-net-turns-20-today/)
|
||||
and [automatic TLS](https://blog.nearlyfreespeech.net/2024/05/10/automatic-tls-is-now-a-thing/)
|
||||
|
||||
**bookmark** [Material Flow Analysis of discarded materials, KC metro](https://regeneration.us/material-flow-analysis-of-discarded-materials-in-the-kansas-city-metropolitan-area/)
|
||||
*draft:* (continuing W39's thread)
|
||||
|
||||
**plate** social.coop · **plate** GitHub activity (potluck itself
|
||||
started this week)
|
||||
|
||||
*Left on the table:* AgentsView, freeq, Rivet self-host, the R5contrib
|
||||
FTP index ("XcRichText-1.5.tar.Z"), the Sygil draft, the AT Protocol
|
||||
Wikipedia page.
|
||||
|
||||
---
|
||||
|
||||
## What the sketch says about the schema
|
||||
|
||||
- **Clusters happen every week.** A heading over 2–5 bookmarks is the
|
||||
natural unit, more than the lone bookmark. So either a `cluster`
|
||||
block type (heading + list of bookmarks, via a repeater), or a
|
||||
`note` block used as a heading. A repeater inside a block is
|
||||
supported; references are not, so bookmarks are copies.
|
||||
- **Threads span weeks** (KDE: W38 → W39; circular economy: W39 →
|
||||
W40). A light "continuing from W39" link is enough; no new type.
|
||||
- **"Left on the table" matters**: the editorial step is mostly
|
||||
*leaving out*. The draft generator should propose everything for
|
||||
the week and let Dan cut, not pick for him.
|
||||
- **Duplicates** (Graze twice, utm-tagged URLs) need a URL
|
||||
normalization pass before drafting.
|
||||
- **Annotations are the best commentary.** Policy (goal 1g in the
|
||||
capsite checklist): notes on public items are public too, so they're
|
||||
fair to quote; this sketch didn't use them yet.
|
||||
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"name": "potluck",
|
||||
"version": "0.0.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"emdash": {
|
||||
"label": "Blog",
|
||||
"seed": "seed/seed.json"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"build": "astro build",
|
||||
"preview": "astro preview",
|
||||
"deploy": "astro build && wrangler deploy",
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/cloudflare": "^14.3.1",
|
||||
"@astrojs/react": "^6.0.5",
|
||||
"@emdash-cms/cloudflare": "^1.0.1",
|
||||
"astro": "^7.3.2",
|
||||
"emdash": "^1.0.1",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.10",
|
||||
"@cloudflare/workers-types": "^5.20260820.1",
|
||||
"wrangler": "^4.125.0"
|
||||
},
|
||||
"packageManager": "pnpm@11.9.0+sha512.bd682d5d03fe525ef7c9fd6780c6884d1e756ac4c9c9fe00c538782824310dcf90e3ddc4f53835f06dfaebd5085e41855e0bcbb3b60de2ac5bbab89e5036f03b"
|
||||
}
|
||||
Generated
-8106
File diff suppressed because it is too large.
Load diff
@@ -1,15 +0,0 @@
|
||||
# Build scripts: allow only what each runtime needs; rest false so
|
||||
# strictDepBuilds (pnpm >=10.26 / 11) passes.
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
workerd: true
|
||||
sharp: false
|
||||
|
||||
# Supply-chain hardening: cooldown on brand-new releases (EmDash exempt)
|
||||
# and no non-registry transitive sources. (No trustPolicy: no-downgrade --
|
||||
# it trips on upstream provenance regressions we don't control.)
|
||||
minimumReleaseAge: 1440
|
||||
minimumReleaseAgeExclude:
|
||||
- emdash
|
||||
- "@emdash-cms/*"
|
||||
blockExoticSubdeps: true
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,387 +0,0 @@
|
||||
{
|
||||
"$schema": "https://emdashcms.com/seed.schema.json",
|
||||
"version": "1",
|
||||
"meta": {
|
||||
"name": "Blog Starter",
|
||||
"description": "A blog with posts and pages",
|
||||
"author": "EmDash"
|
||||
},
|
||||
"settings": {
|
||||
"title": "potluck",
|
||||
"tagline": "A weekly zine: everyone brings a dish"
|
||||
},
|
||||
"collections": [
|
||||
{
|
||||
"slug": "posts",
|
||||
"label": "Posts",
|
||||
"labelSingular": "Post",
|
||||
"urlPattern": "/posts/{slug}",
|
||||
"supports": ["drafts", "revisions", "preview", "scheduling", "search", "seo"],
|
||||
"commentsEnabled": true,
|
||||
"fields": [
|
||||
{
|
||||
"slug": "title",
|
||||
"label": "Title",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"searchable": true
|
||||
},
|
||||
{
|
||||
"slug": "featured_image",
|
||||
"label": "Featured Image",
|
||||
"type": "image"
|
||||
},
|
||||
{
|
||||
"slug": "content",
|
||||
"label": "Content",
|
||||
"type": "portableText",
|
||||
"searchable": true
|
||||
},
|
||||
{
|
||||
"slug": "excerpt",
|
||||
"label": "Excerpt",
|
||||
"type": "text"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"slug": "pages",
|
||||
"label": "Pages",
|
||||
"labelSingular": "Page",
|
||||
"urlPattern": "/pages/{slug}",
|
||||
"supports": ["drafts", "revisions", "preview", "search", "seo"],
|
||||
"fields": [
|
||||
{
|
||||
"slug": "title",
|
||||
"label": "Title",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"searchable": true
|
||||
},
|
||||
{
|
||||
"slug": "content",
|
||||
"label": "Content",
|
||||
"type": "portableText",
|
||||
"searchable": true
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"taxonomies": [
|
||||
{
|
||||
"name": "category",
|
||||
"label": "Categories",
|
||||
"labelSingular": "Category",
|
||||
"hierarchical": true,
|
||||
"collections": ["posts"],
|
||||
"terms": [
|
||||
{
|
||||
"slug": "development",
|
||||
"label": "Development"
|
||||
},
|
||||
{
|
||||
"slug": "design",
|
||||
"label": "Design"
|
||||
},
|
||||
{
|
||||
"slug": "notes",
|
||||
"label": "Notes"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "tag",
|
||||
"label": "Tags",
|
||||
"labelSingular": "Tag",
|
||||
"hierarchical": false,
|
||||
"collections": ["posts", "issues"],
|
||||
"terms": [
|
||||
{
|
||||
"slug": "webdev",
|
||||
"label": "Web Development"
|
||||
},
|
||||
{
|
||||
"slug": "opinion",
|
||||
"label": "Opinion"
|
||||
},
|
||||
{
|
||||
"slug": "tools",
|
||||
"label": "Tools"
|
||||
},
|
||||
{
|
||||
"slug": "creativity",
|
||||
"label": "Creativity"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"bylines": [
|
||||
{
|
||||
"id": "byline-editorial",
|
||||
"slug": "emdash-editorial",
|
||||
"displayName": "EmDash Editorial"
|
||||
},
|
||||
{
|
||||
"id": "byline-guest",
|
||||
"slug": "guest-contributor",
|
||||
"displayName": "Guest Contributor",
|
||||
"isGuest": true
|
||||
}
|
||||
],
|
||||
"menus": [
|
||||
{
|
||||
"name": "primary",
|
||||
"label": "Primary Navigation",
|
||||
"items": [
|
||||
{
|
||||
"type": "custom",
|
||||
"label": "Home",
|
||||
"url": "/"
|
||||
},
|
||||
{
|
||||
"type": "custom",
|
||||
"label": "About",
|
||||
"url": "/pages/about"
|
||||
},
|
||||
{
|
||||
"type": "custom",
|
||||
"label": "Issues",
|
||||
"url": "/issues"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"widgetAreas": [
|
||||
{
|
||||
"name": "sidebar",
|
||||
"label": "Sidebar",
|
||||
"description": "Widget area displayed on single post pages",
|
||||
"widgets": [
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:search",
|
||||
"title": "Search"
|
||||
},
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:categories",
|
||||
"title": "Categories"
|
||||
},
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:tags",
|
||||
"title": "Tags"
|
||||
},
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:recent-posts",
|
||||
"title": "Recent Posts",
|
||||
"settings": {
|
||||
"count": 5,
|
||||
"showDate": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "component",
|
||||
"componentId": "core:archives",
|
||||
"title": "Archives",
|
||||
"settings": {
|
||||
"type": "monthly",
|
||||
"limit": 6
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "footer",
|
||||
"label": "Footer",
|
||||
"description": "Widget area displayed in the site footer",
|
||||
"widgets": [
|
||||
{
|
||||
"type": "content",
|
||||
"title": "About",
|
||||
"content": [
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [
|
||||
{
|
||||
"_type": "span",
|
||||
"text": "A weekly zine: everyone brings a dish. Bookmarks and notes from the week, gathered and trimmed.",
|
||||
"_key": "k1"
|
||||
}
|
||||
],
|
||||
"_key": "k0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sections": [
|
||||
{
|
||||
"slug": "newsletter-signup",
|
||||
"title": "Newsletter Signup",
|
||||
"description": "A call-to-action block for newsletter subscriptions",
|
||||
"keywords": ["newsletter", "subscribe", "email", "cta"],
|
||||
"source": "theme",
|
||||
"content": [
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "h3",
|
||||
"children": [
|
||||
{
|
||||
"_type": "span",
|
||||
"text": "Stay in the loop",
|
||||
"_key": "k1"
|
||||
}
|
||||
],
|
||||
"_key": "k0"
|
||||
},
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [
|
||||
{
|
||||
"_type": "span",
|
||||
"text": "Get notified when new posts are published. No spam, unsubscribe anytime.",
|
||||
"_key": "k3"
|
||||
}
|
||||
],
|
||||
"_key": "k2"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"slug": "about-author",
|
||||
"title": "About the Author",
|
||||
"description": "Brief author bio for use in posts or pages",
|
||||
"keywords": ["author", "bio", "about"],
|
||||
"source": "theme",
|
||||
"content": [
|
||||
{
|
||||
"_type": "block",
|
||||
"style": "normal",
|
||||
"children": [
|
||||
{
|
||||
"_type": "span",
|
||||
"text": "A software developer who writes about building things on the web. Based somewhere with good coffee and reliable internet.",
|
||||
"_key": "k1"
|
||||
}
|
||||
],
|
||||
"_key": "k0"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"content": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "about",
|
||||
"slug": "about",
|
||||
"status": "published",
|
||||
"data": {
|
||||
"title": "About",
|
||||
"content": [
|
||||
{
|
||||
"_type": "block",
|
||||
"_key": "k1",
|
||||
"style": "normal",
|
||||
"markDefs": [],
|
||||
"children": [
|
||||
{
|
||||
"_type": "span",
|
||||
"_key": "k0",
|
||||
"text": "potluck is a weekly zine. Everyone brings a dish: each source contributes what it found that week, and an issue is the table they share.",
|
||||
"marks": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"_type": "block",
|
||||
"_key": "k6",
|
||||
"style": "normal",
|
||||
"markDefs": [
|
||||
{
|
||||
"_key": "k3",
|
||||
"_type": "link",
|
||||
"href": "https://www.diigo.com/user/dckc-madmode"
|
||||
}
|
||||
],
|
||||
"children": [
|
||||
{
|
||||
"_type": "span",
|
||||
"_key": "k2",
|
||||
"text": "Right now the dishes are bookmarks from ",
|
||||
"marks": []
|
||||
},
|
||||
{
|
||||
"_type": "span",
|
||||
"_key": "k4",
|
||||
"text": "diigo",
|
||||
"marks": [
|
||||
"k3"
|
||||
]
|
||||
},
|
||||
{
|
||||
"_type": "span",
|
||||
"_key": "k5",
|
||||
"text": ", with their tags. Posts from social.coop, photos, and new Zotero items are meant to join them. Each issue is a draft first: everything from the week is proposed, then trimmed by hand and given a few lines of commentary.",
|
||||
"marks": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"_type": "block",
|
||||
"_key": "k8",
|
||||
"style": "normal",
|
||||
"markDefs": [],
|
||||
"children": [
|
||||
{
|
||||
"_type": "span",
|
||||
"_key": "k7",
|
||||
"text": "The name is about cooperation without vulnerability: at a potluck you share food without letting anyone into your kitchen. The software behind it works the same way, with each source passing finished dishes rather than handing over its keys.",
|
||||
"marks": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"_type": "block",
|
||||
"_key": "kd",
|
||||
"style": "normal",
|
||||
"markDefs": [
|
||||
{
|
||||
"_key": "ka",
|
||||
"_type": "link",
|
||||
"href": "https://www.madmode.com/"
|
||||
}
|
||||
],
|
||||
"children": [
|
||||
{
|
||||
"_type": "span",
|
||||
"_key": "k9",
|
||||
"text": "potluck is a sibling of ",
|
||||
"marks": []
|
||||
},
|
||||
{
|
||||
"_type": "span",
|
||||
"_key": "kb",
|
||||
"text": "madmode.com",
|
||||
"marks": [
|
||||
"ka"
|
||||
]
|
||||
},
|
||||
{
|
||||
"_type": "span",
|
||||
"_key": "kc",
|
||||
"text": ", Dan Connolly's tinkering lab notebook.",
|
||||
"marks": []
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
---
|
||||
/**
|
||||
* Portable Text link mark for issue bodies: an off-site link is a citation,
|
||||
* marked up as an `h-cite` (name + url) so microformats parsers see each
|
||||
* bookmark; a `/tag/<tag>` link is a rel-tag `p-category` of the issue
|
||||
* (the `#` is CSS, so the category value is the bare tag); other on-site
|
||||
* and anchor links stay plain.
|
||||
*
|
||||
* @see https://microformats.org/wiki/h-cite
|
||||
* @see https://microformats.org/wiki/rel-tag
|
||||
*/
|
||||
export interface Props {
|
||||
node: { markDef: { _type: "link"; _key: string; href: string; blank?: boolean } };
|
||||
}
|
||||
|
||||
const href = Astro.props.node?.markDef?.href ?? "";
|
||||
// only these schemes become hrefs (the stored href is editor input)
|
||||
const safe = /^(https?:|mailto:|\/|#)/i.test(href) ? href : "";
|
||||
const offSite = /^https?:/i.test(safe);
|
||||
const isTag = safe.startsWith("/tag/");
|
||||
---
|
||||
|
||||
{
|
||||
offSite ? (
|
||||
<cite class="h-cite"><a class="u-url p-name" href={safe}><slot /></a></cite>
|
||||
) : isTag ? (
|
||||
<a rel="tag" class="p-category" href={safe}><slot /></a>
|
||||
) : (
|
||||
<a href={safe || undefined}><slot /></a>
|
||||
)
|
||||
}
|
||||
|
||||
<style>
|
||||
cite {
|
||||
font-style: normal;
|
||||
}
|
||||
a[rel="tag"] {
|
||||
font-size: 90%;
|
||||
}
|
||||
a[rel="tag"]::before {
|
||||
content: "#";
|
||||
}
|
||||
</style>
|
||||
@@ -1,281 +0,0 @@
|
||||
---
|
||||
import type { ContentBylineCredit, EditProxy, MediaValue } from "emdash";
|
||||
import { Image } from "emdash/ui";
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
excerpt?: string;
|
||||
featuredImage?: MediaValue | string;
|
||||
href: string;
|
||||
date?: Date;
|
||||
readingTime?: number;
|
||||
tags?: Array<{ slug: string; label: string }>;
|
||||
bylines?: ContentBylineCredit[];
|
||||
edit?: EditProxy;
|
||||
}
|
||||
|
||||
const {
|
||||
title,
|
||||
excerpt,
|
||||
featuredImage,
|
||||
href,
|
||||
date,
|
||||
readingTime,
|
||||
tags,
|
||||
bylines,
|
||||
edit,
|
||||
} = Astro.props;
|
||||
|
||||
const formattedDate = date
|
||||
? date.toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
: null;
|
||||
---
|
||||
|
||||
<article class="post-card">
|
||||
<a href={href} class="card-link">
|
||||
{
|
||||
featuredImage ? (
|
||||
<div class="card-image" {...edit?.featured_image}>
|
||||
<Image image={featuredImage} />
|
||||
</div>
|
||||
) : (
|
||||
<div class="card-placeholder" />
|
||||
)
|
||||
}
|
||||
<div class="card-body">
|
||||
<div class="card-meta">
|
||||
{
|
||||
bylines && bylines.length > 0 && (
|
||||
<>
|
||||
<div class="card-bylines">
|
||||
{bylines.slice(0, 1).map((credit) => (
|
||||
<span class="card-byline">
|
||||
{credit.byline.avatarMediaId && (
|
||||
<img
|
||||
src={`/_emdash/api/media/file/${credit.byline.avatarMediaId}`}
|
||||
alt={credit.byline.displayName}
|
||||
class="card-byline-avatar"
|
||||
/>
|
||||
)}
|
||||
<span class="card-byline-name">
|
||||
{credit.byline.displayName}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
{bylines.length > 1 && (
|
||||
<span
|
||||
class="byline-more"
|
||||
data-tooltip={bylines
|
||||
.slice(1)
|
||||
.map((c) => c.byline.displayName)
|
||||
.join(", ")}
|
||||
title={bylines
|
||||
.slice(1)
|
||||
.map((c) => c.byline.displayName)
|
||||
.join(", ")}
|
||||
tabindex="0"
|
||||
>
|
||||
+{bylines.length - 1}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{(formattedDate || readingTime) && <span class="meta-dot" />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
{formattedDate && <time>{formattedDate}</time>}
|
||||
{formattedDate && readingTime && <span class="meta-dot" />}
|
||||
{readingTime && <span>{readingTime} min</span>}
|
||||
</div>
|
||||
<h2 class="card-title" {...edit?.title}>{title}</h2>
|
||||
{excerpt && <p class="card-excerpt" {...edit?.excerpt}>{excerpt}</p>}
|
||||
</div>
|
||||
</a>
|
||||
{
|
||||
tags && tags.length > 0 && (
|
||||
<div class="card-tags">
|
||||
{tags.slice(0, 2).map((tag) => (
|
||||
<a href={`/tag/${tag.slug}`} class="card-tag">
|
||||
{tag.label}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</article>
|
||||
|
||||
<style>
|
||||
.post-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.card-link {
|
||||
display: block;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.card-image {
|
||||
aspect-ratio: 16 / 10;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--color-surface);
|
||||
margin-bottom: var(--spacing-4);
|
||||
}
|
||||
|
||||
.card-image img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.card-link:hover .card-image img {
|
||||
transform: scale(1.03);
|
||||
}
|
||||
|
||||
.card-placeholder {
|
||||
aspect-ratio: 16 / 10;
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--color-surface);
|
||||
margin-bottom: var(--spacing-4);
|
||||
}
|
||||
|
||||
.card-body {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.card-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
column-gap: var(--spacing-3);
|
||||
row-gap: 0;
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--color-muted);
|
||||
margin-bottom: var(--spacing-2);
|
||||
}
|
||||
|
||||
.card-meta time,
|
||||
.card-meta span:not(.meta-dot) {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.meta-dot {
|
||||
width: 3px;
|
||||
height: 3px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-muted);
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: var(--font-size-xl);
|
||||
font-weight: var(--font-weight-heading);
|
||||
line-height: var(--leading-snug);
|
||||
letter-spacing: var(--tracking-snug);
|
||||
margin-bottom: var(--spacing-2);
|
||||
transition: color var(--transition-fast);
|
||||
}
|
||||
|
||||
.card-link:hover .card-title {
|
||||
color: var(--color-brand);
|
||||
}
|
||||
|
||||
.card-excerpt {
|
||||
font-size: var(--font-size-base);
|
||||
line-height: var(--leading-relaxed);
|
||||
color: var(--color-text-secondary);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.card-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--spacing-2);
|
||||
margin-top: var(--spacing-3);
|
||||
}
|
||||
|
||||
.card-tag {
|
||||
display: inline-block;
|
||||
padding: var(--tag-padding-y) var(--spacing-2);
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--color-text-secondary);
|
||||
background: var(--color-surface);
|
||||
border-radius: var(--radius);
|
||||
text-decoration: none;
|
||||
transition:
|
||||
color var(--transition-fast),
|
||||
background var(--transition-fast);
|
||||
}
|
||||
|
||||
.card-tag:hover {
|
||||
color: var(--color-text);
|
||||
background: var(--color-border);
|
||||
}
|
||||
|
||||
/* Byline styles */
|
||||
.card-bylines {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.card-byline {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-1);
|
||||
}
|
||||
|
||||
.card-byline-avatar {
|
||||
width: var(--avatar-size-xs);
|
||||
height: var(--avatar-size-xs);
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.card-byline-name {
|
||||
font-weight: 500;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.byline-more {
|
||||
position: relative;
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--color-muted);
|
||||
margin-left: 2px;
|
||||
cursor: default;
|
||||
border-radius: var(--radius);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.byline-more:focus-visible {
|
||||
outline: 2px solid var(--color-brand);
|
||||
}
|
||||
|
||||
.byline-more[data-tooltip]:hover::after,
|
||||
.byline-more[data-tooltip]:focus-visible::after {
|
||||
content: attr(data-tooltip);
|
||||
position: absolute;
|
||||
bottom: calc(100% + 6px);
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
white-space: nowrap;
|
||||
background: var(--color-text);
|
||||
color: var(--color-bg);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: 400;
|
||||
padding: var(--spacing-1) var(--spacing-2);
|
||||
border-radius: var(--radius);
|
||||
pointer-events: none;
|
||||
z-index: 10;
|
||||
}
|
||||
</style>
|
||||
@@ -1,899 +0,0 @@
|
||||
---
|
||||
import { getMenuWithCacheHint, getSiteSettingsWithCacheHint } from "emdash";
|
||||
import {
|
||||
WidgetArea,
|
||||
EmDashHead,
|
||||
EmDashBodyStart,
|
||||
EmDashBodyEnd,
|
||||
} from "emdash/ui";
|
||||
import { createPublicPageContext } from "emdash/page";
|
||||
import LiveSearch from "emdash/ui/search";
|
||||
import { resolveBlogSiteIdentity } from "../utils/site-identity";
|
||||
import "../styles/tokens.css";
|
||||
import "../styles/theme.css";
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
pageTitle?: string | null;
|
||||
description?: string | null;
|
||||
image?: string | null;
|
||||
canonical?: string | null;
|
||||
robots?: string | null;
|
||||
type?: "website" | "article";
|
||||
publishedTime?: string | null;
|
||||
modifiedTime?: string | null;
|
||||
author?: string | null;
|
||||
/** Pass content reference for plugin page contributions on content pages */
|
||||
content?: { collection: string; id: string; slug?: string | null };
|
||||
}
|
||||
|
||||
const {
|
||||
title,
|
||||
pageTitle,
|
||||
description,
|
||||
image,
|
||||
canonical,
|
||||
robots,
|
||||
type = "website",
|
||||
publishedTime,
|
||||
modifiedTime,
|
||||
author,
|
||||
content,
|
||||
} = Astro.props;
|
||||
const [settingsResult, menuResult] = await Promise.all([
|
||||
getSiteSettingsWithCacheHint(),
|
||||
getMenuWithCacheHint("primary"),
|
||||
]);
|
||||
if (Astro.cache?.enabled) {
|
||||
Astro.cache.set(settingsResult.cacheHint);
|
||||
Astro.cache.set(menuResult.cacheHint);
|
||||
}
|
||||
|
||||
const { siteTitle, siteTagline, siteLogo } = resolveBlogSiteIdentity(
|
||||
settingsResult.data,
|
||||
);
|
||||
const titleIncludesSiteName =
|
||||
title === siteTitle ||
|
||||
title.endsWith(` | ${siteTitle}`) ||
|
||||
title.endsWith(` — ${siteTitle}`);
|
||||
const fullTitle = titleIncludesSiteName ? title : `${title} — ${siteTitle}`;
|
||||
|
||||
const menu = menuResult.data;
|
||||
|
||||
// Build public page context for plugin contributions
|
||||
// SEO data is passed here and rendered securely by EmDashHead
|
||||
const pageCtx = createPublicPageContext({
|
||||
Astro,
|
||||
kind: content ? "content" : "custom",
|
||||
pageType: type,
|
||||
title: fullTitle,
|
||||
pageTitle: pageTitle ?? title,
|
||||
description,
|
||||
canonical,
|
||||
image,
|
||||
content,
|
||||
seo: { ogImage: image, robots },
|
||||
articleMeta: { publishedTime, modifiedTime, author },
|
||||
siteName: siteTitle,
|
||||
});
|
||||
|
||||
// Check if user is logged in (for showing admin link)
|
||||
const isLoggedIn = !!Astro.locals.user;
|
||||
---
|
||||
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>{fullTitle}</title>
|
||||
<EmDashHead page={pageCtx} />
|
||||
<script is:inline>
|
||||
// Apply an explicit theme choice immediately to prevent flash.
|
||||
// With no cookie, color-scheme: light dark follows the OS.
|
||||
(function () {
|
||||
var row = document.cookie.split("; ").find(function (item) {
|
||||
return item.startsWith("theme=");
|
||||
});
|
||||
var theme = row ? row.slice(6) : null;
|
||||
if (theme === "dark" || theme === "light") {
|
||||
document.documentElement.classList.add(theme);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<EmDashBodyStart page={pageCtx} />
|
||||
<header class="site-header">
|
||||
<nav class="nav">
|
||||
<a href="/" class="site-title">
|
||||
{
|
||||
siteLogo ? (
|
||||
<img
|
||||
src={siteLogo.url}
|
||||
alt={siteLogo.alt || siteTitle}
|
||||
class="site-logo-img"
|
||||
/>
|
||||
) : (
|
||||
siteTitle
|
||||
)
|
||||
}
|
||||
</a>
|
||||
<div class="nav-right">
|
||||
<LiveSearch
|
||||
placeholder="Search..."
|
||||
class="site-search"
|
||||
inputClass="site-search-input"
|
||||
resultsClass="site-search-results"
|
||||
resultClass="site-search-result"
|
||||
collections={["issues", "pages"]}
|
||||
/>
|
||||
<div class="nav-links">
|
||||
{
|
||||
menu?.items.map((item) => (
|
||||
<a
|
||||
href={item.url}
|
||||
target={item.target}
|
||||
rel={
|
||||
item.target === "_blank" ? "noopener noreferrer" : undefined
|
||||
}
|
||||
>
|
||||
{item.label}
|
||||
</a>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
{
|
||||
isLoggedIn && (
|
||||
<a href="/_emdash/admin" class="nav-admin">
|
||||
Admin
|
||||
</a>
|
||||
)
|
||||
}
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<slot />
|
||||
</main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="footer-inner">
|
||||
<div class="footer-grid">
|
||||
<div class="footer-brand">
|
||||
<a href="/" class="footer-logo">
|
||||
{
|
||||
siteLogo ? (
|
||||
<img
|
||||
src={siteLogo.url}
|
||||
alt={siteLogo.alt || siteTitle}
|
||||
class="footer-logo-img"
|
||||
/>
|
||||
) : (
|
||||
siteTitle
|
||||
)
|
||||
}
|
||||
</a>
|
||||
<p class="footer-tagline">{siteTagline}</p>
|
||||
</div>
|
||||
<div class="footer-nav">
|
||||
<h2 class="footer-heading">Navigate</h2>
|
||||
<ul class="footer-links">
|
||||
{
|
||||
menu?.items.map((item) => (
|
||||
<li>
|
||||
<a
|
||||
href={item.url}
|
||||
target={item.target}
|
||||
rel={
|
||||
item.target === "_blank"
|
||||
? "noopener noreferrer"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{item.label}
|
||||
</a>
|
||||
</li>
|
||||
))
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer-nav">
|
||||
<h2 class="footer-heading">Connect</h2>
|
||||
<ul class="footer-links">
|
||||
<li><a href="/rss.xml">RSS Feed</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer-widgets-section">
|
||||
<WidgetArea name="footer" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer-bottom">
|
||||
<p class="footer-copyright">
|
||||
Powered by <a href="https://emdashcms.com">EmDash</a>
|
||||
</p>
|
||||
<div class="theme-switcher">
|
||||
<button
|
||||
type="button"
|
||||
class="theme-btn"
|
||||
data-theme="light"
|
||||
aria-label="Light mode"
|
||||
>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
><circle cx="12" cy="12" r="5"></circle><line
|
||||
x1="12"
|
||||
y1="1"
|
||||
x2="12"
|
||||
y2="3"></line><line x1="12" y1="21" x2="12" y2="23"
|
||||
></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"
|
||||
></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"
|
||||
></line><line x1="1" y1="12" x2="3" y2="12"></line><line
|
||||
x1="21"
|
||||
y1="12"
|
||||
x2="23"
|
||||
y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"
|
||||
></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"
|
||||
></line></svg
|
||||
>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="theme-btn"
|
||||
data-theme="dark"
|
||||
aria-label="Dark mode"
|
||||
>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"
|
||||
></path></svg
|
||||
>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="theme-btn"
|
||||
data-theme="system"
|
||||
aria-label="System theme"
|
||||
>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
><rect x="2" y="3" width="20" height="14" rx="2" ry="2"
|
||||
></rect><line x1="8" y1="21" x2="16" y2="21"></line><line
|
||||
x1="12"
|
||||
y1="17"
|
||||
x2="12"
|
||||
y2="21"></line></svg
|
||||
>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
// Theme switcher
|
||||
const themeBtns =
|
||||
document.querySelectorAll<HTMLButtonElement>(".theme-btn");
|
||||
const root = document.documentElement;
|
||||
|
||||
function setCookie(
|
||||
name: string,
|
||||
value: string,
|
||||
maxAge: number = 31536000,
|
||||
) {
|
||||
const secure = location.protocol === "https:" ? "; Secure" : "";
|
||||
if (value === "") {
|
||||
document.cookie = `${name}=; path=/; max-age=0; SameSite=Lax${secure}`;
|
||||
} else {
|
||||
document.cookie = `${name}=${value}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`;
|
||||
}
|
||||
}
|
||||
|
||||
function setTheme(theme: string) {
|
||||
if (theme === "system") {
|
||||
setCookie("theme", "");
|
||||
root.classList.remove("light", "dark");
|
||||
} else {
|
||||
setCookie("theme", theme);
|
||||
root.classList.remove("light", "dark");
|
||||
root.classList.add(theme);
|
||||
}
|
||||
updateActiveBtn(theme);
|
||||
}
|
||||
|
||||
function updateActiveBtn(theme: string) {
|
||||
themeBtns.forEach((btn) => {
|
||||
const active = btn.dataset.theme === theme;
|
||||
btn.classList.toggle("active", active);
|
||||
btn.setAttribute("aria-pressed", String(active));
|
||||
});
|
||||
}
|
||||
|
||||
function getStoredTheme(): string {
|
||||
const row = document.cookie
|
||||
.split("; ")
|
||||
.find((item) => item.startsWith("theme="));
|
||||
return row?.slice(6) || "system";
|
||||
}
|
||||
|
||||
// Initialize
|
||||
const storedTheme = getStoredTheme();
|
||||
setTheme(storedTheme);
|
||||
|
||||
themeBtns.forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
setTheme(btn.dataset.theme || "system");
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<style is:global>
|
||||
/*
|
||||
* Establish layer order: "base" has lower priority than unlayered
|
||||
* styles, so theme.css overrides always win regardless of source
|
||||
* order in the bundled CSS.
|
||||
*/
|
||||
@layer base;
|
||||
|
||||
@layer base {
|
||||
*:where(:not([class*="emdash"]):not([class*="ec-"])),
|
||||
*:where(:not([class*="emdash"]):not([class*="ec-"]))::before,
|
||||
*:where(:not([class*="emdash"]):not([class*="ec-"]))::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body,
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6,
|
||||
p,
|
||||
ul,
|
||||
ol,
|
||||
figure,
|
||||
blockquote,
|
||||
dl,
|
||||
dd {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
ul,
|
||||
ol {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Design tokens live in src/styles/tokens.css. Colors are
|
||||
* defined with light-dark(); these rules pin the scheme when
|
||||
* the footer switcher sets an explicit choice. With no class,
|
||||
* color-scheme: light dark follows the OS preference. The
|
||||
* @supports guard keeps the toggle from forcing dark UA form
|
||||
* controls on browsers stuck on the plain-light fallback.
|
||||
*/
|
||||
@supports (color: light-dark(#000, #fff)) {
|
||||
:root.light {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
:root.dark {
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--font-body);
|
||||
font-size: var(--font-size-base);
|
||||
line-height: var(--leading-relaxed);
|
||||
color: var(--color-text);
|
||||
background: var(--color-bg);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
a:where(:not([class*="emdash"]):not([class*="ec-"])) {
|
||||
color: var(--color-brand);
|
||||
text-decoration: none;
|
||||
transition: color var(--transition-fast);
|
||||
}
|
||||
|
||||
a:where(:not([class*="emdash"]):not([class*="ec-"])):hover {
|
||||
color: var(--color-brand-hover);
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
font-family: var(--font-heading);
|
||||
line-height: var(--leading-tight);
|
||||
font-weight: var(--font-weight-heading);
|
||||
letter-spacing: var(--tracking-snug);
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-weight: var(--font-weight-display);
|
||||
letter-spacing: var(--tracking-tight);
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: var(--color-brand);
|
||||
color: var(--color-on-brand);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
.site-header {
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
max-width: var(--wide-width);
|
||||
margin: 0 auto;
|
||||
padding: var(--spacing-4) var(--spacing-6);
|
||||
height: var(--nav-height);
|
||||
}
|
||||
|
||||
.site-title {
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
letter-spacing: var(--tracking-snug);
|
||||
}
|
||||
|
||||
.site-title:hover {
|
||||
color: var(--color-brand);
|
||||
}
|
||||
|
||||
.site-logo-img {
|
||||
height: 48px;
|
||||
width: auto;
|
||||
display: block;
|
||||
margin: -8px 0;
|
||||
}
|
||||
|
||||
.nav-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-6);
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
display: flex;
|
||||
gap: var(--spacing-5);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.nav-links a {
|
||||
text-decoration: none;
|
||||
color: var(--color-text);
|
||||
transition: color var(--transition-fast);
|
||||
}
|
||||
|
||||
.nav-links a:hover {
|
||||
color: var(--color-brand);
|
||||
}
|
||||
|
||||
.nav-admin {
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--color-text-secondary);
|
||||
text-decoration: none;
|
||||
transition: color var(--transition-fast);
|
||||
}
|
||||
|
||||
.nav-admin:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* Search styling */
|
||||
.site-search {
|
||||
position: relative;
|
||||
width: var(--search-input-width);
|
||||
--emdash-search-border-focus: var(--color-brand);
|
||||
}
|
||||
|
||||
:global(.site-search-input) {
|
||||
width: var(--search-input-width);
|
||||
padding: var(--spacing-2) var(--spacing-3);
|
||||
font-family: var(--font-body);
|
||||
font-size: var(--font-size-sm);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
transition:
|
||||
border-color var(--transition-fast),
|
||||
box-shadow var(--transition-fast);
|
||||
}
|
||||
|
||||
:global(.site-search-input)::placeholder {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
:global(.site-search-input):focus,
|
||||
:global(.site-search-input):focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--color-brand) !important;
|
||||
box-shadow: 0 0 0 3px var(--color-brand-ring);
|
||||
}
|
||||
|
||||
:global(.site-search-results) {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
right: 0;
|
||||
margin-top: var(--spacing-2);
|
||||
background: var(--color-bg);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-lg);
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
:global(.site-search-results .emdash-live-search-loading),
|
||||
:global(.site-search-results .emdash-live-search-no-results) {
|
||||
padding: var(--spacing-4);
|
||||
text-align: center;
|
||||
color: var(--color-muted);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
:global(.site-search-result) {
|
||||
display: block;
|
||||
padding: var(--spacing-3) var(--spacing-4);
|
||||
text-decoration: none;
|
||||
color: var(--color-text);
|
||||
border-bottom: 1px solid var(--color-border-subtle);
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
|
||||
:global(.site-search-result):last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
:global(.site-search-result):hover,
|
||||
:global(.site-search-result):focus,
|
||||
:global(.site-search-result.focused) {
|
||||
background: var(--color-surface);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
:global(.site-search-result .emdash-live-search-result-title) {
|
||||
display: block;
|
||||
font-weight: 500;
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
:global(.site-search-result .emdash-live-search-result-collection) {
|
||||
display: block;
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--color-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--tracking-wide);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
:global(.site-search-result .emdash-live-search-result-snippet) {
|
||||
display: block;
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--color-muted);
|
||||
margin-top: var(--spacing-1);
|
||||
line-height: var(--leading-snug);
|
||||
}
|
||||
|
||||
:global(.site-search-result .emdash-live-search-result-snippet mark) {
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
main {
|
||||
min-height: calc(100vh - var(--nav-height) - 300px);
|
||||
}
|
||||
|
||||
/* Footer */
|
||||
.site-footer {
|
||||
background: var(--color-bg-subtle);
|
||||
border-top: 1px solid var(--color-border-subtle);
|
||||
}
|
||||
|
||||
.footer-inner {
|
||||
max-width: var(--wide-width);
|
||||
margin: 0 auto;
|
||||
padding: var(--spacing-16) var(--spacing-6) var(--spacing-8);
|
||||
}
|
||||
|
||||
.footer-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr 1fr 1fr;
|
||||
gap: var(--spacing-12);
|
||||
margin-bottom: var(--spacing-12);
|
||||
}
|
||||
|
||||
.footer-brand {
|
||||
max-width: 280px;
|
||||
}
|
||||
|
||||
.footer-logo {
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
letter-spacing: var(--tracking-snug);
|
||||
}
|
||||
|
||||
.footer-logo-img {
|
||||
height: 24px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.footer-tagline {
|
||||
margin-top: var(--spacing-3);
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--color-muted);
|
||||
line-height: var(--leading-relaxed);
|
||||
}
|
||||
|
||||
.footer-nav {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.footer-heading {
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--tracking-wider);
|
||||
color: var(--color-muted);
|
||||
margin-bottom: var(--spacing-4);
|
||||
}
|
||||
|
||||
.footer-links {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.footer-links li {
|
||||
margin-bottom: var(--spacing-2);
|
||||
}
|
||||
|
||||
.footer-links a {
|
||||
color: var(--color-text-secondary);
|
||||
text-decoration: none;
|
||||
font-size: var(--font-size-sm);
|
||||
transition: color var(--transition-fast);
|
||||
}
|
||||
|
||||
.footer-links a:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.footer-widgets-section :global(.widget-area) {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.footer-widgets-section :global(.widget) {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.footer-widgets-section :global(.widget__title) {
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--tracking-wider);
|
||||
color: var(--color-muted);
|
||||
margin-bottom: var(--spacing-4);
|
||||
}
|
||||
|
||||
.footer-widgets-section :global(.widget__content) {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-sm);
|
||||
line-height: var(--leading-relaxed);
|
||||
}
|
||||
|
||||
.footer-bottom {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-top: var(--spacing-6);
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.footer-copyright {
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.footer-copyright a {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
/* Theme switcher */
|
||||
.theme-switcher {
|
||||
display: flex;
|
||||
gap: var(--spacing-1);
|
||||
padding: var(--spacing-1);
|
||||
background: var(--color-surface);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.theme-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 28px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--color-muted);
|
||||
border-radius: var(--radius);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.theme-btn:hover {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.theme-btn.active {
|
||||
background: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
.theme-btn svg {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.footer-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--spacing-8);
|
||||
}
|
||||
|
||||
.footer-brand {
|
||||
grid-column: span 2;
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.site-header {
|
||||
position: relative;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
height: auto;
|
||||
column-gap: var(--spacing-3);
|
||||
row-gap: var(--spacing-2);
|
||||
padding: var(--spacing-3) var(--spacing-4);
|
||||
}
|
||||
|
||||
.site-title {
|
||||
grid-column: 1;
|
||||
grid-row: 1;
|
||||
font-size: var(--font-size-base);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.nav-right {
|
||||
grid-column: 1 / -1;
|
||||
grid-row: 2;
|
||||
display: grid;
|
||||
row-gap: var(--spacing-2);
|
||||
}
|
||||
|
||||
.site-search {
|
||||
grid-column: 1;
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
:global(.site-search-input) {
|
||||
width: 100% !important;
|
||||
padding: var(--spacing-1) var(--spacing-2) !important;
|
||||
font-size: var(--font-size-sm) !important;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
grid-column: 1;
|
||||
display: flex;
|
||||
column-gap: var(--spacing-3);
|
||||
row-gap: var(--spacing-1);
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.nav-admin {
|
||||
grid-column: 2;
|
||||
grid-row: 1;
|
||||
justify-self: end;
|
||||
font-size: var(--font-size-xs);
|
||||
margin-inline-start: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.footer-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.footer-brand {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
.footer-bottom {
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-4);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.footer-controls {
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// ⌘K / Ctrl+K to focus search
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === "k") {
|
||||
e.preventDefault();
|
||||
const searchInput = document.querySelector(
|
||||
".site-search-input",
|
||||
) as HTMLInputElement;
|
||||
if (searchInput) {
|
||||
searchInput.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<EmDashBodyEnd page={pageCtx} />
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,13 +0,0 @@
|
||||
/**
|
||||
* EmDash Live Content Collections
|
||||
*
|
||||
* Defines the _emdash collection that handles all content types from the database.
|
||||
* Query specific types using getEmDashCollection() and getEmDashEntry().
|
||||
*/
|
||||
|
||||
import { defineLiveCollection } from "astro:content";
|
||||
import { emdashLoader } from "emdash/runtime";
|
||||
|
||||
export const collections = {
|
||||
_emdash: defineLiveCollection({ loader: emdashLoader() }),
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
---
|
||||
import Base from "../layouts/Base.astro";
|
||||
---
|
||||
|
||||
<Base title="Page not found">
|
||||
<div class="not-found">
|
||||
<h1>404</h1>
|
||||
<p>The page you're looking for doesn't exist.</p>
|
||||
<a href="/">Go back home</a>
|
||||
</div>
|
||||
</Base>
|
||||
|
||||
<style>
|
||||
.not-found {
|
||||
text-align: center;
|
||||
padding: var(--spacing-24) var(--spacing-6);
|
||||
}
|
||||
|
||||
.not-found h1 {
|
||||
font-size: var(--font-size-5xl);
|
||||
margin-bottom: var(--spacing-2);
|
||||
color: var(--color-border);
|
||||
}
|
||||
|
||||
.not-found p {
|
||||
color: var(--color-muted);
|
||||
margin-bottom: var(--spacing-6);
|
||||
}
|
||||
|
||||
.not-found a {
|
||||
color: var(--color-text);
|
||||
}
|
||||
</style>
|
||||
@@ -1,146 +0,0 @@
|
||||
---
|
||||
import {
|
||||
getTaxonomyTermsWithCacheHint,
|
||||
getEmDashCollection,
|
||||
getTermsForEntries,
|
||||
decodeSlug,
|
||||
} from "emdash";
|
||||
import Base from "../../layouts/Base.astro";
|
||||
import PostCard from "../../components/PostCard.astro";
|
||||
import { getReadingTime } from "../../utils/reading-time";
|
||||
|
||||
const slug = decodeSlug(Astro.params.slug);
|
||||
const termsResult = await getTaxonomyTermsWithCacheHint("category", {
|
||||
includeCounts: false,
|
||||
});
|
||||
const term = slug ? termsResult.data.find((item) => item.slug === slug) : null;
|
||||
|
||||
if (!term) {
|
||||
return Astro.redirect("/404");
|
||||
}
|
||||
|
||||
const cursor = Astro.url.searchParams.get("cursor") || undefined;
|
||||
const {
|
||||
entries: posts,
|
||||
cacheHint,
|
||||
nextCursor,
|
||||
} = await getEmDashCollection("posts", {
|
||||
where: { category: term.slug },
|
||||
orderBy: { published_at: "desc" },
|
||||
limit: 20,
|
||||
cursor,
|
||||
});
|
||||
|
||||
if (Astro.cache?.enabled) {
|
||||
Astro.cache.set(termsResult.cacheHint);
|
||||
Astro.cache.set(cacheHint);
|
||||
}
|
||||
|
||||
// Single batched query for tags on every post in this category, rather
|
||||
// than calling getEntryTerms() per post (which would be one round-trip
|
||||
// per post).
|
||||
const tagsByEntry = await getTermsForEntries(
|
||||
"posts",
|
||||
posts.map((p) => p.data.id),
|
||||
"tag",
|
||||
);
|
||||
const filteredPosts = posts.map((post) => ({
|
||||
post,
|
||||
tags: tagsByEntry.get(post.data.id) ?? [],
|
||||
}));
|
||||
---
|
||||
|
||||
<Base title={`${term.label} posts`} description={`All posts in ${term.label}`}>
|
||||
<section class="archive-section">
|
||||
<header class="archive-header">
|
||||
<span class="archive-label">Category</span>
|
||||
<h1 class="archive-title">{term.label}</h1>
|
||||
</header>
|
||||
|
||||
{
|
||||
filteredPosts.length === 0 ? (
|
||||
<p class="no-posts">No posts in this category yet.</p>
|
||||
) : (
|
||||
<div class="posts-grid">
|
||||
{filteredPosts.map(({ post, tags }) => (
|
||||
<PostCard
|
||||
title={post.data.title}
|
||||
excerpt={post.data.excerpt}
|
||||
featuredImage={post.data.featured_image}
|
||||
href={`/posts/${post.id}`}
|
||||
date={post.data.publishedAt ?? undefined}
|
||||
readingTime={getReadingTime(post.data.content)}
|
||||
tags={tags.map((t) => ({ slug: t.slug, label: t.label }))}
|
||||
edit={post.edit}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<nav class="pagination" aria-label="Pagination">
|
||||
{cursor && <a href={`/category/${term.slug}`}>First page</a>}
|
||||
{
|
||||
nextCursor && (
|
||||
<a
|
||||
href={`/category/${term.slug}?cursor=${encodeURIComponent(nextCursor)}`}
|
||||
>
|
||||
Next page
|
||||
</a>
|
||||
)
|
||||
}
|
||||
</nav>
|
||||
</section>
|
||||
</Base>
|
||||
|
||||
<style>
|
||||
.archive-section {
|
||||
max-width: var(--wide-width);
|
||||
margin: 0 auto;
|
||||
padding: var(--spacing-12) var(--spacing-6);
|
||||
}
|
||||
|
||||
.archive-header {
|
||||
margin-bottom: var(--spacing-12);
|
||||
padding-bottom: var(--spacing-8);
|
||||
border-bottom: 1px solid var(--color-border-subtle);
|
||||
}
|
||||
|
||||
.archive-label {
|
||||
display: block;
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: 500;
|
||||
color: var(--color-brand);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--tracking-wider);
|
||||
margin-bottom: var(--spacing-2);
|
||||
}
|
||||
|
||||
.archive-title {
|
||||
font-size: var(--font-size-4xl);
|
||||
font-weight: var(--font-weight-display);
|
||||
letter-spacing: var(--tracking-tight);
|
||||
margin-bottom: var(--spacing-2);
|
||||
}
|
||||
|
||||
.posts-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: var(--spacing-12) var(--spacing-8);
|
||||
}
|
||||
|
||||
.no-posts {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.posts-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.posts-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,48 +0,0 @@
|
||||
---
|
||||
import { getEmDashCollection } from "emdash";
|
||||
import Base from "../layouts/Base.astro";
|
||||
|
||||
const { entries: issues, cacheHint } = await getEmDashCollection("issues", {
|
||||
orderBy: { published_at: "desc" },
|
||||
limit: 12,
|
||||
});
|
||||
|
||||
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
|
||||
---
|
||||
|
||||
<Base title="potluck" description="A weekly zine: everyone brings a dish">
|
||||
<div class="column">
|
||||
<h1>potluck</h1>
|
||||
<p>A weekly zine: everyone brings a dish.</p>
|
||||
{
|
||||
issues.length === 0 ? (
|
||||
<p>No issues yet.</p>
|
||||
) : (
|
||||
<ul class="h-feed">
|
||||
{issues.map((issue) => (
|
||||
<li class="h-entry">
|
||||
<span class="week">{issue.data.week}</span>{" "}
|
||||
<a class="u-url p-name" href={`/issues/${issue.id}`}>{issue.data.title}</a>
|
||||
{issue.data.dek && <>: <span class="p-summary">{issue.data.dek}</span></>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
<p><a href="/issues">all issues</a></p>
|
||||
</div>
|
||||
</Base>
|
||||
|
||||
<style>
|
||||
h1,
|
||||
p,
|
||||
ul {
|
||||
margin-block: 1em;
|
||||
}
|
||||
ul {
|
||||
padding-inline-start: 1.5em;
|
||||
}
|
||||
.week {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
</style>
|
||||
@@ -1,59 +0,0 @@
|
||||
---
|
||||
import { getEmDashEntry, decodeSlug } from "emdash";
|
||||
import { PortableText } from "emdash/ui";
|
||||
import Base from "../../layouts/Base.astro";
|
||||
import CiteLink from "../../components/CiteLink.astro";
|
||||
|
||||
const slug = decodeSlug(Astro.params.slug);
|
||||
if (!slug) return Astro.redirect("/404");
|
||||
|
||||
const { entry: issue, cacheHint } = await getEmDashEntry("issues", slug);
|
||||
if (!issue) return Astro.redirect("/404");
|
||||
|
||||
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
|
||||
|
||||
const published = issue.data.publishedAt;
|
||||
---
|
||||
|
||||
<Base
|
||||
title={issue.data.title}
|
||||
description={issue.data.dek}
|
||||
type="article"
|
||||
publishedTime={published?.toISOString()}
|
||||
content={{ collection: "issues", id: issue.data.id, slug: issue.id }}
|
||||
>
|
||||
<div class="column">
|
||||
<article class="issue h-entry">
|
||||
<header>
|
||||
<p class="week">
|
||||
<a class="u-url" href={`/issues/${issue.id}`}>{issue.data.week}</a>
|
||||
{published && <> · <time class="dt-published" datetime={published.toISOString()}>{published.toISOString().slice(0, 10)}</time></>}
|
||||
</p>
|
||||
<h1 class="p-name">{issue.data.title}</h1>
|
||||
{issue.data.dek && <p class="p-summary"><i>{issue.data.dek}</i></p>}
|
||||
</header>
|
||||
<div class="e-content">
|
||||
<PortableText value={issue.data.body ?? []} components={{ mark: { link: CiteLink } }} />
|
||||
</div>
|
||||
<footer><a href="/issues">all issues</a></footer>
|
||||
</article>
|
||||
</div>
|
||||
</Base>
|
||||
|
||||
<style>
|
||||
.issue :global(h1),
|
||||
.issue :global(h2),
|
||||
.issue :global(p),
|
||||
.issue :global(ul) {
|
||||
margin-block: 0.75em;
|
||||
}
|
||||
.issue :global(h2) {
|
||||
margin-block-start: 1.5em;
|
||||
}
|
||||
.issue :global(ul) {
|
||||
padding-inline-start: 1.5em;
|
||||
}
|
||||
.week {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
</style>
|
||||
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user