@uniweb/build 1.23.0 → 1.23.1

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/build",
3
- "version": "1.23.0",
3
+ "version": "1.23.1",
4
4
  "description": "Build tooling for the Uniweb Component Web Platform",
5
5
  "type": "module",
6
6
  "exports": {
@@ -58,14 +58,14 @@
58
58
  "sharp": "^0.35.5",
59
59
  "yaml": "^2.5.0",
60
60
  "@uniweb/schemas": "~1.7.2",
61
- "@uniweb/content-writer": "~1.3.2",
62
61
  "@uniweb/projections": "~1.2.17",
62
+ "@uniweb/content-writer": "~1.3.2",
63
63
  "@uniweb/content-reader": "~1.5.10",
64
64
  "@uniweb/semantic-parser": "~1.13.4",
65
65
  "@uniweb/theming": "~1.3.2"
66
66
  },
67
67
  "optionalDependencies": {
68
- "@uniweb/runtime": "~1.6.2"
68
+ "@uniweb/runtime": "~1.6.3"
69
69
  },
70
70
  "peerDependencies": {
71
71
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0",
@@ -74,7 +74,7 @@
74
74
  "@tailwindcss/vite": "^4.0.0",
75
75
  "@vitejs/plugin-react": "^4.0.0 || ^5.0.0",
76
76
  "vite-plugin-svgr": "^4.0.0",
77
- "@uniweb/runtime": "~1.6.2",
77
+ "@uniweb/runtime": "~1.6.3",
78
78
  "@uniweb/core": "~1.6.12"
79
79
  },
80
80
  "peerDependenciesMeta": {
@@ -0,0 +1,109 @@
1
+ /**
2
+ * ⭐ A LIBRARY'S MAPPINGS, CARRIED BY A FOUNDATION THAT NAMES THEM. A library (one back office, many
3
+ * front desks) may hold `mappings/` beside its `schemas/`, under its scope. A foundation carries one
4
+ * by naming it in full in its `main.js`:
5
+ *
6
+ * ```js
7
+ * export default {
8
+ * name: '@shop/storefront',
9
+ * mappings: ['@acme/vehicle-to-meta'],
10
+ * }
11
+ * ```
12
+ *
13
+ * The build reads each from the library that defines it (`workspaceMappingFiles`, the rule a
14
+ * library's types are found by), checks it as a foundation's own mapping is checked, against the
15
+ * library's types and mappings, and keeps it in `_mappings` under its full name, with every name in
16
+ * it in full. `register` names it in the foundation's `mappings` refs, and registers it from the
17
+ * library first.
18
+ *
19
+ * A name no package here defines only warns: it may be registered already, and the registry judges.
20
+ *
21
+ * @module
22
+ */
23
+
24
+ import { basename, dirname } from 'node:path'
25
+ import { parseSchemaRef } from '@uniweb/schemas/format'
26
+ import { qualifyRef } from '@uniweb/schemas/refs'
27
+ import { ownSchemaRefs } from '../resolve-data-schema.js'
28
+ import { workspaceMappingFiles } from './shared-types.js'
29
+ import { MAPPINGS_DIR, loadMappingFile, mappingInFull, mappingProblems, ownMappingFiles } from './mappings.js'
30
+
31
+ /**
32
+ * The library mappings a foundation's `main.js` names.
33
+ *
34
+ * @param {*} names - `main.js`'s `mappings:`, as written
35
+ * @param {object} p
36
+ * @param {string} p.srcDir - the foundation's source root
37
+ * @param {string|null} p.ownScope - the foundation's scope, when its name gives one
38
+ * @returns {Promise<{ map: Object<string, object|null>, warnings: string[] }>} `map`: full name →
39
+ * the mapping with its names in full, or null when no package here defines it
40
+ * @throws {Error} naming each one that cannot be carried, and why
41
+ */
42
+ export async function resolveLibraryMappings(names, { srcDir, ownScope = null }) {
43
+ if (names === undefined) return { map: {}, warnings: [] }
44
+ if (!Array.isArray(names) || names.some((n) => typeof n !== 'string')) {
45
+ throw new Error(
46
+ "[uniweb] main.js: `mappings` lists the library mappings the foundation carries, each named in full — `mappings: ['@acme/vehicle-to-meta']`."
47
+ )
48
+ }
49
+ const map = {}
50
+ const warnings = []
51
+ const found = []
52
+ for (const name of names) {
53
+ const at = `main.js: \`mappings\` names \`${name}\``
54
+ let scope
55
+ try {
56
+ ;({ scope } = parseSchemaRef(name))
57
+ } catch {
58
+ found.push(`${at}, which is not a mapping's full name, \`'@scope/<name>'\`.`)
59
+ continue
60
+ }
61
+ if (!scope || name.startsWith('@/')) {
62
+ found.push(`${at}: a mapping of the foundation's own is a file in src/${MAPPINGS_DIR}/, and is not listed. List a library's, in full.`)
63
+ continue
64
+ }
65
+ if (ownScope && `@${String(ownScope).replace(/^@/, '')}` === `@${scope}`) {
66
+ found.push(`${at}, in the foundation's own scope: a mapping of its own is a file in src/${MAPPINGS_DIR}/.`)
67
+ continue
68
+ }
69
+ const files = await workspaceMappingFiles(name, srcDir)
70
+ if (files.length > 1) {
71
+ found.push(`${at}, which ${files.length} packages define: ${files.join(', ')}. Keep one.`)
72
+ continue
73
+ }
74
+ if (!files.length) {
75
+ warnings.push(
76
+ `${at}, which no package here defines, so the build can't check it. \`uniweb register\` names it, and the registry refuses the foundation unless it is registered under @${scope}.`
77
+ )
78
+ map[name] = null
79
+ continue
80
+ }
81
+ const file = files[0]
82
+ const root = dirname(dirname(file))
83
+ const shown = `${MAPPINGS_DIR}/${basename(file)} (for ${name})`
84
+ let decl
85
+ try {
86
+ decl = await loadMappingFile(file)
87
+ } catch (err) {
88
+ found.push(`${shown}: ${String(err?.message || err).split('\n')[0]}`)
89
+ continue
90
+ }
91
+ const problems = mappingProblems(decl, {
92
+ types: new Set(ownSchemaRefs(root)),
93
+ names: new Set(ownMappingFiles(root).map((m) => `@/${m.name}`)),
94
+ })
95
+ if (problems.length) {
96
+ found.push(...problems.map((p) => `${shown}: ${p}`))
97
+ continue
98
+ }
99
+ map[name] = mappingInFull(decl, (ref) => qualifyRef(ref, scope))
100
+ }
101
+ if (found.length) {
102
+ throw new Error(
103
+ found.length === 1
104
+ ? `[uniweb] ${found[0]}`
105
+ : `[uniweb] library mappings the foundation cannot carry:\n${found.map((f) => ` - ${f}`).join('\n')}`
106
+ )
107
+ }
108
+ return { map, warnings }
109
+ }
@@ -61,7 +61,8 @@ export function ownMappingFiles(srcDir) {
61
61
  .map((file) => ({ name: basename(file, extname(file)), file: join(dir, file) }))
62
62
  }
63
63
 
64
- async function loadMappingFile(file) {
64
+ /** One mapping file, as written. */
65
+ export async function loadMappingFile(file) {
65
66
  if (file.endsWith('.js')) return (await import(pathToFileURL(file).href)).default
66
67
  const text = await readFile(file, 'utf8')
67
68
  return file.endsWith('.json') ? JSON.parse(text) : yaml.load(text, YAML_OPTIONS)
@@ -73,10 +74,11 @@ async function loadMappingFile(file) {
73
74
  * @param {string} srcDir - the foundation's source root
74
75
  * @param {object} [opts]
75
76
  * @param {Iterable<string>} [opts.ownTypes] - the `@/x` data schemas the foundation defines
77
+ * @param {string} [opts.shownIn] - the folder as its errors name it (a library's is `mappings`)
76
78
  * @returns {Promise<Object<string, object>>} `{ '@/<name>': declaration }` as written (`@/x` unqualified)
77
79
  * @throws {Error} naming every mapping that cannot be registered, and why
78
80
  */
79
- export async function buildMappingMap(srcDir, { ownTypes = [] } = {}) {
81
+ export async function buildMappingMap(srcDir, { ownTypes = [], shownIn = `src/${MAPPINGS_DIR}` } = {}) {
80
82
  const files = ownMappingFiles(srcDir)
81
83
  if (!files.length) return {}
82
84
  const types = new Set(ownTypes)
@@ -84,7 +86,7 @@ export async function buildMappingMap(srcDir, { ownTypes = [] } = {}) {
84
86
  const map = {}
85
87
  const found = []
86
88
  for (const { name, file } of files) {
87
- const at = `src/${MAPPINGS_DIR}/${basename(file)}`
89
+ const at = `${shownIn}/${basename(file)}`
88
90
  let decl
89
91
  try {
90
92
  decl = await loadMappingFile(file)
@@ -141,6 +143,33 @@ export function mappingProblems(decl, { types, names }) {
141
143
  return found
142
144
  }
143
145
 
146
+ /**
147
+ * A mapping with every type and mapping it names in full (`scoped`: `@/x` → `@scope/x`): its `model`,
148
+ * its `keys_from` and a reverse `follow` line's `model`. Nothing else moves, and the file's own object
149
+ * is never touched.
150
+ *
151
+ * @param {object} decl - as written
152
+ * @param {(ref: string) => string} scoped
153
+ * @returns {object}
154
+ */
155
+ export function mappingInFull(decl, scoped) {
156
+ const out = { ...decl }
157
+ if (typeof out.model === 'string') out.model = scoped(out.model)
158
+ if (typeof out.keys_from === 'string') out.keys_from = scoped(out.keys_from)
159
+ if (Array.isArray(out.follow)) {
160
+ out.follow = out.follow.map((line) =>
161
+ isMap(line)
162
+ ? Object.fromEntries(
163
+ Object.entries(line).map(([alias, spec]) =>
164
+ isMap(spec) && typeof spec.model === 'string' ? [alias, { ...spec, model: scoped(spec.model) }] : [alias, spec]
165
+ )
166
+ )
167
+ : line
168
+ )
169
+ }
170
+ return out
171
+ }
172
+
144
173
  /**
145
174
  * `follow` — a list of one-entry maps, `{ alias: { field, from? } }` forward, or
146
175
  * `{ alias: { model, field, names? } }` reverse. Only a reverse line's `model` is a name (a type);
@@ -24,6 +24,7 @@ import { workspacePackages } from '../workspace-patterns.js'
24
24
  import { workspaceRootOf } from '../site/workspace-extension.js'
25
25
  import { classifyPackage, isSchemasPackage } from '../utils/classify-package.js'
26
26
  import { librariesOf } from './libraries.js'
27
+ import { MAPPINGS_DIR, ownMappingFiles } from './mappings.js'
27
28
 
28
29
  const real = (path) => {
29
30
  try {
@@ -177,6 +178,25 @@ function packageDirOf(dir) {
177
178
  * @returns {Promise<string[]>} the files that define it, each once; the caller refuses more than one
178
179
  */
179
180
  export async function workspaceTypeFiles(ref, fromDir) {
181
+ return workspaceDeclarationFiles(ref, fromDir, 'schemas', ownSchemaFiles)
182
+ }
183
+
184
+ /**
185
+ * ⭐ A MAPPING ANOTHER PACKAGE DEFINES, found by the rule `workspaceTypeFiles` finds a type by: a
186
+ * foundation whose name gives the scope and whose own `mappings/` holds it, or a library (a schemas
187
+ * package) of that scope that holds `mappings/` (`foundation/mappings.js`). A foundation names one in
188
+ * its `main.js` (`mappings: ['@acme/vehicle-to-meta']`); the build reads it from there.
189
+ *
190
+ * @param {string} ref - `@scope/name`
191
+ * @param {string} fromDir - the foundation (its source folder) or site asking
192
+ * @returns {Promise<string[]>} the files that define it, each once; the caller refuses more than one
193
+ */
194
+ export async function workspaceMappingFiles(ref, fromDir) {
195
+ return workspaceDeclarationFiles(ref, fromDir, MAPPINGS_DIR, ownMappingFiles)
196
+ }
197
+
198
+ /** The files of the packages a package may read that define `ref` in their `folder`. */
199
+ async function workspaceDeclarationFiles(ref, fromDir, folder, ownFiles) {
180
200
  const m = /^(@[^/]+)\/(.+)$/.exec(ref || '')
181
201
  if (!m) return []
182
202
  const [, scope, name] = m
@@ -198,8 +218,8 @@ export async function workspaceTypeFiles(ref, fromDir) {
198
218
  if (!kind) continue
199
219
  if ((await cachedTypeScope(dir, kind)) !== scope) continue
200
220
  const typesAt = typeRoot(dir, kind)
201
- if (!existsSync(join(typesAt, 'schemas'))) continue
202
- for (const own of ownSchemaFiles(typesAt)) {
221
+ if (!existsSync(join(typesAt, folder))) continue
222
+ for (const own of ownFiles(typesAt)) {
203
223
  if (own.name === name) files.set(real(own.file), own.file)
204
224
  }
205
225
  }
package/src/index.js CHANGED
@@ -98,7 +98,8 @@ export { classifyPackage, isExtensionPackage, isSchemasPackage } from './utils/c
98
98
  export { collectStandaloneSchemas, routedSchema } from './resolve-data-schema.js'
99
99
 
100
100
  // One name in a scope is one type: the names a workspace's packages define twice
101
- export { typesDefinedTwice, packageTypeScope, workspaceTypeFiles } from './foundation/shared-types.js'
101
+ export { typesDefinedTwice, packageTypeScope, workspaceTypeFiles, workspaceMappingFiles } from './foundation/shared-types.js'
102
+ export { buildMappingMap, ownMappingFiles, loadMappingFile } from './foundation/mappings.js'
102
103
 
103
104
  // Default export is the combined Vite plugin
104
105
  export { default } from './vite-foundation-plugin.js'
package/src/schema.js CHANGED
@@ -1409,6 +1409,17 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null,
1409
1409
  // The mappings it defines — every file in its `mappings/` folder (`foundation/mappings.js`),
1410
1410
  // registered beside its data schemas. Editor-time: `_mappings`, never on a page.
1411
1411
  const mappings = await buildMappingMap(srcDir, { ownTypes: ownSchemaRefs(srcDir) })
1412
+ // And the library mappings its main.js carries (`mappings: ['@acme/x']`), in full — imported
1413
+ // here, not above, since what finds them reads foundations' names through this module.
1414
+ if (foundationConfig.mappings !== undefined) {
1415
+ const { resolveLibraryMappings } = await import('./foundation/library-mappings.js')
1416
+ const { map, warnings } = await resolveLibraryMappings(foundationConfig.mappings, {
1417
+ srcDir,
1418
+ ownScope: splitFoundationName(foundationNameOf({ config: foundationConfig, pkg: identity }).name || '').scope,
1419
+ })
1420
+ for (const warning of warnings) console.warn(`[uniweb] ${warning}`)
1421
+ Object.assign(mappings, map)
1422
+ }
1412
1423
 
1413
1424
  // Discover layouts from src/layouts/
1414
1425
  const layouts = await discoverLayoutsInPath(srcDir)
@@ -1442,7 +1453,8 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null,
1442
1453
 
1443
1454
  // Build _self, stripping the raw extension boolean in favor of normalized role, and the
1444
1455
  // declared `defaultLayout` in favor of the resolved one (`resolveDefaultLayout`)
1445
- const { extension: _ext, defaultLayout: _declaredLayout, ...configWithoutExtension } = foundationConfig
1456
+ // `mappings` goes to `_mappings` with the foundation's own, each fact once.
1457
+ const { extension: _ext, defaultLayout: _declaredLayout, mappings: _libraryMappings, ...configWithoutExtension } = foundationConfig
1446
1458
 
1447
1459
  // `supports` is the one identity field the build knows better than the file.
1448
1460
  // `identity.supports` is already normalized (absent stays absent, `[]` stays
@@ -249,10 +249,21 @@ import { mountDevSubmit } from '../dev/submit-mount.js'
249
249
  * A shell carrying the page's look by the runtime's own rule (`@uniweb/runtime/ssr`, which a
250
250
  * prerendered page's seam writes too): the scheme class on its `<html>`, and the pre-paint script
251
251
  * where the browser decides. Unchanged for a site with no dark scheme. Loaded once.
252
+ *
253
+ * ⛔ A runtime without the rule (before @uniweb/runtime 1.6.2) stops with what to do. Until
254
+ * 2026-11-11 every page threw `(intermediate value) is not a function` instead: a runtime held back
255
+ * while this package moved, or a linked runtime whose SSR bundle wasn't rebuilt.
252
256
  */
253
257
  let writeAppearanceOf = null
254
258
  async function writeShellAppearance(html, appearance) {
255
- writeAppearanceOf ||= import('@uniweb/runtime/ssr').then((runtime) => runtime.writePageAppearance)
259
+ writeAppearanceOf ||= import('@uniweb/runtime/ssr').then(({ writePageAppearance }) => {
260
+ if (typeof writePageAppearance === 'function') return writePageAppearance
261
+ throw new Error(
262
+ '@uniweb/runtime has no writePageAppearance, which this @uniweb/build needs (@uniweb/runtime 1.6.2 or later). ' +
263
+ 'Update the Uniweb packages together: npx uniweb@latest update --yes. ' +
264
+ 'For a linked @uniweb/runtime, rebuild its SSR bundle (pnpm build:ssr), then restart.'
265
+ )
266
+ })
256
267
  return (await writeAppearanceOf)(html, appearance)
257
268
  }
258
269
 
@@ -68,6 +68,7 @@ import { isDraftRecord } from './record-draft.js'
68
68
  import { refuseNotOneRecord } from './record-file.js'
69
69
  import { resolveRecordSchemas, resolveQueriesConfig, dataKeyTyping } from './queries-config.js'
70
70
  import { keyOfDefaultRef } from '../uwx/data-key-types.js'
71
+ import { standardTypeFor } from './standard-type-for.js'
71
72
  import { parseFrontmatter } from '../utils/frontmatter.js'
72
73
  import { toDeliveredRecord, toStoredRecord, storedPath, briefFieldMap, contentBodyField, misplacedFields, mapReferences, recordLayout } from '@uniweb/schemas/conform'
73
74
  import { collectNestedRefs } from '@uniweb/schemas/format'
@@ -1297,15 +1298,20 @@ export function refuseRecordsWithoutSchema(missing, { dir, poolBySchema, queries
1297
1298
  .map(([name]) => `query "${name}"`)
1298
1299
  const held = poolBySchema.get(ref)
1299
1300
  const where = held?.length ? `${dir}/${held[0].dirs.join('/')}/` : readers.shift()
1300
- return ` ${where} — ${ref}${readers.length ? `, read by ${readers.join(', ')}` : ''}`
1301
+ const std = standardTypeFor(ref.replace(/^@\//, ''))
1302
+ return (
1303
+ ` ${where} — ${ref}${readers.length ? `, read by ${readers.join(', ')}` : ''}` +
1304
+ (std ? ` — a standard type fits: @std/${std}, kept in ${dir}/std/${std}/` : '')
1305
+ )
1301
1306
  })
1302
1307
  const name = missing[0].replace(/^@\//, '')
1303
1308
  throw new Error(
1304
1309
  `[uniweb] Every record needs a data schema, and nothing defines ${missing.length === 1 ? 'this one' : 'these'}:\n` +
1305
1310
  `${lines.join('\n')}\n` +
1306
- ` A folder's name is its records' data schema. Define it in the foundation, as schemas/${name}.yml ` +
1307
- '(`uniweb guide data` shows one), or keep records of a data schema registered under another scope ' +
1308
- 'in records/<scope>/<name>/.'
1311
+ ` A folder's name is its records' data schema. Use a standard type where one fits: records/std/<name>/ ` +
1312
+ 'holds @std/<name>, which the app edits with its own form (`uniweb guide data` lists them). Keep records ' +
1313
+ 'of a type registered under another scope in records/<scope>/<name>/. Else define your own in the ' +
1314
+ `foundation, as schemas/${name}.yml.`
1309
1315
  )
1310
1316
  }
1311
1317
 
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The standard data schema a records folder's or a query's name points to, if any: `testimonials`
3
+ * and `testimonial` → `testimonial` (`@std/testimonial`). Named in a refusal of records with no
4
+ * data schema, so the agent that meets it reaches for the type the app already edits with a form
5
+ * made for it rather than writing a new one [Diego, 2026-11-11: "we should question what we
6
+ * explain … so as to not reinvent the wheel"]. A suggestion only: nothing is typed by it — a guess
7
+ * applied silently is what the retired schema-guessing of record translation was.
8
+ */
9
+ import { isStandardSchema } from '@uniweb/schemas'
10
+
11
+ /**
12
+ * @param {string|null|undefined} name - a folder's or a query's name (`testimonials`)
13
+ * @returns {string|null} the standard schema's name (`testimonial`), or null
14
+ */
15
+ export function standardTypeFor(name) {
16
+ if (typeof name !== 'string' || !name) return null
17
+ const candidates = [name]
18
+ if (name.endsWith('ies')) candidates.push(name.slice(0, -3) + 'y')
19
+ if (name.endsWith('es')) candidates.push(name.slice(0, -2))
20
+ if (name.endsWith('s')) candidates.push(name.slice(0, -1))
21
+ return candidates.find((n) => isStandardSchema(n)) || null
22
+ }
@@ -89,7 +89,8 @@ export function classifyPackage(packagePath) {
89
89
  * framework's `@uniweb/schemas`, referenced as `@std`) — the same convention
90
90
  * `@org/x` data-schema refs already resolve through.
91
91
  * 2. a `schemas/` directory at the package root holding ≥1 schema file
92
- * (`*.{js,json,yml,yaml}`) — a bare folder of schema files with no index.
92
+ * (`*.{js,json,yml,yaml}`) — a bare folder of schema files with no index —
93
+ * or a `mappings/` directory holding ≥1 mapping file.
93
94
  *
94
95
  * Gated on the directory NOT already classifying as a foundation/site, so a
95
96
  * foundation that happens to carry schemas is never misread. The enumeration of
@@ -113,13 +114,15 @@ export function isSchemasPackage(packagePath) {
113
114
  }
114
115
  }
115
116
 
116
- // 2. A schemas/ directory of schema files.
117
- const dir = join(packagePath, 'schemas')
118
- if (existsSync(dir)) {
117
+ // 2. A schemas/ directory of schema files, or a mappings/ one of mappings (a library of
118
+ // mappings alone is one too: `register` in it registers them).
119
+ for (const folder of ['schemas', 'mappings']) {
120
+ const dir = join(packagePath, folder)
121
+ if (!existsSync(dir)) continue
119
122
  try {
120
- return readdirSync(dir).some((f) => /\.(js|json|ya?ml)$/.test(f))
123
+ if (readdirSync(dir).some((f) => /\.(js|json|ya?ml)$/.test(f))) return true
121
124
  } catch {
122
- return false
125
+ // unreadable: not this signal
123
126
  }
124
127
  }
125
128
  return false
@@ -179,8 +179,9 @@ export function blueprintFromWire(wire, { scope = null, own = null, local = null
179
179
 
180
180
  /**
181
181
  * A mapping's full name → as a pull writes it: as the file already spells it when it names the same
182
- * one, else `@/x` when it is in the site's foundation's scope. A foundation registers only its own
183
- * mappings, so every mapping in that scope is the foundation's.
182
+ * one, else `@/x` when it is in the site's foundation's scope — which a push names in full the same
183
+ * way, so the two agree whoever registered it. A library's mapping, in its own scope, comes back in
184
+ * full, as the file wrote it.
184
185
  */
185
186
  function mappingAsFileSpells(full, localIntegrations, scope) {
186
187
  if (isMap(localIntegrations)) {
package/src/uwx/index.js CHANGED
@@ -75,6 +75,7 @@ export {
75
75
  export {
76
76
  recordsToProject,
77
77
  declarationsToQueriesYml,
78
+ readSiteFoundationDeclarations,
78
79
  folderToFolderYml,
79
80
  findRecordFileByUuid,
80
81
  indexFolder,
@@ -42,6 +42,7 @@ import { YAML_OPTIONS } from '../utils/yaml-schema.js'
42
42
  import { parseFrontmatter } from './entity-source.js'
43
43
  import { writeRecordFile, writeQueriesConfig, writeRecordsConfig } from './project-writer.js'
44
44
  import { foundationDataSchemas, foundationSchemaJson, QUERIES_YML_RELPATH } from './queries-config.js'
45
+ import { foundationSections } from '../site/queries-config.js'
45
46
  import { dataKeyTypes } from './data-key-types.js'
46
47
  import { poolDirsForSchema, schemaForPoolDirs, resolveRecordsDir, readEntityPoolSync, resolveRecordMounts } from '../site/entity-pool.js'
47
48
  import { folderYmlPath, resolveFolder } from '../site/records-config.js'
@@ -232,9 +233,43 @@ function recordDirsReadingAs(recordsRoot, model, scope, { own = null, keyTypes =
232
233
  return dirs
233
234
  }
234
235
 
235
- // What the site's foundation declares, when its declarations are in this project: its own
236
- // data-schema names (`ownSchemaNames`) and the types of its data keys (`dataKeyTypes`). Both
237
- // null otherwise — a clone's foundation is not in the project.
236
+ /**
237
+ * What the site's foundation declares, read as the build reads it (`foundationSections`): from its
238
+ * SOURCE when it is local, else from the registered version a clone keeps. Its own data-schema names
239
+ * (`ownSchemaNames`) and the types of its data keys (`dataKeyTypes`); both null when neither is there,
240
+ * or before a clone's `site.yml` exists. A pull reads it once and hands it to `recordsToProject`
241
+ * (`opts.foundation`) and `siteContentDocumentToProject` (`foundation`).
242
+ *
243
+ * ⛔ Until 2026-11-11 the pull read only a built `dist/meta/schema.json`, so in a copy whose local
244
+ * foundation had not been built — every fresh clone — it knew no data key's type: a record kept in
245
+ * a folder named for a typed key (`records/articles/` for `articles: '@/blog-post'`) was written
246
+ * again in its type's folder (`records/blog-post/`), two files for one record, and `queries.yml`
247
+ * gained a `schema:` the author had not written.
248
+ *
249
+ * @param {string} siteRoot
250
+ * @returns {Promise<{ own: Set<string>|null, keyTypes: Map<string, string>|null }>}
251
+ */
252
+ export async function readSiteFoundationDeclarations(siteRoot) {
253
+ let siteYml = null
254
+ try {
255
+ siteYml = yaml.load(readFileSync(join(siteRoot, 'site.yml'), 'utf8'), YAML_OPTIONS) || null
256
+ } catch {
257
+ return { own: null, keyTypes: null }
258
+ }
259
+ let schema = null
260
+ try {
261
+ schema = siteYml ? await foundationSections(siteRoot, siteYml) : null
262
+ } catch {
263
+ schema = null // a foundation that does not read is reported by the build that builds it
264
+ }
265
+ // ⛔ Own names only from a schema that carries its data schemas — see `siteFoundationDeclarations`.
266
+ return schema ? { own: ownSchemaNames(schema.dataSchemas), keyTypes: dataKeyTypes(schema) } : { own: null, keyTypes: null }
267
+ }
268
+
269
+ // What the site's foundation declares, from its BUILT or registered `schema.json` — what a projection
270
+ // reads when its caller hands it nothing (`readSiteFoundationDeclarations`): its own data-schema names
271
+ // (`ownSchemaNames`) and the types of its data keys (`dataKeyTypes`). Both null otherwise — a clone's
272
+ // foundation is not in the project.
238
273
  function siteFoundationDeclarations(siteRoot) {
239
274
  let siteYml = null
240
275
  try {
@@ -460,7 +495,7 @@ function typedQueryFolders(siteRoot, recordsRoot, scope, own, keyTypes) {
460
495
  return out
461
496
  }
462
497
 
463
- export function declarationsToQueriesYml({ document, siteRoot, scope, ...rest }) {
498
+ export function declarationsToQueriesYml({ document, siteRoot, scope, foundation = null, ...rest }) {
464
499
  refuseOrgOption(rest, 'declarationsToQueriesYml')
465
500
  const decls = Array.isArray(document?.queries) ? document.queries : []
466
501
  const report = {}
@@ -474,13 +509,13 @@ export function declarationsToQueriesYml({ document, siteRoot, scope, ...rest })
474
509
  } catch {
475
510
  siteYml = null
476
511
  }
477
- const dataSchemas = siteYml ? foundationDataSchemas(siteRoot, siteYml) : null
478
512
  const selfScope =
479
513
  scope !== undefined ? scope : (parseCatalogRef(document?.info?.foundation)?.scope ?? null)
480
514
  // Which of the scope's schemas are the foundation's own — the rest keep their scope
481
- // (`unresolveSelfScope`) — and the types of its data keys.
482
- const own = ownSchemaNames(dataSchemas)
483
- const keyTypes = siteYml ? dataKeyTypes(foundationSchemaJson(siteRoot, siteYml)) : null
515
+ // (`unresolveSelfScope`) — and the types of its data keys: as the caller read them, from the
516
+ // foundation's source where it is local (`readSiteFoundationDeclarations`), else its built schema.
517
+ const own = foundation?.own ?? ownSchemaNames(siteYml ? foundationDataSchemas(siteRoot, siteYml) : null)
518
+ const keyTypes = foundation?.keyTypes ?? (siteYml ? dataKeyTypes(foundationSchemaJson(siteRoot, siteYml)) : null)
484
519
  const authored = authoredQuerySchemas(siteRoot, siteYml)
485
520
  // The key types a catalog-ref foundation has come from the registered version the project keeps.
486
521
  const markedOnly = Boolean(parseCatalogRef(siteYml?.foundation))
@@ -700,6 +735,8 @@ function holdsPattern(abs) {
700
735
  * back where the author wrote it. The caller resolves it up front, as it does
701
736
  * Models (`siteSelfScope`); absent, a model is placed under its own scope.
702
737
  * @param {string} [params.opts.backend] - whose record map to read and extend
738
+ * @param {{ own: Set<string>|null, keyTypes: Map<string, string>|null }} [params.opts.foundation] - what the
739
+ * site's foundation declares, as `readSiteFoundationDeclarations` reads it; absent, its built schema
703
740
  * @param {string} [params.opts.sourceLocale]
704
741
  * @returns {{ updated: string[], placed: string[], unchanged: string[], skipped: object[], warnings: string[], locales: object }}
705
742
  */
@@ -715,7 +752,10 @@ export function recordsToProject({ folderDoc, recordDocs = [], siteRoot, opts =
715
752
  // Which of that scope's Models are the foundation's own — the rest keep their scope, so
716
753
  // a standard `@std/person` under a foundation in `@std` is placed in `records/std/person/`
717
754
  // (`unresolveSelfScope`).
718
- const { own, keyTypes } = siteFoundationDeclarations(siteRoot)
755
+ // …as the caller read them, from the foundation's source where it is local
756
+ // (`readSiteFoundationDeclarations`); else from its built or registered schema.
757
+ const declared = opts.foundation?.keyTypes || opts.foundation?.own ? opts.foundation : siteFoundationDeclarations(siteRoot)
758
+ const { own, keyTypes } = declared
719
759
  if (typeof resolveDeclaration !== 'function') {
720
760
  throw new Error('uwx/records-project: opts.resolveDeclaration(modelName) is required')
721
761
  }
@@ -60,6 +60,7 @@ import { toDataSchemaDeclaration, isProseMirrorField, isMarkupTextField } from '
60
60
  import { recordFileLayout, contentBodyTarget } from './record-layout.js'
61
61
  import { emitEntitySyncPackage } from './entity-document.js'
62
62
  import { qualifyRef } from '@uniweb/schemas/refs'
63
+ import { standardTypeFor } from '../site/standard-type-for.js'
63
64
  import { siteSelfScope, refuseOrgOption } from './self-scope.js'
64
65
  import { sha256Hex, toJsonBuffer } from './manifest.js'
65
66
  import { isUuid } from './uuid.js'
@@ -1006,15 +1007,21 @@ export async function buildRecordEntities(siteRoot, opts = {}) {
1006
1007
  // query that reads no folder: the push sends nothing, and says what to write. ⛔ Until
1007
1008
  // 2026-11-11 it was a soft skip: the records were not sent, a publish uploaded their compiled
1008
1009
  // files instead, in the site's own language only, and the app could not edit them.
1009
- const noDataSchema = (where, modelName) =>
1010
- `${where}: no data schema resolves for ${modelName}` +
1011
- (resolveModel?.offline === true
1012
- ? ' here (this run does not ask the backend)'
1013
- : resolveModel
1014
- ? ', in the foundation or on the backend'
1015
- : '') +
1016
- ', and every record needs one. Define it in the foundation (`schemas/<name>.yml`), or name a ' +
1017
- 'registered one on the query (`schema:` in queries.yml) — `uniweb guide data`.'
1010
+ const noDataSchema = (where, modelName) => {
1011
+ const std = standardTypeFor(String(modelName).split('/').pop())
1012
+ return (
1013
+ `${where}: no data schema resolves for ${modelName}` +
1014
+ (resolveModel?.offline === true
1015
+ ? ' here (this run does not ask the backend)'
1016
+ : resolveModel
1017
+ ? ', in the foundation or on the backend'
1018
+ : '') +
1019
+ ', and every record needs one. ' +
1020
+ (std ? `A standard type fits its name: @std/${std}, kept in ${pool.dir}/std/${std}/. ` : '') +
1021
+ 'Use a standard type where one fits (`records/std/<name>/`; `uniweb guide data` lists them), name a ' +
1022
+ 'registered one on the query (`schema:` in queries.yml), or define your own in the foundation (`schemas/<name>.yml`).'
1023
+ )
1024
+ }
1018
1025
 
1019
1026
  // ⚠️ AN EXPLICIT SCHEMA THAT RESOLVES TO NOTHING IS THE AUTHOR'S ERROR — and a
1020
1027
  // depth-2 folder has two readings worth naming. `records/person/2024/ada.md`
@@ -31,6 +31,7 @@ import { join } from 'node:path'
31
31
  import { normalizeFoundationSchema } from '@uniweb/schemas/foundation'
32
32
  import { parseOptionsRef } from '@uniweb/schemas/format'
33
33
  import { qualifyRef } from '@uniweb/schemas/refs'
34
+ import { mappingInFull } from '../foundation/mappings.js'
34
35
  import { toDataSchemaDeclaration, optionsSectionPath } from './data-schema.js'
35
36
  import { checkFoundationName, checkRegistrationScope, splitFoundationName } from '../foundation-name.js'
36
37
 
@@ -85,6 +86,16 @@ export function buildRegistryPackage({ schema, foundationDir, scope, exporter, e
85
86
  )
86
87
 
87
88
  const mappingEntities = buildMappingEntities(schema._mappings || {}, scoped)
89
+ // Its own, and the library mappings its main.js carries (`_mappings` keys in full), which their
90
+ // library registers: a foundation names those, and registers none.
91
+ const mappingRefs = [
92
+ ...new Set([
93
+ ...mappingEntities.map((e) => e.name),
94
+ ...Object.keys(schema._mappings || {}).filter((ref) => !ref.startsWith('@/')),
95
+ ]),
96
+ ]
97
+ .sort((a, b) => a.localeCompare(b))
98
+ .map((name) => ({ name }))
88
99
 
89
100
  const foundationEntity = {
90
101
  model: FOUNDATION_SCHEMA,
@@ -92,9 +103,7 @@ export function buildRegistryPackage({ schema, foundationDir, scope, exporter, e
92
103
  schema: buildSchemaBlob(schema, org),
93
104
  i18n: { locales: loadI18nLocales(foundationDir) },
94
105
  'data-schemas': { refs: buildRefs(dataSchemas, scoped) },
95
- ...(mappingEntities.length && {
96
- mappings: { refs: mappingEntities.map((e) => ({ name: e.name })).sort((a, b) => a.name.localeCompare(b.name)) },
97
- }),
106
+ ...(mappingRefs.length && { mappings: { refs: mappingRefs } }),
98
107
  }
99
108
 
100
109
  // Data schemas, then mappings, then the foundation: a backend installs them in the order they
@@ -103,31 +112,36 @@ export function buildRegistryPackage({ schema, foundationDir, scope, exporter, e
103
112
  }
104
113
 
105
114
  /**
106
- * Assemble a foundation-LESS registry-publish `.uwx` — only `@uniweb/data-schema`
107
- * entities, no foundation-schema. `uniweb register` submits this for a
108
- * schemas-only package (the standard schemas under `@std`, or an org's own
109
- * `@org/schemas`). A data-schema may be published on its own (`uwx-format.md` §2
110
- * "A data-schema may also be published on its own", §5) — the wire shape is a
111
- * names-only `.uwx` whose entities are all data-schemas.
115
+ * Assemble a foundation-LESS registry-publish `.uwx` — `@uniweb/data-schema` entities,
116
+ * then a library's `@uniweb/mapping-schema` ones, and no foundation-schema. `uniweb
117
+ * register` submits this for a schemas-only package (the standard schemas under `@std`,
118
+ * an org's own `@org/schemas`, a library). A data-schema may be published on its own
119
+ * (`uwx-format.md` §2 "A data-schema may also be published on its own", §5), and a
120
+ * library may hold mappings alone — the wire shape is a names-only `.uwx` with no
121
+ * foundation.
112
122
  *
113
123
  * @param {Object} params
114
124
  * @param {Object} params.schemas - map `{ '@/<name>': normalizedSchema }` of the
115
125
  * schemas the package defines (from `collectStandaloneSchemas`).
126
+ * @param {Object} [params.mappings] - map `{ '@/<name>': declaration }` of the
127
+ * mappings it defines (`buildMappingMap` over its `mappings/`).
116
128
  * @param {string} [params.scope] - org scope (`@std`/`std`) resolving `@/x` -> `@std/x`.
117
129
  * @param {Object} [params.exporter] - `{ tool, version, instance }` envelope.
118
130
  * @param {string} [params.exportedAt] - ISO timestamp (default: now).
119
- * @returns {Object} the `.uwx` document (uwx/1; only data-schema entities, no uuids).
131
+ * @returns {Object} the `.uwx` document (uwx/1; no foundation, no uuids).
120
132
  */
121
- export function buildSchemaOnlyPackage({ schemas, scope, exporter, exportedAt } = {}) {
133
+ export function buildSchemaOnlyPackage({ schemas, mappings, scope, exporter, exportedAt } = {}) {
122
134
  // ⛔ The producer's own guard, as `buildInfo`'s name check is for a foundation:
123
135
  // `uniweb register` refuses a reserved scope before it gets here.
124
136
  const reserved = checkRegistrationScope(scope)
125
137
  if (reserved) throw new Error(`buildSchemaOnlyPackage: ${reserved}`)
126
- const { entities } = buildDataSchemaEntities(schemas || {}, scope)
127
- if (entities.length === 0) {
128
- throw new Error('buildSchemaOnlyPackage: no data schemas to register (expected a map of "@/<name>" -> schema).')
138
+ const { entities, scoped } = buildDataSchemaEntities(schemas || {}, scope)
139
+ // A library's mappings (its `mappings/`) after its types, as in a foundation's package.
140
+ const mappingEntities = buildMappingEntities(mappings || {}, scoped)
141
+ if (entities.length === 0 && mappingEntities.length === 0) {
142
+ throw new Error('buildSchemaOnlyPackage: no data schemas or mappings to register (expected a map of "@/<name>" -> declaration).')
129
143
  }
130
- return wrapEntities(entities, exporter, exportedAt)
144
+ return wrapEntities([...entities, ...mappingEntities], exporter, exportedAt)
131
145
  }
132
146
 
133
147
  // The scope a foundation registers under: the one in its name, else `scope`.
@@ -192,10 +206,7 @@ function buildMappingEntities(mappings, scoped) {
192
206
  .filter(([ref]) => ref.startsWith('@/'))
193
207
  .sort(([a], [b]) => a.localeCompare(b))
194
208
  .map(([ref, decl]) => {
195
- const { label, description, ...rules } = decl
196
- if (typeof rules.model === 'string') rules.model = scoped(rules.model)
197
- if (typeof rules.keys_from === 'string') rules.keys_from = scoped(rules.keys_from)
198
- if (Array.isArray(rules.follow)) rules.follow = rules.follow.map((line) => followNamed(line, scoped))
209
+ const { label, description, ...rules } = mappingInFull(decl, scoped)
199
210
  return {
200
211
  model: MAPPING_SCHEMA,
201
212
  name: scoped(ref),
@@ -218,18 +229,6 @@ function buildMappingEntities(mappings, scoped) {
218
229
  return ordered
219
230
  }
220
231
 
221
- /** One `follow` line, `{ alias: { model?, … } }`, with each `model` named in full; a copy, never the file's. */
222
- function followNamed(line, scoped) {
223
- if (line === null || typeof line !== 'object' || Array.isArray(line)) return line
224
- return Object.fromEntries(
225
- Object.entries(line).map(([alias, spec]) =>
226
- spec && typeof spec === 'object' && !Array.isArray(spec) && typeof spec.model === 'string'
227
- ? [alias, { ...spec, model: scoped(spec.model) }]
228
- : [alias, spec]
229
- )
230
- )
231
- }
232
-
233
232
  /**
234
233
  * The data schemas in an order a backend can install one at a time: a schema another one in
235
234
  * the package references comes BEFORE it — alphabetical otherwise, so the order is stable.
@@ -245,7 +245,7 @@ function readAuthoredYaml(filePath) {
245
245
  * per-file write status ('updated' | 'unchanged'); `blueprint` when the document has a
246
246
  * `services` Section (`./blueprint.js`, `writePulledBlueprint`)
247
247
  */
248
- export function siteInfoToConfig({ document, siteRoot, backend = null, sourceLocale = documentSourceLocale(document), collector, keepAuthoredFoundation = false, sameFile = null, scope }) {
248
+ export function siteInfoToConfig({ document, siteRoot, backend = null, sourceLocale = documentSourceLocale(document), collector, keepAuthoredFoundation = false, sameFile = null, scope, foundation = null }) {
249
249
  const info = document?.info || {}
250
250
  const settingsSection = document?.settings || {}
251
251
 
@@ -394,7 +394,7 @@ export function siteInfoToConfig({ document, siteRoot, backend = null, sourceLoc
394
394
  siteRoot,
395
395
  rows: document.services,
396
396
  scope: blueprintScope,
397
- own: siteYmlNow ? ownSchemaNames(foundationDataSchemas(siteRoot, siteYmlNow)) : null
397
+ own: foundation?.own ?? (siteYmlNow ? ownSchemaNames(foundationDataSchemas(siteRoot, siteYmlNow)) : null)
398
398
  })
399
399
  }
400
400
 
@@ -1993,7 +1993,7 @@ function seenPageRoutes(items) {
1993
1993
  * page at both its routes
1994
1994
  * @returns {{ config: object, collections: object, locales: object, pages: string[], sections: string[], layout: string[], deleted: string[], renamed: object[] }}
1995
1995
  */
1996
- export function siteContentDocumentToProject({ document, siteRoot, backend = null, sourceLocale = documentSourceLocale(document), prune = false, keepAuthoredFoundation = false, scope, dataModel = null, sectionType = DEFAULT_SECTION_TYPE, writableMounts = [], priorItems = null }) {
1996
+ export function siteContentDocumentToProject({ document, siteRoot, backend = null, sourceLocale = documentSourceLocale(document), prune = false, keepAuthoredFoundation = false, scope, dataModel = null, sectionType = DEFAULT_SECTION_TYPE, writableMounts = [], priorItems = null, foundation = null }) {
1997
1997
  // Before anything is written: a pull that would leave content out of the files stops here.
1998
1998
  refuseContentFilesCannotHold(document, sourceLocale)
1999
1999
 
@@ -2026,8 +2026,10 @@ export function siteContentDocumentToProject({ document, siteRoot, backend = nul
2026
2026
  // section's writer to make relative to its own file (`located-media.js`).
2027
2027
  const mediaKeys = siteFileKeys(assetMap)
2028
2028
 
2029
- report.config = siteInfoToConfig({ document, siteRoot, backend, sourceLocale, collector, keepAuthoredFoundation, sameFile: sameStoredFile(assetMap, { siteRoot }), scope })
2030
- report.queries = declarationsToQueriesYml({ document, siteRoot, scope })
2029
+ // What the site's foundation declares, as the caller read it from the foundation's source where it
2030
+ // is local (`readSiteFoundationDeclarations`): absent, each projection reads the built schema.
2031
+ report.config = siteInfoToConfig({ document, siteRoot, backend, sourceLocale, collector, keepAuthoredFoundation, sameFile: sameStoredFile(assetMap, { siteRoot }), scope, foundation })
2032
+ report.queries = declarationsToQueriesYml({ document, siteRoot, scope, foundation })
2031
2033
 
2032
2034
  // The uuid identity index (gitignored `.uniweb/`): read the prior map to anchor
2033
2035
  // rename detection, build a fresh one as we project, then persist it. Items not
@@ -53,9 +53,13 @@ import { processQueries } from './site/query-processor.js'
53
53
 
54
54
  /**
55
55
  * The keys a section type declares with an inline shape — a field map or a form — whose every
56
- * field gives a `default:`: the words a section draws itself, which it shows when the section holds
57
- * no block of its own (`uniweb guide foundation` § A section's own words). Read by the one
58
- * normalizer every form of a declaration goes through (`normalizeData`).
56
+ * field gives a `default:` with something in it: the words a section draws itself, which it shows
57
+ * when the section holds no block of its own (`uniweb guide foundation` § A section's own words).
58
+ * Read by the one normalizer every form of a declaration goes through (`normalizeData`).
59
+ *
60
+ * ⛔ A blank default is not a word: `default: ''`, `null` or an empty list leaves the section nothing
61
+ * to show, which an editor pre-fills as empty — an older way to declare a key a fetch fills, every
62
+ * field blank. ⛔ Until 2026-11-11 (the day this check learned of own words) any `default:` counted.
59
63
  *
60
64
  * @param {object|undefined} data - a section type's `data:`
61
65
  * @returns {Set<string>}
@@ -70,13 +74,22 @@ function keysWithOwnWords(data) {
70
74
  }
71
75
  for (const [key, decl] of Object.entries(normalized)) {
72
76
  const fields = decl?.kind === 'fields' ? Object.values(decl.fields || {}) : decl?.kind === 'form' ? decl.fields : null
73
- if (Array.isArray(fields) && fields.length > 0 && fields.every((f) => f && typeof f === 'object' && f.default !== undefined)) {
77
+ if (Array.isArray(fields) && fields.length > 0 && fields.every((f) => f && typeof f === 'object' && shows(f.default))) {
74
78
  out.add(key)
75
79
  }
76
80
  }
77
81
  return out
78
82
  }
79
83
 
84
+ /** Whether a field's `default:` gives the section something to show. */
85
+ function shows(value) {
86
+ if (value === undefined || value === null) return false
87
+ if (typeof value === 'string') return value.trim() !== ''
88
+ if (Array.isArray(value)) return value.length > 0
89
+ if (typeof value === 'object') return Object.keys(value).length > 0
90
+ return true
91
+ }
92
+
80
93
  /**
81
94
  * Walk a site's sections, pair each governed data input with its schema, and
82
95
  * validate. The section is the join point: it has a *type* (→ `meta.js` → a