@0001-labs/idv1 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,23 +17,29 @@ const parsed = parseCode(candidate)
17
17
 
18
18
  `codeCandidate(kind)` draws with Web Crypto and returns the corresponding branded ID. All generators use mixed-case ASCII letters. Account and Project accept an optional exact two-letter prefix, preserving case: `codeCandidate('project', { letters: 'AR' })`. Candidates obey word filters; Project also excludes blocked digit pairs. A bounded draw fails after 1,000 attempts. An injected `random` must return finite numbers in `[0, 1)`. These are candidate generators, not allocators: claim a candidate in its namespace and store it next to the record's UUID. A code is a short handle for agents, not a permanent identity; when a pool runs out it resets and its codes are issued again.
19
19
 
20
- `ID_SPACE` counts the five structural pools before generation filters; `TOTAL_ID_SPACE` is their sum. Event is part of the main API, without a separate expanded classifier. Scan encoding retains its checksum and payload format, accepts exactly the same six-character IDs, and all scanner paths support all five shapes. Scan results are branded IDs; use `parseCode` to read their kind.
20
+ `ID_CAPACITY` counts the five structural pools before generation filters; `TOTAL_ID_CAPACITY` is their sum. Event is part of the main API, without a separate expanded classifier. Scan encoding retains its checksum and payload format, accepts exactly the same six-character IDs, and all scanner paths support all five shapes. Scan results are branded IDs; use `parseCode` to read their kind.
21
21
 
22
22
  ## The idv1 command
23
23
 
24
24
  A codebase that uses IDv1 keeps one `.id` file at its root: its namespaces and taxonomies, each with its shorthand and real name, then its parts and the facts between them ([format](https://idv1.0001.dev/docs/annotate)). The `idv1` command reads it from any folder below:
25
25
 
26
26
  ```sh
27
- npx idv1 architecture # namespaces, taxonomies, the parts as a tree, the facts
27
+ npx idv1 directory # namespaces, taxonomies, the parts as a tree, the facts
28
28
  npx idv1 status # counts by shape and taxonomy, and whether it is healthy
29
29
  npx idv1 health # every broken rule; exits 1 so it can run in a build
30
30
  npx idv1 resolve co14Ch # one id, a -SH- qualified id or a junction, with its facts
31
31
  ```
32
32
 
33
- It runs on Node 22.18 or later. The same functions are exported for apps: `readArchitecture`, `architectureHealth`, `resolveCode`, `taxonomyOf`, `describeArchitecture`, `describeStatus` and `runArchitectureCommand`.
33
+ It runs on Node 22.18 or later. The same functions are exported for apps: `readDirectory`, `directoryHealth`, `resolveCode`, `taxonomyOf`, `describeDirectory`, `describeStatus` and `runDirectoryCommand`.
34
34
 
35
35
  The package ships TypeScript source. Bundlers and `tsx` read it as is; for a plain Node script, import `@0001-labs/idv1/register` first, then load the code that imports the package with `await import()`.
36
36
 
37
+ ## Explorer utility
38
+
39
+ Import `createExplorer` and `mountExplorer` from `@0001-labs/idv1/explorer`, and `@0001-labs/idv1/explorer.css` for the browser view. Supply `ExplorerData`: namespace names, shapes, taxonomies, identifiers, nodes and their links. The utility owns drill-down, counts, identifier resolution, taxonomy highlighting, keyboard navigation and URL history. Optional `collections` carry existing source records and lazy `load` functions; records may link to their host’s details with `href`. It contains no application records or network requests.
40
+
41
+ `createExplorer(data)` returns `entries(path)`, `title(path)` and `stepName(path, depth)` for any renderer. `mountExplorer(element, data)` renders that model and returns a cleanup function. Theme it with the `--idv1-explorer-*` CSS variables; its host owns loading and authorization.
42
+
37
43
  ## Upgrading from 0.3.x to Release 1
38
44
 
39
45
  Release 1 uses five shapes. Here `L` is an ASCII letter and `N` is a digit.
package/bin/idv1.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { existsSync, readFileSync } from 'node:fs'
3
3
  import { dirname, join, resolve } from 'node:path'
4
4
  import '../register.mjs'
5
- const { runArchitectureCommand } = await import('../src/idv1.ts')
5
+ const { runDirectoryCommand } = await import('../src/idv1.ts')
6
6
 
7
7
  const [command, ...args] = process.argv.slice(2)
8
8
  let dir = resolve(process.cwd())
@@ -12,6 +12,6 @@ if (!existsSync(file)) {
12
12
  console.error('No .id file here or above. See https://idv1.0001.dev/docs/annotate')
13
13
  process.exit(2)
14
14
  }
15
- const { code, out } = runArchitectureCommand(command, args, readFileSync(file, 'utf8'), path => existsSync(join(dir, path)))
15
+ const { code, out } = runDirectoryCommand(command, args, readFileSync(file, 'utf8'), path => existsSync(join(dir, path)))
16
16
  console.log(out)
17
17
  process.exit(code)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0001-labs/idv1",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "Six-character IDs for agents: five shapes, taxonomy and namespaces, and a CLI that reads a codebase's .id file.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -19,8 +19,10 @@
19
19
  ],
20
20
  "type": "module",
21
21
  "exports": {
22
- ".": "./src/idv1.ts",
23
- "./register": "./register.mjs"
22
+ ".": "./src/directory.ts",
23
+ "./register": "./register.mjs",
24
+ "./explorer": "./src/util/explorer.ts",
25
+ "./explorer.css": "./src/util/explorer.css"
24
26
  },
25
27
  "engines": {
26
28
  "node": ">=22.18"
@@ -29,7 +31,6 @@
29
31
  "@types/node": "^22.13.1",
30
32
  "tsrs": "0.18.0-ts7.1.0-dev.20260929",
31
33
  "typescript": "^6.0.3",
32
- "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0",
33
34
  "vite-plus": "1.3.0"
34
35
  },
35
36
  "devEngines": {
@@ -46,7 +47,6 @@
46
47
  },
47
48
  "scripts": {
48
49
  "check": "vp exec tsrs --noEmit",
49
- "test": "vp test run",
50
50
  "release": "node scripts/release.mjs",
51
51
  "release:pilot": "node scripts/release-pilot.mjs"
52
52
  }
@@ -0,0 +1,8 @@
1
+ export type { AccountId, ListId, ProjectId, ItemId, EventId } from './identifier'
2
+ export * from './identifier'
3
+ export type { Namespace } from './namespace'
4
+ export { taxonomyOf, type Taxonomy } from './taxonomy'
5
+ export * from './util/capacity'
6
+ export * from './util/blockedWords'
7
+ export * from './util/scan'
8
+ export * from './idv1'
package/src/identifier.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { blockedCodeLetters, blockedProjectCode } from './words'
1
+ import { blockedCodeLetters, blockedProjectCode } from './util/blockedWords'
2
2
 
3
3
  export const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
4
4
  export const CAPITALS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
@@ -105,3 +105,20 @@ export function accountCodeCaseVariants(code: string): string[] {
105
105
  const [first, second] = [code[0], code[1]].map(letter => [...new Set([letter.toUpperCase(), letter.toLowerCase()])])
106
106
  return first.flatMap(a => second.map(b => a + b + code.slice(2)))
107
107
  }
108
+
109
+ export const JUNCTION_SEPARATOR = '-'
110
+
111
+ export function junction(...codes: string[]): string {
112
+ if (codes.length < 2) throw new Error('A junction joins two codes or more.')
113
+ for (const code of codes) if (!codeKind(code)) throw new Error(`${code} is no IDv1 code.`)
114
+ return codes.join(JUNCTION_SEPARATOR)
115
+ }
116
+
117
+ export function junctionParts(value: string): { code: string; kind: CodeKind }[] | null {
118
+ const codes = value.split(JUNCTION_SEPARATOR)
119
+ if (codes.length < 2) return null
120
+ const parts = codes.map(code => ({ code, kind: codeKind(code) }))
121
+ return parts.every((part): part is { code: string; kind: CodeKind } => part.kind !== null) ? parts : null
122
+ }
123
+
124
+ export const isJunction = (value: string): boolean => junctionParts(value) !== null
package/src/idv1.ts CHANGED
@@ -1,8 +1,111 @@
1
- export * from './identifier'
1
+ import { JUNCTION_SEPARATOR, parseCode, type CodeKind } from './identifier'
2
+ import { blockedCodeLetters, blockedProjectCode } from './util/blockedWords'
3
+ import { namespaceHealth, namespaceOf, type Namespace } from './namespace'
4
+ import { taxonomyHealth, taxonomyOf, type Taxonomy } from './taxonomy'
5
+
2
6
  export type { Namespace } from './namespace'
3
7
  export { taxonomyOf, type Taxonomy } from './taxonomy'
4
- export * from './space'
5
- export * from './junction'
6
- export * from './words'
7
- export * from './scanCode'
8
- export * from './architecture'
8
+ export type Part = { id: string; shape: CodeKind; name: string; path: string | null }
9
+ export type Directory = { namespaces: Namespace[]; taxonomies: Taxonomy[]; parts: Part[]; facts: string[] }
10
+ export type Resolved = { id: string; shape: CodeKind | null; namespace?: Namespace; taxonomy?: Taxonomy; part?: Part; facts: string[] }
11
+
12
+ const SHAPES: CodeKind[] = ['account', 'list', 'project', 'item', 'event']
13
+ const list = <T>(value: unknown): T[] => (Array.isArray(value) ? value : []) as T[]
14
+
15
+ export function readDirectory(text: string): Directory {
16
+ const value = JSON.parse(text) as Partial<Directory>
17
+ return { namespaces: list(value.namespaces), taxonomies: list(value.taxonomies), parts: list(value.parts), facts: list(value.facts) }
18
+ }
19
+
20
+ export function directoryHealth(directory: Directory, exists: (path: string) => boolean = () => true): string[] {
21
+ const problems: string[] = []
22
+ const seen = (values: string[], what: string) => values.forEach((value, index) => { if (values.indexOf(value) !== index) problems.push(`${what} ${value} is declared twice`) })
23
+ problems.push(...namespaceHealth(directory.namespaces), ...taxonomyHealth(directory.taxonomies))
24
+ seen(directory.namespaces.map(namespace => namespace.shorthand), 'Namespace')
25
+ seen(directory.taxonomies.map(taxonomy => taxonomy.shorthand), 'Taxonomy')
26
+ seen(directory.parts.map(part => part.id), 'Id')
27
+ const ids = new Set(directory.parts.map(part => part.id))
28
+ for (const part of directory.parts) {
29
+ const shape = parseCode(part.id)?.kind
30
+ if (shape !== part.shape) problems.push(`${part.id} reads as ${shape ?? 'no shape'}, not ${part.shape}`)
31
+ else if (shape === 'project' ? blockedProjectCode(part.id) : blockedCodeLetters(part.id)) problems.push(`${part.id} uses blocked letters or digits`)
32
+ if (!part.name) problems.push(`${part.id} has no name`)
33
+ if (part.path && !exists(part.path)) problems.push(`${part.id}: ${part.path} is gone`)
34
+ }
35
+ for (const fact of directory.facts) {
36
+ const [subject, relation, object, extra] = fact.split(' ')
37
+ if (extra !== undefined || !/^r[A-Za-z]{5}$/.test(relation ?? '')) problems.push(`Not a fact: ${fact}`)
38
+ else for (const id of [subject, object]) if (!ids.has(id)) problems.push(`Unknown id ${id} in: ${fact}`)
39
+ }
40
+ return problems
41
+ }
42
+
43
+ export function resolveCode(directory: Directory, value: string): Resolved[] {
44
+ const qualified = /^-([A-Z]{2})-(.+)$/.exec(value)
45
+ const ids = (qualified ? qualified[2] : value).split(JUNCTION_SEPARATOR)
46
+ return ids.map(id => {
47
+ const shape = parseCode(id)?.kind ?? null
48
+ const namespace = namespaceOf(directory, id, qualified?.[1])
49
+ const facts = directory.facts.filter(fact => { const [subject, , object] = fact.split(' '); return subject === id || object === id })
50
+ return { id, shape, namespace, taxonomy: shape ? taxonomyOf(directory, id) : undefined, part: directory.parts.find(part => part.id === id), facts }
51
+ })
52
+ }
53
+
54
+ const nameOf = (directory: Directory, id: string) => directory.parts.find(part => part.id === id)?.name ?? id
55
+ const readFact = (directory: Directory, fact: string) => { const [subject, relation, object] = fact.split(' '); return `${subject} ${relation} ${object} ${nameOf(directory, subject)} → ${nameOf(directory, object)}` }
56
+
57
+ export function describeResolved(directory: Directory, resolved: Resolved[]): string {
58
+ return resolved.map(({ id, shape, namespace, taxonomy, part, facts }) => [
59
+ `${id} ${part?.name ?? (shape ? 'not in .id' : 'not a code')}`,
60
+ ` shape ${shape ?? '—'}`,
61
+ ...(taxonomy ? [` taxonomy ${taxonomy.shorthand} · ${taxonomy.name}`] : []),
62
+ ...(namespace ? [` namespace ${namespace.shorthand} · ${namespace.name}`] : []),
63
+ ...(part?.path ? [` path ${part.path}`] : []),
64
+ ...facts.map(fact => ` fact ${readFact(directory, fact)}`),
65
+ ].join('\n')).join('\n\n')
66
+ }
67
+
68
+ export function describeStatus(directory: Directory, problems: string[]): string {
69
+ const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
70
+ const shapes = SHAPES.map(shape => [shape, directory.parts.filter(part => part.shape === shape).length] as const).filter(([, n]) => n)
71
+ return [
72
+ `${count(directory.parts.length, 'part')} · ${count(directory.facts.length, 'fact')} · ${count(directory.namespaces.length, 'namespace')} · ${count(directory.taxonomies.length, 'taxonomy', 'taxonomies')}`,
73
+ problems.length ? `${count(problems.length, 'problem')}: run idv1 health` : 'healthy',
74
+ '',
75
+ ...shapes.map(([shape, n]) => ` ${shape.padEnd(9)}${n}`),
76
+ ...directory.taxonomies.map(taxonomy => ` ${taxonomy.shorthand.padEnd(9)}${directory.parts.filter(part => taxonomyOf(directory, part.id) === taxonomy).length} ${taxonomy.name}`),
77
+ ].join('\n')
78
+ }
79
+
80
+ export function describeDirectory(directory: Directory): string {
81
+ const contains = directory.facts.map(fact => fact.split(' ')).filter(([, relation]) => relation === 'rHasPt')
82
+ const children = (id: string) => contains.filter(([subject]) => subject === id).map(([, , object]) => object)
83
+ const roots = directory.parts.filter(part => !contains.some(([, , object]) => object === part.id))
84
+ const line = (part: Part | undefined, id: string, depth: number) => `${' '.repeat(depth)}${id} ${part?.name ?? '?'}${part && taxonomyOf(directory, id) ? ` (${taxonomyOf(directory, id)!.name})` : ''}${part?.path ? ` ${part.path}` : ''}`
85
+ const tree = (id: string, depth: number, trail: Set<string>): string[] => trail.has(id) ? [] : [line(directory.parts.find(part => part.id === id), id, depth), ...children(id).flatMap(child => tree(child, depth + 1, new Set([...trail, id])))]
86
+ return [
87
+ 'Namespaces',
88
+ ...directory.namespaces.map(({ shorthand, name }) => ` ${shorthand} ${name}`),
89
+ '',
90
+ 'Taxonomies',
91
+ ...directory.taxonomies.map(({ shorthand, name, shape, pattern }) => ` ${shorthand} ${name} ${shape} ${pattern}`),
92
+ '',
93
+ 'Parts',
94
+ ...roots.flatMap(part => tree(part.id, 1, new Set())),
95
+ '',
96
+ 'Facts',
97
+ ...directory.facts.filter(fact => fact.split(' ')[1] !== 'rHasPt').map(fact => ` ${readFact(directory, fact)}`),
98
+ ].join('\n')
99
+ }
100
+
101
+ export function runDirectoryCommand(command: string | undefined, args: string[], text: string, exists?: (path: string) => boolean): { code: number; out: string } {
102
+ const directory = readDirectory(text)
103
+ const problems = directoryHealth(directory, exists)
104
+ switch (command) {
105
+ case 'health': return { code: problems.length ? 1 : 0, out: problems.length ? problems.join('\n') : 'healthy' }
106
+ case 'status': return { code: 0, out: describeStatus(directory, problems) }
107
+ case 'resolve': return args.length ? { code: 0, out: args.map(value => describeResolved(directory, resolveCode(directory, value))).join('\n\n') } : { code: 2, out: 'idv1 resolve <id | junction | -NS-id>' }
108
+ case 'directory': case undefined: return { code: 0, out: describeDirectory(directory) }
109
+ default: return { code: 2, out: 'idv1 directory | status | health | resolve <id>' }
110
+ }
111
+ }
package/src/taxonomy.ts CHANGED
@@ -2,9 +2,9 @@ import { CODE_PATTERN, parseCode, type CodeKind } from './identifier'
2
2
 
3
3
  export type Taxonomy = { shorthand: string; name: string; shape: CodeKind; pattern: string }
4
4
 
5
- export function taxonomyOf(architecture: { taxonomies: Taxonomy[] }, id: string): Taxonomy | undefined {
5
+ export function taxonomyOf(directory: { taxonomies: Taxonomy[] }, id: string): Taxonomy | undefined {
6
6
  const shape = parseCode(id)?.kind
7
- return architecture.taxonomies.find(taxonomy => {
7
+ return directory.taxonomies.find(taxonomy => {
8
8
  const at = taxonomy.pattern.replace(/\s/g, '').indexOf(taxonomy.shorthand)
9
9
  return taxonomy.shape === shape && at >= 0 && id.slice(at, at + 2) === taxonomy.shorthand
10
10
  })
@@ -0,0 +1,16 @@
1
+ const LETTERS = 52
2
+ const DIGITS = 10
3
+ export const TOTAL_ID_CAPACITY = (LETTERS + DIGITS) ** 6
4
+ const accounts = LETTERS ** 2 * DIGITS ** 4
5
+ const lists = DIGITS ** 2 * LETTERS ** 4
6
+ const projects = LETTERS ** 4 * DIGITS ** 2
7
+ const items = LETTERS ** 2 * DIGITS ** 2 * ((LETTERS + DIGITS) ** 2 - DIGITS ** 2)
8
+
9
+ export const ID_CAPACITY = { accounts, lists, projects, items, events: TOTAL_ID_CAPACITY - accounts - lists - projects - items } as const
10
+ export type IdCapacityKind = keyof typeof ID_CAPACITY
11
+
12
+ export function idUsage(kind: IdCapacityKind, used: number): { used: number; capacity: number; left: number; percent: number } {
13
+ const capacity = ID_CAPACITY[kind]
14
+ if (!Number.isSafeInteger(used) || used < 0) throw new RangeError('Usage must be a nonnegative safe integer.')
15
+ return { used, capacity, left: Math.max(0, capacity - used), percent: (used / capacity) * 100 }
16
+ }
@@ -0,0 +1,10 @@
1
+ .explorer { --unit: var(--idv1-explorer-unit, 20px); --cell: calc(var(--unit) / 2); --ink: var(--idv1-explorer-ink, #fff); --rule: color-mix(in oklab, var(--ink) 22%, transparent); color-scheme: dark; min-height: calc(6 * var(--unit)); background-color: var(--idv1-explorer-paper, #282828); color: var(--ink); font-family: var(--idv1-explorer-font, sans-serif); font-size: var(--idv1-explorer-size, 14px); }
2
+ .explorer-path { display: flex; flex-wrap: wrap; column-gap: calc(var(--unit) / 2); }
3
+ .explorer-rows { display: flex; flex-direction: column; }
4
+ .explorer-taxonomy { color: var(--idv1-explorer-accent, #fec20d); }
5
+ .explorer-row { display: grid; grid-template-columns: calc(8 * var(--cell)) minmax(0, 1fr) auto calc(4 * var(--cell)); column-gap: calc(var(--unit) / 2); margin: 0; color: inherit; text-decoration: none; }
6
+ .explorer-step, .explorer-title, .explorer-row > span, p.explorer-row { box-sizing: border-box; display: block; height: var(--unit); padding-top: calc(var(--unit) / 5); line-height: calc(var(--unit) * 4 / 5); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: inherit; text-decoration: none; }
7
+ .explorer-row > .explorer-mono { font-family: var(--idv1-explorer-mono, monospace); font-variant-numeric: tabular-nums; white-space: pre; text-overflow: clip; letter-spacing: calc(var(--cell) - 1ch); padding-inline-start: calc((var(--cell) - 1ch) / 2); box-shadow: inset 0 0 0 1px var(--rule); background-image: linear-gradient(to right, var(--rule) 2px, transparent 2px), linear-gradient(to right, color-mix(in oklab, var(--ink) 9%, transparent) 1px, transparent 1px); background-size: var(--unit) 100%, var(--cell) 100%; }
8
+ .explorer-title { margin-inline-start: auto; }
9
+ .explorer-dim, .explorer-step:not(:last-of-type) { color: color-mix(in oklab, var(--ink) 55%, transparent); }
10
+ .explorer :is(a:hover, a:focus-visible) { background-color: color-mix(in oklab, var(--ink) 14%, transparent); outline: none; }
@@ -0,0 +1,233 @@
1
+ export type ExplorerRecord = { key: string; id?: string; label: string; kind?: string; href?: string; children?: ExplorerRecord[]; load?: () => Promise<ExplorerRecord[]> };
2
+ export type ExplorerNode = { qualifiedId: string; namespace: string; shape: string; label: string; group: string; at?: number };
3
+ export type ExplorerLink = { subject: string; relation: string; object: string };
4
+ export type ExplorerTaxonomy = { tag: string; name: string; shape: string; pattern: string };
5
+ export type ExplorerShape = { name: string; label: string; pattern: string };
6
+ export type ExplorerIdentifier = { namespace: string; code: string; name: string; shape: string; on?: string };
7
+ export type ExplorerData = {
8
+ name: string;
9
+ namespace: string;
10
+ namespaces: { pair: string; name: string }[];
11
+ nodes: ExplorerNode[];
12
+ links: ExplorerLink[];
13
+ taxonomy: ExplorerTaxonomy[];
14
+ shapes: ExplorerShape[];
15
+ identifiers: ExplorerIdentifier[];
16
+ collections?: ExplorerRecord[];
17
+ };
18
+ type Node = ExplorerNode;
19
+ type Taxonomy = ExplorerTaxonomy;
20
+ type Identifier = ExplorerIdentifier;
21
+ export type ExplorerEntry = { path: string[]; id: string; label: string; kind: string; count: number; href?: string };
22
+ type Entry = ExplorerEntry;
23
+
24
+ export function createExplorer(data: ExplorerData) {
25
+ const { taxonomy, shapes, identifiers } = data;
26
+ const nodes = new Map(data.nodes.map(node => [node.qualifiedId, node]));
27
+ const children = new Map<string, string[]>();
28
+ const parents = new Map<string, string[]>();
29
+ const add = (map: Map<string, string[]>, parent: string, child: string) => {
30
+ const list = map.get(parent) ?? [];
31
+ if (!list.includes(child)) map.set(parent, [...list, child]);
32
+ };
33
+ for (const { subject, relation, object } of data.links) {
34
+ if (!nodes.has(subject) || !nodes.has(object)) continue;
35
+ if (['part of', 'defined by', 'member of'].includes(relation)) {
36
+ add(children, object, subject);
37
+ add(parents, subject, object);
38
+ } else if (relation === 'uses') {
39
+ add(children, subject, object);
40
+ add(children, object, subject);
41
+ }
42
+ }
43
+ const namespaces = () => [...new Set([...nodes.values()].map(node => node.namespace))]
44
+ .sort((a, b) => (a === data.namespace ? -1 : b === data.namespace ? 1 : a.localeCompare(b)));
45
+ const topLevel = (namespace: string) => [...nodes.values()].filter(node => node.namespace === namespace && node.at === undefined
46
+ && !(parents.get(node.qualifiedId) ?? []).some(parent => nodes.get(parent)?.namespace === namespace));
47
+ const owner = (namespace: string) => data.namespaces.find(entry => entry.pair === namespace);
48
+ const short = (id: string) => id.length === 2 ? id : id.slice(1, 3) + id.slice(4);
49
+ const byKind = (a: Node, b: Node) => (b.at ?? 0) - (a.at ?? 0) || a.group.localeCompare(b.group) || a.label.localeCompare(b.label);
50
+
51
+ const tagged = (entry: Taxonomy) => [...nodes.values()].filter(node =>
52
+ node.shape === entry.shape && node.qualifiedId.slice(4).slice(entry.pattern.indexOf(entry.tag)).startsWith(entry.tag));
53
+ const identifierKey = (entry: Identifier) => `-${entry.namespace}-${entry.code}`;
54
+ const named = (id: string) => {
55
+ const entry = identifiers.find(entry => identifierKey(entry) === id);
56
+ const target = entry && 'on' in entry && entry.on ? `-${entry.namespace}-${entry.on}` : id;
57
+ return [...nodes.values()].filter(node => node.qualifiedId === target);
58
+ };
59
+ const lists: Record<string, string> = { shapes: 'Shapes', namespaces: 'Namespaces', taxonomies: 'Taxonomies', identifiers: 'Identifiers' };
60
+ const shapeName = (name: string) => shapes.find(kind => kind.name === name)?.label ?? name;
61
+ const ofShape = (name: string) => [...nodes.values()].filter(node => node.shape === name);
62
+ const scope = (path: string[]) => { const at = path.at(-1); return !at || lists[at] ? data.namespace : at.length === 2 ? at : at.includes(':') ? '' : nodes.get(at)?.namespace ?? ''; };
63
+ const idIn = (id: string, namespace: string) => id.length > 2 && id.slice(1, 3) === namespace ? id.slice(4) : short(id);
64
+ const kindOf = (node: Node) => taxonomy.find(entry => entry.shape === node.shape && node.qualifiedId.slice(4).slice(entry.pattern.indexOf(entry.tag)).startsWith(entry.tag))?.name ?? shapeName(node.shape);
65
+ const rowsOf = (path: string[], list: Node[]): Entry[] => list.sort(byKind).map(node => ({
66
+ path: [...path, node.qualifiedId], id: idIn(node.qualifiedId, scope(path)), label: node.label, kind: kindOf(node), count: children.get(node.qualifiedId)?.length ?? 0,
67
+ }));
68
+
69
+ const record = (path: string[]) => {
70
+ let records = data.collections ?? [];
71
+ let found: ExplorerRecord | undefined;
72
+ for (const step of path) {
73
+ found = records.find(entry => `rc:${encodeURIComponent(entry.key)}` === step);
74
+ if (!found) return undefined;
75
+ records = found.children ?? [];
76
+ }
77
+ return found;
78
+ };
79
+ const recordEntries = (path: string[], records: ExplorerRecord[]) => records.map(entry => ({ path: [...path, `rc:${encodeURIComponent(entry.key)}`], id: entry.id ?? '', label: entry.label, kind: entry.kind ?? '', count: entry.children?.length ?? 0, href: entry.href }));
80
+ const load = async (path: string[]) => {
81
+ for (let depth = 1; depth <= path.length; depth++) {
82
+ const entry = record(path.slice(0, depth));
83
+ if (entry?.load && !entry.children) entry.children = await entry.load();
84
+ }
85
+ };
86
+ function entries(path: string[]): Entry[] {
87
+ const at = path.at(-1);
88
+ if (!at) return [
89
+ { path: ['shapes'], id: '', label: 'Shapes', kind: '', count: shapes.length },
90
+ { path: ['namespaces'], id: '', label: 'Namespaces', kind: '', count: namespaces().length },
91
+ { path: ['taxonomies'], id: '', label: 'Taxonomies', kind: '', count: taxonomy.length },
92
+ { path: ['identifiers'], id: '', label: 'Identifiers', kind: '', count: identifiers.length },
93
+ ...recordEntries([], data.collections ?? []),
94
+ ];
95
+ if (at.startsWith('rc:')) return recordEntries(path, record(path)?.children ?? []);
96
+ if (at === 'namespaces') return namespaces().map(namespace => ({
97
+ path: [namespace], id: namespace, label: owner(namespace)?.name ?? namespace, kind: 'Namespace', count: topLevel(namespace).length,
98
+ }));
99
+ if (at === 'shapes') return shapes.map(kind => ({ path: [`sh:${kind.name}`], id: kind.pattern, label: kind.label, kind: 'Shape', count: ofShape(kind.name).length }));
100
+ if (at === 'taxonomies') return taxonomy.map(entry => ({
101
+ path: [`tx:${entry.tag}`], id: entry.pattern, label: entry.name, kind: shapeName(entry.shape), count: tagged(entry).length,
102
+ }));
103
+ if (at === 'identifiers') return identifiers.map(entry => ({
104
+ path: [`id:${identifierKey(entry)}`], id: idIn(identifierKey(entry), scope(path)), label: entry.name, kind: named(identifierKey(entry))[0] ? kindOf(named(identifierKey(entry))[0]) : shapeName(entry.shape), count: named(identifierKey(entry)).length,
105
+ }));
106
+ if (at.startsWith('id:')) return rowsOf(path, named(at.slice(3)));
107
+ if (at.startsWith('sh:')) return rowsOf(path, ofShape(at.slice(3)));
108
+ if (at.startsWith('tx:')) { const entry = taxonomy.find(item => item.tag === at.slice(3)); return entry ? rowsOf(path, tagged(entry)) : []; }
109
+ if (at.length === 2) return rowsOf(path, topLevel(at));
110
+ return rowsOf(path, (children.get(at) ?? []).flatMap(id => nodes.get(id) ?? []));
111
+ }
112
+
113
+ const stepName = (path: string[], depth: number) => { const step = path[depth - 1]; return record(path.slice(0, depth))?.label ?? lists[step] ?? (step.startsWith('sh:') ? shapeName(step.slice(3)) : step.startsWith('tx:') ? step.slice(3) : step.startsWith('id:') ? idIn(step.slice(3), scope(path.slice(0, depth - 1))) : idIn(step, scope(path.slice(0, depth - 1)))); };
114
+ function title(path: string[]) {
115
+ const at = path.at(-1);
116
+ if (!at) return data.name;
117
+ if (lists[at]) return lists[at];
118
+ if (at.startsWith('rc:')) return record(path)?.label ?? '';
119
+ if (at.startsWith('sh:')) return `${shapeName(at.slice(3))} · Shape`;
120
+ if (at.startsWith('tx:')) return `${taxonomy.find(entry => entry.tag === at.slice(3))?.name ?? at.slice(3)} · Taxonomy`;
121
+ if (at.startsWith('id:')) return `${identifiers.find(entry => identifierKey(entry) === at.slice(3))?.name ?? at.slice(3)} · Identifier`;
122
+ if (at.length === 2) return `${owner(at)?.name ?? at} · Namespace`;
123
+ const node = nodes.get(at);
124
+ return node ? `${node.label} · ${kindOf(node)}` : '';
125
+ }
126
+ return { entries, title, stepName, load };
127
+ }
128
+
129
+ export function mountExplorer(surface: HTMLElement, data: ExplorerData) {
130
+ const document = surface.ownerDocument;
131
+ const window = document.defaultView!;
132
+ const abort = new AbortController();
133
+ const { entries, title, stepName, load } = createExplorer(data);
134
+ const taxonomy = data.taxonomy;
135
+ surface.classList.add('explorer');
136
+ const pathLine = document.createElement('nav');
137
+ pathLine.className = 'explorer-path';
138
+ pathLine.setAttribute('aria-label', 'Path');
139
+ const rows = document.createElement('div');
140
+ rows.className = 'explorer-rows';
141
+ surface.replaceChildren(pathLine, rows);
142
+ const readPath = () => (new URLSearchParams(window.location.search).get('path') ?? '').split(',').filter(Boolean);
143
+ const href = (path: string[]) => { const url = new URL(window.location.href); if (path.length) url.searchParams.set('path', path.join(',')); else url.searchParams.delete('path'); return url.pathname + url.search + url.hash; };
144
+
145
+ function link(path: string[], className: string, parts: [string, string][], target?: string) {
146
+ const anchor = document.createElement('a');
147
+ anchor.className = className;
148
+ anchor.href = target ?? href(path);
149
+ if (!target) anchor.dataset.path = path.join(',');
150
+ for (const [text, part] of parts) {
151
+ const span = document.createElement('span');
152
+ span.className = part;
153
+ span.textContent = text;
154
+ const pattern = part === 'explorer-mono' && taxonomy.find(entry => entry.pattern === text.trim());
155
+ if (pattern) {
156
+ const start = text.indexOf(pattern.tag);
157
+ const letters = document.createElement('span');
158
+ letters.className = 'explorer-taxonomy';
159
+ letters.textContent = pattern.tag;
160
+ span.replaceChildren(text.slice(0, start), letters, text.slice(start + pattern.tag.length));
161
+ }
162
+ anchor.append(span);
163
+ }
164
+ return anchor;
165
+ }
166
+
167
+ function render(focusFirst = false) {
168
+ const path = readPath();
169
+ const corner = document.createElement('span');
170
+ corner.className = 'explorer-title';
171
+ corner.textContent = title(path);
172
+ pathLine.replaceChildren(...[data.name, ...path].map((step, depth) =>
173
+ link(path.slice(0, depth), 'explorer-step', [[`${depth ? stepName(path, depth) : step} /`, '']])), corner);
174
+ const list = entries(path);
175
+ rows.replaceChildren(...list.map(entry => link(entry.path, 'explorer-row', [
176
+ [entry.id.padEnd(8), 'explorer-mono'],
177
+ [entry.label, ''],
178
+ [entry.kind, 'explorer-dim'],
179
+ [entry.count ? `${String(entry.count).padStart(3)}/` : ' ', 'explorer-mono explorer-dim'],
180
+ ], entry.href)));
181
+ if (!list.length) {
182
+ const empty = document.createElement('p');
183
+ empty.className = 'explorer-row explorer-dim';
184
+ empty.textContent = 'Nothing recorded inside.';
185
+ rows.append(empty);
186
+ }
187
+ if (focusFirst) (rows.querySelector<HTMLElement>('a') ?? pathLine.lastElementChild as HTMLElement)?.focus();
188
+ }
189
+
190
+ let pending = 0;
191
+ async function show(focus = false) {
192
+ const current = ++pending;
193
+ const path = readPath();
194
+ surface.setAttribute('aria-busy', 'true');
195
+ try {
196
+ await load(path);
197
+ if (current === pending && !abort.signal.aborted) render(focus);
198
+ } catch {
199
+ if (current === pending && !abort.signal.aborted) { render(); rows.textContent = 'Could not load these records. Open this list again to retry.'; }
200
+ } finally {
201
+ if (current === pending) surface.removeAttribute('aria-busy');
202
+ }
203
+ }
204
+ function go(path: string[]) {
205
+ window.history.pushState(null, '', href(path));
206
+ void show(true);
207
+ }
208
+
209
+ surface.addEventListener('click', event => {
210
+ const anchor = (event.target as HTMLElement).closest<HTMLAnchorElement>('a[data-path]');
211
+ if (!anchor || event.metaKey || event.ctrlKey || event.shiftKey) return;
212
+ event.preventDefault();
213
+ go(anchor.dataset.path!.split(',').filter(Boolean));
214
+ }, { signal: abort.signal });
215
+ surface.addEventListener('keydown', event => {
216
+ const links = [...rows.querySelectorAll<HTMLElement>('a')];
217
+ const at = links.indexOf(document.activeElement as HTMLElement);
218
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
219
+ event.preventDefault();
220
+ links[Math.max(0, Math.min(links.length - 1, at + (event.key === 'ArrowDown' ? 1 : -1)))]?.focus();
221
+ } else if (event.key === 'ArrowRight' && at >= 0) {
222
+ event.preventDefault();
223
+ links[at].click();
224
+ } else if ((event.key === 'ArrowLeft' || event.key === 'Backspace') && readPath().length) {
225
+ event.preventDefault();
226
+ go(readPath().slice(0, -1));
227
+ }
228
+ }, { signal: abort.signal });
229
+ window.addEventListener('popstate', () => { void show(true); }, { signal: abort.signal });
230
+
231
+ void show();
232
+ return () => { abort.abort(); surface.replaceChildren(); };
233
+ }
@@ -1,11 +1,11 @@
1
- import { ALPHABET, isAccountCode, isListCode, parseCode, type Id } from './identifier'
1
+ import { ALPHABET, isAccountCode, isListCode, parseCode, type Id } from '../identifier'
2
2
 
3
3
  const alphabet = ALPHABET
4
- export const scanCodeColumns = 16
5
- export const scanCodeRows = 4
4
+ export const scanColumns = 16
5
+ export const scanRows = 4
6
6
  export const CODE_END_RADIUS = 0.1
7
7
 
8
- function scanCodeChecksum(bytes: readonly number[]): number {
8
+ function scanChecksum(bytes: readonly number[]): number {
9
9
  let crc = 0xffff
10
10
  for (const byte of bytes) {
11
11
  crc ^= byte << 8
@@ -14,28 +14,28 @@ function scanCodeChecksum(bytes: readonly number[]): number {
14
14
  return crc
15
15
  }
16
16
 
17
- export function encodeScanCode(id: string): boolean[] | null {
17
+ export function encodeScan(id: string): boolean[] | null {
18
18
  if (!parseCode(id)) return null
19
19
  let value = 0
20
20
  for (const character of id) value = value * 62 + alphabet.indexOf(character)
21
21
  const bytes = [3]
22
22
  for (let shift = 32; shift >= 0; shift -= 8) bytes.push(Math.floor(value / 2 ** shift) & 255)
23
- const crc = scanCodeChecksum(bytes)
23
+ const crc = scanChecksum(bytes)
24
24
  bytes.push(crc >> 8, crc & 255)
25
25
  return bytes.flatMap(byte => Array.from({ length: 8 }, (_, bit) => !!(byte & (1 << (7 - bit)))))
26
26
  }
27
27
 
28
- export function scanCodePath(bits: readonly boolean[], { ink = (bit: boolean) => !bit, cell = 1, x = 0, y = 0, radius = 0 }: { ink?: (bit: boolean) => boolean; cell?: number; x?: number; y?: number; radius?: number } = {}): string {
28
+ export function scanPath(bits: readonly boolean[], { ink = (bit: boolean) => !bit, cell = 1, x = 0, y = 0, radius = 0 }: { ink?: (bit: boolean) => boolean; cell?: number; x?: number; y?: number; radius?: number } = {}): string {
29
29
  const round = (value: number) => Math.round(value * 1e4) / 1e4
30
30
  const inked = (row: number, column: number) =>
31
- row >= 0 && row < scanCodeRows && column >= 0 && column < scanCodeColumns && ink(bits[row * scanCodeColumns + column])
31
+ row >= 0 && row < scanRows && column >= 0 && column < scanColumns && ink(bits[row * scanColumns + column])
32
32
  const r = Math.min(Math.max(radius, 0), 0.5) * cell
33
33
  let d = ''
34
- for (let row = 0; row < scanCodeRows; row++) {
35
- for (let column = 0; column < scanCodeColumns;) {
34
+ for (let row = 0; row < scanRows; row++) {
35
+ for (let column = 0; column < scanColumns;) {
36
36
  if (!inked(row, column)) { column++; continue }
37
37
  const start = column
38
- while (column < scanCodeColumns && inked(row, column)) column++
38
+ while (column < scanColumns && inked(row, column)) column++
39
39
  const left = x + start * cell, right = x + column * cell, top = y + row * cell, bottom = top + cell
40
40
  if (!r) {
41
41
  d += `M${round(left)} ${round(top)}h${round(right - left)}v${round(cell)}h${round(left - right)}z`
@@ -54,8 +54,8 @@ export function scanCodePath(bits: readonly boolean[], { ink = (bit: boolean) =>
54
54
  }
55
55
  }
56
56
  if (!r) return d
57
- for (let row = 0; row < scanCodeRows; row++) {
58
- for (let column = 0; column < scanCodeColumns; column++) {
57
+ for (let row = 0; row < scanRows; row++) {
58
+ for (let column = 0; column < scanColumns; column++) {
59
59
  if (inked(row, column)) continue
60
60
  const left = x + column * cell, top = y + row * cell
61
61
  for (const [dy, dx] of [[-1, -1], [-1, 1], [1, 1], [1, -1]] as const) {
@@ -73,7 +73,7 @@ export function scanCodePath(bits: readonly boolean[], { ink = (bit: boolean) =>
73
73
 
74
74
  const idSpace = 62 ** 6
75
75
 
76
- export function decodeScanCode(bits: readonly boolean[]): Id | null {
76
+ export function decodeScan(bits: readonly boolean[]): Id | null {
77
77
  if (bits.length !== 64) return null
78
78
  const bytes: number[] = []
79
79
  for (let offset = 0; offset < 64; offset += 8) {
@@ -81,7 +81,7 @@ export function decodeScanCode(bits: readonly boolean[]): Id | null {
81
81
  for (let bit = 0; bit < 8; bit++) byte = (byte << 1) | (bits[offset + bit] ? 1 : 0)
82
82
  bytes.push(byte)
83
83
  }
84
- if (bytes[0] !== 3 || scanCodeChecksum(bytes.slice(0, 6)) !== ((bytes[6] << 8) | bytes[7])) return null
84
+ if (bytes[0] !== 3 || scanChecksum(bytes.slice(0, 6)) !== ((bytes[6] << 8) | bytes[7])) return null
85
85
  let value = 0
86
86
  for (const byte of bytes.slice(1, 6)) value = value * 256 + byte
87
87
  if (value >= idSpace) return null
@@ -107,7 +107,7 @@ const insetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({
107
107
  const offsetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({ ...rect, x: rect.x + dx, y: rect.y + dy })
108
108
  const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, value))
109
109
 
110
- export function sampleScanCode(width: number, height: number, luminance: Luminance, rect?: ScanRect): Id | null {
110
+ export function sampleScan(width: number, height: number, luminance: Luminance, rect?: ScanRect): Id | null {
111
111
  if (width < 80 || height < 20) return null
112
112
  const guideWidth = rect?.width ?? width * 0.8
113
113
  const guideHeight = rect?.height ?? guideWidth / 4
@@ -116,10 +116,10 @@ export function sampleScanCode(width: number, height: number, luminance: Luminan
116
116
  const top = rect?.y ?? (height - guideHeight) / 2
117
117
  const radius = guideWidth / 16 < 6 ? 0 : 1
118
118
  const levels: number[] = []
119
- for (let y = 0; y < scanCodeRows; y++) {
120
- for (let x = 0; x < scanCodeColumns; x++) {
121
- const px = Math.trunc(left + (x + 0.5) * guideWidth / scanCodeColumns)
122
- const py = Math.trunc(top + (y + 0.5) * guideHeight / scanCodeRows)
119
+ for (let y = 0; y < scanRows; y++) {
120
+ for (let x = 0; x < scanColumns; x++) {
121
+ const px = Math.trunc(left + (x + 0.5) * guideWidth / scanColumns)
122
+ const py = Math.trunc(top + (y + 0.5) * guideHeight / scanRows)
123
123
  let level = 0
124
124
  for (let dy = -radius; dy <= radius; dy++) {
125
125
  for (let dx = -radius; dx <= radius; dx++) level += luminance(clamp(px + dx, 0, width - 1), clamp(py + dy, 0, height - 1))
@@ -130,7 +130,7 @@ export function sampleScanCode(width: number, height: number, luminance: Luminan
130
130
  const low = Math.min(...levels), high = Math.max(...levels)
131
131
  if (high - low <= 8) return null
132
132
  const mid = (low + high) / 2
133
- return decodeScanCode(levels.map(level => level < mid)) ?? decodeScanCode(levels.map(level => level > mid))
133
+ return decodeScan(levels.map(level => level < mid)) ?? decodeScan(levels.map(level => level > mid))
134
134
  }
135
135
 
136
136
  function partedLevels(levels: readonly number[]): number | null {
@@ -151,17 +151,17 @@ function partedLevels(levels: readonly number[]): number | null {
151
151
 
152
152
  function levelledColumns(levels: readonly number[], lightest: boolean): number[] {
153
153
  const ground: number[] = []
154
- for (let column = 0; column < scanCodeColumns; column++) {
154
+ for (let column = 0; column < scanColumns; column++) {
155
155
  let found = lightest ? -Infinity : Infinity
156
- for (let near = Math.max(0, column - 1); near <= Math.min(scanCodeColumns - 1, column + 1); near++) {
157
- for (let row = 0; row < scanCodeRows; row++) {
158
- const level = levels[row * scanCodeColumns + near]
156
+ for (let near = Math.max(0, column - 1); near <= Math.min(scanColumns - 1, column + 1); near++) {
157
+ for (let row = 0; row < scanRows; row++) {
158
+ const level = levels[row * scanColumns + near]
159
159
  found = lightest ? Math.max(found, level) : Math.min(found, level)
160
160
  }
161
161
  }
162
162
  ground.push(found)
163
163
  }
164
- return levels.map((level, index) => level - ground[index % scanCodeColumns])
164
+ return levels.map((level, index) => level - ground[index % scanColumns])
165
165
  }
166
166
 
167
167
  const WRITTEN_SHARES = [0.8, 0.2, 0.95, 0.05] as const
@@ -170,20 +170,20 @@ export type ScanCorners = readonly [x0: number, y0: number, x1: number, y1: numb
170
170
 
171
171
  const rectCorners = (rect: ScanRect): ScanCorners => [rect.x, rect.y, rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height]
172
172
 
173
- export function sampleWrittenScanCode(width: number, height: number, luminance: Luminance, place: ScanRect | ScanCorners): Id | null {
173
+ export function sampleWrittenScan(width: number, height: number, luminance: Luminance, place: ScanRect | ScanCorners): Id | null {
174
174
  const [x0, y0, x1, y1, x2, y2, x3, y3] = 'width' in place ? rectCorners(place) : place
175
- const cell = Math.min(Math.hypot(x1 - x0, y1 - y0), Math.hypot(x2 - x3, y2 - y3)) / scanCodeColumns
175
+ const cell = Math.min(Math.hypot(x1 - x0, y1 - y0), Math.hypot(x2 - x3, y2 - y3)) / scanColumns
176
176
  if (cell < 5) return null
177
177
  const sampled = (inner: number): number[][] => {
178
178
  const across = Math.max(2, Math.min(7, Math.floor(cell * inner)))
179
179
  const cells: number[][] = []
180
- for (let row = 0; row < scanCodeRows; row++) {
181
- for (let column = 0; column < scanCodeColumns; column++) {
180
+ for (let row = 0; row < scanRows; row++) {
181
+ for (let column = 0; column < scanColumns; column++) {
182
182
  const values: number[] = []
183
183
  for (let j = 0; j < across; j++) {
184
- const v = (row + (1 - inner) / 2 + (inner * (j + 0.5)) / across) / scanCodeRows
184
+ const v = (row + (1 - inner) / 2 + (inner * (j + 0.5)) / across) / scanRows
185
185
  for (let i = 0; i < across; i++) {
186
- const u = (column + (1 - inner) / 2 + (inner * (i + 0.5)) / across) / scanCodeColumns
186
+ const u = (column + (1 - inner) / 2 + (inner * (i + 0.5)) / across) / scanColumns
187
187
  const px = Math.round((1 - v) * ((1 - u) * x0 + u * x1) + v * ((1 - u) * x3 + u * x2))
188
188
  const py = Math.round((1 - v) * ((1 - u) * y0 + u * y1) + v * ((1 - u) * y3 + u * y2))
189
189
  values.push(luminance(clamp(px, 0, width - 1), clamp(py, 0, height - 1)))
@@ -196,7 +196,7 @@ export function sampleWrittenScanCode(width: number, height: number, luminance:
196
196
  return cells
197
197
  }
198
198
  const taken = (dark: readonly boolean[]): Id | null => {
199
- const id = decodeScanCode(dark as boolean[]) ?? decodeScanCode(dark.map(bit => !bit))
199
+ const id = decodeScan(dark as boolean[]) ?? decodeScan(dark.map(bit => !bit))
200
200
  return id
201
201
  }
202
202
  const middles = sampled(0.6)
@@ -209,31 +209,31 @@ export function sampleWrittenScanCode(width: number, height: number, luminance:
209
209
  if (id) return id
210
210
  }
211
211
  }
212
- return sampleCutScanCode((u, v) => {
212
+ return sampleCutScan((u, v) => {
213
213
  const px = Math.round((1 - v) * ((1 - u) * x0 + u * x1) + v * ((1 - u) * x3 + u * x2))
214
214
  const py = Math.round((1 - v) * ((1 - u) * y0 + u * y1) + v * ((1 - u) * y3 + u * y2))
215
215
  return luminance(clamp(px, 0, width - 1), clamp(py, 0, height - 1))
216
216
  }, cell, taken)
217
217
  }
218
218
 
219
- function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, taken: (dark: readonly boolean[]) => Id | null): Id | null {
219
+ function sampleCutScan(at: (u: number, v: number) => number, cell: number, taken: (dark: readonly boolean[]) => Id | null): Id | null {
220
220
  const n = Math.max(4, Math.min(8, Math.round(cell * 0.8)))
221
- const count = scanCodeColumns * scanCodeRows, each = n * n
221
+ const count = scanColumns * scanRows, each = n * n
222
222
  const light = new Float32Array(count * each)
223
- for (let row = 0; row < scanCodeRows; row++) {
224
- for (let column = 0; column < scanCodeColumns; column++) {
225
- const base = (row * scanCodeColumns + column) * each
223
+ for (let row = 0; row < scanRows; row++) {
224
+ for (let column = 0; column < scanColumns; column++) {
225
+ const base = (row * scanColumns + column) * each
226
226
  for (let j = 0; j < n; j++) {
227
- for (let i = 0; i < n; i++) light[base + j * n + i] = at((column + 0.05 + (0.9 * (i + 0.5)) / n) / scanCodeColumns, (row + 0.05 + (0.9 * (j + 0.5)) / n) / scanCodeRows)
227
+ for (let i = 0; i < n; i++) light[base + j * n + i] = at((column + 0.05 + (0.9 * (i + 0.5)) / n) / scanColumns, (row + 0.05 + (0.9 * (j + 0.5)) / n) / scanRows)
228
228
  }
229
229
  }
230
230
  }
231
231
  const share = new Float32Array(count)
232
- for (let column = 0; column < scanCodeColumns; column++) {
232
+ for (let column = 0; column < scanColumns; column++) {
233
233
  const near: number[] = []
234
- for (let other = Math.max(0, column - 1); other <= Math.min(scanCodeColumns - 1, column + 1); other++) {
235
- for (let row = 0; row < scanCodeRows; row++) {
236
- const base = (row * scanCodeColumns + other) * each
234
+ for (let other = Math.max(0, column - 1); other <= Math.min(scanColumns - 1, column + 1); other++) {
235
+ for (let row = 0; row < scanRows; row++) {
236
+ const base = (row * scanColumns + other) * each
237
237
  for (let index = 0; index < each; index++) near.push(light[base + index])
238
238
  }
239
239
  }
@@ -241,8 +241,8 @@ function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, t
241
241
  const low = near[Math.floor(near.length * 0.1)], high = near[Math.floor(near.length * 0.9)]
242
242
  if (high - low <= 16) return null
243
243
  const cut = (low + high) / 2
244
- for (let row = 0; row < scanCodeRows; row++) {
245
- const index = row * scanCodeColumns + column
244
+ for (let row = 0; row < scanRows; row++) {
245
+ const index = row * scanColumns + column
246
246
  let dark = 0
247
247
  for (let k = 0; k < each; k++) if (light[index * each + k] < cut) dark++
248
248
  share[index] = dark / each
@@ -279,7 +279,7 @@ function lineThrough(points: readonly (readonly [number, number])[]): { a: numbe
279
279
  return { a: middle(points.map(([t, value]) => value - b * t)), b }
280
280
  }
281
281
 
282
- export function locateWrittenScanCode(width: number, height: number, luminance: Luminance, chroma: Chroma): ScanFound | null {
282
+ export function locateWrittenScan(width: number, height: number, luminance: Luminance, chroma: Chroma): ScanFound | null {
283
283
  const step = 2, columns = Math.floor(width / step), rows = Math.floor(height / step)
284
284
  if (columns < 40 || rows < 10) return null
285
285
  const size = columns * rows
@@ -354,7 +354,7 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
354
354
  const middleY = (corners[0][1] + corners[1][1] + corners[2][1] + corners[3][1]) / 4
355
355
  for (const scale of [1, 0.97, 1.03]) {
356
356
  const place = corners.flatMap(([x, y]) => [middleX + (x - middleX) * scale, middleY + (y - middleY) * scale]) as unknown as ScanCorners
357
- const id = sampleWrittenScanCode(width, height, luminance, place)
357
+ const id = sampleWrittenScan(width, height, luminance, place)
358
358
  if (id) return { id, rect: { x: left * step, y: top * step, width: w * step, height: h * step } }
359
359
  }
360
360
  }
@@ -362,7 +362,7 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
362
362
  return null
363
363
  }
364
364
 
365
- export function scanCodeRegions(width: number, height: number, foreground: Chroma): ScanRect[] {
365
+ export function scanRegions(width: number, height: number, foreground: Chroma): ScanRect[] {
366
366
  const step = 2, columns = Math.floor(width / step), rows = Math.floor(height / step)
367
367
  if (columns <= 0 || rows <= 0) return []
368
368
  const mask = new Uint8Array(columns * rows)
@@ -464,14 +464,14 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
464
464
  for (const dy of [0, -1, 1]) {
465
465
  for (const dx of [0, -1, 1]) {
466
466
  const at = offsetRect(rect, dx, dy)
467
- const id = sampleScanCode(width, height, luminance, at)
467
+ const id = sampleScan(width, height, luminance, at)
468
468
  if (id) return { id, rect: at }
469
469
  }
470
470
  }
471
471
  }
472
472
  return null
473
473
  }
474
- const colored = scanCodeRegions(width, height, (x, y) => luminance(x, y) > 70 && chroma(x, y))
474
+ const colored = scanRegions(width, height, (x, y) => luminance(x, y) > 70 && chroma(x, y))
475
475
  for (const bounds of colored) {
476
476
  const id = read(bounds)
477
477
  if (id) return id
@@ -486,7 +486,7 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
486
486
  }
487
487
  for (const threshold of [(darkest + lightest) / 2, 60, 130, 200]) {
488
488
  for (const light of [true, false]) {
489
- const candidates = scanCodeRegions(width, height, (x, y) => (light ? luminance(x, y) > threshold : luminance(x, y) < threshold))
489
+ const candidates = scanRegions(width, height, (x, y) => (light ? luminance(x, y) > threshold : luminance(x, y) < threshold))
490
490
  for (const bounds of candidates) {
491
491
  const id = read(bounds)
492
492
  if (id) return id
@@ -496,13 +496,13 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
496
496
  const w = width * 0.8
497
497
  const guide = read({ x: (width - w) / 2, y: (height - w / 4) / 2, width: w, height: w / 4 })
498
498
  if (guide) return guide
499
- const field = locateWrittenScanCode(width, height, luminance, chroma)
499
+ const field = locateWrittenScan(width, height, luminance, chroma)
500
500
  if (field) return field
501
501
  for (const bounds of tried) {
502
502
  if (bounds.width < 80) continue
503
503
  for (const fraction of [0, 0.03]) {
504
504
  const rect = insetRect(bounds, bounds.width * fraction, bounds.height * fraction)
505
- const id = sampleWrittenScanCode(width, height, luminance, rect)
505
+ const id = sampleWrittenScan(width, height, luminance, rect)
506
506
  if (id) return { id, rect }
507
507
  }
508
508
  }
@@ -1,112 +0,0 @@
1
- import { parseCode, type CodeKind } from './identifier'
2
- import { blockedCodeLetters, blockedProjectCode } from './words'
3
- import { JUNCTION_SEPARATOR } from './junction'
4
- import { namespaceHealth, namespaceOf, type Namespace } from './namespace'
5
- import { taxonomyHealth, taxonomyOf, type Taxonomy } from './taxonomy'
6
-
7
- export type { Namespace } from './namespace'
8
- export { taxonomyOf, type Taxonomy } from './taxonomy'
9
- export type Part = { id: string; shape: CodeKind; name: string; path: string | null }
10
- export type Architecture = { namespaces: Namespace[]; taxonomies: Taxonomy[]; parts: Part[]; facts: string[] }
11
- export type Resolved = { id: string; shape: CodeKind | null; namespace?: Namespace; taxonomy?: Taxonomy; part?: Part; facts: string[] }
12
-
13
- const SHAPES: CodeKind[] = ['account', 'list', 'project', 'item', 'event']
14
- const list = <T>(value: unknown): T[] => (Array.isArray(value) ? value : []) as T[]
15
-
16
- export function readArchitecture(text: string): Architecture {
17
- const value = JSON.parse(text) as Partial<Architecture>
18
- return { namespaces: list(value.namespaces), taxonomies: list(value.taxonomies), parts: list(value.parts), facts: list(value.facts) }
19
- }
20
-
21
- export function architectureHealth(architecture: Architecture, exists: (path: string) => boolean = () => true): string[] {
22
- const problems: string[] = []
23
- const seen = (values: string[], what: string) => values.forEach((value, index) => { if (values.indexOf(value) !== index) problems.push(`${what} ${value} is declared twice`) })
24
- problems.push(...namespaceHealth(architecture.namespaces), ...taxonomyHealth(architecture.taxonomies))
25
- seen(architecture.namespaces.map(namespace => namespace.shorthand), 'Namespace')
26
- seen(architecture.taxonomies.map(taxonomy => taxonomy.shorthand), 'Taxonomy')
27
- seen(architecture.parts.map(part => part.id), 'Id')
28
- const ids = new Set(architecture.parts.map(part => part.id))
29
- for (const part of architecture.parts) {
30
- const shape = parseCode(part.id)?.kind
31
- if (shape !== part.shape) problems.push(`${part.id} reads as ${shape ?? 'no shape'}, not ${part.shape}`)
32
- else if (shape === 'project' ? blockedProjectCode(part.id) : blockedCodeLetters(part.id)) problems.push(`${part.id} uses blocked letters or digits`)
33
- if (!part.name) problems.push(`${part.id} has no name`)
34
- if (part.path && !exists(part.path)) problems.push(`${part.id}: ${part.path} is gone`)
35
- }
36
- for (const fact of architecture.facts) {
37
- const [subject, relation, object, extra] = fact.split(' ')
38
- if (extra !== undefined || !/^r[A-Za-z]{5}$/.test(relation ?? '')) problems.push(`Not a fact: ${fact}`)
39
- else for (const id of [subject, object]) if (!ids.has(id)) problems.push(`Unknown id ${id} in: ${fact}`)
40
- }
41
- return problems
42
- }
43
-
44
- export function resolveCode(architecture: Architecture, value: string): Resolved[] {
45
- const qualified = /^-([A-Z]{2})-(.+)$/.exec(value)
46
- const ids = (qualified ? qualified[2] : value).split(JUNCTION_SEPARATOR)
47
- return ids.map(id => {
48
- const shape = parseCode(id)?.kind ?? null
49
- const namespace = namespaceOf(architecture, id, qualified?.[1])
50
- const facts = architecture.facts.filter(fact => { const [subject, , object] = fact.split(' '); return subject === id || object === id })
51
- return { id, shape, namespace, taxonomy: shape ? taxonomyOf(architecture, id) : undefined, part: architecture.parts.find(part => part.id === id), facts }
52
- })
53
- }
54
-
55
- const nameOf = (architecture: Architecture, id: string) => architecture.parts.find(part => part.id === id)?.name ?? id
56
- const readFact = (architecture: Architecture, fact: string) => { const [subject, relation, object] = fact.split(' '); return `${subject} ${relation} ${object} ${nameOf(architecture, subject)} → ${nameOf(architecture, object)}` }
57
-
58
- export function describeResolved(architecture: Architecture, resolved: Resolved[]): string {
59
- return resolved.map(({ id, shape, namespace, taxonomy, part, facts }) => [
60
- `${id} ${part?.name ?? (shape ? 'not in .id' : 'not a code')}`,
61
- ` shape ${shape ?? '—'}`,
62
- ...(taxonomy ? [` taxonomy ${taxonomy.shorthand} · ${taxonomy.name}`] : []),
63
- ...(namespace ? [` namespace ${namespace.shorthand} · ${namespace.name}`] : []),
64
- ...(part?.path ? [` path ${part.path}`] : []),
65
- ...facts.map(fact => ` fact ${readFact(architecture, fact)}`),
66
- ].join('\n')).join('\n\n')
67
- }
68
-
69
- export function describeStatus(architecture: Architecture, problems: string[]): string {
70
- const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
71
- const shapes = SHAPES.map(shape => [shape, architecture.parts.filter(part => part.shape === shape).length] as const).filter(([, n]) => n)
72
- return [
73
- `${count(architecture.parts.length, 'part')} · ${count(architecture.facts.length, 'fact')} · ${count(architecture.namespaces.length, 'namespace')} · ${count(architecture.taxonomies.length, 'taxonomy', 'taxonomies')}`,
74
- problems.length ? `${count(problems.length, 'problem')}: run idv1 health` : 'healthy',
75
- '',
76
- ...shapes.map(([shape, n]) => ` ${shape.padEnd(9)}${n}`),
77
- ...architecture.taxonomies.map(taxonomy => ` ${taxonomy.shorthand.padEnd(9)}${architecture.parts.filter(part => taxonomyOf(architecture, part.id) === taxonomy).length} ${taxonomy.name}`),
78
- ].join('\n')
79
- }
80
-
81
- export function describeArchitecture(architecture: Architecture): string {
82
- const contains = architecture.facts.map(fact => fact.split(' ')).filter(([, relation]) => relation === 'rHasPt')
83
- const children = (id: string) => contains.filter(([subject]) => subject === id).map(([, , object]) => object)
84
- const roots = architecture.parts.filter(part => !contains.some(([, , object]) => object === part.id))
85
- const line = (part: Part | undefined, id: string, depth: number) => `${' '.repeat(depth)}${id} ${part?.name ?? '?'}${part && taxonomyOf(architecture, id) ? ` (${taxonomyOf(architecture, id)!.name})` : ''}${part?.path ? ` ${part.path}` : ''}`
86
- const tree = (id: string, depth: number, trail: Set<string>): string[] => trail.has(id) ? [] : [line(architecture.parts.find(part => part.id === id), id, depth), ...children(id).flatMap(child => tree(child, depth + 1, new Set([...trail, id])))]
87
- return [
88
- 'Namespaces',
89
- ...architecture.namespaces.map(({ shorthand, name }) => ` ${shorthand} ${name}`),
90
- '',
91
- 'Taxonomies',
92
- ...architecture.taxonomies.map(({ shorthand, name, shape, pattern }) => ` ${shorthand} ${name} ${shape} ${pattern}`),
93
- '',
94
- 'Parts',
95
- ...roots.flatMap(part => tree(part.id, 1, new Set())),
96
- '',
97
- 'Facts',
98
- ...architecture.facts.filter(fact => fact.split(' ')[1] !== 'rHasPt').map(fact => ` ${readFact(architecture, fact)}`),
99
- ].join('\n')
100
- }
101
-
102
- export function runArchitectureCommand(command: string | undefined, args: string[], text: string, exists?: (path: string) => boolean): { code: number; out: string } {
103
- const architecture = readArchitecture(text)
104
- const problems = architectureHealth(architecture, exists)
105
- switch (command) {
106
- case 'health': return { code: problems.length ? 1 : 0, out: problems.length ? problems.join('\n') : 'healthy' }
107
- case 'status': return { code: 0, out: describeStatus(architecture, problems) }
108
- case 'resolve': return args.length ? { code: 0, out: args.map(value => describeResolved(architecture, resolveCode(architecture, value))).join('\n\n') } : { code: 2, out: 'idv1 resolve <id | junction | -NS-id>' }
109
- case 'architecture': case undefined: return { code: 0, out: describeArchitecture(architecture) }
110
- default: return { code: 2, out: 'idv1 architecture | status | health | resolve <id>' }
111
- }
112
- }
package/src/junction.ts DELETED
@@ -1,18 +0,0 @@
1
- import { codeKind, type CodeKind } from './identifier'
2
-
3
- export const JUNCTION_SEPARATOR = '-'
4
-
5
- export function junction(...codes: string[]): string {
6
- if (codes.length < 2) throw new Error('A junction joins two codes or more.')
7
- for (const code of codes) if (!codeKind(code)) throw new Error(`${code} is no IDv1 code.`)
8
- return codes.join(JUNCTION_SEPARATOR)
9
- }
10
-
11
- export function junctionParts(value: string): { code: string; kind: CodeKind }[] | null {
12
- const codes = value.split(JUNCTION_SEPARATOR)
13
- if (codes.length < 2) return null
14
- const parts = codes.map(code => ({ code, kind: codeKind(code) }))
15
- return parts.every((part): part is { code: string; kind: CodeKind } => part.kind !== null) ? parts : null
16
- }
17
-
18
- export const isJunction = (value: string): boolean => junctionParts(value) !== null
package/src/space.ts DELETED
@@ -1,16 +0,0 @@
1
- const LETTERS = 52
2
- const DIGITS = 10
3
- export const TOTAL_ID_SPACE = (LETTERS + DIGITS) ** 6
4
- const accounts = LETTERS ** 2 * DIGITS ** 4
5
- const lists = DIGITS ** 2 * LETTERS ** 4
6
- const projects = LETTERS ** 4 * DIGITS ** 2
7
- const items = LETTERS ** 2 * DIGITS ** 2 * ((LETTERS + DIGITS) ** 2 - DIGITS ** 2)
8
-
9
- export const ID_SPACE = { accounts, lists, projects, items, events: TOTAL_ID_SPACE - accounts - lists - projects - items } as const
10
- export type IdSpaceKind = keyof typeof ID_SPACE
11
-
12
- export function idUsage(kind: IdSpaceKind, used: number): { used: number; space: number; left: number; percent: number } {
13
- const space = ID_SPACE[kind]
14
- if (!Number.isSafeInteger(used) || used < 0) throw new RangeError('Usage must be a nonnegative safe integer.')
15
- return { used, space, left: Math.max(0, space - used), percent: (used / space) * 100 }
16
- }
File without changes