From 7d6b0f8fadd8b7eafa7d1f2e49829e96258b3383 Mon Sep 17 00:00:00 2001
From: "Fabian @ Blax Software"
Date: Mon, 26 Oct 2026 18:14:46 +0100
Subject: [PATCH 1/2] A public library of components: publish yours, add
everybody's
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
"Publish to the library…" in the menu on a circuit's name (or Space)
sends the component with every component it uses and their connector
types, under your leaderboard name. The server checks it like any
project, refuses what is missing, inside itself, nested too deep or too
big to run, and counts its transistors and pins itself. Publishing again
from the same browser makes the next version of the same entry; only that
browser holds the entry's key, so only it can update or remove it.
Challenge circuits and puzzle solutions stay private.
The Library (Components in the bottom bar, Space, the main menu) lists
every entry, newest first, searchable by name, description and author,
with a picture of its box, its transistors, pins and what comes along.
Add brings an entry into the open project and starts placing it: what the
project has in exactly that form already is used as it is, the rest comes
with new ids, a taken name gets a number, connector types join one with
the same lines. The This panel says where a component came from and
offers a newer version, which replaces it in place. A campaign only adds
what is built from parts it has earned, and its challenges take nothing
from the library.
Components keep an optional "from" mark; projects without it load and
compute as before.
Co-Authored-By: Claude Opus 5.5
---
README.md | 6 +
app/assets/css/main.css | 117 ++++++
app/components/editor/App.vue | 2 +
app/components/editor/BottomBar.vue | 1 +
app/components/editor/CircuitPane.vue | 33 +-
app/components/editor/Help.vue | 1 +
app/components/editor/LibraryDialog.vue | 173 +++++++++
.../editor/LibraryPublishDialog.vue | 137 +++++++
app/components/editor/MainMenu.vue | 7 +
app/components/editor/QuickAdd.vue | 17 +
app/components/editor/Toolbar.vue | 7 +
app/composables/useEditor.ts | 139 +++++++-
app/composables/usePlace.ts | 2 +-
app/lib/logic/compile.ts | 2 +-
app/lib/logic/library.ts | 323 +++++++++++++++++
app/lib/logic/ops.ts | 1 +
app/lib/logic/project.ts | 12 +
app/lib/logic/storage.ts | 27 ++
app/lib/logic/types.ts | 13 +
server/api/library/[id].delete.ts | 14 +
server/api/library/[id].get.ts | 8 +
server/api/library/[id].put.ts | 19 +
server/api/library/index.get.ts | 9 +
server/api/library/index.post.ts | 24 ++
server/plugins/storage.ts | 2 +-
server/utils/library.ts | 70 ++++
tests/library-api.test.ts | 95 +++++
tests/library.test.ts | 335 ++++++++++++++++++
28 files changed, 1587 insertions(+), 9 deletions(-)
create mode 100644 app/components/editor/LibraryDialog.vue
create mode 100644 app/components/editor/LibraryPublishDialog.vue
create mode 100644 app/lib/logic/library.ts
create mode 100644 server/api/library/[id].delete.ts
create mode 100644 server/api/library/[id].get.ts
create mode 100644 server/api/library/[id].put.ts
create mode 100644 server/api/library/index.get.ts
create mode 100644 server/api/library/index.post.ts
create mode 100644 server/utils/library.ts
create mode 100644 tests/library-api.test.ts
create mode 100644 tests/library.test.ts
diff --git a/README.md b/README.md
index f5f4f59..d3aa84e 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)).
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
+- Library: everyone's published components in one public list (bottom bar → Components → Library, Space, or the main menu), searchable by name, description and author, each with its transistors, pins and what it uses. "Publish to the library…" in the menu on a circuit's name sends it with every component it uses and their connector types, under your leaderboard name; the server checks it like any project and counts transistors and pins itself. Publishing again from the same browser makes the next version of the same entry; only that browser has the entry's edit key, so only it can update or remove it. "Add" brings an entry into the open project and starts placing it: what the project has in exactly that form already is used as it is, the rest comes with new ids (a name that is taken gets a number) and connector types join one with the same lines. The This panel says where a component came from and offers a newer version, which replaces it in place. Challenge circuits and puzzle solutions are never published. A campaign can only add what is built from parts it has earned, and its challenges take none of it: they are solved with your own work. Logic in [app/lib/logic/library.ts](app/lib/logic/library.ts).
- Sound (speaker in the top bar; volume and clock ticks in Settings, the gear in the top bar): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it.
- Cables: a bundle gathers 2 to 32 wires into one cable, a split fans it out again in the same order; one bundle can feed several splits. Select the wires (a box across them, or Shift + click) and press "Bundle into cable" or Ctrl+G: the cable starts right after the sources on their middle row and ends right before the targets on theirs, so the wires keep running as they did (backwards too); an end steps aside when another part is in the way. "Place the ends yourself…" (Ctrl+Shift+G) lets you click where it starts and ends, with a preview; Esc cancels. "Unlink all" on a bundle or split removes only the wires going in or out; the cable stays. Drag the bundle and split later to move the ends. Up to 16 wires, the cable is drawn as a ribbon: each wire is its own thin line inside, in its own colour, lit while it carries a 1. The sleeve starts neutral and gets its own colour (cable or bundle/split settings). "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
@@ -51,6 +52,7 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout).
+- `library.ts` gathers a component with everything it uses for the public library, checks what comes from outside and adds entries to a project (shared with the server, [server/api/library/](server/api/library/)).
- `progress.ts` holds the campaign rules; `puzzles.ts` makes, checks and scores puzzles and generates the weekly one (shared with the server, [server/api/puzzles/](server/api/puzzles/), storage in `data/puzzles`).
- `cables.ts` bundles wires into cables (ends where you click, or next to sources and targets), takes them apart again, and lays out the ribbon lines (`offsetPath`, `ribbon`).
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
@@ -62,6 +64,10 @@ The editor UI is in [app/components/editor/](app/components/editor/) with state
[server/api/p/](server/api/p/): `POST /api/p` stores a project and returns `{ id, key }`; `GET /api/p/:id` reads it; `PUT /api/p/:id` with header `x-edit-key` replaces it. Only a SHA-256 of the key is stored. Each link is one JSON file in `data/shares/` (Nitro fs storage). Limits: 2 MB and 100,000 nodes per project, 30 new links and 600 saves per IP per 10 minutes (in memory). The edit key lives only in the creator's browser (project index in localStorage), never in exported files.
+## Library
+
+[server/api/library/](server/api/library/): `POST /api/library` publishes `{ player, root, components, connectors }` and returns `{ id, key, version }`; `PUT /api/library/:id` with header `x-edit-key` publishes the next version; `DELETE /api/library/:id` with the key takes it out. `GET /api/library?q=` lists every entry, newest first, narrowed to those with every word in name, description, group or author; `GET /api/library/:id` returns one with its components (`?meta`: without). Each entry is one JSON file in `data/library/entries/`, plus `data/library/index` for the list (both in the daily backup). Only a SHA-256 of the key is stored; authors show by their leaderboard name, never by their player id. Limits: 1 MB per entry, 30 publishes per IP per 10 minutes, 20,000 entries.
+
## Accounts
[server/api/auth/](server/api/auth/) (register, login, logout, me, password, delete) and [server/api/me/projects/](server/api/me/projects/) (list, get, put, delete). Passwords are hashed with scrypt; the session is a random token in an httpOnly, SameSite=Lax cookie, stored server-side as a SHA-256. API calls that change something are refused when their Origin is another site. Storage: `data/users`, `data/sessions`, `data/accounts//` with an index (revision per project, deletions for a year), one file per project, and savegames in `h//`. Each save sends the revision it started from; a mismatch answers 409 and the browser keeps the other version as a copy. Limits: 1000 projects and 100 MB per account, 2 MB per project, login 20 tries per 10 minutes per IP, 10 new accounts per hour per IP.
diff --git a/app/assets/css/main.css b/app/assets/css/main.css
index 690fa0b..a338339 100644
--- a/app/assets/css/main.css
+++ b/app/assets/css/main.css
@@ -3362,6 +3362,123 @@ kbd {
color: var(--muted);
}
+/* ── Library: components everyone published ─────────────────────── */
+.modal.library-modal {
+ width: min(720px, 100%);
+}
+
+.library-modal .search.part-search {
+ margin: 12px 0 4px;
+}
+
+.lib-list {
+ display: grid;
+ gap: 6px;
+ margin-top: 10px;
+}
+
+.lib-entry {
+ display: grid;
+ grid-template-columns: 56px minmax(0, 1fr) auto;
+ gap: 12px;
+ align-items: start;
+ padding: 10px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--panel-2);
+}
+
+.lib-thumb {
+ width: 56px;
+ height: 56px;
+}
+
+.lib-thumb rect {
+ fill: var(--chip);
+ stroke: var(--chip-stroke);
+ stroke-width: 0.12;
+}
+
+.lib-thumb line {
+ stroke: var(--chip-stroke);
+ stroke-width: 0.12;
+}
+
+.lib-title {
+ display: flex;
+ align-items: baseline;
+ min-width: 0;
+ font-weight: 600;
+}
+
+.lib-by,
+.lib-stats {
+ font-size: 12px;
+ color: var(--muted);
+}
+
+.lib-desc {
+ display: -webkit-box;
+ margin-top: 4px;
+ overflow: hidden;
+ font-size: 12.5px;
+ line-height: 1.45;
+ color: #c3ccd6;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+}
+
+.lib-stats {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 12px;
+ margin-top: 6px;
+ font-family: var(--font-mono);
+ font-size: 11px;
+}
+
+.lib-lock {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ margin-top: 6px;
+ font-size: 12px;
+ color: #e8a23a;
+}
+
+.lib-actions {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 6px;
+}
+
+@media (max-width: 560px) {
+ .lib-entry {
+ grid-template-columns: 40px minmax(0, 1fr);
+ }
+
+ .lib-thumb {
+ width: 40px;
+ height: 40px;
+ }
+
+ .lib-actions {
+ grid-column: 1 / -1;
+ flex-direction: row;
+ }
+}
+
+/* A component from the library, in the This panel. */
+.lib-origin {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: -6px 0 12px;
+ font-size: 12px;
+ color: var(--muted);
+}
+
/* ── Face designer ──────────────────────────────────────────────── */
.modal.face-modal {
width: min(900px, 100%);
diff --git a/app/components/editor/App.vue b/app/components/editor/App.vue
index db4cc7f..56a280c 100644
--- a/app/components/editor/App.vue
+++ b/app/components/editor/App.vue
@@ -81,5 +81,7 @@ watch(
+
+
diff --git a/app/components/editor/BottomBar.vue b/app/components/editor/BottomBar.vue
index 44951cc..aac7968 100644
--- a/app/components/editor/BottomBar.vue
+++ b/app/components/editor/BottomBar.vue
@@ -320,6 +320,7 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))
New component
Examples
+ Library
diff --git a/app/components/editor/CircuitPane.vue b/app/components/editor/CircuitPane.vue
index 2130691..0b18a77 100644
--- a/app/components/editor/CircuitPane.vue
+++ b/app/components/editor/CircuitPane.vue
@@ -1,6 +1,7 @@
+
+
+
+
+
+
Library
+
+
+
+ Components everyone published. Add one to "{{ ed.project.value.name }}": it comes with every component it uses, ready to place. To publish your own,
+ open it and use the menu on its name.
+
+
+
+
+
+
+ In a campaign you can add what is built from parts you have earned. Challenges are still yours to solve: nothing from the library goes into them.
+
+
{{ error }}
+
+
{{ error ? '' : 'Loading…' }}
+
+ {{ query.trim() ? `Nothing called "${query.trim()}" yet.` : 'Nothing published yet. Be the first: open a component and publish it from the menu on its name.' }}
+
+
+
The newest {{ entries.length }} of {{ total }}. Search to find the others.
+
+
+
diff --git a/app/components/editor/LibraryPublishDialog.vue b/app/components/editor/LibraryPublishDialog.vue
new file mode 100644
index 0000000..fbd6de9
--- /dev/null
+++ b/app/components/editor/LibraryPublishDialog.vue
@@ -0,0 +1,137 @@
+
+
+
+
+
+
+
{{ own ? 'Update in the library' : 'Publish to the library' }}
+
+
+
+
+
+ It goes up as the next version of your entry; projects that added it before are offered the update.
+ Everyone can find it in the library and add it to their projects, together with everything it uses.
+ Only this browser can update or remove it later.
+
+
+ Name
+
+
+
+ Description
+
+
+
+ Your name, also on the leaderboards
+
+
+ {{ pins.inputs.length }} in, {{ pins.outputs.length }} out, {{ shortCount(ed.transistors(def.id)) }} transistors. {{ along.text }}
+ {{ problem }}
+ {{ error }}
+
+
+ {{ busy ? 'Publishing…' : own ? 'Publish new version' : 'Publish' }}
+
+
+ {{ confirmRemove ? 'Remove from the library?' : 'Remove from the library' }}
+
+
+
+
+
+
+
+ "{{ def.name }}" is in the library as version {{ done.version }}. Everyone can find it and add it to their projects.
+
+
+ Open the library
+ Done
+
+
+
+
+
diff --git a/app/components/editor/MainMenu.vue b/app/components/editor/MainMenu.vue
index 03c5801..5e421c3 100644
--- a/app/components/editor/MainMenu.vue
+++ b/app/components/editor/MainMenu.vue
@@ -93,6 +93,13 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
+
+
+
+ Library
+ Components everyone published, to add to your project
+
+
Settings
diff --git a/app/components/editor/QuickAdd.vue b/app/components/editor/QuickAdd.vue
index a43ab8d..3a0ae49 100644
--- a/app/components/editor/QuickAdd.vue
+++ b/app/components/editor/QuickAdd.vue
@@ -43,6 +43,23 @@ const ACTIONS: Action[] = [
{ id: 'tidy', label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', aka: 'wires clean route layout', when: () => ed.def.value.wires.length > 0, run: () => ed.tidyAll() },
{ id: 'tidy-all', label: 'Tidy every circuit', icon: 'lucide:sparkles', aka: 'wires clean route layout all components', run: () => ed.tidyEverything() },
{ id: 'examples', label: 'Add example parts', icon: 'lucide:book-open', aka: 'library not and or adder counter', run: () => ed.loadExamples() },
+ { id: 'library', label: 'Library: components everyone published', icon: 'lucide:library-big', aka: 'public shared community download import browse', run: () => (ed.dialog.value = 'library') },
+ {
+ id: 'lib-publish',
+ label: 'Publish to the library',
+ icon: 'lucide:book-up',
+ aka: 'share upload public community',
+ when: () => !ed.libraryProblem.value && !ed.ownEntry(ed.def.value),
+ run: () => (ed.dialog.value = 'library-publish'),
+ },
+ {
+ id: 'lib-update',
+ label: 'Update in the library',
+ icon: 'lucide:book-up',
+ aka: 'publish share upload new version public',
+ when: () => !ed.libraryProblem.value && !!ed.ownEntry(ed.def.value),
+ run: () => (ed.dialog.value = 'library-publish'),
+ },
{ id: 'connector', label: 'New connector type', icon: 'lucide:plug', aka: 'cable hdmi rj45 bus port', when: () => ed.canPlaceKind('portin'), run: () => ed.addConnector() },
{ id: 'undo', label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', when: () => ed.canUndo.value, run: () => ed.undo() },
{ id: 'print', label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', aka: 'sheet export', run: () => ed.exportSheet('print') },
diff --git a/app/components/editor/Toolbar.vue b/app/components/editor/Toolbar.vue
index 39c2a01..b777cc4 100644
--- a/app/components/editor/Toolbar.vue
+++ b/app/components/editor/Toolbar.vue
@@ -60,6 +60,13 @@ const circuitEntries = computed(() => {
{ label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: empty, run: () => ed.exportSheet('print') },
{ label: 'Export as SVG', icon: 'lucide:file-image', disabled: empty, run: () => ed.exportSheet('svg') },
{ label: 'Publish as a puzzle…', icon: 'lucide:puzzle', disabled: !!ed.task.value || empty, run: () => (ed.dialog.value = 'publish') },
+ {
+ label: ed.ownEntry(d) ? 'Update in the library…' : 'Publish to the library…',
+ icon: 'lucide:book-up',
+ disabled: !!ed.task.value || empty,
+ note: ed.task.value ? 'challenges stay private' : undefined,
+ run: () => (ed.dialog.value = 'library-publish'),
+ },
]
})
diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts
index acf6975..07b6077 100644
--- a/app/composables/useEditor.ts
+++ b/app/composables/useEditor.ts
@@ -24,6 +24,7 @@ import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch'
+import { cleanBundle, closure, importBundle, kindsIn, LIBRARY_LIMITS, libraryBundle, lockedKinds, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library'
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
import { chipPins, MAX_BITS, panelOffsets, pinKindOf, shapeOf, type Pt } from '~/lib/logic/geometry'
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
@@ -58,6 +59,7 @@ import { Simulator } from '~/lib/logic/sim'
import {
cachedAccount,
currentId,
+ libraryKeys,
listProjects,
loadProject,
migrateLegacy,
@@ -68,11 +70,12 @@ import {
saveProject,
setCachedAccount,
setCurrentId,
+ setLibraryKey,
setPendingDeletes,
type AccountUser,
type ProjectMeta,
} from '~/lib/logic/storage'
-import type { CircuitNode, ConnectorType, LampColor, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
+import type { CircuitNode, ComponentDef, ConnectorType, LampColor, LibraryOrigin, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
/** A challenge check plus how many transistors the solution uses. */
/** How everyone did on a puzzle, from the server. */
@@ -166,7 +169,7 @@ function create() {
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0)
const showHelp = ref(false)
- const dialog = ref(null)
+ const dialog = ref(null)
/** The component whose box is being drawn in the face designer. */
const faceFor = ref(null)
function designFace(defId: string) {
@@ -520,7 +523,13 @@ function create() {
function canPlace(chipId: string) {
const d = getDef.value(chipId)
- return !containsDef(project.value, chipId, def.value.id) && (!d || defUsable(project.value, d))
+ return !containsDef(project.value, chipId, def.value.id) && (!d || defUsable(project.value, d)) && !borrowed(chipId)
+ }
+
+ /** In a campaign, challenges are solved with your own work: nothing someone else published goes into them. */
+ function borrowed(chipId: string): boolean {
+ if (!isCampaign(project.value) || !def.value.challenge) return false
+ return closure(getDef.value, chipId).some(d => d.from && !libKeys.value[d.from.id])
}
/** In a campaign, basic parts are earned; elsewhere everything can be placed. */
@@ -1480,6 +1489,119 @@ function create() {
return `${location.origin}/puzzle/${res.id}`
}
+ // ── Public library ────────────────────────────────────────────────
+ /** Edit keys of the library entries this browser published. */
+ const libKeys = ref(libraryKeys())
+
+ /** The library entry a component is, when this browser published it (and so can update or remove it). */
+ function ownEntry(d: ComponentDef | undefined): string | undefined {
+ if (!d) return undefined
+ if (d.from && !d.from.inside && libKeys.value[d.from.id]) return d.from.id
+ // Published from here, and the mark undone since.
+ return Object.entries(libKeys.value).find(([, k]) => k.project === meta.value.id && k.def === d.id)?.[0]
+ }
+
+ /** Why the open circuit can't go to the library; null when it can. */
+ const libraryProblem = computed(() => publishProblem(project.value, def.value.id))
+
+ async function listLibrary(q = ''): Promise<{ entries: LibraryMeta[]; total: number }> {
+ return api('GET', `/api/library?q=${encodeURIComponent(q.trim())}`)
+ }
+
+ /**
+ * Publishes the open circuit to the library with everything it uses, or a
+ * new version when this browser published it before. The name and
+ * description go to the component too; the author is your leaderboard name.
+ */
+ async function publishToLibrary(name: string, description: string, author: string): Promise {
+ const d = def.value
+ const problem = publishProblem(project.value, d.id)
+ if (problem) throw new Error(problem)
+ if (author.trim() !== playerName.value) await setPlayerName(author)
+ const text = description.trim().slice(0, LIBRARY_LIMITS.description)
+ d.name = name.trim().slice(0, LIBRARY_LIMITS.name) || d.name
+ if (text) d.description = text
+ else delete d.description
+ try {
+ const body = { player: playerId(), ...libraryBundle(toRaw(project.value), d.id) }
+ const own = ownEntry(d)
+ let res: { id: string; key?: string; version: number } | undefined
+ if (own) {
+ try {
+ res = await api('PUT', `/api/library/${own}`, body, libKeys.value[own]!.key)
+ } catch (e) {
+ // Gone from the library: it goes in again as a new entry.
+ if ((e as { status?: number }).status !== 404) throw e
+ setLibraryKey(own, null)
+ }
+ }
+ res ??= await api<{ id: string; key: string; version: number }>('POST', '/api/library', body)
+ if (res.key) setLibraryKey(res.id, { key: res.key, project: meta.value.id, def: d.id })
+ libKeys.value = libraryKeys()
+ d.from = { id: res.id, version: res.version, author: playerName.value }
+ return d.from
+ } finally {
+ commit(false)
+ }
+ }
+
+ /** Takes an entry this browser published out of the library; components here keep working, just without the mark. */
+ async function removeFromLibrary(id: string) {
+ try {
+ await api('DELETE', `/api/library/${id}`, undefined, libKeys.value[id]?.key)
+ } catch (e) {
+ if ((e as { status?: number }).status !== 404) throw e
+ }
+ setLibraryKey(id, null)
+ libKeys.value = libraryKeys()
+ for (const d of project.value.components) if (d.from?.id === id && !d.from.inside) delete d.from
+ commit(false)
+ }
+
+ async function fetchEntry(id: string): Promise<{ entry: LibraryMeta; bundle: LibraryBundle }> {
+ const res = await api<{ entry: LibraryMeta; bundle: unknown }>('GET', `/api/library/${encodeURIComponent(id)}`)
+ const bundle = cleanBundle(res.bundle)
+ // A campaign earns its parts: only what could have been built with the parts earned so far comes in.
+ const locked = lockedKinds(project.value, kindsIn(bundle.components))
+ if (locked.length) throw new Error(`It uses parts this campaign has not earned yet: ${locked.map(k => KIND_NAMES[k] ?? k).join(', ')}`)
+ return { entry: res.entry, bundle }
+ }
+
+ const originOf = (entry: LibraryMeta): LibraryOrigin => ({ id: entry.id, version: entry.version, author: entry.author })
+
+ /** Adds a library entry to the open project; returns the id of its component here, ready to place. */
+ async function addFromLibrary(id: string): Promise {
+ const { entry, bundle } = await fetchEntry(id)
+ const res = importBundle(project.value, bundle, originOf(entry))
+ commit()
+ const along = res.added > 1 ? ` and ${res.added - 1} component${res.added === 2 ? '' : 's'} it uses` : ''
+ notify(res.added ? `Added "${entry.name}"${entry.author ? ` by ${entry.author}` : ''}${along}` : `"${entry.name}" is in this project already`)
+ return res.root
+ }
+
+ /** Brings a component from the library to the newest version of its entry, in place: wherever it is used follows. */
+ async function updateFromLibrary(defId: string) {
+ const d = getDef.value(defId)
+ if (!d?.from || d.from.inside) return
+ try {
+ const { entry, bundle } = await fetchEntry(d.from.id)
+ importBundle(project.value, bundle, originOf(entry), d.id)
+ commit()
+ notify(`"${d.name}" is now version ${entry.version} (Ctrl+Z goes back)`)
+ } catch (e) {
+ notify((e as Error).message, 'error')
+ }
+ }
+
+ /** The newest version of a library entry; null when the library can't be reached or no longer has it. */
+ async function libraryVersion(id: string): Promise {
+ try {
+ return (await api<{ entry: LibraryMeta }>('GET', `/api/library/${encodeURIComponent(id)}?meta`)).entry.version
+ } catch {
+ return null
+ }
+ }
+
// ── Several parts at once ─────────────────────────────────────────
const nodesById = (ids: string[]) => {
const set = new Set(ids)
@@ -1855,7 +1977,7 @@ function create() {
body: body === undefined ? undefined : JSON.stringify(body),
})
const data = await res.json().catch(() => ({}))
- if (!res.ok) throw new Error((data as { message?: string }).message || `Server error ${res.status}`)
+ if (!res.ok) throw Object.assign(new Error((data as { message?: string }).message || `Server error ${res.status}`), { status: res.status })
return data as T
}
@@ -2420,6 +2542,15 @@ function create() {
beginPuzzle,
openPuzzle,
publishPuzzle,
+ ownEntry,
+ libraryProblem,
+ listLibrary,
+ publishToLibrary,
+ removeFromLibrary,
+ addFromLibrary,
+ updateFromLibrary,
+ libraryVersion,
+ libKeys,
isBus,
pinKind,
connectorFor,
diff --git a/app/composables/usePlace.ts b/app/composables/usePlace.ts
index e878c34..9f022e0 100644
--- a/app/composables/usePlace.ts
+++ b/app/composables/usePlace.ts
@@ -43,7 +43,7 @@ export function usePlace() {
function place(kind: NodeKind, chip?: string, conn?: string) {
if (chip && !ed.canPlace(chip)) {
ed.play('error')
- return ed.notify('That component cannot go in here (it is this circuit, contains it, or is not solved yet)', 'error')
+ return ed.notify('That component cannot go in here (it is this circuit, contains it, is not solved yet, or is from the library and this is a campaign challenge)', 'error')
}
if (!ed.canPlaceKind(kind)) {
ed.play('error')
diff --git a/app/lib/logic/compile.ts b/app/lib/logic/compile.ts
index 0bff2b5..eec26cc 100644
--- a/app/lib/logic/compile.ts
+++ b/app/lib/logic/compile.ts
@@ -117,7 +117,7 @@ export function cableKeys(node: CircuitNode): string[] {
/** Key of a panel row in the simulator's sources, like a switch's node id. */
export const rowSource = rowPin
-const MAX_DEPTH = 64
+export const MAX_DEPTH = 64
export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist {
const parent: number[] = [LOW, HIGH]
diff --git a/app/lib/logic/library.ts b/app/lib/logic/library.ts
new file mode 100644
index 0000000..0ab6ef9
--- /dev/null
+++ b/app/lib/logic/library.ts
@@ -0,0 +1,323 @@
+// The public component library: components people published for everyone,
+// each with every component it uses and the connector types those need.
+// Publishing sends one component and what it uses (a bundle); adding an
+// entry to a project brings the bundle in with new ids, and uses what the
+// project has in exactly that form already. Shared by the browser and the
+// library server, so it must stay free of browser APIs.
+
+import { nandCounts, TRANSISTORS_PER_NAND } from './analyze'
+import { CHALLENGES } from './challenges'
+import { MAX_DEPTH } from './compile'
+import { chipPins, type DefLookup } from './geometry'
+import { containsDef, lookup, uid, uniqueName } from './ops'
+import { KIND_NAMES, kindUnlocked } from './progress'
+import { toProject } from './project'
+import type { ComponentDef, ConnectorType, LibraryOrigin, NodeKind, Project } from './types'
+import { NAND_BASE } from './wide'
+
+/** Upper bounds for a published component: the request, its name and description. */
+export const LIBRARY_LIMITS = { bytes: 1_000_000, name: 60, description: 400 }
+
+/** What gets published: a component (`root`) and everything it uses, used ones first, with their connector types. */
+export interface LibraryBundle {
+ root: string
+ components: ComponentDef[]
+ connectors?: ConnectorType[]
+}
+
+/** A library entry as it is listed: what it is, who published it, what it takes. */
+export interface LibraryMeta {
+ id: string
+ name: string
+ description: string
+ group: string
+ /** The publisher's leaderboard name; empty for anonymous. */
+ author: string
+ version: number
+ created: number
+ updated: number
+ /** Transistors at every depth, 4 per NAND. */
+ transistors: number
+ /** Pin names, top to bottom. */
+ inputs: string[]
+ outputs: string[]
+ /** Components it uses, at every depth; they come along. */
+ uses: number
+ /** Connector types that come along. */
+ connectors: number
+ /** Built-in parts used anywhere inside (a campaign has to have earned them). */
+ kinds: NodeKind[]
+}
+
+/** Deep copy that also works on Vue reactive proxies (structuredClone does not). */
+function clone(value: T): T {
+ return JSON.parse(JSON.stringify(value)) as T
+}
+
+/**
+ * A component and every component it uses, at every depth, each once: the
+ * used ones before the ones that use them, the component itself last. A
+ * component that contains itself is not followed round again.
+ */
+export function closure(get: DefLookup, defId: string): ComponentDef[] {
+ const out: ComponentDef[] = []
+ const seen = new Set()
+ const visit = (id: string) => {
+ if (seen.has(id)) return
+ seen.add(id)
+ const def = get(id)
+ if (!def) return
+ for (const n of def.nodes) if (n.kind === 'chip' && n.chip) visit(n.chip)
+ if (def.wide && def.wide.base !== NAND_BASE) visit(def.wide.base)
+ out.push(def)
+ }
+ visit(defId)
+ return out
+}
+
+/** Connector types the ports of these components use, in the project's order. */
+function connectorsUsed(connectors: ConnectorType[] | undefined, defs: ComponentDef[]): ConnectorType[] {
+ const used = new Set(defs.flatMap(d => d.nodes.filter(n => (n.kind === 'portin' || n.kind === 'portout') && n.conn).map(n => n.conn!)))
+ return (connectors ?? []).filter(c => used.has(c.id))
+}
+
+/** Built-in parts used anywhere in these components, in a fixed order. */
+export function kindsIn(defs: ComponentDef[]): NodeKind[] {
+ return [...new Set(defs.flatMap(d => d.nodes.map(n => n.kind)))].filter(k => k !== 'chip').sort()
+}
+
+/** Built-in parts a project has not earned yet (in a campaign), out of these. */
+export function lockedKinds(project: Project, kinds: NodeKind[]): NodeKind[] {
+ return kinds.filter(k => !kindUnlocked(project, k))
+}
+
+/**
+ * Why a component can't go to the library, in words; null when it can.
+ * Challenges and puzzles stay private, so nobody gets the answer: neither
+ * a challenge circuit itself nor a puzzle solution used inside.
+ */
+export function publishProblem(project: Project, defId: string): string | null {
+ const get = lookup(project)
+ const def = get(defId)
+ if (!def) return 'Circuit not found'
+ if (def.challenge) return 'Challenges and puzzles stay private, so nobody gets the answer'
+ if (!def.nodes.length) return 'There is nothing in it yet'
+ const puzzle = closure(get, defId).find(d => d.challenge && !CHALLENGES.some(c => c.id === d.challenge))
+ if (puzzle) return `It uses your solution to the puzzle "${puzzle.name}", which stays private`
+ return null
+}
+
+/**
+ * What publishing a component sends: copies of it and of what it uses,
+ * without challenge marks, and their connector types. Components it uses
+ * keep their own library marks, so their authors stay named.
+ */
+export function libraryBundle(project: Project, defId: string): LibraryBundle {
+ const components = clone(closure(lookup(project), defId))
+ for (const d of components) delete d.challenge
+ const root = components.find(d => d.id === defId)
+ if (root) delete root.from
+ const connectors = clone(connectorsUsed(project.connectors, components))
+ return { root: defId, components, ...(connectors.length ? { connectors } : {}) }
+}
+
+/** Parts a published component may have at every depth, so whoever adds it can still run it. */
+export const MAX_FLAT_PARTS = 10_000_000
+
+/**
+ * What the simulator would refuse in a component, or choke on: a component
+ * inside that is missing, one that contains itself, nesting too deep, or
+ * too many parts once every component inside is opened up. Found by looking
+ * at each component once, never by building the whole circuit, so a part
+ * made to be huge costs no more to check than a small one.
+ */
+function nestingProblem(get: DefLookup, rootId: string): string | null {
+ const seen = new Map()
+ const busy = new Set()
+ let problem: string | null = null
+ const visit = (def: ComponentDef): { depth: number; parts: number } => {
+ const known = seen.get(def.id)
+ if (known) return known
+ busy.add(def.id)
+ const size = { depth: 1, parts: 0 }
+ for (const n of def.nodes) {
+ const child = n.kind === 'chip' && n.chip ? get(n.chip) : undefined
+ if (n.kind !== 'chip') size.parts++
+ else if (!child) problem ??= `Missing component in "${def.name}"`
+ else if (busy.has(child.id)) problem ??= `"${child.name}" contains itself`
+ else {
+ const inner = visit(child)
+ size.depth = Math.max(size.depth, 1 + inner.depth)
+ size.parts += inner.parts
+ }
+ }
+ busy.delete(def.id)
+ seen.set(def.id, size)
+ return size
+ }
+ const size = visit(get(rootId)!)
+ if (size.depth > MAX_DEPTH) problem ??= `Nesting deeper than ${MAX_DEPTH} levels`
+ if (size.parts > MAX_FLAT_PARTS) problem ??= `Too large to run: over ${MAX_FLAT_PARTS.toLocaleString('en')} parts with everything inside opened up`
+ return problem
+}
+
+/** Every kind of node there is: the built-in parts and components. */
+const KINDS = new Set([...Object.keys(KIND_NAMES), 'chip'])
+
+/**
+ * Checks a bundle from outside with the same checks as any project, plus
+ * the ones a part from a stranger needs: every node and wire well formed,
+ * nothing missing, nothing inside itself, nothing too big to run. Keeps only
+ * the component and what it uses, and drops challenge marks. Throws with a
+ * readable message.
+ */
+export function cleanBundle(raw: unknown): LibraryBundle {
+ const b = raw as Partial
+ if (!b || typeof b !== 'object' || typeof b.root !== 'string') throw new Error('Not a component for the library')
+ const p = toProject({ name: 'Library', components: b.components, connectors: b.connectors, openId: b.root })
+ for (const d of p.components) {
+ const broken = () => new Error(`"${d.name}" is broken`)
+ for (const n of d.nodes) {
+ if (!n || typeof n.id !== 'string' || !KINDS.has(n.kind) || !Number.isFinite(n.x) || !Number.isFinite(n.y)) throw broken()
+ if (n.label !== undefined && typeof n.label !== 'string') delete n.label
+ }
+ for (const w of d.wires) {
+ if (!w || typeof w.id !== 'string' || [w.from, w.to].some(r => !r || typeof r.node !== 'string' || typeof r.pin !== 'string')) throw broken()
+ }
+ for (const k of ['description', 'group'] as const) if (d[k] !== undefined && typeof d[k] !== 'string') delete d[k]
+ }
+ const get = lookup(p)
+ const root = get(b.root)
+ if (!root) throw new Error('The component itself is missing')
+ const problem = nestingProblem(get, root.id)
+ if (problem) throw new Error(problem)
+ const components = closure(get, root.id)
+ for (const d of components) delete d.challenge
+ delete root.from
+ root.name = root.name.trim().slice(0, LIBRARY_LIMITS.name) || 'Component'
+ if (root.description !== undefined) root.description = root.description.trim().slice(0, LIBRARY_LIMITS.description)
+ const connectors = connectorsUsed(p.connectors, components)
+ return { root: root.id, components, ...(connectors.length ? { connectors } : {}) }
+}
+
+/** What the listing says about a bundle, counted from the circuit itself so it can be trusted. */
+export function describeBundle(b: LibraryBundle): Pick {
+ const root = b.components.find(d => d.id === b.root)
+ if (!root) throw new Error('The component itself is missing')
+ const pins = chipPins(root)
+ return {
+ name: root.name,
+ description: root.description ?? '',
+ group: root.group?.trim() ?? '',
+ transistors: (nandCounts(b.components).get(root.id) ?? 0) * TRANSISTORS_PER_NAND,
+ inputs: pins.inputs.map(p => p.label),
+ outputs: pins.outputs.map(p => p.label),
+ uses: b.components.length - 1,
+ connectors: b.connectors?.length ?? 0,
+ kinds: kindsIn(b.components),
+ }
+}
+
+/** JSON with object keys sorted, so the same data always gives the same text. */
+function canon(value: unknown): string {
+ return JSON.stringify(value, (_, v) =>
+ v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : v,
+ )
+}
+
+/** What a component is, apart from its id, name, texts and marks: the same for two copies of one thing. */
+const form = (d: ComponentDef) => canon({ symbol: d.symbol, face: d.face, wide: d.wide, design: d.design, nodes: d.nodes, wires: d.wires })
+
+const sameLines = (a: ConnectorType, b: ConnectorType) => canon(a.lines.map(l => [l.name, !!l.back])) === canon(b.lines.map(l => [l.name, !!l.back]))
+
+/** Parts of a component that an update replaces; its name and group stay as they are here. */
+const CONTENT = ['symbol', 'description', 'face', 'wide', 'design', 'nodes', 'wires'] as const
+
+/**
+ * Adds a library entry to a project. What the project has in exactly this
+ * form already (an earlier import, the examples) is used as it is; the rest
+ * comes in with new ids, and with a number after its name when the name is
+ * taken. A connector type joins the project's type of the same id or name
+ * when their lines match, and comes in as a new type otherwise. The entry's
+ * component is marked with where it came from; the ones it uses are marked
+ * as having come along, unless they carry a mark of their own.
+ *
+ * With `replace` (a component here from the same entry), that component
+ * takes the entry's new version instead, so every place it is used follows.
+ * Returns the id of the entry's component here and how many were added.
+ */
+export function importBundle(project: Project, bundle: LibraryBundle, origin: LibraryOrigin, replace?: string): { root: string; added: number } {
+ const conns = new Map()
+ for (const c of bundle.connectors ?? []) {
+ const have = project.connectors ?? []
+ const same = have.find(h => (h.id === c.id || h.name.toLowerCase() === c.name.toLowerCase()) && sameLines(h, c))
+ if (same) {
+ conns.set(c.id, same.id)
+ continue
+ }
+ const copy = clone(c)
+ if (have.some(h => h.id === copy.id)) copy.id = uid('k')
+ const names = new Set(have.map(h => h.name.toLowerCase()))
+ for (let i = 2; names.has(copy.name.toLowerCase()); i++) copy.name = `${c.name} ${i}`
+ project.connectors = [...have, copy]
+ conns.set(c.id, copy.id)
+ }
+
+ // Components already here, by form. Not challenge attempts, which are
+ // still being worked on, nor anything that contains the one being
+ // replaced, or it would end up inside itself.
+ const forms = new Map()
+ for (const d of project.components) {
+ if (d.challenge || (replace && containsDef(project, d.id, replace))) continue
+ const k = form(d)
+ if (!forms.has(k)) forms.set(k, d.id)
+ }
+ const target = replace ? project.components.find(d => d.id === replace) : undefined
+ const byId = new Map(bundle.components.map(d => [d.id, d]))
+ const ids = new Map()
+ let root = ''
+ let added = 0
+ for (const d of closure(id => byId.get(id), bundle.root)) {
+ const copy = clone(d)
+ for (const n of copy.nodes) {
+ if (n.kind === 'chip' && n.chip) n.chip = ids.get(n.chip) ?? n.chip
+ if (n.conn) n.conn = conns.get(n.conn) ?? n.conn
+ }
+ if (copy.wide && copy.wide.base !== NAND_BASE) copy.wide.base = ids.get(copy.wide.base) ?? copy.wide.base
+ delete copy.challenge
+ const isRoot = d.id === bundle.root
+ if (isRoot) copy.from = { ...origin }
+ else copy.from ??= { ...origin, inside: true }
+
+ if (isRoot && target) {
+ const t = target as unknown as Record
+ for (const k of CONTENT) {
+ if (copy[k] === undefined) delete t[k]
+ else t[k] = copy[k]
+ }
+ target.from = copy.from
+ delete target.challenge
+ ids.set(d.id, target.id)
+ root = target.id
+ continue
+ }
+ const same = forms.get(form(copy))
+ if (same) {
+ ids.set(d.id, same)
+ // The same entry again, unchanged: it now counts as the newer version.
+ const have = project.components.find(x => x.id === same)!
+ if (have.from?.id === copy.from.id && (isRoot ? !have.from.inside : have.from.inside)) have.from = copy.from
+ if (isRoot) root = same
+ continue
+ }
+ copy.id = uid('c')
+ while (project.components.some(x => x.id === copy.id)) copy.id = uid('c')
+ copy.name = uniqueName(project, copy.name)
+ project.components.push(copy)
+ forms.set(form(copy), copy.id)
+ ids.set(d.id, copy.id)
+ added++
+ if (isRoot) root = copy.id
+ }
+ return { root, added }
+}
diff --git a/app/lib/logic/ops.ts b/app/lib/logic/ops.ts
index 288ce03..459cc5f 100644
--- a/app/lib/logic/ops.ts
+++ b/app/lib/logic/ops.ts
@@ -160,6 +160,7 @@ export function duplicateComponent(project: Project, id: string): ComponentDef |
if (!src) return undefined
const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) }
delete copy.challenge
+ delete copy.from
project.components.push(copy)
return copy
}
diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts
index 734befc..e49fc8e 100644
--- a/app/lib/logic/project.ts
+++ b/app/lib/logic/project.ts
@@ -12,6 +12,7 @@ import {
type ComponentDef,
type ConnectorType,
type FaceDesign,
+ type LibraryOrigin,
type PanelRow,
type Project,
type PuzzleSpec,
@@ -106,6 +107,16 @@ function cleanDesign(d: ComponentDef) {
}
}
+/** Where a library component came from: an entry id, a version and a name; anything else is dropped. */
+function cleanOrigin(d: ComponentDef) {
+ const f = d.from as Partial | undefined
+ if (!f || typeof f.id !== 'string' || !/^[A-Za-z0-9]{6,16}$/.test(f.id) || !Number.isInteger(f.version) || f.version! < 1) {
+ delete d.from
+ return
+ }
+ d.from = { id: f.id, version: f.version!, author: typeof f.author === 'string' ? f.author.slice(0, 24) : '', ...(f.inside === true ? { inside: true } : {}) }
+}
+
/** Upper bounds for a project that comes from outside. */
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 }
@@ -125,6 +136,7 @@ export function toProject(data: unknown): Project {
d.symbol ??= 'box'
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
if (d.design !== undefined) cleanDesign(d)
+ if (d.from !== undefined) cleanOrigin(d)
for (const n of d.nodes) cleanNode(n)
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
}
diff --git a/app/lib/logic/storage.ts b/app/lib/logic/storage.ts
index 18a2313..6ac159d 100644
--- a/app/lib/logic/storage.ts
+++ b/app/lib/logic/storage.ts
@@ -37,6 +37,7 @@ const CURRENT = 'logigate:current'
const LEGACY = 'logigate:project:v1'
const ACCOUNT = 'logigate:account'
const PENDING_DELETES = 'logigate:pending-deletes'
+const LIBRARY_KEYS = 'logigate:library-keys'
const entry = (id: string) => `logigate:p:${id}`
function read(key: string): string | null {
@@ -157,3 +158,29 @@ export function pendingDeletes(): { owner: string; id: string }[] {
export function setPendingDeletes(list: { owner: string; id: string }[]) {
write(PENDING_DELETES, JSON.stringify(list))
}
+
+/** A library entry published from this browser. */
+export interface LibraryKey {
+ /** Edit key: updates or removes the entry. */
+ key: string
+ /** The project and component it was published from. */
+ project: string
+ def: string
+}
+
+/** Library entries published from this browser, by entry id. Never part of a project, so whoever gets a copy of it can't change them. */
+export function libraryKeys(): Record {
+ try {
+ const keys = JSON.parse(read(LIBRARY_KEYS) ?? '{}')
+ return keys && typeof keys === 'object' && !Array.isArray(keys) ? keys : {}
+ } catch {
+ return {}
+ }
+}
+
+export function setLibraryKey(id: string, own: LibraryKey | null) {
+ const keys = libraryKeys()
+ if (own) keys[id] = own
+ else delete keys[id]
+ write(LIBRARY_KEYS, JSON.stringify(keys))
+}
diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts
index 49c9547..ed98bee 100644
--- a/app/lib/logic/types.ts
+++ b/app/lib/logic/types.ts
@@ -141,6 +141,19 @@ export interface ComponentDef {
wide?: { base: string; n: number }
/** The component's box drawn by hand; empty: laid out automatically. */
design?: FaceDesign
+ /** Set when the component came from the public library (or was published there from here). */
+ from?: LibraryOrigin
+}
+
+/** Where a component of the public library came from: the entry, its version and who published it. */
+export interface LibraryOrigin {
+ /** Id of the library entry. */
+ id: string
+ version: number
+ /** The publisher's name at the time; empty for anonymous. */
+ author: string
+ /** Came along inside the entry (a part it uses), rather than being the entry itself. */
+ inside?: true
}
export const FACE_INKS = ['muted', 'text', 'red', 'yellow', 'green', 'blue'] as const
diff --git a/server/api/library/[id].delete.ts b/server/api/library/[id].delete.ts
new file mode 100644
index 0000000..49000a0
--- /dev/null
+++ b/server/api/library/[id].delete.ts
@@ -0,0 +1,14 @@
+// Take an entry out of the library. Needs its edit key. Components already
+// added to projects stay where they are.
+export default defineEventHandler(async event => {
+ rateLimit(event, 'library', 30, 10 * 60_000)
+ const id = getRouterParam(event, 'id')
+ const key = getHeader(event, 'x-edit-key')
+ await locked('library', async () => {
+ const record = await findEntry(id)
+ if (!keyMatches(key, record.keyHash)) throw createError({ statusCode: 403, message: 'This component belongs to someone else' })
+ await libraryStorage().removeItem(entryKey(record.meta.id))
+ await libraryStorage().setItem('index', (await libraryIndex()).filter(m => m.id !== record.meta.id))
+ })
+ return { ok: true }
+})
diff --git a/server/api/library/[id].get.ts b/server/api/library/[id].get.ts
new file mode 100644
index 0000000..cfc898b
--- /dev/null
+++ b/server/api/library/[id].get.ts
@@ -0,0 +1,8 @@
+// One library entry with everything it uses, ready to add to a project.
+// With ?meta only what it is, to look for a newer version.
+export default defineEventHandler(async event => {
+ const record = await findEntry(getRouterParam(event, 'id'))
+ const entry = publicMeta(record.meta, await playerNames())
+ setHeader(event, 'cache-control', 'no-store')
+ return 'meta' in getQuery(event) ? { entry } : { entry, bundle: record.bundle }
+})
diff --git a/server/api/library/[id].put.ts b/server/api/library/[id].put.ts
new file mode 100644
index 0000000..d2e3730
--- /dev/null
+++ b/server/api/library/[id].put.ts
@@ -0,0 +1,19 @@
+// Publish a new version of a library entry. Needs the edit key from the
+// first publish; the entry keeps its id and publisher, its version goes up.
+import { describeBundle } from '../../../app/lib/logic/library'
+
+export default defineEventHandler(async event => {
+ rateLimit(event, 'library', 30, 10 * 60_000)
+ const id = getRouterParam(event, 'id')
+ const { bundle } = await readLibraryBody(event)
+ const key = getHeader(event, 'x-edit-key')
+ const meta = await locked('library', async () => {
+ const record = await findEntry(id)
+ if (!keyMatches(key, record.keyHash)) throw createError({ statusCode: 403, message: 'This component belongs to someone else' })
+ const meta: LibraryItem = { ...record.meta, ...describeBundle(bundle), version: record.meta.version + 1, updated: Date.now() }
+ await libraryStorage().setItem(entryKey(meta.id), { ...record, meta, bundle })
+ await libraryStorage().setItem('index', (await libraryIndex()).map(m => (m.id === meta.id ? meta : m)))
+ return meta
+ })
+ return { id: meta.id, version: meta.version }
+})
diff --git a/server/api/library/index.get.ts b/server/api/library/index.get.ts
new file mode 100644
index 0000000..f139125
--- /dev/null
+++ b/server/api/library/index.get.ts
@@ -0,0 +1,9 @@
+// Everybody's published components, newest first. ?q= narrows them to the
+// ones whose name, description, group or author has every word typed.
+export default defineEventHandler(async event => {
+ const q = getQuery(event).q
+ const names = await playerNames()
+ const list = (await libraryIndex()).map(m => publicMeta(m, names))
+ setHeader(event, 'cache-control', 'no-store')
+ return { entries: searchLibrary(list, typeof q === 'string' ? q.slice(0, 100) : '').slice(0, 500), total: list.length }
+})
diff --git a/server/api/library/index.post.ts b/server/api/library/index.post.ts
new file mode 100644
index 0000000..af2a9d7
--- /dev/null
+++ b/server/api/library/index.post.ts
@@ -0,0 +1,24 @@
+// Publish a component to the library, with everything it uses. The server
+// counts its transistors and pins itself, so the listing can be trusted.
+// Returns its id and the edit key that updates or removes it later.
+import { describeBundle } from '../../../app/lib/logic/library'
+
+export default defineEventHandler(async event => {
+ rateLimit(event, 'library', 30, 10 * 60_000)
+ const { player, bundle } = await readLibraryBody(event)
+ const storage = libraryStorage()
+ const key = newEditKey()
+ const meta = await locked('library', async () => {
+ const index = await libraryIndex()
+ if (index.length >= MAX_ENTRIES) throw createError({ statusCode: 507, message: 'The library is full for now' })
+ let id = newShareId()
+ while (await storage.hasItem(entryKey(id))) id = newShareId()
+ const now = Date.now()
+ const meta: LibraryItem = { id, ...describeBundle(bundle), version: 1, created: now, updated: now, player }
+ await storage.setItem(entryKey(id), { meta, bundle, keyHash: hashKey(key) })
+ await storage.setItem('index', [meta, ...index])
+ return meta
+ })
+ setResponseStatus(event, 201)
+ return { id: meta.id, key, version: meta.version }
+})
diff --git a/server/plugins/storage.ts b/server/plugins/storage.ts
index fe02db2..bde41b9 100644
--- a/server/plugins/storage.ts
+++ b/server/plugins/storage.ts
@@ -4,7 +4,7 @@ import { join, resolve } from 'node:path'
export default defineNitroPlugin(() => {
const root = resolve(process.cwd(), 'data')
const storage = useStorage()
- for (const name of ['shares', 'users', 'sessions', 'accounts', 'puzzles']) {
+ for (const name of ['shares', 'users', 'sessions', 'accounts', 'puzzles', 'library']) {
storage.mount(name, safeFsDriver({ base: join(root, name) }))
}
void removeStaleTemp(root)
diff --git a/server/utils/library.ts b/server/utils/library.ts
new file mode 100644
index 0000000..142e1d9
--- /dev/null
+++ b/server/utils/library.ts
@@ -0,0 +1,70 @@
+// The public component library, as JSON files under data/library:
+// entries: holds a published component with everything it uses, index
+// the list everyone browses. Publishers have no account here, just the
+// random player id kept in their browser (as on the leaderboards) and an
+// edit key per entry, which only their browser has; only its hash is stored.
+
+import type { H3Event } from 'h3'
+import { cleanBundle, LIBRARY_LIMITS, type LibraryBundle, type LibraryMeta } from '../../app/lib/logic/library'
+
+/** An entry in the index: its meta with the publisher's player id instead of their name. */
+export type LibraryItem = Omit & { player: string }
+
+export interface LibraryRecord {
+ meta: LibraryItem
+ bundle: LibraryBundle
+ keyHash: string
+}
+
+/** Entries the library holds at most, so the index stays small enough to read on every visit. */
+export const MAX_ENTRIES = 20_000
+
+export const libraryStorage = () => useStorage('library')
+export const entryKey = (id: string) => `entries:${id}`
+
+export async function libraryIndex(): Promise {
+ return (await libraryStorage().getItem('index')) ?? []
+}
+
+/** An entry as everyone sees it: the author by the name they chose, never their player id. */
+export function publicMeta(item: LibraryItem, names: Record): LibraryMeta {
+ const { player, ...meta } = item
+ return { ...meta, author: names[player] ?? '' }
+}
+
+/** Entries whose name, description, group or author contain every word of the query, newest first. */
+export function searchLibrary(list: LibraryMeta[], query: string): LibraryMeta[] {
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean)
+ return list
+ .filter(m => {
+ const text = `${m.name} ${m.description} ${m.group} ${m.author}`.toLowerCase()
+ return words.every(w => text.includes(w))
+ })
+ .sort((a, b) => b.updated - a.updated)
+}
+
+/** The publisher and their component, checked and cleaned like any project. */
+export async function readLibraryBody(event: H3Event): Promise<{ player: string; bundle: LibraryBundle }> {
+ const raw = await readRawBody(event, 'utf8')
+ if (!raw) throw createError({ statusCode: 400, message: 'Empty request' })
+ if (raw.length > LIBRARY_LIMITS.bytes) throw createError({ statusCode: 413, message: 'Too large for the library (1 MB at most)' })
+ let body: { player?: unknown }
+ try {
+ body = JSON.parse(raw)
+ } catch {
+ throw createError({ statusCode: 400, message: 'Not valid JSON' })
+ }
+ if (!isPlayer(body.player)) throw createError({ statusCode: 400, message: 'Missing player' })
+ try {
+ return { player: body.player, bundle: cleanBundle(body) }
+ } catch (e) {
+ throw createError({ statusCode: 400, message: (e as Error).message })
+ }
+}
+
+/** The entry behind an API id, or a 404. */
+export async function findEntry(id: string | undefined): Promise {
+ const record = isShareId(id) ? await libraryStorage().getItem(entryKey(id)) : null
+ if (!record) throw createError({ statusCode: 404, message: 'Not in the library (any more)' })
+ return record
+}
diff --git a/tests/library-api.test.ts b/tests/library-api.test.ts
new file mode 100644
index 0000000..74afcd7
--- /dev/null
+++ b/tests/library-api.test.ts
@@ -0,0 +1,95 @@
+// The library's API handlers, run against stand-ins for Nitro's request
+// helpers and an in-memory store: publish, update, list, read, remove.
+import { beforeAll, describe, expect, it } from 'vitest'
+import { libraryBundle } from '../app/lib/logic/library'
+import { createProject } from '../app/lib/logic/ops'
+
+interface FakeEvent {
+ body?: string
+ params?: Record
+ headers?: Record
+ query?: Record
+ status?: number
+}
+type Handler = (e: FakeEvent) => Promise>
+
+const stores = new Map>()
+const g = globalThis as Record
+const handlers: Record = {}
+
+beforeAll(async () => {
+ Object.assign(g, {
+ defineEventHandler: (fn: Handler) => fn,
+ createError: ({ statusCode, message }: { statusCode: number; message: string }) => Object.assign(new Error(message), { statusCode }),
+ readRawBody: async (e: FakeEvent) => e.body,
+ readBody: async (e: FakeEvent) => JSON.parse(e.body ?? 'null'),
+ getRouterParam: (e: FakeEvent, k: string) => e.params?.[k],
+ getHeader: (e: FakeEvent, k: string) => e.headers?.[k],
+ getQuery: (e: FakeEvent) => e.query ?? {},
+ getRequestIP: () => '127.0.0.1',
+ setHeader: () => {},
+ setResponseStatus: (e: FakeEvent, s: number) => (e.status = s),
+ useStorage: (name: string) => {
+ if (!stores.has(name)) stores.set(name, new Map())
+ const m = stores.get(name)!
+ return {
+ getItem: async (k: string) => structuredClone(m.get(k) ?? null),
+ setItem: async (k: string, v: unknown) => void m.set(k, structuredClone(v)),
+ hasItem: async (k: string) => m.has(k),
+ removeItem: async (k: string) => void m.delete(k),
+ }
+ },
+ })
+ // The server's own helpers, auto-imported there.
+ for (const mod of [await import('../server/utils/shares'), await import('../server/utils/puzzles'), await import('../server/utils/library')]) Object.assign(g, mod)
+ handlers.post = (await import('../server/api/library/index.post')).default as unknown as Handler
+ handlers.list = (await import('../server/api/library/index.get')).default as unknown as Handler
+ handlers.get = (await import('../server/api/library/[id].get')).default as unknown as Handler
+ handlers.put = (await import('../server/api/library/[id].put')).default as unknown as Handler
+ handlers.delete = (await import('../server/api/library/[id].delete')).default as unknown as Handler
+ handlers.name = (await import('../server/api/players/name.post')).default as unknown as Handler
+})
+
+const ADA = 'player-ada-000001'
+const call = (h: string, e: FakeEvent) => handlers[h]!(e)
+
+describe('library API', () => {
+ it('publishes, lists, updates and removes an entry; only the key holder may change it', async () => {
+ const p = createProject({ examples: true })
+ await call('name', { body: JSON.stringify({ player: ADA, name: 'Ada' }) })
+ const made = await call('post', { body: JSON.stringify({ player: ADA, ...libraryBundle(p, 'ex-fa') }) })
+ expect(made).toMatchObject({ version: 1 })
+ const id = made.id as string
+ const key = made.key as string
+
+ const list = await call('list', { query: { q: 'adder ada' } })
+ expect(list.total).toBe(1)
+ const [entry] = list.entries as Record[]
+ // Two half adders (XOR of 4 NANDs, AND of 2) and an OR of 3: 15 NANDs.
+ expect(entry).toMatchObject({ id, name: 'Full Adder', author: 'Ada', transistors: 60, inputs: ['A', 'B', 'Cin'], outputs: ['S', 'Cout'], uses: 5, version: 1 })
+ expect(JSON.stringify(list)).not.toContain(ADA)
+ expect((await call('list', { query: { q: 'counter' } })).entries).toEqual([])
+
+ const full = await call('get', { params: { id } })
+ expect((full.bundle as { root: string }).root).toBe('ex-fa')
+ expect(await call('get', { params: { id }, query: { meta: '' } })).not.toHaveProperty('bundle')
+
+ const next = JSON.stringify({ player: ADA, ...libraryBundle(p, 'ex-fa') })
+ await expect(call('put', { params: { id }, headers: { 'x-edit-key': 'wrong' }, body: next })).rejects.toMatchObject({ statusCode: 403 })
+ expect(await call('put', { params: { id }, headers: { 'x-edit-key': key }, body: next })).toEqual({ id, version: 2 })
+ expect(((await call('list', {})).entries as { version: number }[])[0]!.version).toBe(2)
+
+ await expect(call('delete', { params: { id }, headers: { 'x-edit-key': 'wrong' } })).rejects.toMatchObject({ statusCode: 403 })
+ await call('delete', { params: { id }, headers: { 'x-edit-key': key } })
+ expect((await call('list', {})).total).toBe(0)
+ await expect(call('get', { params: { id } })).rejects.toMatchObject({ statusCode: 404 })
+ })
+
+ it('refuses requests without a player, broken components and oversized ones', async () => {
+ const p = createProject({ examples: true })
+ const bundle = libraryBundle(p, 'ex-ha')
+ await expect(call('post', { body: JSON.stringify(bundle) })).rejects.toMatchObject({ statusCode: 400 })
+ await expect(call('post', { body: JSON.stringify({ player: ADA, root: 'ex-ha', components: [] }) })).rejects.toMatchObject({ statusCode: 400 })
+ await expect(call('post', { body: JSON.stringify({ player: ADA, ...bundle, pad: 'x'.repeat(1_000_001) }) })).rejects.toMatchObject({ statusCode: 413 })
+ })
+})
diff --git a/tests/library.test.ts b/tests/library.test.ts
new file mode 100644
index 0000000..029a9e9
--- /dev/null
+++ b/tests/library.test.ts
@@ -0,0 +1,335 @@
+import { describe, expect, it } from 'vitest'
+import { nandCounts, truthTable } from '../app/lib/logic/analyze'
+import { cleanBundle, closure, describeBundle, importBundle, kindsIn, libraryBundle, lockedKinds, publishProblem, type LibraryMeta } from '../app/lib/logic/library'
+import { createProject, duplicateComponent, lookup, startChallenge } from '../app/lib/logic/ops'
+import { parseProject, toProject } from '../app/lib/logic/project'
+import { libraryKeys, setLibraryKey } from '../app/lib/logic/storage'
+import { CHALLENGES } from '../app/lib/logic/challenges'
+import type { ComponentDef, LibraryOrigin, Project, Wire } from '../app/lib/logic/types'
+import { publicMeta, searchLibrary, type LibraryItem } from '../server/utils/library'
+
+const w = (id: string, from: [string, string], to: [string, string]): Wire => ({ id, from: { node: from[0], pin: from[1] }, to: { node: to[0], pin: to[1] } })
+const origin: LibraryOrigin = { id: 'Lib12345', version: 1, author: 'Ada' }
+
+/** The rows of a component's truth table, as text. */
+function rows(p: Project, id: string) {
+ const t = truthTable(lookup(p), id)
+ return 'error' in t ? t.error : t.rows.map(r => `${r.ins.join('')}|${r.outs.join('')}`)
+}
+
+/** Ada's project: the examples, a link of her own and a part that sends two lines over it. */
+function adasProject(): Project {
+ const p = createProject({ examples: true })
+ p.connectors = [{ id: 'k1', name: 'Link', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }] }]
+ const sender: ComponentDef = {
+ id: 'csend',
+ name: 'Sender',
+ symbol: 'box',
+ nodes: [
+ { id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
+ { id: 'b', kind: 'input', x: 0, y: 2, label: 'B' },
+ { id: 'x', kind: 'chip', chip: 'ex-xor', x: 6, y: 0 },
+ { id: 'tx', kind: 'portout', conn: 'k1', x: 20, y: 0 },
+ ],
+ wires: [w('w1', ['a', 'q'], ['x', 'a']), w('w2', ['b', 'q'], ['x', 'b']), w('w3', ['x', 'q'], ['tx', 'l0']), w('w4', ['a', 'q'], ['tx', 'l1'])],
+ }
+ p.components.push(sender)
+ return p
+}
+
+/** What a library entry hands out: the bundle, cleaned as the server does. */
+const published = (p: Project, id: string) => cleanBundle(JSON.parse(JSON.stringify(libraryBundle(p, id))))
+
+describe('library: what goes along', () => {
+ it('lists a component after everything it uses, each once, itself last', () => {
+ const p = createProject({ examples: true })
+ const order = closure(lookup(p), 'ex-add4').map(d => d.id)
+ expect(order.at(-1)).toBe('ex-add4')
+ expect(new Set(order).size).toBe(order.length)
+ expect([...order].sort()).toEqual(['ex-add4', 'ex-and', 'ex-fa', 'ex-ha', 'ex-not', 'ex-or', 'ex-xor'])
+ const get = lookup(p)
+ for (const [i, id] of order.entries()) {
+ for (const n of get(id)!.nodes) if (n.kind === 'chip') expect(order.indexOf(n.chip!), `${id} uses ${n.chip}`).toBeLessThan(i)
+ }
+ })
+
+ it('carries the connector types its ports use, without challenge marks', () => {
+ const p = adasProject()
+ p.connectors!.push({ id: 'k2', name: 'Unused', lines: [{ name: 'X' }] })
+ p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
+ const b = libraryBundle(p, 'csend')
+ expect(b.root).toBe('csend')
+ expect(b.components.map(d => d.id)).toEqual(['ex-xor', 'csend'])
+ expect(b.connectors?.map(c => c.id)).toEqual(['k1'])
+ expect(b.components.some(d => d.challenge)).toBe(false)
+ // The project itself keeps its marks.
+ expect(p.components.find(d => d.id === 'ex-xor')!.challenge).toBe('xor')
+ })
+
+ it('keeps challenges and puzzle solutions private', () => {
+ const p = createProject({ examples: true })
+ const not = startChallenge(p, CHALLENGES.find(c => c.id === 'not')!)
+ expect(publishProblem(p, not.id)).toMatch(/private/)
+ expect(publishProblem(p, 'ex-add4')).toBeNull()
+ // A solved built-in challenge may be used inside; a puzzle solution may not.
+ p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
+ expect(publishProblem(p, 'ex-add4')).toBeNull()
+ p.components.find(d => d.id === 'ex-xor')!.challenge = 'pz:abc123'
+ expect(publishProblem(p, 'ex-add4')).toMatch(/puzzle "XOR"/)
+ p.components.push({ id: 'empty', name: 'Empty', symbol: 'box', nodes: [], wires: [] })
+ expect(publishProblem(p, 'empty')).toMatch(/nothing/)
+ })
+})
+
+describe('library: checks on the server', () => {
+ it('keeps only what the component uses and counts it honestly', () => {
+ const p = adasProject()
+ const raw = { ...libraryBundle(p, 'csend'), components: p.components }
+ const b = cleanBundle(JSON.parse(JSON.stringify(raw)))
+ expect(b.components.map(d => d.id)).toEqual(closure(lookup(p), 'csend').map(d => d.id))
+ const meta = describeBundle(b)
+ expect(meta.transistors).toBe(nandCounts(p.components).get('csend')! * 4)
+ expect(meta).toMatchObject({ name: 'Sender', inputs: ['A', 'B'], outputs: [], uses: 1, connectors: 1 })
+ expect(meta.kinds).toEqual(['input', 'nand', 'output', 'portout'])
+ })
+
+ it('refuses missing parts, parts that contain themselves and broken nodes', () => {
+ const p = createProject({ examples: true })
+ const b = libraryBundle(p, 'ex-ha')
+ expect(() => cleanBundle({ ...b, components: b.components.filter(d => d.id !== 'ex-xor') })).toThrow(/Missing component/)
+ const loop = JSON.parse(JSON.stringify(b))
+ loop.components.find((d: ComponentDef) => d.id === 'ex-xor').nodes.push({ id: 'me', kind: 'chip', chip: 'ex-ha', x: 0, y: 9 })
+ expect(() => cleanBundle(loop)).toThrow(/contains itself/)
+ const broken = JSON.parse(JSON.stringify(b))
+ broken.components[0].nodes[0].x = 'left'
+ expect(() => cleanBundle(broken)).toThrow(/broken/)
+ expect(() => cleanBundle({ root: 'nope', components: b.components })).toThrow(/missing/)
+ expect(() => cleanBundle('hello')).toThrow()
+ })
+
+ /** Components l0 … l, each holding `n` of the one below; l0 is one NAND. */
+ function tower(depth: number, n: number) {
+ const components: ComponentDef[] = [{ id: 'l0', name: 'L0', symbol: 'box', nodes: [{ id: 'g', kind: 'nand', x: 0, y: 0 }], wires: [] }]
+ for (let i = 1; i <= depth; i++) {
+ const nodes = Array.from({ length: n }, (_, k) => ({ id: `c${k}`, kind: 'chip' as const, chip: `l${i - 1}`, x: 0, y: 4 * k }))
+ components.push({ id: `l${i}`, name: `L${i}`, symbol: 'box', nodes, wires: [] })
+ }
+ return { root: `l${depth}`, components }
+ }
+
+ it('refuses nesting deeper than the simulator goes, and parts too huge to run, without building them', () => {
+ expect(() => cleanBundle(tower(63, 1))).not.toThrow()
+ expect(() => cleanBundle(tower(64, 1))).toThrow(/Nesting deeper than 64/)
+ // 10^12 NANDs once opened up: refused at once.
+ const t = performance.now()
+ expect(() => cleanBundle(tower(12, 10))).toThrow(/Too large to run/)
+ expect(performance.now() - t).toBeLessThan(1000)
+ expect(describeBundle(cleanBundle(tower(6, 10))).transistors).toBe(4_000_000)
+ })
+})
+
+describe('library: adding an entry to a project', () => {
+ it('brings everything with new ids, wired to each other, computing the same', () => {
+ const ada = adasProject()
+ const bob = createProject({ examples: false })
+ const res = importBundle(bob, published(ada, 'csend'), origin)
+ expect(res.added).toBe(closure(lookup(ada), 'csend').length)
+ const root = bob.components.find(d => d.id === res.root)!
+ expect(root.name).toBe('Sender')
+ expect(root.id).not.toBe('csend')
+ // Every component it uses is here, under its new id.
+ const get = lookup(bob)
+ for (const d of closure(get, root.id)) for (const n of d.nodes) if (n.kind === 'chip') expect(get(n.chip!), n.chip).toBeTruthy()
+ expect(closure(get, root.id)).toHaveLength(res.added)
+ expect(nandCounts(bob.components).get(root.id)).toBe(nandCounts(ada.components).get('csend'))
+ const xor = closure(get, root.id).find(d => d.name === 'XOR')!
+ expect(rows(bob, xor.id)).toEqual(rows(ada, 'ex-xor'))
+ // The connector type came along and the port uses it.
+ expect(bob.connectors).toEqual([{ id: 'k1', name: 'Link', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }] }])
+ expect(root.nodes.find(n => n.kind === 'portout')!.conn).toBe('k1')
+ })
+
+ it('marks the entry, and what came along with it', () => {
+ const bob = createProject({ examples: false })
+ const res = importBundle(bob, published(createProject({ examples: true }), 'ex-ha'), origin)
+ const added = bob.components.slice(-res.added)
+ expect(added.find(d => d.id === res.root)!.from).toEqual(origin)
+ for (const d of added.filter(d => d.id !== res.root)) expect(d.from).toEqual({ ...origin, inside: true })
+ })
+
+ it('makes a copy of an added component your own, without the mark', () => {
+ const bob = createProject({ examples: false })
+ const res = importBundle(bob, published(createProject({ examples: true }), 'ex-xor'), origin)
+ expect(duplicateComponent(bob, res.root)!.from).toBeUndefined()
+ })
+
+ it('keeps the marks of library components used inside, so their authors stay named', () => {
+ const ada = createProject({ examples: true })
+ ada.components.find(d => d.id === 'ex-xor')!.from = { id: 'Xor00001', version: 3, author: 'Cy' }
+ const bob = createProject({ examples: false })
+ importBundle(bob, published(ada, 'ex-ha'), origin)
+ expect(bob.components.find(d => d.name === 'XOR')!.from).toEqual({ id: 'Xor00001', version: 3, author: 'Cy' })
+ })
+
+ it('uses what is here in the same form, and adds nothing for the same entry twice', () => {
+ const ada = createProject({ examples: true })
+ const bob = createProject({ examples: true })
+ const before = bob.components.length
+ // Bob has the examples: the half adder and all it uses are his already.
+ const first = importBundle(bob, published(ada, 'ex-ha'), origin)
+ expect(first).toEqual({ root: 'ex-ha', added: 0 })
+ expect(bob.components).toHaveLength(before)
+
+ const carl = createProject({ examples: false })
+ const a = importBundle(carl, published(ada, 'ex-fa'), origin)
+ const again = importBundle(carl, published(ada, 'ex-fa'), { ...origin, version: 2 })
+ expect(again).toEqual({ root: a.root, added: 0 })
+ expect(carl.components.find(d => d.id === a.root)!.from).toEqual({ ...origin, version: 2 })
+ })
+
+ it('gives a name that is taken by something else a number', () => {
+ const ada = createProject({ examples: true })
+ const bob = createProject({ examples: true })
+ // Bob's NOT differs from Ada's: hers comes in as "NOT 2", with what uses it pointing at hers.
+ ada.components.find(d => d.id === 'ex-not')!.nodes[0]!.x += 1
+ const res = importBundle(bob, published(ada, 'ex-and'), origin)
+ expect(res.added).toBe(2)
+ const and = bob.components.find(d => d.id === res.root)!
+ expect(and.name).toBe('AND 2')
+ const not = bob.components.find(d => d.id === and.nodes.find(n => n.kind === 'chip')!.chip)!
+ expect(not.name).toBe('NOT 2')
+ expect(not.id).not.toBe('ex-not')
+ expect(rows(bob, and.id)).toEqual(rows(ada, 'ex-and'))
+ })
+
+ it('joins connector types with the same lines, and keeps different ones apart', () => {
+ const ada = adasProject()
+ const same = createProject({ examples: true })
+ same.connectors = [{ id: 'mine', name: 'link', lines: [{ name: 'D0' }, { name: 'D1' }] }]
+ const a = importBundle(same, published(ada, 'csend'), origin)
+ expect(same.connectors).toHaveLength(1)
+ expect(same.components.find(d => d.id === a.root)!.nodes.find(n => n.kind === 'portout')!.conn).toBe('mine')
+
+ const other = createProject({ examples: true })
+ other.connectors = [{ id: 'k1', name: 'Link', lines: [{ name: 'TX' }, { name: 'RX', back: true }] }]
+ const b = importBundle(other, published(ada, 'csend'), origin)
+ expect(other.connectors).toHaveLength(2)
+ const added = other.connectors[1]!
+ expect(added.id).not.toBe('k1')
+ expect(added.name).toBe('Link 2')
+ expect(other.components.find(d => d.id === b.root)!.nodes.find(n => n.kind === 'portout')!.conn).toBe(added.id)
+ })
+
+ it('updates a component in place to a newer version, where it is used too', () => {
+ const ada = createProject({ examples: true })
+ const bob = createProject({ examples: false })
+ const v1 = importBundle(bob, published(ada, 'ex-and'), origin)
+ const main = bob.components.find(d => d.id === 'main')!
+ main.nodes.push({ id: 'u', kind: 'chip', chip: v1.root, x: 10, y: 10 })
+ // Version 2: AND became OR (same pins), now built from Ada's OR.
+ const and = ada.components.find(d => d.id === 'ex-and')!
+ const or = ada.components.find(d => d.id === 'ex-or')!
+ and.nodes = structuredClone(or.nodes)
+ and.wires = structuredClone(or.wires)
+ const v2 = importBundle(bob, published(ada, 'ex-and'), { ...origin, version: 2 }, v1.root)
+ expect(v2.root).toBe(v1.root)
+ const updated = bob.components.find(d => d.id === v1.root)!
+ expect(updated.name).toBe('AND')
+ expect(updated.from).toEqual({ ...origin, version: 2 })
+ expect(rows(bob, v1.root)).toEqual(rows(ada, 'ex-or'))
+ expect(main.nodes.find(n => n.id === 'u')!.chip).toBe(v1.root)
+ })
+
+ it('never reuses the component being updated inside its own new version', () => {
+ const bob = createProject({ examples: false })
+ const ada = createProject({ examples: true })
+ // The entry was Ada's NOT; its next version is her AND, which uses a NOT exactly like the one Bob has.
+ const res = importBundle(bob, published(ada, 'ex-not'), origin)
+ const v2 = importBundle(bob, published(ada, 'ex-and'), { ...origin, version: 2 }, res.root)
+ const get = lookup(bob)
+ expect(closure(get, v2.root).filter(d => d.id === v2.root)).toHaveLength(1)
+ expect(get(v2.root)!.nodes.some(n => n.chip === v2.root)).toBe(false)
+ expect(rows(bob, v2.root)).toEqual(rows(ada, 'ex-and'))
+ })
+})
+
+describe('library: campaign and old projects', () => {
+ it('names the parts a campaign has not earned yet', () => {
+ const p = createProject({ examples: false, campaign: true })
+ const b = published(createProject({ examples: true }), 'ex-cnt4')
+ // The counter's display and the constant 1 in its incrementer.
+ expect(lockedKinds(p, kindsIn(b.components))).toEqual(['hex', 'high'])
+ p.solved.push('not')
+ expect(lockedKinds(p, kindsIn(b.components))).toEqual(['hex'])
+ p.solved.push('dec2')
+ expect(lockedKinds(p, kindsIn(b.components))).toEqual([])
+ expect(lockedKinds(createProject({ examples: false }), ['clock', 'portin'])).toEqual([])
+ })
+
+ it('loads projects without library marks as before, and drops broken marks', () => {
+ const p = createProject({ examples: true })
+ const plain = toProject(JSON.parse(JSON.stringify(p)))
+ expect(plain.components.some(d => 'from' in d)).toBe(false)
+ expect(plain).toEqual(JSON.parse(JSON.stringify(p)))
+ const marked = JSON.parse(JSON.stringify(p))
+ marked.components[1].from = { id: 'Lib12345', version: 2, author: 'Ada', inside: true, extra: 1 }
+ marked.components[2].from = { id: '../etc', version: 1, author: 'x' }
+ marked.components[3].from = { id: 'Lib12345', version: 0 }
+ const q = parseProject(JSON.stringify(marked))
+ expect(q.components[1]!.from).toEqual({ id: 'Lib12345', version: 2, author: 'Ada', inside: true })
+ expect(q.components[2]!.from).toBeUndefined()
+ expect(q.components[3]!.from).toBeUndefined()
+ })
+})
+
+describe('library keys in the browser', () => {
+ it('keeps what was published from here, and reads anything broken as nothing', () => {
+ const map = new Map()
+ globalThis.localStorage = { getItem: k => map.get(k) ?? null, setItem: (k, v) => void map.set(k, v), removeItem: k => void map.delete(k) } as Storage
+ expect(libraryKeys()).toEqual({})
+ setLibraryKey('Lib12345', { key: 'secret', project: 'p1', def: 'c1' })
+ setLibraryKey('Lib67890', { key: 'other', project: 'p1', def: 'c2' })
+ setLibraryKey('Lib67890', null)
+ expect(libraryKeys()).toEqual({ Lib12345: { key: 'secret', project: 'p1', def: 'c1' } })
+ map.set('logigate:library-keys', '[1, 2]')
+ expect(libraryKeys()).toEqual({})
+ map.set('logigate:library-keys', 'not json')
+ expect(libraryKeys()).toEqual({})
+ })
+})
+
+describe('library listing', () => {
+ const item = (id: string, name: string, updated: number, player: string, description = ''): LibraryItem => ({
+ id,
+ name,
+ description,
+ group: '',
+ version: 1,
+ created: 0,
+ updated,
+ transistors: 8,
+ inputs: ['A'],
+ outputs: ['Q'],
+ uses: 0,
+ connectors: 0,
+ kinds: ['nand'],
+ player,
+ })
+ const names = { 'player-ada-0001': 'Ada' }
+ const list = [item('a1', 'Adder 8', 10, 'player-ada-0001', 'ripple carry'), item('a2', 'ALU', 30, 'player-bob-0002'), item('a3', 'Shifter', 20, 'player-ada-0001')].map(m =>
+ publicMeta(m, names),
+ )
+
+ it('shows authors by their name, never their player id', () => {
+ expect(list[0]!.author).toBe('Ada')
+ expect(list[1]!.author).toBe('')
+ expect(JSON.stringify(list)).not.toContain('player-')
+ })
+
+ it('finds every word in name, description or author, newest first', () => {
+ expect(searchLibrary(list, '').map((m: LibraryMeta) => m.id)).toEqual(['a2', 'a3', 'a1'])
+ expect(searchLibrary(list, 'ada').map(m => m.id)).toEqual(['a3', 'a1'])
+ expect(searchLibrary(list, 'Carry ADA').map(m => m.id)).toEqual(['a1'])
+ expect(searchLibrary(list, 'nothing')).toEqual([])
+ })
+})
From b823e8fef9fc66e83187a822643d1e2e08bf614f Mon Sep 17 00:00:00 2001
From: "Fabian @ Blax Software"
Date: Mon, 26 Oct 2026 18:44:13 +0100
Subject: [PATCH 2/2] BF library: no solutions inside, nothing into a campaign,
marks only from the entry, a small listing, updates clear what they replace
A component with a challenge or puzzle solution anywhere inside stays
private, not only a challenge circuit itself, so wrapping a solution in a
part of its own no longer publishes it.
A campaign takes nothing from the library: Add and "Get version" are off
there, with a line saying why. A library part could be duplicated,
published again or taken apart into a solution, so a check on placing was
not enough.
Library marks come only from the entry being added. The server drops the
marks a publisher sends, and whether an entry is yours depends only on the
key this browser keeps for that project and component, so a part claiming
to be someone's entry can't be published over it.
The listing keeps pin counts and the first 16 pin names a side, short, and
a group of 40 characters at most, so it stays small whatever is sent.
"Get version" clears away what came along with the old version once
nothing else uses it, and the new parts take its names. Adding never
reuses another entry's component, so updating one entry leaves the others
as they were.
Wire corner points that aren't number pairs are dropped when a project,
link or library entry is read, so a circuit can always be drawn.
Co-Authored-By: Claude Opus 5.5
---
README.md | 4 +-
app/assets/css/main.css | 9 --
app/components/editor/CircuitPane.vue | 5 +-
app/components/editor/Help.vue | 2 +-
app/components/editor/LibraryDialog.vue | 43 +++----
app/composables/useEditor.ts | 25 ++--
app/composables/usePlace.ts | 2 +-
app/lib/logic/library.ts | 139 ++++++++++++++-------
app/lib/logic/project.ts | 4 +
tests/library-api.test.ts | 2 +-
tests/library.test.ts | 159 ++++++++++++++++++++----
11 files changed, 270 insertions(+), 124 deletions(-)
diff --git a/README.md b/README.md
index d3aa84e..d0f5f65 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)).
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
-- Library: everyone's published components in one public list (bottom bar → Components → Library, Space, or the main menu), searchable by name, description and author, each with its transistors, pins and what it uses. "Publish to the library…" in the menu on a circuit's name sends it with every component it uses and their connector types, under your leaderboard name; the server checks it like any project and counts transistors and pins itself. Publishing again from the same browser makes the next version of the same entry; only that browser has the entry's edit key, so only it can update or remove it. "Add" brings an entry into the open project and starts placing it: what the project has in exactly that form already is used as it is, the rest comes with new ids (a name that is taken gets a number) and connector types join one with the same lines. The This panel says where a component came from and offers a newer version, which replaces it in place. Challenge circuits and puzzle solutions are never published. A campaign can only add what is built from parts it has earned, and its challenges take none of it: they are solved with your own work. Logic in [app/lib/logic/library.ts](app/lib/logic/library.ts).
+- Library: everyone's published components in one public list (bottom bar → Components → Library, Space, or the main menu), searchable by name, description and author, each with its transistors, pins and what it uses. "Publish to the library…" in the menu on a circuit's name sends it with every component it uses and their connector types, under your leaderboard name; the server checks it like any project and counts transistors and pins itself. Publishing the same component again from the same browser and project makes the next version of the same entry; only that browser has the entry's edit key, so only it can update or remove it. "Add" brings an entry into the open project and starts placing it: what the project has in exactly that form already is used as it is, the rest comes with new ids (a name that is taken gets a number) and connector types join one with the same lines. The This panel says where a component came from and offers a newer version, which replaces it in place; what came along with the old version goes once nothing else uses it. Another entry's component is never reused, so updating one entry leaves the others as they were. Challenges and puzzles, and components with a solution anywhere inside, are never published. A campaign takes nothing from the library: it is built from your own work. Logic in [app/lib/logic/library.ts](app/lib/logic/library.ts).
- Sound (speaker in the top bar; volume and clock ticks in Settings, the gear in the top bar): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it.
- Cables: a bundle gathers 2 to 32 wires into one cable, a split fans it out again in the same order; one bundle can feed several splits. Select the wires (a box across them, or Shift + click) and press "Bundle into cable" or Ctrl+G: the cable starts right after the sources on their middle row and ends right before the targets on theirs, so the wires keep running as they did (backwards too); an end steps aside when another part is in the way. "Place the ends yourself…" (Ctrl+Shift+G) lets you click where it starts and ends, with a preview; Esc cancels. "Unlink all" on a bundle or split removes only the wires going in or out; the cable stays. Drag the bundle and split later to move the ends. Up to 16 wires, the cable is drawn as a ribbon: each wire is its own thin line inside, in its own colour, lit while it carries a 1. The sleeve starts neutral and gets its own colour (cable or bundle/split settings). "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
@@ -66,7 +66,7 @@ The editor UI is in [app/components/editor/](app/components/editor/) with state
## Library
-[server/api/library/](server/api/library/): `POST /api/library` publishes `{ player, root, components, connectors }` and returns `{ id, key, version }`; `PUT /api/library/:id` with header `x-edit-key` publishes the next version; `DELETE /api/library/:id` with the key takes it out. `GET /api/library?q=` lists every entry, newest first, narrowed to those with every word in name, description, group or author; `GET /api/library/:id` returns one with its components (`?meta`: without). Each entry is one JSON file in `data/library/entries/`, plus `data/library/index` for the list (both in the daily backup). Only a SHA-256 of the key is stored; authors show by their leaderboard name, never by their player id. Limits: 1 MB per entry, 30 publishes per IP per 10 minutes, 20,000 entries.
+[server/api/library/](server/api/library/): `POST /api/library` publishes `{ player, root, components, connectors }` and returns `{ id, key, version }`; `PUT /api/library/:id` with header `x-edit-key` publishes the next version; `DELETE /api/library/:id` with the key takes it out. `GET /api/library?q=` lists every entry, newest first, narrowed to those with every word in name, description, group or author; `GET /api/library/:id` returns one with its components (`?meta`: without). Each entry is one JSON file in `data/library/entries/`, plus `data/library/index` for the list (both in the daily backup). Only a SHA-256 of the key is stored; authors show by their leaderboard name, never by their player id. Challenge and library marks are dropped from what comes in, and the list keeps only short texts, pin counts and the first 16 pin names a side, so it stays small. Limits: 1 MB per entry, 30 publishes per IP per 10 minutes, 20,000 entries.
## Accounts
diff --git a/app/assets/css/main.css b/app/assets/css/main.css
index a338339..bdbd4e3 100644
--- a/app/assets/css/main.css
+++ b/app/assets/css/main.css
@@ -3437,15 +3437,6 @@ kbd {
font-size: 11px;
}
-.lib-lock {
- display: flex;
- align-items: center;
- gap: 5px;
- margin-top: 6px;
- font-size: 12px;
- color: #e8a23a;
-}
-
.lib-actions {
display: flex;
flex-direction: column;
diff --git a/app/components/editor/CircuitPane.vue b/app/components/editor/CircuitPane.vue
index 0b18a77..2b9f2fd 100644
--- a/app/components/editor/CircuitPane.vue
+++ b/app/components/editor/CircuitPane.vue
@@ -7,6 +7,7 @@
import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze'
import { transistorBreakdown } from '~/lib/logic/bulk'
import { chipPins } from '~/lib/logic/geometry'
+import { importProblem } from '~/lib/logic/library'
import { usages } from '~/lib/logic/ops'
import type { SymbolKind } from '~/lib/logic/types'
@@ -51,13 +52,13 @@ const origin = computed(() => {
if (!f) return ''
return f.inside ? `Came along with a component from the library by ${f.author || 'Anonymous'}` : `From the library by ${f.author || 'Anonymous'}, version ${f.version}`
})
-/** A newer version of it in the library, to update to. */
+/** A newer version of it in the library, to update to (not in a campaign, which takes nothing from the library). */
const newer = ref(null)
watch(
() => [def.value.id, def.value.from] as const,
async ([id, f]) => {
newer.value = null
- if (!f || f.inside || ed.ownEntry(def.value)) return
+ if (!f || f.inside || ed.ownEntry(def.value) || importProblem(ed.project.value)) return
const v = await ed.libraryVersion(f.id)
if (def.value.id === id && v !== null && v > f.version) newer.value = v
},
diff --git a/app/components/editor/Help.vue b/app/components/editor/Help.vue
index 689696c..9eb8061 100644
--- a/app/components/editor/Help.vue
+++ b/app/components/editor/Help.vue
@@ -27,7 +27,7 @@ const SHORTCUTS: [string, string][] = [
['Bar at the bottom', 'Point at a kind of part to see them all; click to place, drag onto the canvas, pin the ones you use most to the bar itself (right-click a pinned part to unpin it)'],
['Main (top bar)', 'Back to the main circuit; the names after it lead back to each component you entered'],
['[', 'Hide or show the panel on the left (This and Pins)'],
- ['Library (bottom bar: Components, or Space)', 'Components everyone published: search, add one to this project (what it uses comes along) and place it. Publish your own, or a new version, from the menu on the circuit’s name'],
+ ['Library (bottom bar: Components, or Space)', 'Components everyone published: search, add one to this project (what it uses comes along; not in a campaign) and place it. Publish your own, or a new version, from the menu on the circuit’s name'],
['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'],
['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'],
['Select a component, cable button beside its pins', 'A cable plugged onto S0–S3 (or any group); drop its free end on the next part\'s pins'],
diff --git a/app/components/editor/LibraryDialog.vue b/app/components/editor/LibraryDialog.vue
index 5af62f2..52fb02a 100644
--- a/app/components/editor/LibraryDialog.vue
+++ b/app/components/editor/LibraryDialog.vue
@@ -2,10 +2,9 @@
// The public library: components everyone published, newest first. Type to
// search names, descriptions and authors. "Add" brings one into the open
// project with everything it uses and starts placing it; entries published
-// from this browser can be taken out again.
+// from this browser can be taken out again. A campaign can look, not add.
import { shortCount } from '~/lib/logic/analyze'
-import { lockedKinds, type LibraryMeta } from '~/lib/logic/library'
-import { KIND_NAMES } from '~/lib/logic/progress'
+import { importProblem, type LibraryMeta } from '~/lib/logic/library'
const ed = useEditor()
const { place } = usePlace()
@@ -46,22 +45,23 @@ onBeforeUnmount(() => clearTimeout(timer))
const date = (t: number) => new Date(t).toLocaleDateString()
-/** A box with a stub per pin, inputs left and outputs right. */
+/** A box with a stub per pin (16 a side at most), inputs left and outputs right. */
function thumb(m: LibraryMeta) {
- const rows = Math.max(1, m.inputs.length, m.outputs.length)
+ const ins = Math.min(m.inputs, 16)
+ const outs = Math.min(m.outputs, 16)
+ const rows = Math.max(1, ins, outs)
const at = (n: number) => Array.from({ length: n }, (_, i) => 1 + i + (rows - n) / 2)
- return { box: `0 0 8 ${rows + 1}`, h: rows, ins: at(m.inputs.length), outs: at(m.outputs.length) }
+ return { box: `0 0 8 ${rows + 1}`, h: rows, ins: at(ins), outs: at(outs) }
}
-/** The entries with their pictures, whether they are yours, and the parts a campaign still lacks for them. */
-const shown = computed(() =>
- (entries.value ?? []).map(m => ({
- m,
- t: thumb(m),
- mine: m.id in ed.libKeys.value,
- missing: lockedKinds(ed.project.value, m.kinds).map(k => KIND_NAMES[k] ?? k),
- })),
-)
+/** Pin names for a tooltip, with a mark when there are more than the listing keeps. */
+const pinList = (names: string[], n: number) => names.join(', ') + (n > names.length ? ', …' : '')
+
+/** The entries with their pictures, and whether they are yours. */
+const shown = computed(() => (entries.value ?? []).map(m => ({ m, t: thumb(m), mine: m.id in ed.libKeys.value })))
+
+/** Why nothing can be added to this project (a campaign); null when it can. */
+const blocked = computed(() => importProblem(ed.project.value))
async function add(m: LibraryMeta) {
busy.value = m.id
@@ -117,9 +117,7 @@ function onKey(e: KeyboardEvent) {
-
- In a campaign you can add what is built from parts you have earned. Challenges are still yours to solve: nothing from the library goes into them.
-
+ {{ blocked }}.
{{ error }}
{{ error ? '' : 'Loading…' }}
@@ -127,7 +125,7 @@ function onKey(e: KeyboardEvent) {
{{ query.trim() ? `Nothing called "${query.trim()}" yet.` : 'Nothing published yet. Be the first: open a component and publish it from the menu on its name.' }}
-
+
@@ -142,15 +140,14 @@ function onKey(e: KeyboardEvent) {
{{ m.description }}
{{ shortCount(m.transistors) }} transistors
- {{ m.inputs.length }} in
- {{ m.outputs.length }} out
+ {{ m.inputs }} in
+ {{ m.outputs }} out
{{ m.uses }} inside
{{ m.connectors }} connector {{ m.connectors === 1 ? 'type' : 'types' }}
- Needs parts you have not earned yet: {{ missing.join(', ') }}
-
+
{{ busy === m.id ? 'Adding…' : 'Add' }}
d.from && !libKeys.value[d.from.id])
+ return !containsDef(project.value, chipId, def.value.id) && (!d || defUsable(project.value, d))
}
/** In a campaign, basic parts are earned; elsewhere everything can be placed. */
@@ -1493,12 +1487,9 @@ function create() {
/** Edit keys of the library entries this browser published. */
const libKeys = ref(libraryKeys())
- /** The library entry a component is, when this browser published it (and so can update or remove it). */
+ /** The library entry a component is, when this browser published it from here (and so can update or remove it). */
function ownEntry(d: ComponentDef | undefined): string | undefined {
- if (!d) return undefined
- if (d.from && !d.from.inside && libKeys.value[d.from.id]) return d.from.id
- // Published from here, and the mark undone since.
- return Object.entries(libKeys.value).find(([, k]) => k.project === meta.value.id && k.def === d.id)?.[0]
+ return d && ownedEntry(libKeys.value, meta.value.id, d.id)
}
/** Why the open circuit can't go to the library; null when it can. */
@@ -1559,12 +1550,10 @@ function create() {
}
async function fetchEntry(id: string): Promise<{ entry: LibraryMeta; bundle: LibraryBundle }> {
+ const problem = importProblem(project.value)
+ if (problem) throw new Error(problem)
const res = await api<{ entry: LibraryMeta; bundle: unknown }>('GET', `/api/library/${encodeURIComponent(id)}`)
- const bundle = cleanBundle(res.bundle)
- // A campaign earns its parts: only what could have been built with the parts earned so far comes in.
- const locked = lockedKinds(project.value, kindsIn(bundle.components))
- if (locked.length) throw new Error(`It uses parts this campaign has not earned yet: ${locked.map(k => KIND_NAMES[k] ?? k).join(', ')}`)
- return { entry: res.entry, bundle }
+ return { entry: res.entry, bundle: cleanBundle(res.bundle) }
}
const originOf = (entry: LibraryMeta): LibraryOrigin => ({ id: entry.id, version: entry.version, author: entry.author })
diff --git a/app/composables/usePlace.ts b/app/composables/usePlace.ts
index 9f022e0..e878c34 100644
--- a/app/composables/usePlace.ts
+++ b/app/composables/usePlace.ts
@@ -43,7 +43,7 @@ export function usePlace() {
function place(kind: NodeKind, chip?: string, conn?: string) {
if (chip && !ed.canPlace(chip)) {
ed.play('error')
- return ed.notify('That component cannot go in here (it is this circuit, contains it, is not solved yet, or is from the library and this is a campaign challenge)', 'error')
+ return ed.notify('That component cannot go in here (it is this circuit, contains it, or is not solved yet)', 'error')
}
if (!ed.canPlaceKind(kind)) {
ed.play('error')
diff --git a/app/lib/logic/library.ts b/app/lib/logic/library.ts
index 0ab6ef9..9fc8ebf 100644
--- a/app/lib/logic/library.ts
+++ b/app/lib/logic/library.ts
@@ -10,13 +10,17 @@ import { CHALLENGES } from './challenges'
import { MAX_DEPTH } from './compile'
import { chipPins, type DefLookup } from './geometry'
import { containsDef, lookup, uid, uniqueName } from './ops'
-import { KIND_NAMES, kindUnlocked } from './progress'
+import { isCampaign, KIND_NAMES } from './progress'
import { toProject } from './project'
-import type { ComponentDef, ConnectorType, LibraryOrigin, NodeKind, Project } from './types'
+import type { ComponentDef, ConnectorType, LibraryOrigin, Project } from './types'
import { NAND_BASE } from './wide'
-/** Upper bounds for a published component: the request, its name and description. */
-export const LIBRARY_LIMITS = { bytes: 1_000_000, name: 60, description: 400 }
+/**
+ * Upper bounds for a published component: the request, its name,
+ * description and group, and the pin names the listing shows (how many per
+ * side, how long each).
+ */
+export const LIBRARY_LIMITS = { bytes: 1_000_000, name: 60, description: 400, group: 40, pinNames: 16, pinName: 24 }
/** What gets published: a component (`root`) and everything it uses, used ones first, with their connector types. */
export interface LibraryBundle {
@@ -38,15 +42,16 @@ export interface LibraryMeta {
updated: number
/** Transistors at every depth, 4 per NAND. */
transistors: number
- /** Pin names, top to bottom. */
- inputs: string[]
- outputs: string[]
+ /** Pins on each side. */
+ inputs: number
+ outputs: number
+ /** Names of the first pins on each side, top to bottom, shortened. */
+ inNames: string[]
+ outNames: string[]
/** Components it uses, at every depth; they come along. */
uses: number
/** Connector types that come along. */
connectors: number
- /** Built-in parts used anywhere inside (a campaign has to have earned them). */
- kinds: NodeKind[]
}
/** Deep copy that also works on Vue reactive proxies (structuredClone does not). */
@@ -81,20 +86,10 @@ function connectorsUsed(connectors: ConnectorType[] | undefined, defs: Component
return (connectors ?? []).filter(c => used.has(c.id))
}
-/** Built-in parts used anywhere in these components, in a fixed order. */
-export function kindsIn(defs: ComponentDef[]): NodeKind[] {
- return [...new Set(defs.flatMap(d => d.nodes.map(n => n.kind)))].filter(k => k !== 'chip').sort()
-}
-
-/** Built-in parts a project has not earned yet (in a campaign), out of these. */
-export function lockedKinds(project: Project, kinds: NodeKind[]): NodeKind[] {
- return kinds.filter(k => !kindUnlocked(project, k))
-}
-
/**
* Why a component can't go to the library, in words; null when it can.
* Challenges and puzzles stay private, so nobody gets the answer: neither
- * a challenge circuit itself nor a puzzle solution used inside.
+ * a challenge circuit itself nor a solution used anywhere inside it.
*/
export function publishProblem(project: Project, defId: string): string | null {
const get = lookup(project)
@@ -102,21 +97,39 @@ export function publishProblem(project: Project, defId: string): string | null {
if (!def) return 'Circuit not found'
if (def.challenge) return 'Challenges and puzzles stay private, so nobody gets the answer'
if (!def.nodes.length) return 'There is nothing in it yet'
- const puzzle = closure(get, defId).find(d => d.challenge && !CHALLENGES.some(c => c.id === d.challenge))
- if (puzzle) return `It uses your solution to the puzzle "${puzzle.name}", which stays private`
+ const solution = closure(get, defId).find(d => d.challenge)
+ if (solution) return `It uses your solution to the ${CHALLENGES.some(c => c.id === solution.challenge) ? 'challenge' : 'puzzle'} "${solution.name}", which stays private`
return null
}
+/**
+ * Why library entries can't be added to a project, in words; null when they
+ * can. A campaign is earned part by part, and a part from the library could
+ * be copied or taken apart into a solution, so a campaign takes none.
+ */
+export function importProblem(project: Project): string | null {
+ return isCampaign(project) ? 'A campaign is built from your own work: add library components to another project' : null
+}
+
+/**
+ * The library entry a component is when this browser published it, from
+ * this very project and component; its key is in `keys`. The component's
+ * own mark never counts for this, since marks come along in files and links.
+ */
+export function ownedEntry(keys: Record, projectId: string, defId: string): string | undefined {
+ return Object.entries(keys).find(([, k]) => k.project === projectId && k.def === defId)?.[0]
+}
+
/**
* What publishing a component sends: copies of it and of what it uses,
- * without challenge marks, and their connector types. Components it uses
- * keep their own library marks, so their authors stay named.
+ * without challenge or library marks, and their connector types.
*/
export function libraryBundle(project: Project, defId: string): LibraryBundle {
const components = clone(closure(lookup(project), defId))
- for (const d of components) delete d.challenge
- const root = components.find(d => d.id === defId)
- if (root) delete root.from
+ for (const d of components) {
+ delete d.challenge
+ delete d.from
+ }
const connectors = clone(connectorsUsed(project.connectors, components))
return { root: defId, components, ...(connectors.length ? { connectors } : {}) }
}
@@ -168,8 +181,9 @@ const KINDS = new Set([...Object.keys(KIND_NAMES), 'chip'])
* Checks a bundle from outside with the same checks as any project, plus
* the ones a part from a stranger needs: every node and wire well formed,
* nothing missing, nothing inside itself, nothing too big to run. Keeps only
- * the component and what it uses, and drops challenge marks. Throws with a
- * readable message.
+ * the component and what it uses, and drops challenge and library marks:
+ * an entry's components are marked when they are added, never by whoever
+ * published them. Throws with a readable message.
*/
export function cleanBundle(raw: unknown): LibraryBundle {
const b = raw as Partial
@@ -192,29 +206,38 @@ export function cleanBundle(raw: unknown): LibraryBundle {
const problem = nestingProblem(get, root.id)
if (problem) throw new Error(problem)
const components = closure(get, root.id)
- for (const d of components) delete d.challenge
- delete root.from
+ for (const d of components) {
+ delete d.challenge
+ delete d.from
+ }
root.name = root.name.trim().slice(0, LIBRARY_LIMITS.name) || 'Component'
if (root.description !== undefined) root.description = root.description.trim().slice(0, LIBRARY_LIMITS.description)
+ if (root.group !== undefined) root.group = root.group.trim().slice(0, LIBRARY_LIMITS.group)
const connectors = connectorsUsed(p.connectors, components)
return { root: root.id, components, ...(connectors.length ? { connectors } : {}) }
}
-/** What the listing says about a bundle, counted from the circuit itself so it can be trusted. */
-export function describeBundle(b: LibraryBundle): Pick {
+/**
+ * What the listing says about a cleaned bundle, counted from the circuit
+ * itself so it can be trusted. Small whatever was sent: every entry's
+ * listing is read on each visit to the library.
+ */
+export function describeBundle(b: LibraryBundle): Pick {
const root = b.components.find(d => d.id === b.root)
if (!root) throw new Error('The component itself is missing')
const pins = chipPins(root)
+ const names = (list: { label: string }[]) => list.slice(0, LIBRARY_LIMITS.pinNames).map(p => p.label.slice(0, LIBRARY_LIMITS.pinName))
return {
- name: root.name,
- description: root.description ?? '',
- group: root.group?.trim() ?? '',
+ name: root.name.slice(0, LIBRARY_LIMITS.name),
+ description: (root.description ?? '').slice(0, LIBRARY_LIMITS.description),
+ group: (root.group ?? '').slice(0, LIBRARY_LIMITS.group),
transistors: (nandCounts(b.components).get(root.id) ?? 0) * TRANSISTORS_PER_NAND,
- inputs: pins.inputs.map(p => p.label),
- outputs: pins.outputs.map(p => p.label),
+ inputs: pins.inputs.length,
+ outputs: pins.outputs.length,
+ inNames: names(pins.inputs),
+ outNames: names(pins.outputs),
uses: b.components.length - 1,
connectors: b.connectors?.length ?? 0,
- kinds: kindsIn(b.components),
}
}
@@ -240,10 +263,12 @@ const CONTENT = ['symbol', 'description', 'face', 'wide', 'design', 'nodes', 'wi
* taken. A connector type joins the project's type of the same id or name
* when their lines match, and comes in as a new type otherwise. The entry's
* component is marked with where it came from; the ones it uses are marked
- * as having come along, unless they carry a mark of their own.
+ * as having come along.
*
* With `replace` (a component here from the same entry), that component
* takes the entry's new version instead, so every place it is used follows.
+ * What came along with the old version and is used nowhere else any more
+ * goes, and the parts that replace it take its names.
* Returns the id of the entry's component here and how many were added.
*/
export function importBundle(project: Project, bundle: LibraryBundle, origin: LibraryOrigin, replace?: string): { root: string; added: number } {
@@ -264,17 +289,21 @@ export function importBundle(project: Project, bundle: LibraryBundle, origin: Li
}
// Components already here, by form. Not challenge attempts, which are
- // still being worked on, nor anything that contains the one being
- // replaced, or it would end up inside itself.
+ // still being worked on; not another entry's component, which a newer
+ // version of that entry would change under this one; nor anything that
+ // contains the one being replaced, or it would end up inside itself.
const forms = new Map()
for (const d of project.components) {
- if (d.challenge || (replace && containsDef(project, d.id, replace))) continue
+ if (d.challenge || (d.from && !d.from.inside && d.from.id !== origin.id) || (replace && containsDef(project, d.id, replace))) continue
const k = form(d)
if (!forms.has(k)) forms.set(k, d.id)
}
const target = replace ? project.components.find(d => d.id === replace) : undefined
+ // What came along with the version being replaced.
+ const before = target ? closure(lookup(project), target.id).filter(d => d.from?.inside && d.from.id === origin.id) : []
const byId = new Map(bundle.components.map(d => [d.id, d]))
const ids = new Map()
+ const fresh: { def: ComponentDef; name: string }[] = []
let root = ''
let added = 0
for (const d of closure(id => byId.get(id), bundle.root)) {
@@ -286,8 +315,7 @@ export function importBundle(project: Project, bundle: LibraryBundle, origin: Li
if (copy.wide && copy.wide.base !== NAND_BASE) copy.wide.base = ids.get(copy.wide.base) ?? copy.wide.base
delete copy.challenge
const isRoot = d.id === bundle.root
- if (isRoot) copy.from = { ...origin }
- else copy.from ??= { ...origin, inside: true }
+ copy.from = isRoot ? { ...origin } : { ...origin, inside: true }
if (isRoot && target) {
const t = target as unknown as Record
@@ -316,8 +344,29 @@ export function importBundle(project: Project, bundle: LibraryBundle, origin: Li
project.components.push(copy)
forms.set(form(copy), copy.id)
ids.set(d.id, copy.id)
+ fresh.push({ def: copy, name: d.name })
added++
if (isRoot) root = copy.id
}
+ if (target) {
+ dropUnused(project, before)
+ for (const f of fresh) if (f.def.name !== f.name && !project.components.some(x => x.name.toLowerCase() === f.name.toLowerCase())) f.def.name = f.name
+ }
return { root, added }
}
+
+/** Removes those of these components that nothing uses (or has open), and then those only they used. */
+function dropUnused(project: Project, defs: ComponentDef[]) {
+ const left = new Set(defs.map(d => d.id))
+ const used = (id: string) =>
+ id === project.openId || project.components.some(d => d.id !== id && (d.wide?.base === id || d.nodes.some(n => n.kind === 'chip' && n.chip === id)))
+ for (let gone = true; gone; ) {
+ gone = false
+ for (const id of left) {
+ if (used(id)) continue
+ project.components = project.components.filter(d => d.id !== id)
+ left.delete(id)
+ gone = true
+ }
+ }
+}
diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts
index e49fc8e..ebcdc78 100644
--- a/app/lib/logic/project.ts
+++ b/app/lib/logic/project.ts
@@ -117,6 +117,9 @@ function cleanOrigin(d: ComponentDef) {
d.from = { id: f.id, version: f.version!, author: typeof f.author === 'string' ? f.author.slice(0, 24) : '', ...(f.inside === true ? { inside: true } : {}) }
}
+/** A wire's corner points: [x, y] pairs of plain numbers, or the wire can't be drawn. */
+const cornersOk = (pts: unknown) => Array.isArray(pts) && pts.every(p => Array.isArray(p) && p.length === 2 && p.every(v => typeof v === 'number' && Number.isFinite(v)))
+
/** Upper bounds for a project that comes from outside. */
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 }
@@ -139,6 +142,7 @@ export function toProject(data: unknown): Project {
if (d.from !== undefined) cleanOrigin(d)
for (const n of d.nodes) cleanNode(n)
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
+ for (const w of d.wires) if (w.pts !== undefined && !cornersOk(w.pts)) delete w.pts
}
if (nodes > LIMITS.nodes) throw new Error('Project too large')
return {
diff --git a/tests/library-api.test.ts b/tests/library-api.test.ts
index 74afcd7..2b1b554 100644
--- a/tests/library-api.test.ts
+++ b/tests/library-api.test.ts
@@ -66,7 +66,7 @@ describe('library API', () => {
expect(list.total).toBe(1)
const [entry] = list.entries as Record[]
// Two half adders (XOR of 4 NANDs, AND of 2) and an OR of 3: 15 NANDs.
- expect(entry).toMatchObject({ id, name: 'Full Adder', author: 'Ada', transistors: 60, inputs: ['A', 'B', 'Cin'], outputs: ['S', 'Cout'], uses: 5, version: 1 })
+ expect(entry).toMatchObject({ id, name: 'Full Adder', author: 'Ada', transistors: 60, inputs: 3, outputs: 2, inNames: ['A', 'B', 'Cin'], outNames: ['S', 'Cout'], uses: 5, version: 1 })
expect(JSON.stringify(list)).not.toContain(ADA)
expect((await call('list', { query: { q: 'counter' } })).entries).toEqual([])
diff --git a/tests/library.test.ts b/tests/library.test.ts
index 029a9e9..2ea891a 100644
--- a/tests/library.test.ts
+++ b/tests/library.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { nandCounts, truthTable } from '../app/lib/logic/analyze'
-import { cleanBundle, closure, describeBundle, importBundle, kindsIn, libraryBundle, lockedKinds, publishProblem, type LibraryMeta } from '../app/lib/logic/library'
+import { cleanBundle, closure, describeBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryMeta } from '../app/lib/logic/library'
import { createProject, duplicateComponent, lookup, startChallenge } from '../app/lib/logic/ops'
import { parseProject, toProject } from '../app/lib/logic/project'
import { libraryKeys, setLibraryKey } from '../app/lib/logic/storage'
@@ -66,19 +66,29 @@ describe('library: what goes along', () => {
expect(p.components.find(d => d.id === 'ex-xor')!.challenge).toBe('xor')
})
- it('keeps challenges and puzzle solutions private', () => {
+ it('keeps challenges and puzzle solutions private, at any depth', () => {
const p = createProject({ examples: true })
const not = startChallenge(p, CHALLENGES.find(c => c.id === 'not')!)
expect(publishProblem(p, not.id)).toMatch(/private/)
expect(publishProblem(p, 'ex-add4')).toBeNull()
- // A solved built-in challenge may be used inside; a puzzle solution may not.
+ // A solution anywhere inside stays private too, a challenge's or a puzzle's.
p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
- expect(publishProblem(p, 'ex-add4')).toBeNull()
+ expect(publishProblem(p, 'ex-add4')).toMatch(/challenge "XOR"/)
p.components.find(d => d.id === 'ex-xor')!.challenge = 'pz:abc123'
expect(publishProblem(p, 'ex-add4')).toMatch(/puzzle "XOR"/)
p.components.push({ id: 'empty', name: 'Empty', symbol: 'box', nodes: [], wires: [] })
expect(publishProblem(p, 'empty')).toMatch(/nothing/)
})
+
+ it('does not publish a solved challenge wrapped in a component of its own', () => {
+ const p = createProject({ examples: false, campaign: true })
+ const not = startChallenge(p, CHALLENGES.find(c => c.id === 'not')!)
+ not.nodes.push({ id: 'g', kind: 'nand', x: 8, y: 0 })
+ p.solved.push('not')
+ p.components.push({ id: 'wrap', name: 'Wrap', symbol: 'box', nodes: [{ id: 'c', kind: 'chip', chip: not.id, x: 0, y: 0 }], wires: [] })
+ expect(publishProblem(p, 'wrap')).toMatch(/challenge "NOT", which stays private/)
+ expect(publishProblem(p, not.id)).toMatch(/private/)
+ })
})
describe('library: checks on the server', () => {
@@ -89,8 +99,40 @@ describe('library: checks on the server', () => {
expect(b.components.map(d => d.id)).toEqual(closure(lookup(p), 'csend').map(d => d.id))
const meta = describeBundle(b)
expect(meta.transistors).toBe(nandCounts(p.components).get('csend')! * 4)
- expect(meta).toMatchObject({ name: 'Sender', inputs: ['A', 'B'], outputs: [], uses: 1, connectors: 1 })
- expect(meta.kinds).toEqual(['input', 'nand', 'output', 'portout'])
+ expect(meta).toMatchObject({ name: 'Sender', inputs: 2, outputs: 0, inNames: ['A', 'B'], outNames: [], uses: 1, connectors: 1 })
+ })
+
+ it('keeps the listing small whatever is sent', () => {
+ const p = createProject({ examples: true })
+ const b = JSON.parse(JSON.stringify(libraryBundle(p, 'ex-not')))
+ const root = b.components.find((d: ComponentDef) => d.id === 'ex-not')
+ root.group = 'g'.repeat(50_000)
+ root.description = 'd'.repeat(50_000)
+ root.nodes.find((n: { kind: string }) => n.kind === 'input').label = 'x'.repeat(500_000)
+ for (let i = 0; i < 200; i++) root.nodes.push({ id: `o${i}`, kind: 'output', x: 30, y: i, label: 'y'.repeat(1000) })
+ const clean = cleanBundle(b)
+ expect(clean.components.find(d => d.id === 'ex-not')!.group).toHaveLength(LIBRARY_LIMITS.group)
+ const meta = describeBundle(clean)
+ expect(meta).toMatchObject({ inputs: 1, outputs: 201 })
+ expect(meta.outNames).toHaveLength(LIBRARY_LIMITS.pinNames)
+ expect(meta.inNames[0]).toHaveLength(LIBRARY_LIMITS.pinName)
+ expect(JSON.stringify(meta).length).toBeLessThan(2000)
+ })
+
+ it('drops corner points a wire could not be drawn with', () => {
+ const p = createProject({ examples: true })
+ const b = JSON.parse(JSON.stringify(libraryBundle(p, 'ex-ha')))
+ const ha = b.components.find((d: ComponentDef) => d.id === 'ex-ha')
+ const bent = ha.wires.filter((x: Wire) => x.pts)
+ expect(bent.length).toBeGreaterThan(1)
+ bent[0].pts = [null]
+ bent[1].pts = [[1, 'x']]
+ const clean = cleanBundle(b).components.find(d => d.id === 'ex-ha')!
+ expect(clean.wires.find(x => x.id === bent[0].id)!.pts).toBeUndefined()
+ expect(clean.wires.find(x => x.id === bent[1].id)!.pts).toBeUndefined()
+ // Corners that are fine stay, as in projects loaded from a file or link.
+ expect(clean.wires.filter(x => x.pts)).toHaveLength(bent.length - 2)
+ expect(toProject(JSON.parse(JSON.stringify(p))).components.find(d => d.id === 'ex-ha')!.wires).toEqual(p.components.find(d => d.id === 'ex-ha')!.wires)
})
it('refuses missing parts, parts that contain themselves and broken nodes', () => {
@@ -163,12 +205,20 @@ describe('library: adding an entry to a project', () => {
expect(duplicateComponent(bob, res.root)!.from).toBeUndefined()
})
- it('keeps the marks of library components used inside, so their authors stay named', () => {
+ it('marks what comes in only by the entry it came with, never by marks the publisher sent', () => {
const ada = createProject({ examples: true })
ada.components.find(d => d.id === 'ex-xor')!.from = { id: 'Xor00001', version: 3, author: 'Cy' }
+ expect(libraryBundle(ada, 'ex-ha').components.some(d => d.from)).toBe(false)
+ // Eve sends a part claiming to be Cy's entry; the server drops the claim.
+ const forged = JSON.parse(JSON.stringify(libraryBundle(ada, 'ex-ha')))
+ forged.components[0].from = { id: 'Xor00001', version: 3, author: 'Cy' }
+ const b = cleanBundle(forged)
+ expect(b.components.some(d => d.from)).toBe(false)
+ // And adding never keeps a mark that came with the bundle.
+ forged.components[0].from = { id: 'Xor00001', version: 3, author: 'Cy' }
const bob = createProject({ examples: false })
- importBundle(bob, published(ada, 'ex-ha'), origin)
- expect(bob.components.find(d => d.name === 'XOR')!.from).toEqual({ id: 'Xor00001', version: 3, author: 'Cy' })
+ importBundle(bob, forged, origin)
+ for (const d of bob.components.filter(d => d.from)) expect(d.from!.id).toBe(origin.id)
})
it('uses what is here in the same form, and adds nothing for the same entry twice', () => {
@@ -240,6 +290,54 @@ describe('library: adding an entry to a project', () => {
expect(main.nodes.find(n => n.id === 'u')!.chip).toBe(v1.root)
})
+ it('clears away what came along with the old version, and the new parts take its names', () => {
+ const ada = createProject({ examples: true })
+ const bob = createProject({ examples: false })
+ const v1 = importBundle(bob, published(ada, 'ex-ha'), origin)
+ const oldXor = bob.components.find(d => d.name === 'XOR')!
+ // Version 2: Ada drew her XOR differently.
+ ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
+ importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 2 }, v1.root)
+ expect(bob.components.map(d => d.name).sort()).toEqual(['AND', 'Half Adder', 'Main', 'NOT', 'XOR'])
+ expect(bob.components.some(d => d.id === oldXor.id)).toBe(false)
+ expect(rows(bob, v1.root)).toEqual(rows(ada, 'ex-ha'))
+ // Updated again: still no "XOR 2".
+ ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
+ importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 3 }, v1.root)
+ expect(bob.components.map(d => d.name).sort()).toEqual(['AND', 'Half Adder', 'Main', 'NOT', 'XOR'])
+ })
+
+ it('keeps an old part that is used elsewhere', () => {
+ const ada = createProject({ examples: true })
+ const bob = createProject({ examples: false })
+ const v1 = importBundle(bob, published(ada, 'ex-ha'), origin)
+ const oldXor = bob.components.find(d => d.name === 'XOR')!
+ bob.components.find(d => d.id === 'main')!.nodes.push({ id: 'x', kind: 'chip', chip: oldXor.id, x: 20, y: 0 })
+ ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
+ importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 2 }, v1.root)
+ expect(bob.components.find(d => d.id === oldXor.id)!.name).toBe('XOR')
+ expect(bob.components.some(d => d.name === 'XOR 2')).toBe(true)
+ })
+
+ it('never reuses another entry’s component, so updating one entry leaves the others as they were', () => {
+ const ada = createProject({ examples: true })
+ const bob = createProject({ examples: false })
+ // Bob has Ada's XOR entry; Carl's half adder holds an XOR exactly like it.
+ const xor = importBundle(bob, published(ada, 'ex-xor'), origin)
+ const carl = importBundle(bob, published(ada, 'ex-ha'), { id: 'Carl0001', version: 1, author: 'Carl' })
+ const carlsXor = closure(lookup(bob), carl.root).find(d => d.name.startsWith('XOR'))!
+ expect(carlsXor.id).not.toBe(xor.root)
+ expect(carlsXor.from).toEqual({ id: 'Carl0001', version: 1, author: 'Carl', inside: true })
+ // Ada's XOR, version 2, is an OR now: Carl's half adder still adds.
+ const v2 = createProject({ examples: true })
+ const x = v2.components.find(d => d.id === 'ex-xor')!
+ const or = v2.components.find(d => d.id === 'ex-or')!
+ Object.assign(x, { nodes: structuredClone(or.nodes), wires: structuredClone(or.wires) })
+ importBundle(bob, published(v2, 'ex-xor'), { ...origin, version: 2 }, xor.root)
+ expect(rows(bob, xor.root)).toEqual(rows(ada, 'ex-or'))
+ expect(rows(bob, carl.root)).toEqual(rows(ada, 'ex-ha'))
+ })
+
it('never reuses the component being updated inside its own new version', () => {
const bob = createProject({ examples: false })
const ada = createProject({ examples: true })
@@ -254,16 +352,13 @@ describe('library: adding an entry to a project', () => {
})
describe('library: campaign and old projects', () => {
- it('names the parts a campaign has not earned yet', () => {
- const p = createProject({ examples: false, campaign: true })
- const b = published(createProject({ examples: true }), 'ex-cnt4')
- // The counter's display and the constant 1 in its incrementer.
- expect(lockedKinds(p, kindsIn(b.components))).toEqual(['hex', 'high'])
- p.solved.push('not')
- expect(lockedKinds(p, kindsIn(b.components))).toEqual(['hex'])
- p.solved.push('dec2')
- expect(lockedKinds(p, kindsIn(b.components))).toEqual([])
- expect(lockedKinds(createProject({ examples: false }), ['clock', 'portin'])).toEqual([])
+ it('adds nothing to a campaign, however far it is', () => {
+ const campaign = createProject({ examples: false, campaign: true })
+ expect(importProblem(campaign)).toMatch(/campaign/)
+ campaign.solved.push(...CHALLENGES.map(c => c.id))
+ expect(importProblem(campaign)).toMatch(/campaign/)
+ expect(importProblem(createProject({ examples: true }))).toBeNull()
+ expect(importProblem({ ...createProject({ examples: false }), mode: 'challenges' })).toBeNull()
})
it('loads projects without library marks as before, and drops broken marks', () => {
@@ -296,6 +391,25 @@ describe('library keys in the browser', () => {
map.set('logigate:library-keys', 'not json')
expect(libraryKeys()).toEqual({})
})
+
+ it('owns an entry only where it was published from, whatever a component’s mark says', () => {
+ const keys = { Lib12345: { key: 'secret', project: 'p1', def: 'c1' } }
+ expect(ownedEntry(keys, 'p1', 'c1')).toBe('Lib12345')
+ // The same component in another project, or another component here, is not it.
+ expect(ownedEntry(keys, 'p2', 'c1')).toBeUndefined()
+ expect(ownedEntry(keys, 'p1', 'c2')).toBeUndefined()
+ // A part that came in claiming to be Ada's entry stays someone else's: adding
+ // Eve's entry marks it as Eve's, and only the key record counts anyway.
+ const ada = createProject({ examples: true })
+ const forged = JSON.parse(JSON.stringify(libraryBundle(ada, 'ex-and')))
+ forged.components[0].from = { id: 'Lib12345', version: 1, author: 'Ada' }
+ const p = createProject({ examples: false })
+ const res = importBundle(p, cleanBundle(forged), { id: 'Eve00001', version: 1, author: 'Eve' })
+ for (const d of closure(lookup(p), res.root)) {
+ expect(d.from!.id).toBe('Eve00001')
+ expect(ownedEntry(keys, 'p1', d.id)).toBeUndefined()
+ }
+ })
})
describe('library listing', () => {
@@ -308,11 +422,12 @@ describe('library listing', () => {
created: 0,
updated,
transistors: 8,
- inputs: ['A'],
- outputs: ['Q'],
+ inputs: 1,
+ outputs: 1,
+ inNames: ['A'],
+ outNames: ['Q'],
uses: 0,
connectors: 0,
- kinds: ['nand'],
player,
})
const names = { 'player-ada-0001': 'Ada' }