A public library of components: publish yours, add everybody's

"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 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-26 18:14:46 +01:00
parent ad8f6897e0
commit 7d6b0f8fad
28 changed files with 1587 additions and 9 deletions

View File

@ -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)). - 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. - 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/<id>`. 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. - Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/<id>`. 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)). - 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. - 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. - 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. - `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). - `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). - `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`). - `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`). - `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. - `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. [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 ## 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/<uid>/` with an index (revision per project, deletions for a year), one file per project, and savegames in `h/<project>/`. 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. [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/<uid>/` with an index (revision per project, deletions for a year), one file per project, and savegames in `h/<project>/`. 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.

View File

@ -3362,6 +3362,123 @@ kbd {
color: var(--muted); 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 ──────────────────────────────────────────────── */ /* ── Face designer ──────────────────────────────────────────────── */
.modal.face-modal { .modal.face-modal {
width: min(900px, 100%); width: min(900px, 100%);

View File

@ -81,5 +81,7 @@ watch(
<EditorSettingsDialog v-if="ed.dialog.value === 'settings'" /> <EditorSettingsDialog v-if="ed.dialog.value === 'settings'" />
<EditorSearchDialog v-if="ed.dialog.value === 'search'" /> <EditorSearchDialog v-if="ed.dialog.value === 'search'" />
<EditorFaceDialog v-if="ed.dialog.value === 'face'" /> <EditorFaceDialog v-if="ed.dialog.value === 'face'" />
<EditorLibraryDialog v-if="ed.dialog.value === 'library'" />
<EditorLibraryPublishDialog v-if="ed.dialog.value === 'library-publish'" />
</div> </div>
</template> </template>

View File

@ -320,6 +320,7 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))
<div class="flex gap-1"> <div class="flex gap-1">
<button class="flyout-new grow" @click="ed.createComponent(), (open = null)"><Icon name="lucide:plus" class="size-4" /> New component</button> <button class="flyout-new grow" @click="ed.createComponent(), (open = null)"><Icon name="lucide:plus" class="size-4" /> New component</button>
<button class="flyout-new" title="NOT, AND, … up to a 4-bit counter, all built from NAND" @click="ed.loadExamples(), (open = null)"><Icon name="lucide:book-open" class="size-4" /> Examples</button> <button class="flyout-new" title="NOT, AND, … up to a 4-bit counter, all built from NAND" @click="ed.loadExamples(), (open = null)"><Icon name="lucide:book-open" class="size-4" /> Examples</button>
<button class="flyout-new" title="Components everyone published: find one and add it here" @click="(ed.dialog.value = 'library'), (open = null)"><Icon name="lucide:library-big" class="size-4" /> Library</button>
</div> </div>
</template> </template>
</div> </div>

View File

@ -1,6 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
// "This": what the circuit you are in is. Its name and health on top, four // "This": what the circuit you are in is. Its name, where it came from (the
// numbers (the transistors open their breakdown), its truth table and how it // library, with a newer version to get) and health on top, four numbers
// (the transistors open their breakdown), its truth table and how it
// looks as a part. Things to do with it are in the menu on its name in the // looks as a part. Things to do with it are in the menu on its name in the
// top bar; unused components are with the components in the parts bar. // top bar; unused components are with the components in the parts bar.
import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze' import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze'
@ -42,6 +43,27 @@ const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.
const total = computed(() => ed.transistors(def.value.id)) const total = computed(() => ed.transistors(def.value.id))
const breakdown = computed(() => transistorBreakdown(def.value, ed.nands.value, ed.getDef.value)) const breakdown = computed(() => transistorBreakdown(def.value, ed.nands.value, ed.getDef.value))
// ── From the library ────────────────────────────────────────────────
/** Where it came from, when it is in the library. */
const origin = computed(() => {
const f = def.value.from
if (ed.ownEntry(def.value)) return f ? `In the library as version ${f.version}, published from here` : 'In the library, published from here'
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. */
const newer = ref<number | null>(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
const v = await ed.libraryVersion(f.id)
if (def.value.id === id && v !== null && v > f.version) newer.value = v
},
{ immediate: true },
)
function toggleFace(e: Event) { function toggleFace(e: Event) {
def.value.face = (e.target as HTMLInputElement).checked def.value.face = (e.target as HTMLInputElement).checked
ed.commit(false) ed.commit(false)
@ -78,6 +100,13 @@ const showCost = ref(false)
</template> </template>
<template v-else>{{ def.id === ed.mainId.value ? 'The main circuit' : 'Not used in another circuit' }}</template> <template v-else>{{ def.id === ed.mainId.value ? 'The main circuit' : 'Not used in another circuit' }}</template>
</p> </p>
<p v-if="origin" class="lib-origin">
<Icon name="lucide:library-big" class="size-3.5 shrink-0" />
<span class="grow">{{ origin }}</span>
<button v-if="newer" class="btn-sm" title="Replace it here with the newer version, wherever it is used (Ctrl+Z goes back)" @click="ed.updateFromLibrary(def.id)">
Get version {{ newer }}
</button>
</p>
<div class="health" :class="worst"> <div class="health" :class="worst">
<Icon :name="worst === 'ok' ? 'lucide:circle-check' : LEVEL_ICON[worst]" class="size-4 shrink-0" /> <Icon :name="worst === 'ok' ? 'lucide:circle-check' : LEVEL_ICON[worst]" class="size-4 shrink-0" />

View File

@ -27,6 +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)'], ['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'], ['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)'], ['[', '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'],
['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'], ['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 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'], ['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'],

View File

@ -0,0 +1,173 @@
<script setup lang="ts">
// 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.
import { shortCount } from '~/lib/logic/analyze'
import { lockedKinds, type LibraryMeta } from '~/lib/logic/library'
import { KIND_NAMES } from '~/lib/logic/progress'
const ed = useEditor()
const { place } = usePlace()
const close = () => (ed.dialog.value = null)
const query = ref('')
const entries = ref<LibraryMeta[] | null>(null)
const total = ref(0)
const error = ref('')
const busy = ref('')
const confirmRemove = ref('')
const input = ref<HTMLInputElement>()
// Only the answer to the latest search counts.
let asked = 0
let timer: ReturnType<typeof setTimeout> | undefined
async function load() {
const n = ++asked
try {
const res = await ed.listLibrary(query.value)
if (n !== asked) return
entries.value = res.entries
total.value = res.total
error.value = ''
} catch (e) {
if (n === asked) error.value = `Could not load the library: ${(e as Error).message}`
}
}
watch(query, () => {
clearTimeout(timer)
timer = setTimeout(load, 250)
})
onMounted(() => {
void load()
input.value?.focus()
})
onBeforeUnmount(() => clearTimeout(timer))
const date = (t: number) => new Date(t).toLocaleDateString()
/** A box with a stub per pin, inputs left and outputs right. */
function thumb(m: LibraryMeta) {
const rows = Math.max(1, m.inputs.length, m.outputs.length)
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) }
}
/** 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),
})),
)
async function add(m: LibraryMeta) {
busy.value = m.id
error.value = ''
try {
const root = await ed.addFromLibrary(m.id)
close()
if (ed.screen.value === 'menu') ed.enterGame()
place('chip', root)
} catch (e) {
error.value = (e as Error).message
} finally {
busy.value = ''
}
}
async function remove(m: LibraryMeta) {
if (confirmRemove.value !== m.id) return (confirmRemove.value = m.id)
confirmRemove.value = ''
busy.value = m.id
error.value = ''
try {
await ed.removeFromLibrary(m.id)
entries.value = entries.value?.filter(e => e.id !== m.id) ?? null
total.value--
ed.notify(`"${m.name}" is out of the library. Projects that added it keep their copy.`)
} catch (e) {
error.value = (e as Error).message
} finally {
busy.value = ''
}
}
function onKey(e: KeyboardEvent) {
if (e.key !== 'Escape') return
e.stopPropagation()
close()
}
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div class="modal library-modal" role="dialog" aria-labelledby="library-title" @keydown="onKey">
<div class="flex items-start justify-between gap-4">
<h2 id="library-title">Library</h2>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<p class="hint mt-1">
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.
</p>
<div class="search part-search mt-3">
<Icon name="lucide:search" class="size-3.5 text-(--muted)" />
<input ref="input" v-model="query" placeholder="Search by name, description or author…" />
</div>
<p v-if="ed.project.value.mode === 'campaign'" class="hint mt-2">
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.
</p>
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
<p v-if="entries === null" class="hint mt-3">{{ error ? '' : 'Loading…' }}</p>
<p v-else-if="!entries.length" class="hint mt-3">
{{ 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.' }}
</p>
<ul v-else class="lib-list">
<li v-for="{ m, t, mine, missing } in shown" :key="m.id" class="lib-entry">
<svg class="lib-thumb" :viewBox="t.box" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
<line v-for="(y, i) in t.ins" :key="`i${i}`" x1="0.6" :y1="y" x2="2" :y2="y" />
<line v-for="(y, i) in t.outs" :key="`o${i}`" x1="6" :y1="y" x2="7.4" :y2="y" />
<rect x="2" y="0.5" width="4" :height="t.h" rx="0.4" />
</svg>
<div class="lib-main">
<div class="lib-title">
<span class="truncate">{{ m.name }}</span>
<span v-if="mine" class="you-tag">yours</span>
</div>
<div class="lib-by">by {{ m.author || 'Anonymous' }} · version {{ m.version }} · {{ date(m.updated) }}</div>
<p v-if="m.description" class="lib-desc">{{ m.description }}</p>
<div class="lib-stats">
<span title="Transistors at every depth, 4 per NAND">{{ shortCount(m.transistors) }} transistors</span>
<span :title="m.inputs.join(', ')">{{ m.inputs.length }} in</span>
<span :title="m.outputs.join(', ')">{{ m.outputs.length }} out</span>
<span v-if="m.uses" title="Components it uses; they come along">{{ m.uses }} inside</span>
<span v-if="m.connectors">{{ m.connectors }} connector {{ m.connectors === 1 ? 'type' : 'types' }}</span>
</div>
<p v-if="missing.length" class="lib-lock"><Icon name="lucide:lock" class="size-3.5 shrink-0" /> Needs parts you have not earned yet: {{ missing.join(', ') }}</p>
</div>
<div class="lib-actions">
<button class="btn btn-primary" :disabled="!!busy || missing.length > 0" title="Add it to this project and place it" @click="add(m)">
<Icon name="lucide:plus" class="size-4" /> {{ busy === m.id ? 'Adding…' : 'Add' }}
</button>
<button
v-if="mine"
class="btn-sm"
:class="{ danger: confirmRemove === m.id }"
:disabled="!!busy"
:title="confirmRemove === m.id ? 'Click again to take it out of the library' : 'Take it out of the library; copies others added stay theirs'"
@click="remove(m)"
@pointerleave="confirmRemove === m.id && (confirmRemove = '')"
>
{{ confirmRemove === m.id ? 'Remove?' : 'Remove' }}
</button>
</div>
</li>
</ul>
<p v-if="entries && !query.trim() && total > entries.length" class="hint mt-2">The newest {{ entries.length }} of {{ total }}. Search to find the others.</p>
</div>
</div>
</template>

View File

@ -0,0 +1,137 @@
<script setup lang="ts">
// Publishing the open circuit to the library: its name and description as
// everyone will see them, your name, and what goes along with it. Published
// from this browser before, it goes up as a new version of the same entry.
import { shortCount } from '~/lib/logic/analyze'
import { chipPins } from '~/lib/logic/geometry'
import { LIBRARY_LIMITS, libraryBundle } from '~/lib/logic/library'
import type { LibraryOrigin } from '~/lib/logic/types'
const ed = useEditor()
const close = () => (ed.dialog.value = null)
const def = ed.def
/** The entry this is a new version of, when this browser published it before. */
const own = ed.ownEntry(def.value)
const name = ref(def.value.name)
const description = ref(def.value.description ?? '')
const author = ref(ed.playerName.value)
const busy = ref(false)
const error = ref('')
const done = ref<LibraryOrigin | null>(null)
const confirmRemove = ref(false)
const pins = computed(() => chipPins(def.value))
/** A list of names, the first few spelled out. */
const names = (list: string[]) => (list.length > 6 ? `${list.slice(0, 6).join(', ')} and ${list.length - 6} more` : list.join(', '))
/** What goes along with it, in words, and whether it all fits. */
const along = computed(() => {
const b = libraryBundle(ed.project.value, def.value.id)
const uses = b.components.filter(d => d.id !== b.root).map(d => d.name)
const types = (b.connectors ?? []).map(c => c.name)
const parts = [
uses.length ? `the ${uses.length === 1 ? 'component' : `${uses.length} components`} it uses (${names(uses)})` : '',
types.length ? `${types.length === 1 ? 'the connector type' : 'the connector types'} ${names(types)}` : '',
].filter(Boolean)
const text = parts.length ? `Goes along: ${parts.join(' and ')}.` : 'It uses no other components.'
return { text, tooLarge: JSON.stringify(b).length > LIBRARY_LIMITS.bytes }
})
const problem = computed(() => ed.libraryProblem.value ?? (along.value.tooLarge ? 'Too large for the library (1 MB at most)' : null))
async function publish() {
busy.value = true
error.value = ''
try {
done.value = await ed.publishToLibrary(name.value, description.value, author.value)
ed.play('unlock')
} catch (e) {
error.value = (e as Error).message
} finally {
busy.value = false
}
}
async function remove() {
if (!confirmRemove.value) return (confirmRemove.value = true)
busy.value = true
error.value = ''
try {
await ed.removeFromLibrary(own!)
ed.notify(`"${def.value.name}" is out of the library. Projects that added it keep their copy.`)
close()
} catch (e) {
error.value = (e as Error).message
} finally {
busy.value = false
}
}
function onKey(e: KeyboardEvent) {
if (e.key !== 'Escape') return
e.stopPropagation()
close()
}
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div class="modal" role="dialog" aria-labelledby="lib-publish-title" @keydown="onKey">
<div class="flex items-start justify-between gap-4">
<h2 id="lib-publish-title">{{ own ? 'Update in the library' : 'Publish to the library' }}</h2>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<template v-if="!done">
<p class="hint mt-1">
<template v-if="own">It goes up as the next version of your entry; projects that added it before are offered the update.</template>
<template v-else>Everyone can find it in the library and add it to their projects, together with everything it uses.</template>
Only this browser can update or remove it later.
</p>
<label class="field mt-4">
<span>Name</span>
<input v-model="name" :maxlength="LIBRARY_LIMITS.name" />
</label>
<label class="field">
<span>Description</span>
<textarea v-model="description" rows="3" :maxlength="LIBRARY_LIMITS.description" placeholder="What does it do, how do you use it?" />
</label>
<label class="field">
<span>Your name, also on the leaderboards</span>
<input v-model="author" maxlength="24" placeholder="Anonymous" autocomplete="nickname" />
</label>
<p class="hint">{{ pins.inputs.length }} in, {{ pins.outputs.length }} out, {{ shortCount(ed.transistors(def.id)) }} transistors. {{ along.text }}</p>
<p v-if="problem" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ problem }}</p>
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
<div class="mt-3 flex flex-wrap items-center gap-2">
<button class="btn btn-primary" :disabled="!!problem || busy || !name.trim()" @click="publish">
<Icon name="lucide:book-up" class="size-4" /> {{ busy ? 'Publishing…' : own ? 'Publish new version' : 'Publish' }}
</button>
<button
v-if="own"
class="btn-sm ml-auto"
:class="{ danger: confirmRemove }"
:disabled="busy"
:title="confirmRemove ? 'Click again to take it out of the library' : 'Take it out of the library; copies others added stay theirs'"
@click="remove"
@pointerleave="confirmRemove = false"
>
{{ confirmRemove ? 'Remove from the library?' : 'Remove from the library' }}
</button>
</div>
</template>
<template v-else>
<p class="result pass">
<Icon name="lucide:circle-check" class="size-4 shrink-0" />
<span>"{{ def.name }}" is in the library as version {{ done.version }}. Everyone can find it and add it to their projects.</span>
</p>
<div class="mt-3 flex gap-2">
<button class="btn btn-primary" @click="ed.dialog.value = 'library'"><Icon name="lucide:library-big" class="size-4" /> Open the library</button>
<button class="btn" @click="close">Done</button>
</div>
</template>
</div>
</div>
</template>

View File

@ -93,6 +93,13 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
</span> </span>
<Icon name="lucide:chevron-right" class="chev size-4 shrink-0" /> <Icon name="lucide:chevron-right" class="chev size-4 shrink-0" />
</button> </button>
<button class="title-item" :disabled="!ed.savesReady.value" @click="ed.dialog.value = 'library'">
<Icon name="lucide:library-big" class="size-5 shrink-0" />
<span class="grow">
<span class="label">Library</span>
<span class="sub">Components everyone published, to add to your project</span>
</span>
</button>
<button class="title-item" @click="ed.dialog.value = 'settings'"> <button class="title-item" @click="ed.dialog.value = 'settings'">
<Icon name="lucide:settings" class="size-5 shrink-0" /> <Icon name="lucide:settings" class="size-5 shrink-0" />
<span class="grow"><span class="label">Settings</span></span> <span class="grow"><span class="label">Settings</span></span>

View File

@ -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', 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: '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: '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: '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: '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') }, { id: 'print', label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', aka: 'sheet export', run: () => ed.exportSheet('print') },

View File

@ -60,6 +60,13 @@ const circuitEntries = computed<MenuEntry[]>(() => {
{ label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: empty, run: () => ed.exportSheet('print') }, { 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: '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: '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'),
},
] ]
}) })

View File

@ -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 { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges' import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch' 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 { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
import { chipPins, MAX_BITS, panelOffsets, pinKindOf, shapeOf, type Pt } from '~/lib/logic/geometry' import { chipPins, MAX_BITS, panelOffsets, pinKindOf, shapeOf, type Pt } from '~/lib/logic/geometry'
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels' import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
@ -58,6 +59,7 @@ import { Simulator } from '~/lib/logic/sim'
import { import {
cachedAccount, cachedAccount,
currentId, currentId,
libraryKeys,
listProjects, listProjects,
loadProject, loadProject,
migrateLegacy, migrateLegacy,
@ -68,11 +70,12 @@ import {
saveProject, saveProject,
setCachedAccount, setCachedAccount,
setCurrentId, setCurrentId,
setLibraryKey,
setPendingDeletes, setPendingDeletes,
type AccountUser, type AccountUser,
type ProjectMeta, type ProjectMeta,
} from '~/lib/logic/storage' } 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. */ /** A challenge check plus how many transistors the solution uses. */
/** How everyone did on a puzzle, from the server. */ /** 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 notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0) const labelFocus = ref(0)
const showHelp = ref(false) const showHelp = ref(false)
const dialog = ref<null | 'connector' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face'>(null) const dialog = ref<null | 'connector' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face' | 'library' | 'library-publish'>(null)
/** The component whose box is being drawn in the face designer. */ /** The component whose box is being drawn in the face designer. */
const faceFor = ref<string | null>(null) const faceFor = ref<string | null>(null)
function designFace(defId: string) { function designFace(defId: string) {
@ -520,7 +523,13 @@ function create() {
function canPlace(chipId: string) { function canPlace(chipId: string) {
const d = getDef.value(chipId) 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. */ /** In a campaign, basic parts are earned; elsewhere everything can be placed. */
@ -1480,6 +1489,119 @@ function create() {
return `${location.origin}/puzzle/${res.id}` 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<LibraryOrigin> {
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<string> {
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<number | null> {
try {
return (await api<{ entry: LibraryMeta }>('GET', `/api/library/${encodeURIComponent(id)}?meta`)).entry.version
} catch {
return null
}
}
// ── Several parts at once ───────────────────────────────────────── // ── Several parts at once ─────────────────────────────────────────
const nodesById = (ids: string[]) => { const nodesById = (ids: string[]) => {
const set = new Set(ids) const set = new Set(ids)
@ -1855,7 +1977,7 @@ function create() {
body: body === undefined ? undefined : JSON.stringify(body), body: body === undefined ? undefined : JSON.stringify(body),
}) })
const data = await res.json().catch(() => ({})) 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 return data as T
} }
@ -2420,6 +2542,15 @@ function create() {
beginPuzzle, beginPuzzle,
openPuzzle, openPuzzle,
publishPuzzle, publishPuzzle,
ownEntry,
libraryProblem,
listLibrary,
publishToLibrary,
removeFromLibrary,
addFromLibrary,
updateFromLibrary,
libraryVersion,
libKeys,
isBus, isBus,
pinKind, pinKind,
connectorFor, connectorFor,

View File

@ -43,7 +43,7 @@ export function usePlace() {
function place(kind: NodeKind, chip?: string, conn?: string) { function place(kind: NodeKind, chip?: string, conn?: string) {
if (chip && !ed.canPlace(chip)) { if (chip && !ed.canPlace(chip)) {
ed.play('error') 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)) { if (!ed.canPlaceKind(kind)) {
ed.play('error') ed.play('error')

View File

@ -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. */ /** Key of a panel row in the simulator's sources, like a switch's node id. */
export const rowSource = rowPin export const rowSource = rowPin
const MAX_DEPTH = 64 export const MAX_DEPTH = 64
export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist { export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist {
const parent: number[] = [LOW, HIGH] const parent: number[] = [LOW, HIGH]

323
app/lib/logic/library.ts Normal file
View File

@ -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<T>(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<string>()
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<string, { depth: number; parts: number }>()
const busy = new Set<string>()
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<string>([...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<LibraryBundle>
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<LibraryMeta, 'name' | 'description' | 'group' | 'transistors' | 'inputs' | 'outputs' | 'uses' | 'connectors' | 'kinds'> {
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<string, string>()
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<string, string>()
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<string, string>()
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<string, unknown>
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 }
}

View File

@ -160,6 +160,7 @@ export function duplicateComponent(project: Project, id: string): ComponentDef |
if (!src) return undefined if (!src) return undefined
const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) } const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) }
delete copy.challenge delete copy.challenge
delete copy.from
project.components.push(copy) project.components.push(copy)
return copy return copy
} }

View File

@ -12,6 +12,7 @@ import {
type ComponentDef, type ComponentDef,
type ConnectorType, type ConnectorType,
type FaceDesign, type FaceDesign,
type LibraryOrigin,
type PanelRow, type PanelRow,
type Project, type Project,
type PuzzleSpec, 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<LibraryOrigin> | 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. */ /** Upper bounds for a project that comes from outside. */
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 } 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' 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.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.design !== undefined) cleanDesign(d)
if (d.from !== undefined) cleanOrigin(d)
for (const n of d.nodes) cleanNode(n) 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.color && !WIRE_COLORS.includes(w.color)) delete w.color
} }

View File

@ -37,6 +37,7 @@ const CURRENT = 'logigate:current'
const LEGACY = 'logigate:project:v1' const LEGACY = 'logigate:project:v1'
const ACCOUNT = 'logigate:account' const ACCOUNT = 'logigate:account'
const PENDING_DELETES = 'logigate:pending-deletes' const PENDING_DELETES = 'logigate:pending-deletes'
const LIBRARY_KEYS = 'logigate:library-keys'
const entry = (id: string) => `logigate:p:${id}` const entry = (id: string) => `logigate:p:${id}`
function read(key: string): string | null { 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 }[]) { export function setPendingDeletes(list: { owner: string; id: string }[]) {
write(PENDING_DELETES, JSON.stringify(list)) 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<string, LibraryKey> {
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))
}

View File

@ -141,6 +141,19 @@ export interface ComponentDef {
wide?: { base: string; n: number } wide?: { base: string; n: number }
/** The component's box drawn by hand; empty: laid out automatically. */ /** The component's box drawn by hand; empty: laid out automatically. */
design?: FaceDesign 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 export const FACE_INKS = ['muted', 'text', 'red', 'yellow', 'green', 'blue'] as const

View File

@ -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 }
})

View File

@ -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 }
})

View File

@ -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 }
})

View File

@ -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 }
})

View File

@ -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 }
})

View File

@ -4,7 +4,7 @@ import { join, resolve } from 'node:path'
export default defineNitroPlugin(() => { export default defineNitroPlugin(() => {
const root = resolve(process.cwd(), 'data') const root = resolve(process.cwd(), 'data')
const storage = useStorage() 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) })) storage.mount(name, safeFsDriver({ base: join(root, name) }))
} }
void removeStaleTemp(root) void removeStaleTemp(root)

70
server/utils/library.ts Normal file
View File

@ -0,0 +1,70 @@
// The public component library, as JSON files under data/library:
// entries:<id> 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<LibraryMeta, 'author'> & { 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<LibraryItem[]> {
return (await libraryStorage().getItem<LibraryItem[]>('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<string, string>): 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<LibraryRecord> {
const record = isShareId(id) ? await libraryStorage().getItem<LibraryRecord>(entryKey(id)) : null
if (!record) throw createError({ statusCode: 404, message: 'Not in the library (any more)' })
return record
}

95
tests/library-api.test.ts Normal file
View File

@ -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<string, string>
headers?: Record<string, string>
query?: Record<string, string>
status?: number
}
type Handler = (e: FakeEvent) => Promise<Record<string, unknown>>
const stores = new Map<string, Map<string, unknown>>()
const g = globalThis as Record<string, unknown>
const handlers: Record<string, Handler> = {}
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<string, unknown>[]
// 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 })
})
})

335
tests/library.test.ts Normal file
View File

@ -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<depth>, 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<string, string>()
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([])
})
})