@hollis-labs/surface-ui 0.0.0-stage → 0.1.0

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.
Files changed (3) hide show
  1. package/README.md +17 -2
  2. package/package.json +28 -4
  3. package/ui.mjs +400 -0
package/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @hollis-labs/surface-ui
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `ui` tool for apps built on the [Surface](https://github.com/hollis-labs/surface) registry. It copies
4
+ components into the app's source, records them in `ui.lock.json`, and fails when a copy differs from the
5
+ registry: a look is changed in the registry and synced, never edited in the app.
6
+
7
+ ```sh
8
+ npx surface-ui init --ref v0.1.0 # ui.lock.json naming the registry on GitHub at a tag
9
+ npx surface-ui add button dialog # install items and what they depend on
10
+ npx surface-ui add --for <package> # the items an installed package draws with
11
+ npx surface-ui sync # reinstall everything locked (after moving ref)
12
+ npx surface-ui verify # CI: an edited, stale, missing or stray file fails
13
+ npx surface-ui status
14
+ npx surface-ui report <app dir...> # drift across several apps
15
+ ```
16
+
17
+ Options: `--app <dir>` (default the current directory), `--registry <dir or URL template>`. The registry and
18
+ its rules are in the repository's `registry/README.md`.
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@hollis-labs/surface-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Keep an app's copied components identical to the Surface registry: init, add, sync, verify, status and a drift report across apps.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/hollis-labs/surface.git",
9
+ "directory": "packages/ui"
10
+ },
11
+ "homepage": "https://github.com/hollis-labs/surface/tree/main/registry#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/hollis-labs/surface/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public",
17
+ "registry": "https://registry.npmjs.org/"
18
+ },
19
+ "type": "module",
20
+ "bin": {
21
+ "surface-ui": "ui.mjs"
22
+ },
23
+ "files": [
24
+ "ui.mjs",
25
+ "README.md"
26
+ ],
27
+ "engines": {
28
+ "node": ">=20"
29
+ }
30
+ }
package/ui.mjs ADDED
@@ -0,0 +1,400 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync } from "node:child_process"
3
+ // surface ui: keep an app's copied components identical to the @surface registry.
4
+ //
5
+ // Components are installed into an app's own source, where its build sees them and an agent
6
+ // can read them. They are not edited there. This tool installs them, records what it
7
+ // installed in ui.lock.json, and fails when a file differs from what the registry holds:
8
+ // a change is made in the registry, then synced.
9
+ //
10
+ // In this repository it is `node scripts/ui.mjs`; in an app, `npx @hollis-labs/surface-ui` (bin surface-ui).
11
+ //
12
+ // node scripts/ui.mjs init [--ref <tag>] [--dir <components dir>]
13
+ // write ui.lock.json naming the registry on GitHub at a tag
14
+ // node scripts/ui.mjs build registry maintainers: regenerate registry.json and registry/r
15
+ // node scripts/ui.mjs add <item...> install items (and what they depend on) into the app
16
+ // node scripts/ui.mjs add --for <package>
17
+ // install the items an installed package draws with
18
+ // (@hollis-labs/surface-page lists its own)
19
+ // node scripts/ui.mjs sync reinstall every locked item from the registry
20
+ // node scripts/ui.mjs verify exit 1 if any installed file differs from the lock or the registry
21
+ // node scripts/ui.mjs status what is installed, from where
22
+ // node scripts/ui.mjs report <app dir...> [--from <file>] [--json]
23
+ // each app's registry, item count and drift: items missing,
24
+ // edited in place or behind the registry (--registry to compare
25
+ // every app with one registry). --from names a file listing app
26
+ // dirs, one per line (# starts a comment).
27
+ //
28
+ // Options: --app <dir> (default: the current directory), --registry <dir or URL template>.
29
+ // The lock names the registry: a directory holding <name>.json files, or a URL with {name}
30
+ // (and optionally {ref}), for example
31
+ // https://raw.githubusercontent.com/hollis-labs/surface/{ref}/registry/r/{name}.json
32
+ import { createHash } from "node:crypto"
33
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"
34
+ import { createRequire } from "node:module"
35
+ import { basename, dirname, join, relative, resolve } from "node:path"
36
+
37
+ const args = process.argv.slice(2)
38
+ const cmd = args.shift()
39
+ const opt = (name) => {
40
+ const i = args.indexOf(`--${name}`)
41
+ if (i < 0) return undefined
42
+ const v = args[i + 1]
43
+ args.splice(i, 2)
44
+ return v
45
+ }
46
+ const appDir = resolve(opt("app") ?? ".")
47
+ const forPackage = opt("for")
48
+ const initRef = opt("ref")
49
+ const initDir = opt("dir")
50
+ const GITHUB_REGISTRY = "https://raw.githubusercontent.com/hollis-labs/surface/{ref}/registry/r/{name}.json"
51
+ const registryOverride = opt("registry")
52
+ const lockPath = join(appDir, "ui.lock.json")
53
+ const sha = (text) => createHash("sha256").update(text).digest("hex")
54
+ const fail = (msg) => {
55
+ console.error(`surface ui: ${msg}`)
56
+ process.exit(1)
57
+ }
58
+ const bare = (name) => name.replace(/^@surface\//, "")
59
+
60
+ function readLock() {
61
+ if (!existsSync(lockPath)) {
62
+ fail(`no ui.lock.json in ${appDir}. Create one with {"registry": "...", "uiDir": "src/components/ui", "items": {}}`)
63
+ }
64
+ const lock = JSON.parse(readFileSync(lockPath, "utf8"))
65
+ if (registryOverride) lock.registry = registryOverride
66
+ if (!lock.registry || !lock.uiDir) fail("ui.lock.json needs registry and uiDir")
67
+ lock.items ??= {}
68
+ return lock
69
+ }
70
+
71
+ function writeLock(lock) {
72
+ const items = Object.fromEntries(Object.entries(lock.items).sort(([a], [b]) => a.localeCompare(b)))
73
+ writeFileSync(lockPath, `${JSON.stringify({ ...lock, items }, null, 2)}\n`)
74
+ }
75
+
76
+ /** One registry item, from a directory or a URL template. */
77
+ async function fetchItem(lock, name, { base = appDir, soft = false } = {}) {
78
+ const src = lock.registry
79
+ if (/^https?:\/\//.test(src)) {
80
+ const url = src.replace("{name}", name).replace("{ref}", lock.ref ?? "main")
81
+ const res = await fetch(url)
82
+ if (!res.ok) {
83
+ if (soft && res.status === 404) return null
84
+ fail(`${url}: ${res.status} ${res.statusText}`)
85
+ }
86
+ return res.json()
87
+ }
88
+ const file = join(resolve(base, src), `${name}.json`)
89
+ if (!existsSync(file)) {
90
+ if (soft) return null
91
+ fail(`the registry at ${src} has no item "${name}"`)
92
+ }
93
+ return JSON.parse(readFileSync(file, "utf8"))
94
+ }
95
+
96
+ /** The named items and everything they depend on in the registry, dependencies first. */
97
+ async function closure(lock, names) {
98
+ const seen = new Map()
99
+ const visit = async (raw) => {
100
+ const name = bare(raw)
101
+ if (seen.has(name)) return
102
+ const item = await fetchItem(lock, name)
103
+ seen.set(name, null) // reserved: a cycle stops here
104
+ for (const dep of item.registryDependencies ?? []) await visit(dep)
105
+ seen.delete(name)
106
+ seen.set(name, item)
107
+ }
108
+ for (const n of names) await visit(n)
109
+ return seen
110
+ }
111
+
112
+ // Components go in uiDir; the theme (a registry:file) beside it, or in themeDir when the lock names one.
113
+ const targetOf = (lock, file) =>
114
+ join(file.type === "registry:file" ? (lock.themeDir ?? dirname(lock.uiDir)) : lock.uiDir, basename(file.path))
115
+
116
+ async function install(lock, names) {
117
+ const items = await closure(lock, names)
118
+ const npm = new Set()
119
+ for (const [name, item] of items) {
120
+ const files = {}
121
+ for (const f of item.files ?? []) {
122
+ const rel = targetOf(lock, f)
123
+ const abs = join(appDir, rel)
124
+ mkdirSync(dirname(abs), { recursive: true })
125
+ writeFileSync(abs, f.content)
126
+ files[rel] = sha(f.content)
127
+ }
128
+ lock.items[name] = { files }
129
+ for (const d of item.dependencies ?? []) npm.add(d)
130
+ }
131
+ writeLock(lock)
132
+ console.log(`installed ${[...items.keys()].join(", ")}`)
133
+ // The app must have the packages the components import.
134
+ const pkgPath = join(appDir, "package.json")
135
+ if (existsSync(pkgPath)) {
136
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"))
137
+ const have = { ...pkg.dependencies, ...pkg.devDependencies }
138
+ const missing = [...npm].filter((d) => !have[d.replace(/(?<=.)@[^/]+$/, "")])
139
+ if (missing.length)
140
+ console.log(`these packages are needed and not in package.json:\n npm install ${missing.join(" ")}`)
141
+ }
142
+ }
143
+
144
+ async function verify(lock) {
145
+ const problems = []
146
+ const locked = new Set()
147
+ for (const [name, entry] of Object.entries(lock.items)) {
148
+ const item = await fetchItem(lock, name)
149
+ const want = new Map((item.files ?? []).map((f) => [targetOf(lock, f), sha(f.content)]))
150
+ for (const [rel, hash] of Object.entries(entry.files)) {
151
+ locked.add(rel)
152
+ const abs = join(appDir, rel)
153
+ if (!existsSync(abs)) problems.push(`${rel}: missing (item ${name})`)
154
+ else if (sha(readFileSync(abs, "utf8")) !== hash)
155
+ problems.push(`${rel}: edited in place. Change it in the registry, then run "ui sync"`)
156
+ else if (want.get(rel) !== hash) problems.push(`${rel}: behind the registry (item ${name}). Run "ui sync"`)
157
+ }
158
+ for (const rel of want.keys())
159
+ if (!entry.files[rel]) problems.push(`${rel}: the registry's ${name} has a file the app lacks. Run "ui sync"`)
160
+ }
161
+ // Nothing lives beside the copied components that the registry did not put there.
162
+ const dir = join(appDir, lock.uiDir)
163
+ if (existsSync(dir)) {
164
+ for (const f of readdirSync(dir)) {
165
+ const rel = join(lock.uiDir, f)
166
+ if (!locked.has(rel))
167
+ problems.push(`${rel}: not from the registry. Shared components come from @surface; an app's own go elsewhere`)
168
+ }
169
+ }
170
+ if (problems.length) {
171
+ console.error(`surface ui: ${problems.length} problem(s)\n ${problems.join("\n ")}`)
172
+ process.exit(1)
173
+ }
174
+ console.log(`surface ui: ${locked.size} file(s) in ${Object.keys(lock.items).length} item(s) match the registry`)
175
+ }
176
+
177
+ /**
178
+ * One app's drift against its registry (or the one given with --registry): for each locked
179
+ * item, whether a file is missing, edited in place, or behind the registry; files the
180
+ * registry has that the app lacks; and files in the components directory nothing put there.
181
+ */
182
+ async function inspect(dir) {
183
+ const lockFile = join(dir, "ui.lock.json")
184
+ if (!existsSync(lockFile)) return { dir, error: "no ui.lock.json" }
185
+ const lock = JSON.parse(readFileSync(lockFile, "utf8"))
186
+ lock.items ??= {}
187
+ // A registry given on the command line is read from where the command runs.
188
+ const base = registryOverride ? process.cwd() : dir
189
+ if (registryOverride) lock.registry = registryOverride
190
+ let app = basename(resolve(dir))
191
+ try {
192
+ app = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).name ?? app
193
+ } catch {
194
+ // No package.json: the directory's name will do.
195
+ }
196
+ if (!/^https?:\/\//.test(lock.registry ?? "") && !existsSync(resolve(base, lock.registry ?? ""))) {
197
+ return { app, dir, error: `its registry ${lock.registry} is not there (give one with --registry)` }
198
+ }
199
+ const drift = []
200
+ const locked = new Set()
201
+ for (const [name, entry] of Object.entries(lock.items)) {
202
+ const item = await fetchItem(lock, name, { base, soft: true })
203
+ if (!item) {
204
+ for (const rel of Object.keys(entry.files ?? {})) locked.add(rel)
205
+ drift.push({ item: name, kind: "unknown", detail: "the registry has no such item" })
206
+ continue
207
+ }
208
+ const want = new Map((item.files ?? []).map((f) => [targetOf(lock, f), sha(f.content)]))
209
+ for (const [rel, hash] of Object.entries(entry.files ?? {})) {
210
+ locked.add(rel)
211
+ const abs = join(dir, rel)
212
+ if (!existsSync(abs)) drift.push({ item: name, file: rel, kind: "missing" })
213
+ else if (sha(readFileSync(abs, "utf8")) !== hash) drift.push({ item: name, file: rel, kind: "edited" })
214
+ else if (want.get(rel) !== hash) drift.push({ item: name, file: rel, kind: "behind" })
215
+ }
216
+ for (const rel of want.keys())
217
+ if (!entry.files?.[rel]) drift.push({ item: name, file: rel, kind: "behind", detail: "a file the app lacks" })
218
+ }
219
+ const ui = join(dir, lock.uiDir ?? "")
220
+ if (lock.uiDir && existsSync(ui)) {
221
+ for (const f of readdirSync(ui)) {
222
+ const rel = join(lock.uiDir, f)
223
+ if (!locked.has(rel)) drift.push({ item: "", file: rel, kind: "stray" })
224
+ }
225
+ }
226
+ return { app, dir, registry: lock.registry, ref: lock.ref ?? null, items: Object.keys(lock.items).length, drift }
227
+ }
228
+
229
+ const WORDS = {
230
+ missing: "missing",
231
+ edited: "edited in place",
232
+ behind: "behind the registry",
233
+ unknown: "not in the registry",
234
+ stray: "not from the registry",
235
+ }
236
+
237
+ async function report(dirs, asJson) {
238
+ const out = []
239
+ for (const d of dirs) out.push(await inspect(resolve(d)))
240
+ if (asJson) {
241
+ console.log(JSON.stringify(out, null, 2))
242
+ return
243
+ }
244
+ for (const r of out) {
245
+ if (r.error) {
246
+ console.log(`${r.app ?? r.dir} (${r.dir}): ${r.error}`)
247
+ continue
248
+ }
249
+ const rel = relative(process.cwd(), r.dir)
250
+ const where = rel.startsWith("..") ? r.dir : rel || "."
251
+ const state = r.drift.length ? `${r.drift.length} drifting` : "in step"
252
+ console.log(`${r.app} (${where}): ${r.registry}${r.ref ? ` @ ${r.ref}` : ""} · ${r.items} items · ${state}`)
253
+ for (const x of r.drift) {
254
+ const what = [x.item, x.file].filter(Boolean).join(": ")
255
+ console.log(` ${what}: ${WORDS[x.kind] ?? x.kind}${x.detail ? ` (${x.detail})` : ""}`)
256
+ }
257
+ }
258
+ }
259
+
260
+ /** Registry maintainers: derive registry.json from the sources, then let shadcn build the item files. */
261
+ function build() {
262
+ const root = resolve(appDir, "registry")
263
+ const uiDir = join(root, "ui")
264
+ const meta = existsSync(join(root, "items.json")) ? JSON.parse(readFileSync(join(root, "items.json"), "utf8")) : {}
265
+ const items = []
266
+ for (const f of readdirSync(uiDir)
267
+ .filter((x) => x.endsWith(".tsx"))
268
+ .sort()) {
269
+ const name = f.replace(/\.tsx$/, "")
270
+ const text = readFileSync(join(uiDir, f), "utf8")
271
+ const npm = new Set()
272
+ const deps = new Set()
273
+ // Both `import x from "spec"` and a bare `import "spec"` (a stylesheet) count.
274
+ for (const m of text.matchAll(/(?:from|^import)\s+"([^"]+)"/gm)) {
275
+ const spec = m[1]
276
+ if (spec.startsWith("@/components/ui/")) deps.add(`@surface/${spec.slice("@/components/ui/".length)}`)
277
+ else if (!spec.startsWith(".") && !spec.startsWith("@/") && spec !== "react" && spec !== "react-dom") {
278
+ const pkg = spec.startsWith("@") ? spec.split("/").slice(0, 2).join("/") : spec.split("/")[0]
279
+ // A package the item needs at one exact version says so in items.json ("pins").
280
+ npm.add(meta[name]?.pins?.[pkg] ? `${pkg}@${meta[name].pins[pkg]}` : pkg)
281
+ }
282
+ }
283
+ // An item is its .tsx and any file beside it of the same name (its stylesheet).
284
+ const beside = readdirSync(uiDir)
285
+ .filter((x) => x.startsWith(`${name}.`) && x !== f)
286
+ .sort()
287
+ items.push({
288
+ name,
289
+ type: "registry:ui",
290
+ title: meta[name]?.title ?? name.replace(/(^|-)(\w)/g, (_, d, c) => (d ? " " : "") + c.toUpperCase()),
291
+ ...(meta[name]?.description ? { description: meta[name].description } : {}),
292
+ ...(npm.size ? { dependencies: [...npm].sort() } : {}),
293
+ ...(deps.size ? { registryDependencies: [...deps].sort() } : {}),
294
+ files: [f, ...beside].map((x) => ({ path: `registry/ui/${x}`, type: "registry:ui" })),
295
+ })
296
+ }
297
+ // The theme is one item too, so an app outside this repository installs it at the same ref.
298
+ const themeDir = join(root, "theme")
299
+ for (const f of existsSync(themeDir) ? readdirSync(themeDir).filter((x) => x.endsWith(".css")) : []) {
300
+ const text = readFileSync(join(themeDir, f), "utf8")
301
+ const npm = new Set()
302
+ for (const m of text.matchAll(/^@import\s+"([^".][^"]*)"/gm)) {
303
+ if (m[1] !== "tailwindcss")
304
+ npm.add(m[1].startsWith("@") ? m[1].split("/").slice(0, 2).join("/") : m[1].split("/")[0])
305
+ }
306
+ const name = f === "surface.css" ? "theme" : `theme-${f.replace(/\.css$/, "")}`
307
+ items.push({
308
+ name,
309
+ type: "registry:file",
310
+ title: meta[name]?.title ?? "Theme",
311
+ ...(meta[name]?.description ? { description: meta[name].description } : {}),
312
+ ...(npm.size ? { dependencies: [...npm].sort() } : {}),
313
+ files: [{ path: `registry/theme/${f}`, type: "registry:file", target: `src/${f}` }],
314
+ })
315
+ }
316
+ const registry = {
317
+ $schema: "https://ui.shadcn.com/schema/registry.json",
318
+ name: "surface",
319
+ homepage: "https://github.com/hollis-labs/surface",
320
+ items,
321
+ }
322
+ writeFileSync(join(root, "registry.json"), `${JSON.stringify(registry, null, 2)}\n`)
323
+ execFileSync("npx", ["shadcn", "build", "registry/registry.json", "-o", "registry/r"], {
324
+ cwd: appDir,
325
+ stdio: "inherit",
326
+ })
327
+ console.log(`built ${items.length} items into ${relative(appDir, join(root, "r"))}`)
328
+ }
329
+
330
+ /** The registry items an installed package says it draws with ("surface": {"registryItems": file}). */
331
+ function itemsFor(pkg) {
332
+ let manifest
333
+ try {
334
+ manifest = createRequire(join(appDir, "package.json")).resolve(`${pkg}/package.json`)
335
+ } catch {
336
+ fail(`${pkg} is not installed in ${appDir} (npm install it first)`)
337
+ }
338
+ const meta = JSON.parse(readFileSync(manifest, "utf8"))
339
+ const list = meta.surface?.registryItems
340
+ if (!list) fail(`${pkg} does not list the registry items it uses`)
341
+ return JSON.parse(readFileSync(join(dirname(manifest), list), "utf8"))
342
+ }
343
+
344
+ switch (cmd) {
345
+ case "init": {
346
+ if (existsSync(lockPath)) fail(`${lockPath} exists already`)
347
+ const lock = {
348
+ registry: registryOverride ?? GITHUB_REGISTRY,
349
+ ...(registryOverride ? {} : { ref: initRef ?? "main" }),
350
+ uiDir: initDir ?? "src/components/ui",
351
+ items: {},
352
+ }
353
+ writeLock(lock)
354
+ console.log(
355
+ `wrote ${relative(process.cwd(), lockPath) || lockPath}: ${lock.registry}${lock.ref ? ` @ ${lock.ref}` : ""}, components in ${lock.uiDir}`,
356
+ )
357
+ break
358
+ }
359
+ case "build":
360
+ build()
361
+ break
362
+ case "add": {
363
+ const names = [...args, ...(forPackage ? itemsFor(forPackage) : [])]
364
+ if (!names.length) fail("add needs at least one item name (or --for <package>)")
365
+ await install(readLock(), names)
366
+ break
367
+ }
368
+ case "sync": {
369
+ const lock = readLock()
370
+ await install(lock, Object.keys(lock.items))
371
+ break
372
+ }
373
+ case "verify":
374
+ await verify(readLock())
375
+ break
376
+ case "report": {
377
+ const asJson = args.includes("--json")
378
+ const from = opt("from")
379
+ const dirs = args.filter((a) => a !== "--json")
380
+ if (from) {
381
+ for (const line of readFileSync(from, "utf8").split("\n")) {
382
+ const d = line.replace(/#.*/, "").trim()
383
+ if (d) dirs.push(resolve(dirname(resolve(from)), d))
384
+ }
385
+ }
386
+ if (!dirs.length) dirs.push(appDir)
387
+ await report(dirs, asJson)
388
+ break
389
+ }
390
+ case "status": {
391
+ const lock = readLock()
392
+ console.log(`registry: ${lock.registry}${lock.ref ? ` @ ${lock.ref}` : ""}\ninstalled into: ${lock.uiDir}`)
393
+ for (const [name, e] of Object.entries(lock.items)) console.log(` ${name} (${Object.keys(e.files).length} file)`)
394
+ break
395
+ }
396
+ default:
397
+ fail(
398
+ "usage: ui.mjs init [--ref <tag>] [--dir <dir>] | build | add <item...> [--for <package>] | sync | verify | status | report <app dir...> [--from <file>] [--json] [--app <dir>] [--registry <dir or URL>]",
399
+ )
400
+ }