uniweb 1.31.5 → 1.31.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uniweb",
3
- "version": "1.31.5",
3
+ "version": "1.31.6",
4
4
  "description": "Create structured Vite + React sites with content/code separation",
5
5
  "type": "module",
6
6
  "bin": {
@@ -47,9 +47,9 @@
47
47
  "@uniweb/semantic-parser": "~1.13.2"
48
48
  },
49
49
  "peerDependencies": {
50
- "@uniweb/build": "~1.20.5",
50
+ "@uniweb/semantic-parser": "~1.13.2",
51
51
  "@uniweb/content-reader": "~1.5.9",
52
- "@uniweb/semantic-parser": "~1.13.2"
52
+ "@uniweb/build": "~1.20.6"
53
53
  },
54
54
  "peerDependenciesMeta": {
55
55
  "@uniweb/build": {
@@ -107,6 +107,7 @@ When a rule in §2 feels like friction, that is the moment you are about to take
107
107
  | A `Button` or `Card` in `sections/` | `components/`. Everything at the root of `sections/` becomes author vocabulary. | appears in the section picker |
108
108
  | Helpers that take `{ content, params }` | Ordinary props. That signature is for section types only. | — |
109
109
  | One section type per visual variant; or one with a conditional tree inside | A front desk (§1): one `type:`, a `variant` param, workers in `components/` with ordinary props. | author vocabulary bloats; variants invisible to the editor |
110
+ | Copy a worker, hook or data type into a second foundation | A library both depend on: `uniweb add library libraries/ui --foundation a,b`; types named in full (`@acme/plan`). `uniweb guide foundation` § Libraries. | silent: the copies drift; `doctor` names a type defined twice |
110
111
  | Validate, enumerate or warn on content the component doesn't use; treat `content:` as an exact schema | Take what you expect and don't touch the rest (§1). `content:` declares what the type reads. | — |
111
112
  | `params: { theme, background, grid, sticky, query }` | Section settings — read from `block`, never declared. | build warns |
112
113
  | Write `meta.js` as internal metadata | It is the visual editor's UI and other agents' catalog. Labels for people, defaults for everything, author words for params (`columns`, not `gridCols`). | — |
@@ -123,7 +123,7 @@ members:
123
123
 
124
124
  ## The component side
125
125
 
126
- **Keys and schemas.** `meta.js data:` declares each `content.data` key with its shape — a **named ref**, an **inline field map**, an **inline rich form** (`{ fields: [...] }`), or `{}` (a key with no schema — an external API's records). Refs resolve on disk at build time: `@/name` (this foundation's `schemas/`), `@std/name` (from `@uniweb/schemas`), `@org/name` (from `@org/schemas`). A schema drives the editor, checks data (`validate`), lets a fetch of another name fill the key; it fills no field — a record arrives as it is (`record.status ?? 'published'` is yours). A named schema declares no `default:` (inline maps/forms may). `data: false` declares nothing. Keys a foundation's handlers read go in `main.js data:` and reach every section.
126
+ **Keys and schemas.** `meta.js data:` declares each `content.data` key with its shape — a **named ref**, an **inline field map**, an **inline rich form** (`{ fields: [...] }`), or `{}` (a key with no schema — an external API's records). Refs resolve on disk at build time: `@/name` (this foundation's `schemas/`), `@std/name` (from `@uniweb/schemas`), `@org/name` (from the package that defines it: one of the workspace, a library the foundation bundles, or `@org/schemas`; below). A schema drives the editor, checks data (`validate`), lets a fetch of another name fill the key; it fills no field — a record arrives as it is (`record.status ?? 'published'` is yours). A named schema declares no `default:` (inline maps/forms may). `data: false` declares nothing. Keys a foundation's handlers read go in `main.js data:` and reach every section.
127
127
 
128
128
  ```js
129
129
  data: {
@@ -136,7 +136,7 @@ data: {
136
136
 
137
137
  `single`/`whole` are refused over a schema whose root is a list (`@std/nav`, `@std/form`). A `whole` key its source cannot answer whole is `null`. An optional `schemas.config.js` routes a scope to a directory: `export default { '@acme': '../shared/acme-schemas' }` — a routed scope wins, has no package fallback, and `@/`/`@uniweb` are never routable. Worked examples: `development/schemas-in-practice.md`.
138
138
 
139
- **Any foundation can use a data schema another defines, by its full name** — `data: { members: '@acme/member' }`, `schema: '@acme/member'` in `queries.yml`. No backend is involved, and in a workspace nothing to configure: a local build, `uniweb dev` included, reads the type from the foundation whose name gives the `@acme` scope and whose own `schemas/` defines it. Two packages of the workspace defining it stop the build, naming both. A type outside the workspace comes from `schemas.config.js` (`'@acme/member': '../elsewhere/member.yml'`, or the scope's directory), which wins over the workspace, or an installed `@acme/schemas` package. A scope is a namespace that keeps names from colliding, not a limit on who uses a type. So a type another foundation defines is named, never copied: a copy of its file is a second definition of the same type, which `doctor` points out where the two foundations' names give one scope (`type-defined-twice`). Registering, which only a site with a backend does, names such a type and sends no definition of it. A push also needs one of the site's foundations to declare the type, as a section type's data key or a schema of its own: the backend refuses a query whose type none of them declares, since nothing there would render it. A site can hold another site's records of a type too: `paths: { 'records/acme/member': '../../hub/site/records/acme/member' }` in its `site.yml` reads them as its own, a push adds them by reference rather than as copies once their own site has pushed them, and a pull leaves those files alone. A site's records of it sit in `records/acme/member/`; in `records/member/` they'd be the foundation's own `@/member`.
139
+ **Any foundation can use a data schema another defines, by its full name** — `data: { members: '@acme/member' }`, `schema: '@acme/member'` in `queries.yml`. No backend is involved, and nothing to configure: a local build, `uniweb dev` included, reads the type from the package of the workspace that defines it (a foundation whose name gives the `@acme` scope, with the type in its own `schemas/`), or from a library the foundation bundles whose package.json gives that scope (`uniweb guide foundation` § Libraries). Two packages defining it stop the build, naming both. A type no such package defines comes from `schemas.config.js` (`'@acme/member': '../elsewhere/member.yml'`, or the scope's directory), which wins over both, or an installed `@acme/schemas` package. A scope is a namespace that keeps names from colliding, not a limit on who uses a type. So a type another foundation defines is named, never copied: a copy of its file is a second definition of the same type, which `doctor` points out where the two foundations' names give one scope (`type-defined-twice`). Registering, which only a site with a backend does, names such a type and sends no definition of it. A push also needs one of the site's foundations to declare the type, as a section type's data key or a schema of its own: the backend refuses a query whose type none of them declares, since nothing there would render it. A site can hold another site's records of a type too: `paths: { 'records/acme/member': '../../hub/site/records/acme/member' }` in its `site.yml` reads them as its own, a push adds them by reference rather than as copies once their own site has pushed them, and a pull leaves those files alone. A site's records of it sit in `records/acme/member/`; in `records/member/` they'd be the foundation's own `@/member`.
140
140
 
141
141
  ```jsx
142
142
  function Article({ content, block }) { // data: { article: { schema: '@std/article', single: true } }
@@ -161,9 +161,19 @@ export default function Pricing({ content, params }) {
161
161
  }
162
162
  ```
163
163
 
164
- ### Code several foundations share
164
+ ### Libraries: code several foundations share
165
165
 
166
- Code that more than one foundation of a workspace uses lives in a workspace package, not in copies: components are imported as from any package, and Vite bundles them into each foundation. Give the package a stylesheet that reads its own directory, as kit's does — `@source "./**/*.{js,jsx}";` in its `styles.css` — and import it in each foundation's `styles.css` (`@import "@acme/ui/styles.css";`), so Tailwind finds its classes wherever it is installed. A section type the package holds is still each foundation's to offer: a directory in the foundation's `sections/` whose `index.jsx` is `export { default } from '@acme/ui/sections/Banner/index.jsx'`, and whose `meta.js` re-exports the package's the same way. A fix in the package reaches every foundation at its next build and release.
166
+ A section type is a front desk; a **library** is the back office several foundations share: workers, hooks, logic and data types, with no section type of its own. Each foundation keeps its own section types, layouts and look, and calls on the same library. Take the first of these that holds what differs between two sites: the site's `theme.yml` (colors, fonts), foundation vars (radius, shadow, density), a param and the workers it picks, and only then a second foundation sharing a library with the first. A foundation is the vocabulary a kind of site is made with, so a second one is for another vocabulary, never for a smaller bundle.
167
+
168
+ `uniweb add library libraries/ui --foundation classic,modern` makes it and wires each foundation: `"ui": "file:../../libraries/ui"` in its dependencies, and `@import "ui/styles.css";` in its `styles.css`. The library's own stylesheet holds `@source "./**/*.{js,jsx}";`, as kit's does, so Tailwind reads its classes wherever it is installed; without the import they are in no CSS at all, and the build says which line to add. Run it again with another `--foundation` to wire one more. A library is any local package a foundation depends on: one made by hand, cloned or kept as a git submodule inside the workspace works the same, and `uniweb add library <its folder>` wires it.
169
+
170
+ - Export workers from its `index.js` and import them as from any package: `import { PlanCard } from 'ui'`.
171
+ - A worker takes ordinary props and reads every design decision from foundation vars and theme tokens (`var(--card-radius)`, `bg-card`), never a fixed radius or color. That is what lets one worker look classic in one foundation and modern in another.
172
+ - Import `@uniweb/core` by its bare name only, as kit does: a subpath bundles a second core.
173
+ - A section type the library holds stays each foundation's to offer: a directory in the foundation's `sections/` whose `index.jsx` is `export { default } from 'ui/sections/Banner/index.jsx'`, with a `meta.js` that re-exports the library's the same way. Share one only when both vocabularies offer that type with the same content and params; otherwise each foundation writes its own over the same workers.
174
+ - Data types: `uniweb add library libraries/data --schemas --scope @acme` gives it a `schemas/` folder and its scope (`"uniweb": { "scope": "@acme" }` in its package.json). Foundations name its types in full (`data: { plans: '@acme/plan' }`), with nothing to configure (`uniweb guide data`).
175
+ - Each foundation bundles the library, so a build after a change in the library rebuilds every foundation that uses it. A registered foundation version keeps the library as it was built, as it keeps kit: a fix reaches a hosted site when that site's foundation releases again, which `uniweb publish` from the site does.
176
+ - Keep a library inside the workspace. Outside it, under npm a build cannot resolve what the library's own code imports (kit); under pnpm a `file:` library is a copy that misses new files until a reinstall, and a `link:` one has the site load a copy of the foundation.
167
177
 
168
178
  ### The Front Desk pattern
169
179
 
@@ -0,0 +1,394 @@
1
+ /**
2
+ * `uniweb add library <name> [--foundation a,b] [--schemas] [--scope @org]`
3
+ *
4
+ * ⭐ A LIBRARY IS ANY LOCAL PACKAGE A FOUNDATION DEPENDS ON (`librariesOf`, `@uniweb/build`): the
5
+ * components, logic and data types several foundations share, each keeping its own section types,
6
+ * layouts and look. This makes one in the workspace and wires the foundations named, which is all a
7
+ * library takes: a `file:` dependency in each foundation, and its stylesheet imported in each
8
+ * foundation's, so that Tailwind reads its classes. A foundation's build bundles it, its freshness
9
+ * counts its files, and `uniweb dev` serves it, because each finds it through that dependency.
10
+ *
11
+ * Placed by the rule every `add` follows (`utils/placement.js`): a bare name is a folder at the
12
+ * workspace root, a path is that folder, and `--path` is the folder it goes in. The package is named
13
+ * for its folder, as a foundation is, and nothing else marks it: so run on a folder that holds a
14
+ * package already, made by hand, cloned or kept as a git submodule, this wires it without making
15
+ * anything.
16
+ *
17
+ * `--schemas` gives it a `schemas/` folder, whose files are data types its foundations name in full
18
+ * (`@acme/plan`), under the scope in its `package.json` (`uniweb.scope`): `--scope`, or the one the
19
+ * foundations it is wired into share.
20
+ */
21
+
22
+ import { existsSync, readFileSync } from 'node:fs'
23
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
24
+ import { join, relative, sep } from 'node:path'
25
+ import prompts from 'prompts'
26
+ import { checkRegistrationScope, classifyPackage, readFoundationName, resolveFoundationSrcPath, splitFoundationName } from '@uniweb/build'
27
+ import { resolvePlacement, LIBRARY_KIND } from '../utils/placement.js'
28
+ import { registerWorkspacePackage } from '../utils/config.js'
29
+ import { discoverFoundations } from '../utils/discover.js'
30
+ import { validatePackageName } from '../utils/names.js'
31
+ import { workspacePackages } from '../utils/workspace-packages.js'
32
+ import { writeJsonPreservingStyleAsync } from '../utils/json-file.js'
33
+ import { installCmd } from '../utils/pm.js'
34
+ import { getCliPrefix, isNonInteractive } from '../utils/interactive.js'
35
+ import { getVersionsForTemplates } from '../versions.js'
36
+
37
+ const colors = {
38
+ reset: '\x1b[0m',
39
+ bright: '\x1b[1m',
40
+ dim: '\x1b[2m',
41
+ cyan: '\x1b[36m',
42
+ green: '\x1b[32m',
43
+ yellow: '\x1b[33m',
44
+ red: '\x1b[31m'
45
+ }
46
+ const log = (message) => console.log(message)
47
+ const info = (message) => log(`${colors.dim}${message}${colors.reset}`)
48
+ const fail = (message, ...lines) => {
49
+ console.error(`${colors.red}✗${colors.reset} ${message}`)
50
+ for (const line of lines) log(line)
51
+ process.exit(1)
52
+ }
53
+
54
+ const posix = (path) => path.split(sep).join('/')
55
+
56
+ /**
57
+ * A new library's `package.json`. Private, since foundations bundle it and npm never needs it; React
58
+ * and kit as peers, since the foundation that bundles it provides them.
59
+ *
60
+ * @param {{ name: string, projectName: string, scope?: string|null, versions?: Record<string,string> }} o
61
+ */
62
+ export function libraryManifest({ name, projectName, scope = null, versions = getVersionsForTemplates() }) {
63
+ return {
64
+ name,
65
+ version: '0.1.0',
66
+ private: true,
67
+ description: `Components, logic and data types the foundations of ${projectName} share`,
68
+ type: 'module',
69
+ main: './index.js',
70
+ exports: {
71
+ '.': './index.js',
72
+ './styles.css': './styles.css',
73
+ './components/*': './components/*',
74
+ './sections/*': './sections/*'
75
+ },
76
+ peerDependencies: {
77
+ '@uniweb/kit': versions['@uniweb/kit'],
78
+ react: versions.react
79
+ },
80
+ ...(scope && { uniweb: { scope } })
81
+ }
82
+ }
83
+
84
+ const INDEX = (name) => `// What this library shares with the foundations that depend on it. Export each component, hook
85
+ // or helper here, and a foundation imports it by the library's name:
86
+ //
87
+ // export { default as PlanCard } from './components/PlanCard.jsx' (here)
88
+ // import { PlanCard } from '${name}' (in a foundation)
89
+ //
90
+ // A component here takes ordinary props, and reads its look from the foundation's vars and the
91
+ // theme's tokens (var(--card-radius), bg-card), so each foundation that uses it keeps its own.
92
+ export {}
93
+ `
94
+
95
+ // The form kit's own stylesheet uses, which holds wherever a package manager puts the package.
96
+ const STYLES = `/* Tailwind reads this library's files wherever it is installed: each foundation that uses it imports this stylesheet. */
97
+ @source "./**/*.{js,jsx}";
98
+ `
99
+
100
+ const SCHEMAS_README = (scope) => `# Data types
101
+
102
+ Each file here is a data type the foundations share, by its full name: \`plan.yml\` is
103
+ \`${scope}/plan\`. A foundation names it in a section's \`meta.js\` (\`data: { plans: '${scope}/plan' }\`),
104
+ and a site keeps its records in \`records/${scope.slice(1)}/plan/\`. In this workspace nothing else is
105
+ configured: a package with a \`schemas/\` folder serves its scope.
106
+ `
107
+
108
+ const USES_TAILWIND = /@import\s+["']tailwindcss/
109
+
110
+ /**
111
+ * The line that has a foundation's Tailwind read a library: an import of the library's own stylesheet
112
+ * when it has one a foundation can import, else a `@source` to its folder.
113
+ *
114
+ * @param {{ libraryDir: string, libraryName: string, stylesDir: string }} o
115
+ * @returns {string}
116
+ */
117
+ export function libraryLine({ libraryDir, libraryName, stylesDir }) {
118
+ let pkg = null
119
+ try {
120
+ pkg = JSON.parse(readFileSync(join(libraryDir, 'package.json'), 'utf8'))
121
+ } catch {
122
+ // no manifest to refuse the import
123
+ }
124
+ const exp = pkg?.exports
125
+ // ⛔ An `exports` map without the stylesheet refuses the import, in Tailwind and in Node alike.
126
+ const importable = !exp || typeof exp !== 'object' || Object.keys(exp).some((k) => k === './styles.css' || k === './*')
127
+ if (existsSync(join(libraryDir, 'styles.css')) && importable) return `@import "${libraryName}/styles.css";`
128
+ const rel = posix(relative(stylesDir, libraryDir))
129
+ return `@source "${rel.startsWith('.') ? rel : `./${rel}`}";`
130
+ }
131
+
132
+ /**
133
+ * A foundation's stylesheet with `line` after its last `@import`, or null when the stylesheet reads
134
+ * the library already: by that import, or by a `@source` to its folder.
135
+ *
136
+ * @param {string} css
137
+ * @param {string} line - from `libraryLine`
138
+ * @returns {string|null}
139
+ */
140
+ export function withLibraryLine(css, line) {
141
+ const target = /^@(?:import|source) "(.+?)"/.exec(line)[1].replace(/\/+$/, '')
142
+ for (const [, , written] of css.matchAll(/@(import|source)\s+["'](.+?)["']/g)) {
143
+ if (written.replace(/\/+$/, '') === target) return null
144
+ }
145
+ const lines = css.split('\n')
146
+ let last = -1
147
+ lines.forEach((l, i) => {
148
+ if (/^\s*@import\b/.test(l)) last = i
149
+ })
150
+ lines.splice(last + 1, 0, line)
151
+ return lines.join('\n')
152
+ }
153
+
154
+ /** The name each workspace package goes by, with its folder. */
155
+ function workspacePackageNames(rootDir) {
156
+ const names = new Map()
157
+ for (const rel of workspacePackages(rootDir)) {
158
+ try {
159
+ const { name } = JSON.parse(readFileSync(join(rootDir, rel, 'package.json'), 'utf8'))
160
+ if (name) names.set(name, rel)
161
+ } catch {
162
+ // no manifest: no name to collide with
163
+ }
164
+ }
165
+ return names
166
+ }
167
+
168
+ /** The foundations `--foundation` names, or the one the workspace has, or the ones a person picks. */
169
+ async function foundationsToWire(rootDir, flag, relativePath) {
170
+ const foundations = await discoverFoundations(rootDir)
171
+ if (flag) {
172
+ const wanted = flag.split(',').map((s) => s.trim()).filter(Boolean)
173
+ const missing = wanted.filter((n) => !foundations.some((f) => f.name === n))
174
+ if (missing.length) {
175
+ fail(
176
+ `No foundation named ${missing.map((n) => `'${n}'`).join(', ')} in this workspace.`,
177
+ `Foundations: ${foundations.map((f) => f.name).join(', ') || 'none'}`
178
+ )
179
+ }
180
+ return { wire: wanted.map((n) => foundations.find((f) => f.name === n)) }
181
+ }
182
+ if (foundations.length === 0) return { wire: [], note: 'No foundation in this workspace yet. Wire one with --foundation once you add it.' }
183
+ if (foundations.length === 1) return { wire: foundations }
184
+ if (isNonInteractive(process.argv)) {
185
+ return {
186
+ wire: [],
187
+ note: `Several foundations in this workspace, so none was wired. Name them: ${getCliPrefix()} add library ${relativePath} --foundation ${foundations
188
+ .slice(0, 2)
189
+ .map((f) => f.name)
190
+ .join(',')}`
191
+ }
192
+ }
193
+ const { picked } = await prompts(
194
+ {
195
+ type: 'multiselect',
196
+ name: 'picked',
197
+ message: 'Which foundations use this library?',
198
+ choices: foundations.map((f) => ({ title: f.name, description: f.path, value: f.name })),
199
+ min: 0
200
+ },
201
+ { onCancel: () => process.exit(0) }
202
+ )
203
+ return { wire: (picked || []).map((n) => foundations.find((f) => f.name === n)) }
204
+ }
205
+
206
+ /** The scope the foundations share, from their names, or null. */
207
+ async function sharedScope(rootDir, foundations) {
208
+ const scopes = new Set()
209
+ for (const f of foundations) {
210
+ try {
211
+ scopes.add(splitFoundationName((await readFoundationName(join(rootDir, f.path))).name).scope)
212
+ } catch {
213
+ scopes.add(null)
214
+ }
215
+ }
216
+ return scopes.size === 1 ? [...scopes][0] : null
217
+ }
218
+
219
+ /**
220
+ * Wire one foundation to the library: its dependency, and its stylesheet's line for the library's
221
+ * classes. Each step is skipped when it is done already, so wiring twice changes nothing.
222
+ *
223
+ * @returns {Promise<{ changed: boolean, notes: string[] }>} whether a file changed, and what was left
224
+ * as it was, and why
225
+ */
226
+ export async function wireFoundation({ foundationDir, libraryDir, libraryName }) {
227
+ const notes = []
228
+ let changed = false
229
+ const pkgPath = join(foundationDir, 'package.json')
230
+ const src = await readFile(pkgPath, 'utf8')
231
+ const pkg = JSON.parse(src)
232
+ const spec = `file:${posix(relative(foundationDir, libraryDir))}`
233
+ const has = pkg.dependencies?.[libraryName] ?? pkg.devDependencies?.[libraryName]
234
+ if (has && has !== spec) {
235
+ notes.push(`its package.json depends on ${libraryName} as "${has}" already, so that was left as it is`)
236
+ } else if (!has) {
237
+ const deps = { ...(pkg.dependencies || {}), [libraryName]: spec }
238
+ pkg.dependencies = Object.fromEntries(Object.entries(deps).sort(([a], [b]) => a.localeCompare(b)))
239
+ await writeJsonPreservingStyleAsync(pkgPath, pkg, src)
240
+ changed = true
241
+ }
242
+
243
+ const stylesDir = resolveFoundationSrcPath(foundationDir)
244
+ const stylesPath = join(stylesDir, 'styles.css')
245
+ if (!existsSync(stylesPath)) {
246
+ notes.push(`it has no styles.css, so nothing reads the library's classes: add ${libraryLine({ libraryDir, libraryName, stylesDir })} to its stylesheet`)
247
+ return { changed, notes }
248
+ }
249
+ const css = await readFile(stylesPath, 'utf8')
250
+ if (!USES_TAILWIND.test(css)) {
251
+ notes.push('its styles.css does not import Tailwind, so it reads no classes from the library')
252
+ return { changed, notes }
253
+ }
254
+ const wired = withLibraryLine(css, libraryLine({ libraryDir, libraryName, stylesDir }))
255
+ if (wired !== null) {
256
+ await writeFile(stylesPath, wired)
257
+ changed = true
258
+ }
259
+ return { changed, notes }
260
+ }
261
+
262
+ /**
263
+ * Add a library to the workspace, or wire one that is there.
264
+ */
265
+ export async function addLibrary(rootDir, projectName, opts, pm = 'pnpm') {
266
+ const prefix = getCliPrefix()
267
+ if (opts.project) {
268
+ fail(
269
+ `A library is shared by foundations, so it goes in the folder you name, not in one project's:`,
270
+ ` ${prefix} add library libraries/<name> --foundation <a>,<b>`
271
+ )
272
+ }
273
+ let name = opts.name
274
+ if (!name && !opts.path) {
275
+ if (isNonInteractive(process.argv)) fail('Missing library name.', '', `Usage: ${prefix} add library <name> [--foundation <a>,<b>]`)
276
+ const response = await prompts(
277
+ { type: 'text', name: 'name', message: 'Library name:', validate: (v) => validatePackageName(v) },
278
+ { onCancel: () => process.exit(0) }
279
+ )
280
+ name = response.name
281
+ }
282
+ if (name?.startsWith('@')) {
283
+ fail(
284
+ `A library is named for its folder, as a foundation is: name the folder, not a scoped package.`,
285
+ ` ${prefix} add library ${name.split('/').pop()}`,
286
+ `To give its package a scoped name, change "name" in its package.json, and the import that names it.`
287
+ )
288
+ }
289
+
290
+ const placement = resolvePlacement(rootDir, name, opts, LIBRARY_KIND)
291
+ if (placement.outsideRoot) {
292
+ fail(
293
+ `A library's folder must be inside the workspace: ${placement.outsideRoot}`,
294
+ '',
295
+ `A library from another repository goes inside the workspace, as a git submodule or a clone,`,
296
+ `and \`${prefix} add library <its folder>\` lists it in the workspace and wires it.`
297
+ )
298
+ }
299
+ const { relativePath } = placement
300
+ const libraryDir = join(rootDir, relativePath)
301
+
302
+ let libraryName = placement.packageName
303
+ let created = false
304
+ let scope = null
305
+ if (existsSync(libraryDir)) {
306
+ const kind = classifyPackage(libraryDir)
307
+ if (kind) fail(`${relativePath}/ is a ${kind}, not a library.`)
308
+ if (!existsSync(join(libraryDir, 'package.json'))) {
309
+ fail(`${relativePath}/ exists and holds no package.json, so it is no package to wire.`, `Pick another folder, or give it a package.json.`)
310
+ }
311
+ try {
312
+ libraryName = JSON.parse(readFileSync(join(libraryDir, 'package.json'), 'utf8')).name || libraryName
313
+ } catch {
314
+ fail(`${relativePath}/package.json does not parse.`)
315
+ }
316
+ } else {
317
+ const valid = validatePackageName(libraryName)
318
+ if (valid !== true) fail(valid)
319
+ const taken = workspacePackageNames(rootDir).get(libraryName)
320
+ if (taken) {
321
+ fail(
322
+ `A package named ${colors.bright}${libraryName}${colors.reset} is in this workspace already, at ${taken}/.`,
323
+ `A foundation imports a library by its name, so name this one for another folder:`,
324
+ ` ${prefix} add library <name>`
325
+ )
326
+ }
327
+ }
328
+
329
+ const { wire, note } = await foundationsToWire(rootDir, opts.foundation, relativePath)
330
+
331
+ if (opts.schemas || opts.scope) {
332
+ scope = opts.scope ? `@${String(opts.scope).trim().replace(/^@/, '').replace(/\/.*$/, '')}` : await sharedScope(rootDir, wire)
333
+ if (!scope || scope === '@') {
334
+ fail(
335
+ `A library's data types are named in full, under its scope (${colors.bright}@acme/plan${colors.reset}), and none is known yet.`,
336
+ `Give it one:`,
337
+ ` ${prefix} add library ${relativePath} --schemas --scope @<org>`
338
+ )
339
+ }
340
+ const reserved = checkRegistrationScope(scope)
341
+ if (reserved) fail(reserved)
342
+ }
343
+
344
+ if (!existsSync(libraryDir)) {
345
+ await mkdir(join(libraryDir, 'components'), { recursive: true })
346
+ const manifest = libraryManifest({ name: libraryName, projectName, scope })
347
+ await writeFile(join(libraryDir, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`)
348
+ await writeFile(join(libraryDir, 'index.js'), INDEX(libraryName))
349
+ await writeFile(join(libraryDir, 'styles.css'), STYLES)
350
+ created = true
351
+ } else if (scope) {
352
+ const pkgPath = join(libraryDir, 'package.json')
353
+ const src = await readFile(pkgPath, 'utf8')
354
+ const pkg = JSON.parse(src)
355
+ if (pkg.uniweb?.scope && pkg.uniweb.scope !== scope) {
356
+ fail(`${relativePath}/package.json gives the scope ${pkg.uniweb.scope} already; its types are named under it.`)
357
+ }
358
+ if (!pkg.uniweb?.scope) await writeJsonPreservingStyleAsync(pkgPath, { ...pkg, uniweb: { ...(pkg.uniweb || {}), scope } }, src)
359
+ }
360
+ if (scope && !existsSync(join(libraryDir, 'schemas'))) {
361
+ await mkdir(join(libraryDir, 'schemas'), { recursive: true })
362
+ await writeFile(join(libraryDir, 'schemas', 'README.md'), SCHEMAS_README(scope))
363
+ }
364
+
365
+ // Listed by its path, unless a pattern the workspace lists covers it already.
366
+ await registerWorkspacePackage(rootDir, relativePath)
367
+
368
+ const wired = []
369
+ const already = []
370
+ const notes = []
371
+ for (const f of wire) {
372
+ const { changed, notes: left } = await wireFoundation({ foundationDir: join(rootDir, f.path), libraryDir, libraryName })
373
+ ;(changed ? wired : already).push(f.name)
374
+ for (const n of left) notes.push(`${f.name}: ${n}`)
375
+ }
376
+
377
+ if (created || wired.length) {
378
+ log(
379
+ `${colors.green}✓${colors.reset} ${created ? 'Created' : 'Wired'} library ${colors.bright}${libraryName}${colors.reset}` +
380
+ `${created ? ` at ${relativePath}/` : ''}${wired.length ? ` → ${wired.join(', ')}` : ''}`
381
+ )
382
+ } else if (!already.length) {
383
+ log(`Library ${colors.bright}${libraryName}${colors.reset} at ${relativePath}/: no foundation to wire.`)
384
+ }
385
+ if (already.length) log(` ${colors.dim}${already.join(', ')}: wired to ${libraryName} already${colors.reset}`)
386
+ for (const n of notes) log(` ${colors.yellow}⚠ ${n}${colors.reset}`)
387
+ if (note) log(` ${colors.yellow}⚠ ${note}${colors.reset}`)
388
+ if (created) {
389
+ info(` Export its components from ${relativePath}/index.js, and import them in a foundation: import { PlanCard } from '${libraryName}'`)
390
+ if (scope) info(` Its data types go in ${relativePath}/schemas/, named ${scope}/<file name>.`)
391
+ }
392
+ log('')
393
+ log(`Next: ${colors.cyan}${installCmd(pm)}${colors.reset}`)
394
+ }
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * Add Command
3
3
  *
4
- * Adds foundations, sites, extensions, section types, or co-located projects to an existing workspace.
4
+ * Adds foundations, sites, extensions, libraries, section types, or co-located projects to an existing workspace.
5
5
  *
6
6
  * Usage:
7
7
  * uniweb add project [name] [--from <template>]
8
8
  * uniweb add foundation [name] [--from <template>] [--path <dir>] [--project <name>]
9
9
  * uniweb add site [name] [--from <template>] [--foundation <name>] [--path <dir>] [--project <name>]
10
10
  * uniweb add extension [name] [--from <template>] [--site <name>] [--path <dir>]
11
+ * uniweb add library <name> [--foundation <a>,<b>] [--schemas] [--scope <@org>] [--path <dir>]
11
12
  * uniweb add section <name> [--foundation <name>]
12
13
  * uniweb add version <name> [--in <folder>] [--label <text>] [--keep-in-search] [--dry-run] [--site <name>]
13
14
  */
@@ -39,6 +40,7 @@ import {
39
40
  import { registerWorkspacePackage, addRootScripts } from '../utils/config.js'
40
41
  import { discoverFoundations, discoverSites } from '../utils/discover.js'
41
42
  import { generateStarter, reportStarter, declarationFor } from './starter.js'
43
+ import { addLibrary } from './add-library.js'
42
44
  import {
43
45
  validatePackageName,
44
46
  getExistingPackageNames,
@@ -141,12 +143,15 @@ function parseArgs(args) {
141
143
  in: null,
142
144
  label: null,
143
145
  keepInSearch: false,
144
- dryRun: false
146
+ dryRun: false,
147
+ // `add library` only: a `schemas/` folder for data types, and the scope they are named under.
148
+ schemas: false,
149
+ scope: null
145
150
  }
146
151
 
147
152
  // Booleans (no value) consumed up-front so the value-flag loop below
148
153
  // doesn't accidentally swallow the next positional.
149
- const BOOLEAN_FLAGS = new Set(['--force', '--no-previews', '--starter', '--json', '--keep-in-search', '--dry-run'])
154
+ const BOOLEAN_FLAGS = new Set(['--force', '--no-previews', '--starter', '--json', '--keep-in-search', '--dry-run', '--schemas'])
150
155
 
151
156
  // Value flags, mapped to their result key. Both spellings are accepted:
152
157
  // `--host github-pages` and `--host=github-pages`.
@@ -170,7 +175,8 @@ function parseArgs(args) {
170
175
  '--preset': 'preset',
171
176
  '--write': 'write',
172
177
  '--in': 'in',
173
- '--label': 'label'
178
+ '--label': 'label',
179
+ '--scope': 'scope'
174
180
  }
175
181
 
176
182
  /** Split `--flag=value` into [flag, value]; `--flag` into [flag, null]. */
@@ -216,6 +222,8 @@ function parseArgs(args) {
216
222
  result.keepInSearch = true
217
223
  } else if (flag === '--dry-run') {
218
224
  result.dryRun = true
225
+ } else if (flag === '--schemas') {
226
+ result.schemas = true
219
227
  }
220
228
  }
221
229
 
@@ -258,6 +266,7 @@ export async function add(rawArgs) {
258
266
  },
259
267
  { label: 'site', description: 'Content site' },
260
268
  { label: 'extension', description: 'Additional component package' },
269
+ { label: 'library', description: 'Components and data types foundations share' },
261
270
  { label: 'section', description: 'Section type in a foundation' },
262
271
  { label: 'version', description: 'Freeze a site\'s docs as an older version' },
263
272
  {
@@ -268,7 +277,7 @@ export async function add(rawArgs) {
268
277
  )
269
278
  log('')
270
279
  log(
271
- `Usage: ${prefix} add <project|foundation|site|extension|section|ci> [name]`
280
+ `Usage: ${prefix} add <project|foundation|site|extension|library|section|ci> [name]`
272
281
  )
273
282
  process.exit(1)
274
283
  }
@@ -295,6 +304,11 @@ export async function add(rawArgs) {
295
304
  value: 'extension',
296
305
  description: 'Additional component package'
297
306
  },
307
+ {
308
+ title: 'Library',
309
+ value: 'library',
310
+ description: 'Components and data types foundations share'
311
+ },
298
312
  {
299
313
  title: 'Section',
300
314
  value: 'section',
@@ -368,6 +382,9 @@ export async function add(rawArgs) {
368
382
  case 'extension':
369
383
  await addExtension(rootDir, projectName, parsed, pm)
370
384
  break
385
+ case 'library':
386
+ await addLibrary(rootDir, projectName, parsed, pm)
387
+ break
371
388
  case 'section':
372
389
  await addSection(rootDir, parsed)
373
390
  break
@@ -380,7 +397,7 @@ export async function add(rawArgs) {
380
397
  default:
381
398
  error(`Unknown subcommand: ${parsed.subcommand}`)
382
399
  log(
383
- `Valid subcommands: project, foundation, site, extension, section, ci, version`
400
+ `Valid subcommands: project, foundation, site, extension, library, section, ci, version`
384
401
  )
385
402
  process.exit(1)
386
403
  }
@@ -401,7 +418,7 @@ async function addFoundation(rootDir, projectName, opts, pm = 'pnpm') {
401
418
  const placement = resolvePlacement(rootDir, name, opts, FOUNDATION_KIND)
402
419
  refuseProjectConflict(placement, 'foundation', name, opts)
403
420
  if (placement.outsideRoot) {
404
- error(`--path must name a folder inside the workspace: ${placement.outsideRoot}`)
421
+ error(`A package's folder must be inside the workspace: ${placement.outsideRoot}`)
405
422
  log('')
406
423
  log(`The workspace root is ${colors.bright}${rootDir}${colors.reset}.`)
407
424
  log(`A package outside it cannot be a workspace member.`)
@@ -557,7 +574,7 @@ async function addSite(rootDir, projectName, opts, pm = 'pnpm') {
557
574
  const placement = resolvePlacement(rootDir, name, opts, SITE_KIND)
558
575
  refuseProjectConflict(placement, 'site', name, opts)
559
576
  if (placement.outsideRoot) {
560
- error(`--path must name a folder inside the workspace: ${placement.outsideRoot}`)
577
+ error(`A package's folder must be inside the workspace: ${placement.outsideRoot}`)
561
578
  log('')
562
579
  log(`The workspace root is ${colors.bright}${rootDir}${colors.reset}.`)
563
580
  log(`A package outside it cannot be a workspace member.`)
@@ -741,7 +758,7 @@ async function addExtension(rootDir, projectName, opts, pm = 'pnpm') {
741
758
  const placement = resolvePlacement(rootDir, name, opts, EXTENSION_KIND)
742
759
  refuseProjectConflict(placement, 'extension', name, opts)
743
760
  if (placement.outsideRoot) {
744
- error(`--path must name a folder inside the workspace: ${placement.outsideRoot}`)
761
+ error(`A package's folder must be inside the workspace: ${placement.outsideRoot}`)
745
762
  log('')
746
763
  log(`The workspace root is ${colors.bright}${rootDir}${colors.reset}.`)
747
764
  log(`A package outside it cannot be a workspace member.`)
@@ -55,7 +55,7 @@
55
55
  * --bundle # Full vite pipeline (third-party / self-contained; deploy --host / export)
56
56
  */
57
57
 
58
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
58
+ import { existsSync, readFileSync, statSync } from 'node:fs'
59
59
  import { resolve, join, dirname, basename, relative } from 'node:path'
60
60
  import { runRelayed } from '../utils/closed-reader.js'
61
61
  import { writeFile, mkdir } from 'node:fs/promises'
@@ -72,6 +72,7 @@ import {
72
72
  } from '@uniweb/build'
73
73
  import { readSiteConfig } from '@uniweb/build/site'
74
74
  import { workspacePackages } from '../utils/workspace-packages.js'
75
+ import { newerInput } from '../utils/foundation-freshness.js'
75
76
 
76
77
  // Colors for terminal output
77
78
  const colors = {
@@ -279,13 +280,10 @@ async function buildFoundation(projectDir, options = {}) {
279
280
  * without rebuilding. So calling it inside `buildSite()` does not
280
281
  * double-build under `buildWorkspace()`.
281
282
  *
282
- * Freshness rule: a built artifact (`dist/entry.js` or the legacy
283
- * `dist/foundation.js`) exists AND its mtime is >= the newest mtime of
284
- * any tracked source file. Tracked sources: every file under the
285
- * package's source root (the package itself when flat, `src/` when
286
- * nested — `isFoundationSourceNewerThan`), plus root-level `package.json`,
287
- * `foundation.js`, `meta.js` (the structural files that drive entry
288
- * generation and schema). Build outputs and node_modules are skipped.
283
+ * Freshness: a built artifact (`dist/entry.js` or the legacy `dist/foundation.js`)
284
+ * exists, and nothing its build reads is newer: the foundation's sources and
285
+ * those of every library it bundles (`newerInput`, `utils/foundation-freshness.js`,
286
+ * the rule `register` follows too).
289
287
  *
290
288
  * Both artifact names are accepted because the foundation build emitter
291
289
  * was renamed `dist/foundation.js → dist/entry.js` in `@uniweb/build`
@@ -306,12 +304,13 @@ export async function ensureFoundationFresh(foundationDir, label = 'foundation')
306
304
  return { built: true, reason: 'missing' }
307
305
  }
308
306
 
309
- const distMtime = statSync(distArtifact).mtimeMs
310
- const stale = isFoundationSourceNewerThan(foundationDir, distMtime)
307
+ const newer = newerInput(foundationDir, statSync(distArtifact).mtimeMs)
311
308
 
312
- if (stale) {
309
+ if (newer) {
313
310
  info(
314
- `Local ${label} sources changed — rebuilding ${basename(foundationDir)}`
311
+ newer.library
312
+ ? `${newer.library}, a library it bundles, changed — rebuilding ${basename(foundationDir)}`
313
+ : `Local ${label} sources changed — rebuilding ${basename(foundationDir)}`
315
314
  )
316
315
  log('')
317
316
  await buildFoundation(foundationDir)
@@ -335,64 +334,6 @@ function findFoundationDistArtifact(foundationDir) {
335
334
  return null
336
335
  }
337
336
 
338
- /**
339
- * Returns true if any tracked foundation source file has an mtime newer
340
- * than `referenceMtime`. Walks the package's source root — the folder
341
- * `package.json::main` names (`resolveFoundationSrcPath`): the package itself
342
- * for a flat package, `src/` for a nested one — recursively, skipping dotfiles,
343
- * node_modules, dist and the generated entry. Also stats the root structural
344
- * files.
345
- *
346
- * ⛔ Until 2026-10-13 it walked `<foundationDir>/src/` whatever the layout, and
347
- * every package scaffolded since the flat layout keeps its sources at its root —
348
- * so an edit to a section never made one stale. Measured: touching a section of
349
- * a flat foundation and building its site rebuilt nothing, and prerender rendered
350
- * the static HTML with the foundation as last built.
351
- */
352
- export function isFoundationSourceNewerThan(foundationDir, referenceMtime) {
353
- const rootFiles = ['package.json', 'foundation.js', 'meta.js']
354
- for (const f of rootFiles) {
355
- const p = join(foundationDir, f)
356
- if (existsSync(p) && statSync(p).mtimeMs > referenceMtime) return true
357
- }
358
-
359
- const srcDir = resolveFoundationSrcPath(foundationDir)
360
- if (!existsSync(srcDir)) return false
361
-
362
- const stack = [srcDir]
363
- while (stack.length) {
364
- const dir = stack.pop()
365
- let entries
366
- try {
367
- entries = readdirSync(dir, { withFileTypes: true })
368
- } catch {
369
- continue
370
- }
371
- for (const e of entries) {
372
- if (
373
- e.name === 'node_modules' ||
374
- e.name === 'dist' ||
375
- e.name === '_entry.generated.js' ||
376
- e.name.startsWith('.')
377
- )
378
- continue
379
- const full = join(dir, e.name)
380
- if (e.isDirectory()) {
381
- stack.push(full)
382
- continue
383
- }
384
- if (!e.isFile()) continue
385
- try {
386
- if (statSync(full).mtimeMs > referenceMtime) return true
387
- } catch {
388
- /* ignore */
389
- }
390
- }
391
- }
392
-
393
- return false
394
- }
395
-
396
337
  /**
397
338
  * Load site i18n configuration
398
339
  *
@@ -366,7 +366,7 @@ export async function clone(args = [], deps = {}) {
366
366
  return { exitCode: 1 }
367
367
  }
368
368
  if (placement.outsideRoot) {
369
- error(`--path must name a folder inside the workspace: ${placement.outsideRoot}`)
369
+ error(`A site's folder must be inside the workspace: ${placement.outsideRoot}`)
370
370
  note(
371
371
  `The workspace root is ${existingRoot}. A package outside it cannot be a ` +
372
372
  `workspace member — the directory and the manifests would disagree.`
@@ -957,6 +957,23 @@ export async function checkUnreadFolders({ foundationName, srcDir, issues }) {
957
957
  for (const { line } of unread) log(` ${line}`)
958
958
  }
959
959
 
960
+ /**
961
+ * A library the foundation bundles whose classes no `@source` reads (`unreadLibraries`, `@uniweb/build`):
962
+ * missing from the foundation's own CSS, which a hosted site loads with it, and from a site build's.
963
+ * Loaded here for the same reason.
964
+ */
965
+ export async function checkUnreadLibraries({ foundationName, srcDir, foundationDir, issues }) {
966
+ const { unreadLibraries } = await import('@uniweb/build')
967
+ const unread = unreadLibraries?.(join(srcDir, 'styles.css'), foundationDir) || []
968
+ if (unread.length === 0) return
969
+ const id = 'unread-library'
970
+ const named = unread.map(({ name }) => name).join(', ')
971
+ issues.push({ id, type: 'warn', foundation: foundationName, message: `${foundationName} bundles ${named}, whose classes its styles.css does not read` })
972
+ warn(`[${id}] ${foundationName} bundles ${named}, whose classes its styles.css does not read, so they are missing from its CSS and from its sites'`)
973
+ log(` Add to styles.css:`)
974
+ for (const { line } of unread) log(` ${line}`)
975
+ }
976
+
960
977
  /**
961
978
  * Source with its comments removed.
962
979
  *
@@ -2062,6 +2079,7 @@ async function runDoctor(args = []) {
2062
2079
  for (const f of checkedFoundations) {
2063
2080
  await checkStaleSources({ foundationName: f.name, srcDir: resolveFoundationSrcPath(f.path), issues })
2064
2081
  await checkUnreadFolders({ foundationName: f.name, srcDir: resolveFoundationSrcPath(f.path), issues })
2082
+ await checkUnreadLibraries({ foundationName: f.name, srcDir: resolveFoundationSrcPath(f.path), foundationDir: f.path, issues })
2065
2083
  }
2066
2084
 
2067
2085
  // A modifier kit's prose layer does not have — `prose-slate`, `prose-invert`
@@ -8,7 +8,7 @@
8
8
  * (`backend/foundation-bring-along.js`).
9
9
  *
10
10
  * If the foundation's `dist/` is missing or stale — no build, a version bump
11
- * since it, a source file newer than it, no SSR bundle (`foundationNeedsBuild`)
11
+ * since it, a source file or a library's newer than it, no SSR bundle (`foundationNeedsBuild`)
12
12
  * — `register` builds it first. Preview paths (`--dry-run`, `-o`) never write to
13
13
  * `dist/`; they require a pre-built foundation.
14
14
  *
@@ -63,7 +63,6 @@ import {
63
63
  existsSync,
64
64
  readFileSync,
65
65
  writeFileSync,
66
- readdirSync,
67
66
  statSync
68
67
  } from 'node:fs'
69
68
  import { execSync } from 'node:child_process'
@@ -93,6 +92,7 @@ import { deriveScope, publishScope, belongsToScope } from '../utils/registry-org
93
92
  import { BackendClient } from '../backend/client.js'
94
93
  import { resolveWorkspace, scopeOfWorkspace, topOfChildHandle, SOURCE_LABEL } from '../backend/workspace.js'
95
94
  import { writeJsonPreservingStyleAsync } from '../utils/json-file.js'
95
+ import { newerInput } from '../utils/foundation-freshness.js'
96
96
  import {
97
97
  findWorkspaceRoot,
98
98
  findFoundations,
@@ -458,46 +458,6 @@ async function deriveScopeFromLogin(client, args) {
458
458
  return derived ? `@${derived}` : null
459
459
  }
460
460
 
461
- // Directories that are never foundation source. `dist` is the output we compare
462
- // against; the rest are tooling. Dotted entries are skipped wholesale.
463
- const NON_SOURCE_DIRS = new Set(['dist', 'node_modules'])
464
-
465
- /**
466
- * The newest mtime under `dir`, skipping build output and tooling. `0` when the
467
- * tree is unreadable — which reads as "no source is newer", i.e. it degrades to
468
- * the pre-existing behaviour rather than forcing a build on an fs error.
469
- *
470
- * @param {string} dir
471
- * @returns {number} epoch ms
472
- */
473
- function newestSourceMtime(dir) {
474
- let newest = 0
475
- const walk = (d) => {
476
- let entries
477
- try {
478
- entries = readdirSync(d, { withFileTypes: true })
479
- } catch {
480
- return
481
- }
482
- for (const e of entries) {
483
- if (e.name.startsWith('.') || NON_SOURCE_DIRS.has(e.name)) continue
484
- const p = join(d, e.name)
485
- if (e.isDirectory()) {
486
- walk(p)
487
- continue
488
- }
489
- try {
490
- const m = statSync(p).mtimeMs
491
- if (m > newest) newest = m
492
- } catch {
493
- /* unreadable file — ignore */
494
- }
495
- }
496
- }
497
- walk(dir)
498
- return newest
499
- }
500
-
501
461
  /**
502
462
  * Does the foundation's `dist/` need a (re)build before we can register it?
503
463
  *
@@ -509,7 +469,9 @@ function newestSourceMtime(dir) {
509
469
  * so the artifact encodes the OLD version while the register intends the
510
470
  * NEW one (we'd otherwise submit a schema whose version disagrees with the
511
471
  * code we deliver).
512
- * - STALE SOURCE: a source file is newer than `dist/entry.js`.
472
+ * - STALE SOURCE: a file its build reads is newer than `dist/entry.js`: its own,
473
+ * or one of a library it bundles (`newerInput`, the rule `uniweb build`
474
+ * follows too).
513
475
  *
514
476
  * ⛔ **The source signal was missing until 2026-08-16, and its absence shipped the
515
477
  * PREVIOUS bundle silently.** Edit a component's rendered output, re-run
@@ -593,9 +555,14 @@ export function foundationNeedsBuild(targetDir) {
593
555
  const entryPath = existsSync(join(distDir, 'entry.js'))
594
556
  ? join(distDir, 'entry.js')
595
557
  : join(distDir, 'foundation.js')
596
- const builtAt = statSync(entryPath).mtimeMs
597
- if (newestSourceMtime(targetDir) > builtAt)
598
- return { needs: true, reason: 'a source file is newer than dist/entry.js' }
558
+ const newer = newerInput(targetDir, statSync(entryPath).mtimeMs)
559
+ if (newer)
560
+ return {
561
+ needs: true,
562
+ reason: newer.library
563
+ ? `a file of ${newer.library}, a library it bundles, is newer than dist/entry.js`
564
+ : 'a source file is newer than dist/entry.js'
565
+ }
599
566
  } catch {
600
567
  // Can't compare — leave the other signals to decide rather than forcing a
601
568
  // build on an fs error.
@@ -1082,7 +1049,10 @@ async function runRegister(args = []) {
1082
1049
  ` ${colors.dim}Delivery is separate: a foundation that binds ${scope}/<name> resolves it from${colors.reset}`
1083
1050
  )
1084
1051
  log(
1085
- ` ${colors.dim}disk — an ${scope}/schemas package, or a folder routed in schemas.config.js.${colors.reset}`
1052
+ ` ${colors.dim}disk — a package of its workspace or a library it bundles that defines it, an${colors.reset}`
1053
+ )
1054
+ log(
1055
+ ` ${colors.dim}${scope}/schemas package, or a folder routed in schemas.config.js.${colors.reset}`
1086
1056
  )
1087
1057
  }
1088
1058
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-10T03:51:29.247Z",
3
+ "generatedAt": "2026-11-10T05:06:45.377Z",
4
4
  "packages": {
5
5
  "@uniweb/api": {
6
6
  "version": "1.7.0"
7
7
  },
8
8
  "@uniweb/build": {
9
- "version": "1.20.5"
9
+ "version": "1.20.6"
10
10
  },
11
11
  "@uniweb/content-reader": {
12
12
  "version": "1.5.9"
@@ -33,7 +33,7 @@
33
33
  "version": "1.2.2"
34
34
  },
35
35
  "@uniweb/projections": {
36
- "version": "1.2.15"
36
+ "version": "1.2.16"
37
37
  },
38
38
  "@uniweb/runtime": {
39
39
  "version": "1.5.6"
package/src/index.js CHANGED
@@ -1731,13 +1731,14 @@ ${colors.bright}Options:${colors.reset}
1731
1731
  add: `
1732
1732
  ${colors.cyan}${colors.bright}Uniweb Add${colors.reset}
1733
1733
 
1734
- Add projects, foundations, sites, extensions, section types, or CI workflows to your workspace.
1734
+ Add projects, foundations, sites, extensions, libraries, section types, or CI workflows to your workspace.
1735
1735
 
1736
1736
  ${colors.bright}Usage:${colors.reset}
1737
1737
  uniweb add project [name] [options]
1738
1738
  uniweb add foundation [name] [options]
1739
1739
  uniweb add site [name] [options]
1740
1740
  uniweb add extension <name> [options]
1741
+ uniweb add library <name> [options]
1741
1742
  uniweb add section <name> [options]
1742
1743
  uniweb add ci [options]
1743
1744
  uniweb add version <name> [options]
@@ -1757,6 +1758,14 @@ ${colors.bright}Site Options:${colors.reset}
1757
1758
  ${colors.bright}Extension Options:${colors.reset}
1758
1759
  --site <name> Site to wire extension URL into
1759
1760
 
1761
+ ${colors.bright}Library Options:${colors.reset}
1762
+ --foundation <a,b> Foundations that use it: each gets the dependency and the
1763
+ stylesheet import (the workspace's one foundation if omitted;
1764
+ run again with another to wire one more)
1765
+ --schemas A schemas/ folder for the data types its foundations share
1766
+ --scope <@org> The scope those types are named under (default: the one
1767
+ the wired foundations share)
1768
+
1760
1769
  ${colors.bright}Section Options:${colors.reset}
1761
1770
  --foundation <n> Foundation to add section to (prompted if multiple exist)
1762
1771
  --in <folder> add version: the folder under pages/ holding the docs (. for all of pages/)
@@ -1798,6 +1807,9 @@ ${colors.bright}Examples:${colors.reset}
1798
1807
  uniweb add site blog --foundation marketing # Create ./blog/ wired to marketing
1799
1808
  uniweb add extension effects --site site # Create ./effects/ — the folder you name
1800
1809
  uniweb add extension extensions/effects # Create ./extensions/effects/
1810
+ uniweb add library libraries/ui --foundation a,b # Create ./libraries/ui/, shared by a and b
1811
+ uniweb add library libraries/ui --foundation c # Wire one more foundation to it
1812
+ uniweb add library shared --schemas --scope @acme # With data types named @acme/<file>
1801
1813
  uniweb add section Hero # Create Hero section type
1802
1814
  uniweb add section Hero --foundation ui # Target specific foundation
1803
1815
  uniweb add section Hero --starter # Starter content for an existing Hero
@@ -2432,6 +2444,7 @@ ${colors.bright}Add Subcommands:${colors.reset}
2432
2444
  add foundation [name] Add a foundation (--from, --path, --project)
2433
2445
  add site [name] Add a site (--from, --foundation, --path, --project)
2434
2446
  add extension <name> Add an extension (--from, --site, --path)
2447
+ add library <name> Add a library foundations share (--foundation, --schemas)
2435
2448
  add section <name> Add a section type to a foundation (--foundation, --starter)
2436
2449
  add ci Add a CI workflow so every push deploys (--host, --target)
2437
2450
  add version Freeze a site's docs as a version beside them (--in, --label)
@@ -0,0 +1,89 @@
1
+ /**
2
+ * ⭐ IS A LOCAL FOUNDATION'S `dist/` OLDER THAN WHAT ITS BUILD READS? One rule, for every verb that
3
+ * uses a built foundation: `uniweb build` from a site, `export`, `deploy --host` and `dev` before
4
+ * they use it (`ensureFoundationFresh`), and `register` before it uploads it
5
+ * (`foundationNeedsBuild`). A build reads:
6
+ * - the foundation's source root, the folder `package.json::main` names (`resolveFoundationSrcPath`:
7
+ * the package itself when flat, `src/` when nested), and the files at its root that shape the
8
+ * build (`package.json`, `vite.config.js`, a legacy `foundation.js` or `meta.js`);
9
+ * - every library it bundles: any local package it depends on (`librariesOf`, `@uniweb/build`),
10
+ * wherever it is linked from.
11
+ * Dot-folders, `node_modules`, and what a foundation's build writes into one (`dist/`, the
12
+ * generated entry) are never sources. A library that is not a foundation keeps its `dist/`, which
13
+ * may be what the foundation imports.
14
+ *
15
+ * Ties count as fresh: a build writes its output after it reads its input, so equal times mean a
16
+ * build in the same millisecond, and on a fresh clone, where whole trees share a time, a tie
17
+ * counted stale would rebuild every foundation once for nothing.
18
+ *
19
+ * ⛔ Until 2026-11-09 only the foundation's own folder was walked, and the two verbs walked it two
20
+ * ways. Measured: with only a library's file changed, `uniweb build` kept the old `dist/`, so the
21
+ * prerendered page showed the old component while the site's JS had the new one; and `register`
22
+ * answered that nothing needed building. ⛔ Until 2026-10-13 `build` walked `<package>/src/`
23
+ * whatever the layout, and a flat package's edits never made it stale.
24
+ */
25
+
26
+ import { existsSync, readdirSync, statSync } from 'node:fs'
27
+ import { join } from 'node:path'
28
+ import { classifyPackage, librariesOf, resolveFoundationSrcPath } from '@uniweb/build'
29
+
30
+ // The files at a foundation's root that shape its build, when its sources are in `src/`.
31
+ const ROOT_FILES = ['package.json', 'vite.config.js', 'foundation.js', 'meta.js']
32
+
33
+ // What a foundation's build writes into the foundation.
34
+ const BUILD_OUTPUT = new Set(['dist', '_entry.generated.js'])
35
+
36
+ /** The first file under `dir` newer than `builtAt`, or null. */
37
+ function newerUnder(dir, builtAt, { skipOutput }) {
38
+ const stack = [dir]
39
+ while (stack.length) {
40
+ const at = stack.pop()
41
+ let entries
42
+ try {
43
+ entries = readdirSync(at, { withFileTypes: true })
44
+ } catch {
45
+ continue
46
+ }
47
+ for (const e of entries) {
48
+ if (e.name.startsWith('.') || e.name === 'node_modules' || (skipOutput && BUILD_OUTPUT.has(e.name))) continue
49
+ const full = join(at, e.name)
50
+ if (e.isDirectory()) {
51
+ stack.push(full)
52
+ continue
53
+ }
54
+ if (!e.isFile()) continue
55
+ try {
56
+ if (statSync(full).mtimeMs > builtAt) return full
57
+ } catch {
58
+ // unreadable: not newer
59
+ }
60
+ }
61
+ }
62
+ return null
63
+ }
64
+
65
+ /**
66
+ * The first file a foundation's build reads that is newer than `builtAt`, and the library it is
67
+ * in; null when every one is as old as the build or older.
68
+ *
69
+ * @param {string} foundationDir
70
+ * @param {number} builtAt - the built entry's mtime, epoch ms
71
+ * @returns {{ file: string, library: string|null }|null}
72
+ */
73
+ export function newerInput(foundationDir, builtAt) {
74
+ for (const f of ROOT_FILES) {
75
+ const p = join(foundationDir, f)
76
+ try {
77
+ if (existsSync(p) && statSync(p).mtimeMs > builtAt) return { file: p, library: null }
78
+ } catch {
79
+ // unreadable: not newer
80
+ }
81
+ }
82
+ const own = newerUnder(resolveFoundationSrcPath(foundationDir), builtAt, { skipOutput: true })
83
+ if (own) return { file: own, library: null }
84
+ for (const { name, dir } of librariesOf(foundationDir)) {
85
+ const file = newerUnder(dir, builtAt, { skipOutput: classifyPackage(dir) === 'foundation' })
86
+ if (file) return { file, library: name }
87
+ }
88
+ return null
89
+ }
@@ -1,4 +1,4 @@
1
- import { isAbsolute, relative, sep } from 'node:path'
1
+ import { isAbsolute, relative, resolve, sep } from 'node:path'
2
2
 
3
3
  /**
4
4
  * Package placement resolution — shared by `add` and `clone`.
@@ -33,6 +33,21 @@ function normalizeParent(given, rootDir) {
33
33
  return { relative: rel.split(sep).join('/') }
34
34
  }
35
35
 
36
+ /**
37
+ * The folder a package is to be made in, as the root-relative path every consumer expects — or
38
+ * `outsideRoot` when it is not inside the workspace. ⛔ Until 2026-11-09 only `--path` was
39
+ * checked, and a name naming a path was taken as written: `add foundation /tmp/x` made
40
+ * `<workspace>/tmp/x/` while both manifests recorded `/tmp/x` (the split above), and
41
+ * `add foundation ../x` made a package outside the workspace and listed `../x`.
42
+ */
43
+ function insideRoot(rootDir, path) {
44
+ if (!rootDir) return { relativePath: path }
45
+ const trimmed = String(path).replace(/\/+$/, '')
46
+ const rel = relative(rootDir, resolve(rootDir, trimmed))
47
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return { outsideRoot: trimmed, relativePath: null, packageName: null }
48
+ return { relativePath: rel.split(sep).join('/') }
49
+ }
50
+
36
51
  /** Foundation placement defaults (folder `src/`, package `src`). */
37
52
  export const FOUNDATION_KIND = {
38
53
  defaultDir: 'src',
@@ -61,6 +76,16 @@ export const EXTENSION_KIND = {
61
76
  projectSub: null
62
77
  }
63
78
 
79
+ /**
80
+ * Library placement: as an extension's, no defaults. A library always has a name, or a `--path`
81
+ * naming its folder, and belongs to no one project, so `--project` places none.
82
+ */
83
+ export const LIBRARY_KIND = {
84
+ defaultDir: null,
85
+ defaultPkg: null,
86
+ projectSub: null
87
+ }
88
+
64
89
  /**
65
90
  * Resolve where a foundation or site should be placed, given the user's input.
66
91
  *
@@ -110,30 +135,29 @@ export function resolvePlacement(rootDir, name, opts, kind) {
110
135
  const dir = parent.relative
111
136
  if (name) {
112
137
  const last = name.split('/').filter(Boolean).pop()
113
- return {
114
- relativePath: `${dir}/${name}`.replace(/\/+/g, '/'),
115
- packageName: last
116
- }
138
+ const at = insideRoot(rootDir, `${dir}/${name}`.replace(/\/+/g, '/'))
139
+ return at.outsideRoot ? at : { relativePath: at.relativePath, packageName: last }
117
140
  }
118
141
  const lastSegment = dir.split('/').filter(Boolean).pop() || dir
119
- return {
120
- relativePath: dir,
121
- packageName: lastSegment
122
- }
142
+ const at = insideRoot(rootDir, dir)
143
+ return at.outsideRoot ? at : { relativePath: at.relativePath, packageName: lastSegment }
123
144
  }
124
145
 
125
146
  // 2. name contains a slash → treat as a path.
126
147
  if (name && name.includes('/')) {
127
- const relativePath = name.replace(/\/+$/, '')
128
- const lastSegment = relativePath.split('/').filter(Boolean).pop()
148
+ const at = insideRoot(rootDir, name)
149
+ if (at.outsideRoot) return at
150
+ const lastSegment = at.relativePath.split('/').filter(Boolean).pop()
129
151
  return {
130
- relativePath,
152
+ relativePath: at.relativePath,
131
153
  packageName: lastSegment
132
154
  }
133
155
  }
134
156
 
135
157
  // 3. Bare name.
136
158
  if (name) {
159
+ const at = insideRoot(rootDir, name)
160
+ if (at.outsideRoot) return at
137
161
  return {
138
162
  relativePath: name,
139
163
  packageName: name