uniweb 1.30.2 → 1.31.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uniweb",
3
- "version": "1.30.2",
3
+ "version": "1.31.0",
4
4
  "description": "Create structured Vite + React sites with content/code separation",
5
5
  "type": "module",
6
6
  "bin": {
@@ -41,15 +41,15 @@
41
41
  "js-yaml": "^4.3.2",
42
42
  "prompts": "^2.4.2",
43
43
  "tar": "^7.5.21",
44
- "@uniweb/content-writer": "~1.3.1",
45
44
  "@uniweb/core": "~1.6.9",
46
45
  "@uniweb/semantic-parser": "~1.13.2",
47
- "@uniweb/schemas": "~1.6.11"
46
+ "@uniweb/schemas": "~1.7.0",
47
+ "@uniweb/content-writer": "~1.3.1"
48
48
  },
49
49
  "peerDependencies": {
50
- "@uniweb/build": "~1.19.2",
51
- "@uniweb/content-reader": "~1.5.9",
52
- "@uniweb/semantic-parser": "~1.13.2"
50
+ "@uniweb/build": "~1.20.0",
51
+ "@uniweb/semantic-parser": "~1.13.2",
52
+ "@uniweb/content-reader": "~1.5.9"
53
53
  },
54
54
  "peerDependenciesMeta": {
55
55
  "@uniweb/build": {
@@ -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 folder: `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 any registered data schema, by its full name** — `data: { members: '@acme/member' }`, `schema: '@acme/member'` in `queries.yml`. A scope is a namespace that keeps names from colliding, not a limit on who uses a type. So a type another foundation registers 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`). A register names such a type and sends no definition of it. A local build still needs the file: `schemas.config.js` routes that type, `'@acme/member': '../hub/src/schemas/member.yml'`, or its scope's folder. 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 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 folder), 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 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 } }
@@ -1432,15 +1432,24 @@ export function writeHeldTypes(siteDir, backend, folderDoc) {
1432
1432
  * The backend keeps them, in no folder, until they are deleted (`utils/retired-records.js`). A
1433
1433
  * retired record placed again (a move undone) is dropped from the list.
1434
1434
  *
1435
+ * ⭐ ONLY THIS COPY'S OWN RECORDS. A record of another site's directory, mounted here
1436
+ * (`site.yml::paths`), is placed by reference to the entity its owner's push made. This copy never
1437
+ * sent it, and a pull leaves its file to the owner, so the `records` map, which every push and pull
1438
+ * writes for the records they carry, never holds it. Leaving the folder, it is the owner's to
1439
+ * retire. ⛔ Until 2026-11-08 it was retired here too, and one uuid the caller may not administer
1440
+ * refuses the whole delete before anything is deleted [backend, 2026-11-08].
1441
+ *
1435
1442
  * ⚠️ Nothing is known before a copy first banks its types, so a copy banked before 2026-11-04
1436
1443
  * retires nothing on its first push after that.
1437
1444
  *
1438
1445
  * @returns {string[]} the uuids this push retired
1439
1446
  */
1440
1447
  export function retireUnplaced(siteDir, backend, { before, after }) {
1441
- const prior = readBackendState(siteDir, backend).retired || {}
1448
+ const state = readBackendState(siteDir, backend)
1449
+ const prior = state.retired || {}
1450
+ const own = new Set(Object.values(state.records || {}))
1442
1451
  const now = Object.fromEntries(Object.entries(prior).filter(([uuid]) => !(uuid in after)))
1443
- const retired = Object.keys(before).filter((uuid) => !(uuid in after))
1452
+ const retired = Object.keys(before).filter((uuid) => !(uuid in after) && own.has(uuid))
1444
1453
  for (const uuid of retired) now[uuid] = before[uuid]
1445
1454
  setBackendMap(siteDir, backend, 'retired', now)
1446
1455
  return retired
@@ -1686,7 +1686,7 @@ export function checkGeneratedDataDir({ sitePath, siteName, siteYml, issues, sho
1686
1686
  * ⭐ WHAT DOCTOR CHECKS IS WHERE YOU STAND, by the rule `dev` and `status` read the folder you stand in
1687
1687
  * (`pick-site.js::siteAround`): in a site, that site and what it is built from, its foundation and its
1688
1688
  * extensions; in a foundation, the site beside it when that site is built from it, else that foundation;
1689
- * elsewhere, the whole workspace. ⛔ Until 2026-11-09 the site beside a foundation was checked whatever
1689
+ * elsewhere, the whole workspace. ⛔ Until 2026-11-08 the site beside a foundation was checked whatever
1690
1690
  * it was built from, so in `shop/src` beside a site on another foundation, nothing checked `shop/src`.
1691
1691
  * ⛔ Until 2026-11-08 only the sites were narrowed: run in one site, doctor reported on every foundation
1692
1692
  * in the workspace before the site's own checks, which were hard to find among them.
@@ -1753,8 +1753,8 @@ export async function checkTypesDefinedTwice({ workspaceDir, checkedDirs, issues
1753
1753
  info(`[${id}] ${t.ref} is defined in ${t.files.length} places${t.differ ? ', and they differ' : ''}`)
1754
1754
  for (const f of t.files) log(` ${relative(workspaceDir, f)}`)
1755
1755
  log(
1756
- ` A registered data schema is usable by any foundation by its full name, so keep one definition and name ` +
1757
- `it in full in the others (${colors.green}${t.ref}${colors.reset}); schemas.config.js gives a local build its file.`
1756
+ ` Any foundation can use a data schema by its full name, so keep one definition and name it in full in the ` +
1757
+ `others (${colors.green}${t.ref}${colors.reset}): in this workspace their build finds its file, with nothing to configure.`
1758
1758
  )
1759
1759
  }
1760
1760
  }
@@ -1350,6 +1350,11 @@ export async function pull(args = [], deps = {}) {
1350
1350
  removed.push(resolve(projDir, report.recordsFile))
1351
1351
  }
1352
1352
  records += report.placed.length + report.updated.length
1353
+ // ⭐ Another site's records, mounted (`site.yml::paths`): read where they are, and left as the
1354
+ // owner's files hold them, since a pull of this site writes nothing there.
1355
+ if (report.leftToOwner?.length) {
1356
+ note(` ${report.leftToOwner.length} record(s) are mounted from another site (site.yml paths:) and left as its files hold them`)
1357
+ }
1353
1358
  // ⭐ A FILE RECORD'S BYTES (`@uniweb/file`, 2026-09-28): fetched to where `folder.yml` now
1354
1359
  // places each one, as media are fetched. A file that did not arrive is a record not taken —
1355
1360
  // reported, and the pull fails below as it does for any, so the next one fetches it again.
@@ -1379,7 +1384,7 @@ export async function pull(args = [], deps = {}) {
1379
1384
  if (report.skipped.length) {
1380
1385
  recordsNotPlaced = describeUnplacedRecords({
1381
1386
  docs: folderLane.docs,
1382
- taken: report.placed.length + report.updated.length + report.unchanged.length,
1387
+ taken: report.placed.length + report.updated.length + report.unchanged.length + (report.leftToOwner?.length || 0),
1383
1388
  skipped: report.skipped
1384
1389
  })
1385
1390
  error(recordsNotPlaced.headline)
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-09T02:11:16.418Z",
3
+ "generatedAt": "2026-11-09T18:42:57.806Z",
4
4
  "packages": {
5
5
  "@uniweb/api": {
6
- "version": "1.6.9"
6
+ "version": "1.6.10"
7
7
  },
8
8
  "@uniweb/build": {
9
- "version": "1.19.2"
9
+ "version": "1.20.0"
10
10
  },
11
11
  "@uniweb/content-reader": {
12
12
  "version": "1.5.9"
@@ -24,7 +24,7 @@
24
24
  "version": "1.0.8"
25
25
  },
26
26
  "@uniweb/kit": {
27
- "version": "1.7.17"
27
+ "version": "1.7.18"
28
28
  },
29
29
  "@uniweb/loom": {
30
30
  "version": "1.1.3"
@@ -42,7 +42,7 @@
42
42
  "version": "1.0.1"
43
43
  },
44
44
  "@uniweb/schemas": {
45
- "version": "1.6.11"
45
+ "version": "1.7.0"
46
46
  },
47
47
  "@uniweb/scholar": {
48
48
  "version": "1.1.0"
@@ -60,7 +60,7 @@
60
60
  "version": "1.3.2"
61
61
  },
62
62
  "@uniweb/unipress": {
63
- "version": "1.1.36"
63
+ "version": "1.1.37"
64
64
  }
65
65
  },
66
66
  "templates": {
@@ -465,7 +465,7 @@ export async function updateRootScripts(rootDir, sites, pm = 'pnpm') {
465
465
  // scripts named or run another way now (by its project's name; under npm, by its folder). A script
466
466
  // under the person's own name for a command, or whose command the CLI doesn't write, stays.
467
467
  // ⛔ Until 2026-10-13 they were only ever added: after `rename site blog journal`, `dev:blog`
468
- // still ran `uniweb dev blog`. ⛔ From 2026-11-08 to 2026-11-09 only a gone site's went, so a
468
+ // still ran `uniweb dev blog`. ⛔ In 1.30.0 and 1.30.1 only a gone site's went, so a
469
469
  // renamed project kept its old pair beside the new one.
470
470
  for (const [key, value] of Object.entries(scripts)) {
471
471
  if (!(key in newScripts) && cliNamed(key, value)) delete scripts[key]
@@ -25,15 +25,24 @@
25
25
  // and every other key, `onlyBuiltDependencies` and `allowBuilds` among them.
26
26
  //
27
27
  // Node built-ins, js-yaml and Handlebars only: the CLI's startup path reaches this
28
- // module (`utils/workspace.js`), before any project is installed.
28
+ // module (`utils/workspace.js`), before any project is installed. ⭐ The reading half is
29
+ // `./workspace-patterns.js`, mirrored byte for byte in `@uniweb/build`, which reads the same
30
+ // rule; this module keeps the writing and re-exports the reading.
29
31
 
30
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
32
+ import { readFileSync } from 'node:fs'
31
33
  import { dirname, join } from 'node:path'
32
34
  import { fileURLToPath } from 'node:url'
33
35
  import yaml from 'js-yaml'
34
36
  import Handlebars from 'handlebars'
37
+ import { WORKSPACE_FILE, strings } from './workspace-patterns.js'
35
38
 
36
- export const WORKSPACE_FILE = 'pnpm-workspace.yaml'
39
+ export {
40
+ WORKSPACE_FILE,
41
+ readWorkspacePatterns,
42
+ workspacePackages,
43
+ resolveWorkspacePackages,
44
+ patternsCover,
45
+ } from './workspace-patterns.js'
37
46
 
38
47
  const TEMPLATE = join(
39
48
  dirname(fileURLToPath(import.meta.url)),
@@ -44,88 +53,6 @@ const TEMPLATE = join(
44
53
  `${WORKSPACE_FILE}.hbs`
45
54
  )
46
55
 
47
- // ─── Reading ────────────────────────────────────────────────────────────────
48
-
49
- /**
50
- * The package patterns a workspace declares, and the file they are read from:
51
- * pnpm-workspace.yaml when the workspace has one, else package.json's `workspaces`.
52
- *
53
- * @param {string} rootDir
54
- * @returns {{ source: string|null, patterns: string[] }}
55
- */
56
- export function readWorkspacePatterns(rootDir) {
57
- const ymlPath = join(rootDir, WORKSPACE_FILE)
58
- if (existsSync(ymlPath)) {
59
- const doc = yaml.load(readFileSync(ymlPath, 'utf8'))
60
- return { source: WORKSPACE_FILE, patterns: strings(doc?.packages) }
61
- }
62
- try {
63
- const pkg = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf8'))
64
- if (Array.isArray(pkg.workspaces)) return { source: 'package.json', patterns: strings(pkg.workspaces) }
65
- } catch {
66
- // No package.json, or not JSON — a workspace with no packages declared.
67
- }
68
- return { source: null, patterns: [] }
69
- }
70
-
71
- /**
72
- * The workspace's packages: the folders its patterns name.
73
- *
74
- * @param {string} rootDir
75
- * @returns {string[]} see {@link resolveWorkspacePackages}
76
- */
77
- export function workspacePackages(rootDir) {
78
- return resolveWorkspacePackages(rootDir, readWorkspacePatterns(rootDir).patterns)
79
- }
80
-
81
- /**
82
- * The folders `patterns` name under `rootDir`, as workspace-relative paths in `/`
83
- * form, each once, in the order of the first pattern that names it — alphabetical
84
- * within a pattern. A folder a wildcard finds counts only when it holds a
85
- * package.json; one a pattern names by its own path counts if it exists.
86
- *
87
- * @param {string} rootDir
88
- * @param {string[]} patterns
89
- * @returns {string[]}
90
- */
91
- export function resolveWorkspacePackages(rootDir, patterns) {
92
- const { include, exclude } = parsePatterns(patterns)
93
- const seen = new Set()
94
- const out = []
95
- for (const pattern of include) {
96
- const byWildcard = pattern.some((segment) => segment === '**' || hasMagic(segment))
97
- for (const rel of expand(rootDir, pattern, [], 0, [])) {
98
- // The root is the workspace itself, never one of its packages.
99
- if (!rel || seen.has(rel)) continue
100
- if (byWildcard && !existsSync(join(rootDir, rel, 'package.json'))) continue
101
- if (exclude.some((ex) => matches(ex, rel.split('/')))) continue
102
- seen.add(rel)
103
- out.push(rel)
104
- }
105
- }
106
- return out
107
- }
108
-
109
- /**
110
- * Do `patterns` cover the folder at `relPath` — would it be one of the workspace's
111
- * packages? Answered from the patterns alone, so it holds for a folder about to be
112
- * created.
113
- *
114
- * @param {string[]} patterns
115
- * @param {string} relPath - workspace-relative
116
- * @returns {boolean}
117
- */
118
- export function patternsCover(patterns, relPath) {
119
- const path = normalizePath(relPath)
120
- if (!path) return false
121
- const segments = path.split('/')
122
- const { include, exclude } = parsePatterns(patterns)
123
- return (
124
- include.some((p) => matches(p, segments)) &&
125
- !exclude.some((p) => matches(p, segments))
126
- )
127
- }
128
-
129
56
  // ─── Writing ────────────────────────────────────────────────────────────────
130
57
 
131
58
  /**
@@ -178,159 +105,6 @@ export function editWorkspaceFilePackages(text, edit) {
178
105
  return out
179
106
  }
180
107
 
181
- // ─── Patterns ───────────────────────────────────────────────────────────────
182
-
183
- // `@(…)`, `+(…)`, `!(…)`, `*(…)`, `?(…)` — extended globs, which this does not read.
184
- const EXTGLOB = /[@+!*?]\(/
185
- const warned = new Set()
186
-
187
- /** Positive and negative patterns as folder-name lists, `{a,b}` expanded. */
188
- function parsePatterns(patterns) {
189
- const include = []
190
- const exclude = []
191
- for (const raw of strings(patterns)) {
192
- let pattern = raw.trim()
193
- const negated = pattern.startsWith('!')
194
- if (negated) pattern = pattern.slice(1)
195
- if (EXTGLOB.test(pattern)) {
196
- if (!warned.has(raw)) {
197
- warned.add(raw)
198
- process.stderr.write(
199
- `⚠ uniweb does not read the workspace pattern "${raw}" (extended glob syntax) — ` +
200
- `list the folders it stands for instead.\n`
201
- )
202
- }
203
- continue
204
- }
205
- for (const one of expandBraces(pattern)) {
206
- const path = normalizePath(one)
207
- if (path) (negated ? exclude : include).push(path.split('/'))
208
- }
209
- }
210
- return { include, exclude }
211
- }
212
-
213
- /** `a/{b,c}/d` → `a/b/d`, `a/c/d`; nested lists expand innermost first. */
214
- function expandBraces(pattern) {
215
- const m = /\{([^{}]*)\}/.exec(pattern)
216
- if (!m) return [pattern]
217
- const options = m[1].split(',')
218
- // `{x}` lists nothing to choose between: a literal brace, as in pnpm.
219
- if (options.length < 2) return [pattern]
220
- const head = pattern.slice(0, m.index)
221
- const tail = pattern.slice(m.index + m[0].length)
222
- return options.flatMap((o) => expandBraces(head + o + tail))
223
- }
224
-
225
- /** `./a//b/` → `a/b`; `\` becomes `/`; `.` and `` are the root. */
226
- function normalizePath(path) {
227
- let s = String(path).replace(/\\/g, '/').replace(/\/{2,}/g, '/')
228
- while (s.startsWith('./')) s = s.slice(2)
229
- s = s.replace(/^\/+/, '').replace(/\/+$/, '')
230
- return s === '.' ? '' : s
231
- }
232
-
233
- const hasMagic = (segment) => /[*?[]/.test(segment)
234
-
235
- /** Can a wildcard step into this folder? Never `node_modules`, never a dot-folder. */
236
- const wildcardMayEnter = (name) => !name.startsWith('.') && name !== 'node_modules'
237
-
238
- const regexCache = new Map()
239
-
240
- /** One folder-name pattern as a regex: `*`, `?` and `[...]`, everything else literal. */
241
- function segmentRegex(segment) {
242
- let re = regexCache.get(segment)
243
- if (re) return re
244
- let src = ''
245
- for (let i = 0; i < segment.length; i++) {
246
- const c = segment[i]
247
- if (c === '*') src += '[^/]*'
248
- else if (c === '?') src += '[^/]'
249
- else if (c === '[' && segment.indexOf(']', i + 2) > i) {
250
- const end = segment.indexOf(']', i + 2)
251
- let body = segment.slice(i + 1, end).replace(/\\/g, '\\\\')
252
- if (body.startsWith('!')) body = `^${body.slice(1)}`
253
- src += `[${body}]`
254
- i = end
255
- } else src += c.replace(/[.+^$(){}|\\[\]]/g, '\\$&')
256
- }
257
- re = new RegExp(`^${src}$`)
258
- regexCache.set(segment, re)
259
- return re
260
- }
261
-
262
- function segmentMatches(segment, name) {
263
- if (!hasMagic(segment)) return segment === name
264
- // A wildcard does not match a dot-folder unless the pattern spells the dot.
265
- if (name.startsWith('.') && !segment.startsWith('.')) return false
266
- if (name === 'node_modules') return false
267
- return segmentRegex(segment).test(name)
268
- }
269
-
270
- /** Does the folder-name list `path` match the pattern `pattern`? `**` is any depth. */
271
- function matches(pattern, path, i = 0, j = 0) {
272
- if (i === pattern.length) return j === path.length
273
- if (pattern[i] === '**') {
274
- for (let k = j; k <= path.length; k++) {
275
- if (k > j && !wildcardMayEnter(path[k - 1])) break
276
- if (matches(pattern, path, i + 1, k)) return true
277
- }
278
- return false
279
- }
280
- if (j === path.length || !segmentMatches(pattern[i], path[j])) return false
281
- return matches(pattern, path, i + 1, j + 1)
282
- }
283
-
284
- /** The folders under `rootDir` that `pattern` names, found on disk. */
285
- function expand(rootDir, pattern, base, i, out) {
286
- if (i === pattern.length) {
287
- out.push(base.join('/'))
288
- return out
289
- }
290
- const segment = pattern[i]
291
- const here = join(rootDir, ...base)
292
- if (segment === '**') {
293
- expand(rootDir, pattern, base, i + 1, out)
294
- // Real folders only: a symlink back up the tree would never end.
295
- for (const name of subfolders(here, { followLinks: false })) {
296
- if (wildcardMayEnter(name)) expand(rootDir, pattern, [...base, name], i, out)
297
- }
298
- return out
299
- }
300
- if (!hasMagic(segment)) {
301
- if (segment === '.') return expand(rootDir, pattern, base, i + 1, out)
302
- if (isFolder(join(here, segment))) expand(rootDir, pattern, [...base, segment], i + 1, out)
303
- return out
304
- }
305
- for (const name of subfolders(here)) {
306
- if (segmentMatches(segment, name)) expand(rootDir, pattern, [...base, name], i + 1, out)
307
- }
308
- return out
309
- }
310
-
311
- function subfolders(dir, { followLinks = true } = {}) {
312
- let entries
313
- try {
314
- entries = readdirSync(dir, { withFileTypes: true })
315
- } catch {
316
- return []
317
- }
318
- return entries
319
- .filter(
320
- (e) => e.isDirectory() || (followLinks && e.isSymbolicLink() && isFolder(join(dir, e.name)))
321
- )
322
- .map((e) => e.name)
323
- .sort()
324
- }
325
-
326
- function isFolder(path) {
327
- try {
328
- return statSync(path).isDirectory()
329
- } catch {
330
- return false
331
- }
332
- }
333
-
334
108
  // ─── The `packages:` list, as text ──────────────────────────────────────────
335
109
 
336
110
  /**
@@ -422,10 +196,6 @@ function formatEntry(value, quote) {
422
196
 
423
197
  // ─── Helpers ────────────────────────────────────────────────────────────────
424
198
 
425
- function strings(list) {
426
- return Array.isArray(list) ? list.filter((v) => typeof v === 'string') : []
427
- }
428
-
429
199
  function sameValue(a, b) {
430
200
  return JSON.stringify(a) === JSON.stringify(b)
431
201
  }
@@ -0,0 +1,272 @@
1
+ // THE WORKSPACE'S PACKAGES, READ AS PNPM READS THEM: the reading half of the CLI's
2
+ // `utils/workspace-packages.js`, in a module of its own, so that `@uniweb/build` holds the same rule
3
+ // without either package importing the other.
4
+ //
5
+ // ⛔ THIS FILE IS MIRRORED, BYTE FOR BYTE: `framework/cli/src/utils/workspace-patterns.js` and
6
+ // `framework/build/src/workspace-patterns.js`. The CLI's startup path reads it before any project,
7
+ // and so any `@uniweb/build`, is installed; the build reads it to find a data schema another package
8
+ // of the workspace defines (`foundation/shared-types.js`). Edit one and copy it over the other:
9
+ // `_contracts/workspace-patterns-mirror.test.js` fails until they match.
10
+ //
11
+ // A workspace lists its packages as folder patterns: `packages:` in pnpm-workspace.yaml, or
12
+ // `workspaces` in package.json for npm and yarn. Patterns are read as pnpm reads them: `*`, `?` and
13
+ // `[...]` within one folder name, `**` for any depth, `{a,b}` for alternatives, and a leading `!` to
14
+ // exclude what the other patterns match. A folder a wildcard finds counts when it holds a
15
+ // package.json, as pnpm counts it — so `**` never sweeps in a `pages/` or `dist/` folder — and a
16
+ // wildcard never enters `node_modules` or a dot-folder. A folder listed by its own path counts if it
17
+ // exists: listing it says it is one, and a command that reads content only (`validate`) works on a
18
+ // folder with no manifest yet. Any other syntax is refused by name, never read as a path.
19
+ //
20
+ // Node built-ins and js-yaml only.
21
+
22
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
23
+ import { join } from 'node:path'
24
+ import yaml from 'js-yaml'
25
+
26
+ export const WORKSPACE_FILE = 'pnpm-workspace.yaml'
27
+
28
+ // Read as the build reads YAML (`build/src/utils/yaml-schema.js`): js-yaml's types without the
29
+ // implicit timestamp, so a folder named like a date, `packages: [2025-06-01]`, stays its name instead
30
+ // of becoming a Date that the list then drops. Restated here, since this file imports only js-yaml.
31
+ const YAML_OPTIONS = Object.freeze({ schema: yaml.CORE_SCHEMA.extend({ implicit: [yaml.types.merge] }) })
32
+
33
+ // ─── Reading ────────────────────────────────────────────────────────────────
34
+
35
+ /**
36
+ * The package patterns a workspace declares, and the file they are read from:
37
+ * pnpm-workspace.yaml when the workspace has one, else package.json's `workspaces`.
38
+ *
39
+ * @param {string} rootDir
40
+ * @returns {{ source: string|null, patterns: string[] }}
41
+ */
42
+ export function readWorkspacePatterns(rootDir) {
43
+ const ymlPath = join(rootDir, WORKSPACE_FILE)
44
+ if (existsSync(ymlPath)) {
45
+ const doc = yaml.load(readFileSync(ymlPath, 'utf8'), YAML_OPTIONS)
46
+ return { source: WORKSPACE_FILE, patterns: strings(doc?.packages) }
47
+ }
48
+ try {
49
+ const pkg = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf8'))
50
+ if (Array.isArray(pkg.workspaces)) return { source: 'package.json', patterns: strings(pkg.workspaces) }
51
+ } catch {
52
+ // No package.json, or not JSON — a workspace with no packages declared.
53
+ }
54
+ return { source: null, patterns: [] }
55
+ }
56
+
57
+ /**
58
+ * The workspace's packages: the folders its patterns name.
59
+ *
60
+ * @param {string} rootDir
61
+ * @returns {string[]} see {@link resolveWorkspacePackages}
62
+ */
63
+ export function workspacePackages(rootDir) {
64
+ return resolveWorkspacePackages(rootDir, readWorkspacePatterns(rootDir).patterns)
65
+ }
66
+
67
+ /**
68
+ * The folders `patterns` name under `rootDir`, as workspace-relative paths in `/`
69
+ * form, each once, in the order of the first pattern that names it — alphabetical
70
+ * within a pattern. A folder a wildcard finds counts only when it holds a
71
+ * package.json; one a pattern names by its own path counts if it exists.
72
+ *
73
+ * @param {string} rootDir
74
+ * @param {string[]} patterns
75
+ * @returns {string[]}
76
+ */
77
+ export function resolveWorkspacePackages(rootDir, patterns) {
78
+ const { include, exclude } = parsePatterns(patterns)
79
+ const seen = new Set()
80
+ const out = []
81
+ for (const pattern of include) {
82
+ const byWildcard = pattern.some((segment) => segment === '**' || hasMagic(segment))
83
+ for (const rel of expand(rootDir, pattern, [], 0, [])) {
84
+ // The root is the workspace itself, never one of its packages.
85
+ if (!rel || seen.has(rel)) continue
86
+ if (byWildcard && !existsSync(join(rootDir, rel, 'package.json'))) continue
87
+ if (exclude.some((ex) => matches(ex, rel.split('/')))) continue
88
+ seen.add(rel)
89
+ out.push(rel)
90
+ }
91
+ }
92
+ return out
93
+ }
94
+
95
+ /**
96
+ * Do `patterns` cover the folder at `relPath` — would it be one of the workspace's
97
+ * packages? Answered from the patterns alone, so it holds for a folder about to be
98
+ * created.
99
+ *
100
+ * @param {string[]} patterns
101
+ * @param {string} relPath - workspace-relative
102
+ * @returns {boolean}
103
+ */
104
+ export function patternsCover(patterns, relPath) {
105
+ const path = normalizePath(relPath)
106
+ if (!path) return false
107
+ const segments = path.split('/')
108
+ const { include, exclude } = parsePatterns(patterns)
109
+ return (
110
+ include.some((p) => matches(p, segments)) &&
111
+ !exclude.some((p) => matches(p, segments))
112
+ )
113
+ }
114
+
115
+ // ─── Patterns ───────────────────────────────────────────────────────────────
116
+
117
+ // `@(…)`, `+(…)`, `!(…)`, `*(…)`, `?(…)` — extended globs, which this does not read.
118
+ const EXTGLOB = /[@+!*?]\(/
119
+ const warned = new Set()
120
+
121
+ /** Positive and negative patterns as folder-name lists, `{a,b}` expanded. */
122
+ function parsePatterns(patterns) {
123
+ const include = []
124
+ const exclude = []
125
+ for (const raw of strings(patterns)) {
126
+ let pattern = raw.trim()
127
+ const negated = pattern.startsWith('!')
128
+ if (negated) pattern = pattern.slice(1)
129
+ if (EXTGLOB.test(pattern)) {
130
+ if (!warned.has(raw)) {
131
+ warned.add(raw)
132
+ process.stderr.write(
133
+ `⚠ uniweb does not read the workspace pattern "${raw}" (extended glob syntax) — ` +
134
+ `list the folders it stands for instead.\n`
135
+ )
136
+ }
137
+ continue
138
+ }
139
+ for (const one of expandBraces(pattern)) {
140
+ const path = normalizePath(one)
141
+ if (path) (negated ? exclude : include).push(path.split('/'))
142
+ }
143
+ }
144
+ return { include, exclude }
145
+ }
146
+
147
+ /** `a/{b,c}/d` → `a/b/d`, `a/c/d`; nested lists expand innermost first. */
148
+ function expandBraces(pattern) {
149
+ const m = /\{([^{}]*)\}/.exec(pattern)
150
+ if (!m) return [pattern]
151
+ const options = m[1].split(',')
152
+ // `{x}` lists nothing to choose between: a literal brace, as in pnpm.
153
+ if (options.length < 2) return [pattern]
154
+ const head = pattern.slice(0, m.index)
155
+ const tail = pattern.slice(m.index + m[0].length)
156
+ return options.flatMap((o) => expandBraces(head + o + tail))
157
+ }
158
+
159
+ /** `./a//b/` → `a/b`; `\` becomes `/`; `.` and `` are the root. */
160
+ function normalizePath(path) {
161
+ let s = String(path).replace(/\\/g, '/').replace(/\/{2,}/g, '/')
162
+ while (s.startsWith('./')) s = s.slice(2)
163
+ s = s.replace(/^\/+/, '').replace(/\/+$/, '')
164
+ return s === '.' ? '' : s
165
+ }
166
+
167
+ const hasMagic = (segment) => /[*?[]/.test(segment)
168
+
169
+ /** Can a wildcard step into this folder? Never `node_modules`, never a dot-folder. */
170
+ const wildcardMayEnter = (name) => !name.startsWith('.') && name !== 'node_modules'
171
+
172
+ const regexCache = new Map()
173
+
174
+ /** One folder-name pattern as a regex: `*`, `?` and `[...]`, everything else literal. */
175
+ function segmentRegex(segment) {
176
+ let re = regexCache.get(segment)
177
+ if (re) return re
178
+ let src = ''
179
+ for (let i = 0; i < segment.length; i++) {
180
+ const c = segment[i]
181
+ if (c === '*') src += '[^/]*'
182
+ else if (c === '?') src += '[^/]'
183
+ else if (c === '[' && segment.indexOf(']', i + 2) > i) {
184
+ const end = segment.indexOf(']', i + 2)
185
+ let body = segment.slice(i + 1, end).replace(/\\/g, '\\\\')
186
+ if (body.startsWith('!')) body = `^${body.slice(1)}`
187
+ src += `[${body}]`
188
+ i = end
189
+ } else src += c.replace(/[.+^$(){}|\\[\]]/g, '\\$&')
190
+ }
191
+ re = new RegExp(`^${src}$`)
192
+ regexCache.set(segment, re)
193
+ return re
194
+ }
195
+
196
+ function segmentMatches(segment, name) {
197
+ if (!hasMagic(segment)) return segment === name
198
+ // A wildcard does not match a dot-folder unless the pattern spells the dot.
199
+ if (name.startsWith('.') && !segment.startsWith('.')) return false
200
+ if (name === 'node_modules') return false
201
+ return segmentRegex(segment).test(name)
202
+ }
203
+
204
+ /** Does the folder-name list `path` match the pattern `pattern`? `**` is any depth. */
205
+ function matches(pattern, path, i = 0, j = 0) {
206
+ if (i === pattern.length) return j === path.length
207
+ if (pattern[i] === '**') {
208
+ for (let k = j; k <= path.length; k++) {
209
+ if (k > j && !wildcardMayEnter(path[k - 1])) break
210
+ if (matches(pattern, path, i + 1, k)) return true
211
+ }
212
+ return false
213
+ }
214
+ if (j === path.length || !segmentMatches(pattern[i], path[j])) return false
215
+ return matches(pattern, path, i + 1, j + 1)
216
+ }
217
+
218
+ /** The folders under `rootDir` that `pattern` names, found on disk. */
219
+ function expand(rootDir, pattern, base, i, out) {
220
+ if (i === pattern.length) {
221
+ out.push(base.join('/'))
222
+ return out
223
+ }
224
+ const segment = pattern[i]
225
+ const here = join(rootDir, ...base)
226
+ if (segment === '**') {
227
+ expand(rootDir, pattern, base, i + 1, out)
228
+ // Real folders only: a symlink back up the tree would never end.
229
+ for (const name of subfolders(here, { followLinks: false })) {
230
+ if (wildcardMayEnter(name)) expand(rootDir, pattern, [...base, name], i, out)
231
+ }
232
+ return out
233
+ }
234
+ if (!hasMagic(segment)) {
235
+ if (segment === '.') return expand(rootDir, pattern, base, i + 1, out)
236
+ if (isFolder(join(here, segment))) expand(rootDir, pattern, [...base, segment], i + 1, out)
237
+ return out
238
+ }
239
+ for (const name of subfolders(here)) {
240
+ if (segmentMatches(segment, name)) expand(rootDir, pattern, [...base, name], i + 1, out)
241
+ }
242
+ return out
243
+ }
244
+
245
+ function subfolders(dir, { followLinks = true } = {}) {
246
+ let entries
247
+ try {
248
+ entries = readdirSync(dir, { withFileTypes: true })
249
+ } catch {
250
+ return []
251
+ }
252
+ return entries
253
+ .filter(
254
+ (e) => e.isDirectory() || (followLinks && e.isSymbolicLink() && isFolder(join(dir, e.name)))
255
+ )
256
+ .map((e) => e.name)
257
+ .sort()
258
+ }
259
+
260
+ function isFolder(path) {
261
+ try {
262
+ return statSync(path).isDirectory()
263
+ } catch {
264
+ return false
265
+ }
266
+ }
267
+
268
+ // ─── Helpers ────────────────────────────────────────────────────────────────
269
+
270
+ export function strings(list) {
271
+ return Array.isArray(list) ? list.filter((v) => typeof v === 'string') : []
272
+ }