@uniweb/build 1.20.0 → 1.20.2

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.20.0",
3
+ "version": "1.20.2",
4
4
  "description": "Build tooling for the Uniweb Component Web Platform",
5
5
  "type": "module",
6
6
  "exports": {
@@ -20,6 +20,7 @@
20
20
  "./hosts": "./src/hosts/index.js",
21
21
  "./i18n": "./src/i18n/index.js",
22
22
  "./uwx": "./src/uwx/index.js",
23
+ "./blueprint": "./src/uwx/blueprint-file.js",
23
24
  "./import-map-plugin": "./src/import-map-plugin.js",
24
25
  "./emit-surface": "./src/uwx/emit-surface.json"
25
26
  },
@@ -58,9 +59,9 @@
58
59
  "yaml": "^2.5.0",
59
60
  "@uniweb/content-reader": "~1.5.9",
60
61
  "@uniweb/schemas": "~1.7.0",
62
+ "@uniweb/theming": "~1.3.2",
61
63
  "@uniweb/semantic-parser": "~1.13.2",
62
64
  "@uniweb/content-writer": "~1.3.1",
63
- "@uniweb/theming": "~1.3.2",
64
65
  "@uniweb/projections": "~1.2.13"
65
66
  },
66
67
  "optionalDependencies": {
@@ -73,8 +74,8 @@
73
74
  "@tailwindcss/vite": "^4.0.0",
74
75
  "@vitejs/plugin-react": "^4.0.0 || ^5.0.0",
75
76
  "vite-plugin-svgr": "^4.0.0",
76
- "@uniweb/core": "~1.6.9",
77
- "@uniweb/runtime": "~1.5.4"
77
+ "@uniweb/runtime": "~1.5.4",
78
+ "@uniweb/core": "~1.6.9"
78
79
  },
79
80
  "peerDependenciesMeta": {
80
81
  "vite": {
@@ -118,7 +118,9 @@ export async function buildSiteData({
118
118
  // No vite needed — collectSiteContent is a plain async function.
119
119
  // dropUnpublished: link mode is the build `publish` runs, so it reads
120
120
  // the site as published — hidden pages and their subtree pruned.
121
- let siteContent = await collectSiteContent(resolvedSiteRoot, { foundationPath, dropUnpublished: true, base: basePath, strict: true })
121
+ // warnBlueprint: the push that follows says what a backend would leave out of
122
+ // `blueprint.yml` (`uwx/blueprint.js`); said here too, a publish said it twice.
123
+ let siteContent = await collectSiteContent(resolvedSiteRoot, { foundationPath, dropUnpublished: true, base: basePath, strict: true, warnBlueprint: false })
122
124
 
123
125
  // 2. Compile content collections (file-based markdown/yaml/json).
124
126
  // `writeQueryFiles` lands them under `<siteRoot>/public/data/`;
@@ -47,6 +47,8 @@ import { noteSectionFile, rewriteFileLinks } from './file-links.js'
47
47
  import { valuesCutByComment } from '../utils/yaml-comment-trap.js'
48
48
  import { parseGrid } from '@uniweb/schemas/grid'
49
49
  import { runtimeServicesConfig, refuseRetiredServiceKeys, refuseUnreadableServices } from '../uwx/services-request.js'
50
+ import { readBlueprint, refuseUnreadableBlueprint, siteBlueprintWarnings } from '../uwx/blueprint.js'
51
+ import { siteSelfScope } from '../uwx/self-scope.js'
50
52
  import { refuseUnreadableAddress } from './site-address.js'
51
53
  import { warnOutsideVocabulary } from './vocabulary-warnings.js'
52
54
  import { warnPlacementsNotOffered } from './placement-warnings.js'
@@ -2600,8 +2602,11 @@ function payloadSiteConfig(siteConfig) {
2600
2602
  return runtimeSiteConfig
2601
2603
  }
2602
2604
 
2605
+ /** What this process has said of a site's `blueprint.yml` (`collectSiteContent`). */
2606
+ const saidOfBlueprint = new Set()
2607
+
2603
2608
  export async function collectSiteContent(sitePath, options = {}) {
2604
- const { foundationPath, configFile = 'site.yml', profile: profileName, dropUnpublished = false, base = '/', strict = false } = options
2609
+ const { foundationPath, configFile = 'site.yml', profile: profileName, dropUnpublished = false, base = '/', strict = false, warnBlueprint = true } = options
2605
2610
 
2606
2611
  // Fresh accounting per collect — see `yamlFailures`. A dev rebuild runs this
2607
2612
  // function again, so without the reset a typo fixed three saves ago would
@@ -2619,6 +2624,20 @@ export async function collectSiteContent(sitePath, options = {}) {
2619
2624
  refuseRetiredIconKey(siteConfig, configFile)
2620
2625
  refuseUnreadableAddress(siteConfig, configFile)
2621
2626
  refuseUnreadableServices(siteConfig, configFile)
2627
+ // How a backend started from this site begins (`uwx/blueprint.js`): checked as a push checks it,
2628
+ // and then left out of everything the build writes, since no page reads it.
2629
+ const blueprint = readBlueprint(sitePath)
2630
+ refuseUnreadableBlueprint(blueprint, { siteYml: siteConfig })
2631
+ // ⭐ Each said once a process, as the dev server's other notes about a file that seldom changes:
2632
+ // it collects the site again on every edit.
2633
+ if (blueprint && warnBlueprint) {
2634
+ const scope = await siteSelfScope(sitePath)
2635
+ for (const line of await siteBlueprintWarnings(sitePath, { scope, siteYml: siteConfig, primary: sectionTypes })) {
2636
+ if (saidOfBlueprint.has(line)) continue
2637
+ saidOfBlueprint.add(line)
2638
+ console.warn(`[content-collector] ${line}`)
2639
+ }
2640
+ }
2622
2641
 
2623
2642
  // Queries are declared in TWO files — `site.yml::queries` and `queries.yml`,
2624
2643
  // the latter winning per key — and resolving them is one question with one
@@ -0,0 +1,336 @@
1
+ /**
2
+ * `blueprint.yml` read and checked — the file half of a site's backend blueprint (`./blueprint.js`
3
+ * has the rest: the wire, the pull, and what a backend would leave out).
4
+ *
5
+ * ⭐ ITS OWN MODULE, AND A LIGHT ONE, so `uniweb dev`'s mock can read the file without loading the
6
+ * push and pull: YAML and the shape, nothing more. Exported as `@uniweb/build/blueprint`:
7
+ *
8
+ * ```js
9
+ * import { readBlueprint } from '@uniweb/build/blueprint'
10
+ * const blueprint = readBlueprint(siteRoot) // a map, {} for an empty file, or null
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+
16
+ import { existsSync, readFileSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import yaml from 'js-yaml'
19
+ import { parseSchemaRef } from '@uniweb/schemas/format'
20
+ import { YAML_OPTIONS } from '../utils/yaml-schema.js'
21
+
22
+ /** The file, beside `site.yml`. */
23
+ export const BLUEPRINT_FILE = 'blueprint.yml'
24
+
25
+ /** What the file holds, in the order a pull writes it. */
26
+ export const BLUEPRINT_KEYS = Object.freeze(['signup', 'teams', 'access', 'publicQueries'])
27
+
28
+ /** The two keys whose entries are types. */
29
+ export const TYPE_KEYS = Object.freeze(['access', 'publicQueries'])
30
+
31
+ const SIGNUP = Object.freeze(['open', 'invite_only'])
32
+ const LEVELS = Object.freeze(['read', 'edit'])
33
+ const ACCESS_KEYS = Object.freeze(['add', 'all'])
34
+ const QUERY_KEYS = Object.freeze(['whole', 'where', 'sort', 'limit'])
35
+ const TEAM_KEYS = Object.freeze(['label'])
36
+
37
+ /** In `all`, every member of the home org: the one name there that is not a team. */
38
+ const MEMBERS = 'members'
39
+
40
+ const TEAM_ID = /^[a-z0-9-]+$/
41
+
42
+ /**
43
+ * YAML 1.1's words for a switch, which js-yaml (YAML 1.2) reads as text, as
44
+ * `services-request.js` says them.
45
+ */
46
+ const SWITCH_WORDS = /^(y|yes|on|true|n|no|off|false)$/i
47
+ const ON_WORDS = /^(y|yes|on|true)$/i
48
+
49
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
50
+
51
+ /** What a value is, in words — for a message that says what was found. */
52
+ function described(value) {
53
+ if (value === null || value === undefined) return 'empty'
54
+ if (Array.isArray(value)) return 'a list'
55
+ if (typeof value === 'string') return value.trim() ? `the text \`${value}\`` : 'empty'
56
+ return `\`${JSON.stringify(value)}\``
57
+ }
58
+
59
+ /** `a`, `b`, `c` and `d` — each in backticks. */
60
+ function listed(names) {
61
+ const quoted = names.map((n) => `\`${n}\``)
62
+ return quoted.length < 2 ? quoted.join('') : `${quoted.slice(0, -1).join(', ')} and ${quoted.at(-1)}`
63
+ }
64
+
65
+ // ── Reading the file ──────────────────────────────────────────────────────────────
66
+
67
+ /**
68
+ * `blueprint.yml` as written: a map, `{}` for a file that says nothing yet, or null when there is
69
+ * no file.
70
+ *
71
+ * @param {string} siteRoot - the folder holding `site.yml`
72
+ * @returns {object|null}
73
+ * @throws {Error} when the file is not YAML, or not a map
74
+ */
75
+ export function readBlueprint(siteRoot) {
76
+ const file = join(siteRoot, BLUEPRINT_FILE)
77
+ if (!existsSync(file)) return null
78
+ const text = readFileSync(file, 'utf8')
79
+ let value
80
+ try {
81
+ value = yaml.load(text, YAML_OPTIONS)
82
+ } catch (err) {
83
+ throw new Error(`[uniweb] ${BLUEPRINT_FILE}: ${unreadableYaml(err, text)}`)
84
+ }
85
+ if (value === undefined || value === null) return {}
86
+ if (!isMap(value)) {
87
+ throw new Error(`[uniweb] ${BLUEPRINT_FILE} is a map of ${listed(BLUEPRINT_KEYS)} — not ${described(value)}.`)
88
+ }
89
+ return value
90
+ }
91
+
92
+ /**
93
+ * The parser's message, and the fix for the mistake every blueprint invites: a type the foundation
94
+ * names as its own starts with `@`, which YAML reserves, and unquoted it stops the parse with a
95
+ * message that names only the line.
96
+ */
97
+ function unreadableYaml(err, text) {
98
+ const first = String(err?.message || err).split('\n')[0].replace(/\.$/, '')
99
+ const line = Number.isInteger(err?.mark?.line) ? text.split('\n')[err.mark.line] ?? '' : ''
100
+ const key = line.match(/(?:^|[\s{,])(@[^\s'":]*)\s*:/)?.[1]
101
+ return key ? `${first}. A key that starts with \`@\` is quoted: \`'${key}':\`.` : `${first}.`
102
+ }
103
+
104
+ // ── Its shape ─────────────────────────────────────────────────────────────────────
105
+
106
+ /**
107
+ * Everything in a blueprint that its shape does not allow, each said with its key and its fix —
108
+ * `[]` when there is nothing. Only the shape: whether its types are ones the site's foundations
109
+ * declare is `blueprintWarnings`', and never a refusal.
110
+ *
111
+ * @param {*} blueprint - as `readBlueprint` read it
112
+ * @returns {string[]}
113
+ */
114
+ export function blueprintProblems(blueprint) {
115
+ if (blueprint === null || blueprint === undefined) return []
116
+ if (!isMap(blueprint)) return [`it is a map of ${listed(BLUEPRINT_KEYS)} — not ${described(blueprint)}.`]
117
+ const found = []
118
+
119
+ for (const key of Object.keys(blueprint)) {
120
+ if (!BLUEPRINT_KEYS.includes(key)) {
121
+ found.push(`\`${key}\` is not one of its keys, which are ${listed(BLUEPRINT_KEYS)}.`)
122
+ }
123
+ }
124
+
125
+ if ('signup' in blueprint && !SIGNUP.includes(blueprint.signup)) {
126
+ found.push(`\`signup\` is \`open\` or \`invite_only\` — not ${described(blueprint.signup)}.`)
127
+ }
128
+
129
+ // The teams a line may name. Every id the file gives counts, even one it refuses, so that one
130
+ // mistake is said once and not again at every line naming it.
131
+ const teams = blueprint.teams
132
+ const teamIds = isMap(teams) ? new Set(Object.keys(teams)) : null
133
+ if (teams !== undefined) found.push(...teamProblems(teams))
134
+ if (blueprint.access !== undefined) found.push(...accessProblems(blueprint.access, teamIds))
135
+ if (blueprint.publicQueries !== undefined) found.push(...publicQueryProblems(blueprint.publicQueries))
136
+ return found
137
+ }
138
+
139
+ function teamProblems(teams) {
140
+ if (!isMap(teams)) {
141
+ return [`\`teams\` is a map of teams by id — \`teams: { sales: { label: Sales } }\` — not ${described(teams)}.`]
142
+ }
143
+ const found = []
144
+ const named = new Map()
145
+ for (const [id, team] of Object.entries(teams)) {
146
+ const at = `teams.${id}`
147
+ if (id === MEMBERS) {
148
+ found.push(`\`${at}\`: \`members\` means every member in \`all\`, so no team has that id.`)
149
+ continue
150
+ }
151
+ if (!TEAM_ID.test(id)) {
152
+ found.push(`\`${at}\`: a team's id is lowercase letters, digits and dashes — its name goes in its \`label\`.`)
153
+ continue
154
+ }
155
+ if (!isMap(team)) {
156
+ found.push(`\`${at}\` is a map — \`${id}: {}\`, or \`${id}: { label: … }\` to name it — not ${described(team)}.`)
157
+ continue
158
+ }
159
+ for (const key of Object.keys(team)) {
160
+ if (!TEAM_KEYS.includes(key)) {
161
+ found.push(`\`${at}.${key}\` is not a team's key: a team has a \`label\`, and starts with no one in it.`)
162
+ }
163
+ }
164
+ if ('label' in team && (typeof team.label !== 'string' || !team.label.trim())) {
165
+ found.push(`\`${at}.label\` is the team's name — not ${described(team.label)}.`)
166
+ continue
167
+ }
168
+ // A team's name is its label, or its id when it has none, and no two teams share one.
169
+ const name = 'label' in team ? team.label : id
170
+ if (named.has(name)) found.push(`\`teams.${named.get(name)}\` and \`${at}\` are both named \`${name}\`: give each team its own.`)
171
+ else named.set(name, id)
172
+ }
173
+ return found
174
+ }
175
+
176
+ function accessProblems(access, teamIds) {
177
+ if (!isMap(access)) {
178
+ return [`\`access\` is a map of types — \`access: { '@/vehicle': { add: [sales] } }\` — not ${described(access)}.`]
179
+ }
180
+ const found = []
181
+ for (const [type, line] of Object.entries(access)) {
182
+ const at = `access.${type}`
183
+ const name = typeNameProblem(at, type)
184
+ if (name) found.push(name)
185
+ if (!isMap(line)) {
186
+ found.push(`\`${at}\` is a map of \`add\` and \`all\` — \`'${type}': { add: open }\` — not ${described(line)}.`)
187
+ continue
188
+ }
189
+ for (const key of Object.keys(line)) {
190
+ if (!ACCESS_KEYS.includes(key)) {
191
+ found.push(`\`${at}.${key}\` is not one of a type's keys: \`add\`, who adds its entries, and \`all\`, who reads or edits every one.`)
192
+ }
193
+ }
194
+ if ('add' in line) found.push(...addProblems(`${at}.add`, line.add, teamIds))
195
+ if ('all' in line) found.push(...allProblems(`${at}.all`, line.all, teamIds))
196
+ }
197
+ return found
198
+ }
199
+
200
+ function addProblems(at, add, teamIds) {
201
+ if (add === 'open') return []
202
+ if (!Array.isArray(add)) {
203
+ return [`\`${at}\` is \`open\`, a list of teams, or \`[]\` for none — not ${described(add)}.`]
204
+ }
205
+ const found = []
206
+ for (const team of add) {
207
+ if (team === MEMBERS) {
208
+ found.push(`\`${at}\` names \`members\`: to let every signed-in account add entries of the type, write \`add: open\`.`)
209
+ } else if (typeof team !== 'string') {
210
+ found.push(`\`${at}\` lists ${described(team)}, which is not a team's id.`)
211
+ } else if (teamIds && !teamIds.has(team)) {
212
+ found.push(`\`${at}\` names \`${team}\`, which is not one of \`teams\`.`)
213
+ }
214
+ }
215
+ return found
216
+ }
217
+
218
+ function allProblems(at, all, teamIds) {
219
+ if (!isMap(all)) {
220
+ return [`\`${at}\` is a map of teams, or \`members\`, to \`read\` or \`edit\` — \`all: { sales: edit }\` — not ${described(all)}.`]
221
+ }
222
+ const found = []
223
+ for (const [who, level] of Object.entries(all)) {
224
+ if (who !== MEMBERS && teamIds && !teamIds.has(who)) {
225
+ found.push(`\`${at}.${who}\` is neither one of \`teams\` nor \`members\`, every member.`)
226
+ }
227
+ if (!LEVELS.includes(level)) found.push(levelProblem(`${at}.${who}`, level))
228
+ }
229
+ return found
230
+ }
231
+
232
+ function levelProblem(at, level) {
233
+ if (level === 'view') return `\`${at}\` is \`view\`: the level that reads every entry is \`read\`.`
234
+ if (level === 'admin') return `\`${at}\` is \`admin\`, which deletes, and a blueprint gives \`read\` or \`edit\`.`
235
+ return `\`${at}\` is \`read\` or \`edit\` — not ${described(level)}.`
236
+ }
237
+
238
+ function publicQueryProblems(queries) {
239
+ if (!isMap(queries)) {
240
+ return [`\`publicQueries\` is a map of types — \`publicQueries: { '@/vehicle': { whole: false } }\` — not ${described(queries)}.`]
241
+ }
242
+ const found = []
243
+ for (const [type, entry] of Object.entries(queries)) {
244
+ const at = `publicQueries.${type}`
245
+ const name = typeNameProblem(at, type)
246
+ if (name) found.push(name)
247
+ if (!isMap(entry)) {
248
+ found.push(`\`${at}\` is a map that says at least \`whole\` — \`'${type}': { whole: false }\` — not ${described(entry)}.`)
249
+ continue
250
+ }
251
+ for (const key of Object.keys(entry)) {
252
+ if (!QUERY_KEYS.includes(key)) found.push(`\`${at}.${key}\` is not one of a public query's keys, which are ${listed(QUERY_KEYS)}.`)
253
+ }
254
+ // ⭐ STATED EVERY TIME: a public query that leaves `whole` out serves every entry of the type
255
+ // whole, so the file asks for the choice the admin app's screen asks for.
256
+ if (!('whole' in entry)) {
257
+ found.push(
258
+ `\`${at}\` says nothing of \`whole\`: write \`whole: false\` to let visitors read the entries' briefs, ` +
259
+ 'or `whole: true` for whole entries. Left out, every entry is served whole.'
260
+ )
261
+ } else if (typeof entry.whole !== 'boolean') {
262
+ found.push(
263
+ typeof entry.whole === 'string' && SWITCH_WORDS.test(entry.whole.trim())
264
+ ? `\`${at}.whole\` is the text \`${entry.whole}\`, not true or false — YAML reads yes, no, on and off as words. Write \`whole: ${ON_WORDS.test(entry.whole.trim())}\`.`
265
+ : `\`${at}.whole\` is true or false — not ${described(entry.whole)}.`
266
+ )
267
+ }
268
+ }
269
+ return found
270
+ }
271
+
272
+ /** A type's name is `@/x` or `@scope/x` (`parseSchemaRef`), or null. */
273
+ function typeNameProblem(at, type) {
274
+ try {
275
+ parseSchemaRef(type)
276
+ return null
277
+ } catch {
278
+ const bare = String(type).replace(/^@?\/?/, '')
279
+ return `\`${at}\` names no type: one of the foundation's own is \`'@/${bare}'\`, and any other is named in full, \`'@scope/${bare}'\`.`
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Whether `site.yml` names the `backend` service — on, off, or settings. The row a blueprint rides.
285
+ *
286
+ * @param {object} siteYml
287
+ * @returns {boolean}
288
+ */
289
+ function namesBackend(siteYml) {
290
+ const services = siteYml?.services
291
+ return isMap(services) && services.backend !== undefined && services.backend !== null
292
+ }
293
+
294
+ /**
295
+ * Stop on a blueprint neither a build nor a push can take — beside `refuseUnreadableServices`.
296
+ *
297
+ * ⭐ A MALFORMED BLUEPRINT REFUSES THE WHOLE PUSH, content included: the backend refuses a push
298
+ * whose `backend` row it cannot read, and the author who can fix the line is at the keyboard.
299
+ *
300
+ * Also refused, since the two files must agree:
301
+ *
302
+ * - a `blueprint:` in `site.yml::services.backend` — the blueprint's one home is its file, and a
303
+ * push would send that one with its types unqualified;
304
+ * - a blueprint beside a `site.yml` that names no `backend` service: it rides that row, so with
305
+ * none it would go nowhere. ⚠️ A `backend` that is off still carries it — `backend: false`, or
306
+ * `enabled: false` — as the row does: a pull writes an off row's blueprint back, and turning the
307
+ * backend on again in the app starts from it.
308
+ *
309
+ * @param {object|null} blueprint - as `readBlueprint` read it
310
+ * @param {{ siteYml?: object, where?: string }} [opts]
311
+ * @throws {Error} naming each key and its fix
312
+ */
313
+ export function refuseUnreadableBlueprint(blueprint, { siteYml = null, where = BLUEPRINT_FILE } = {}) {
314
+ const inSite = siteYml?.services?.backend
315
+ if (isMap(inSite) && inSite.blueprint !== undefined) {
316
+ throw new Error(
317
+ '[uniweb] site.yml: `services.backend.blueprint` is not read from site.yml — a site\'s blueprint is ' +
318
+ `\`${BLUEPRINT_FILE}\`, beside it. Move the block there, as the file's whole content.`
319
+ )
320
+ }
321
+ if (blueprint === null || blueprint === undefined) return
322
+ const found = blueprintProblems(blueprint)
323
+ if (found.length) {
324
+ throw new Error(
325
+ found.length === 1
326
+ ? `[uniweb] ${where}: ${found[0]}`
327
+ : `[uniweb] ${where} has lines a backend cannot take:\n${found.map((f) => ` - ${f}`).join('\n')}`
328
+ )
329
+ }
330
+ if (siteYml && !namesBackend(siteYml)) {
331
+ throw new Error(
332
+ `[uniweb] ${where} says how a backend started from this site begins, and site.yml asks for none. ` +
333
+ 'Add `backend: true` under `services:` in site.yml, or remove the file.'
334
+ )
335
+ }
336
+ }
@@ -0,0 +1,388 @@
1
+ /**
2
+ * A site's backend blueprint — `blueprint.yml`, beside `site.yml`: how a backend started from this
3
+ * site begins. Who may sign up, the teams it founds, who may add and see each type, and what
4
+ * visitors may read.
5
+ *
6
+ * ```yaml
7
+ * signup: invite_only # open (the default), or invite_only
8
+ * teams: # founded empty: who is in one is set in the admin app
9
+ * sales: { label: Sales }
10
+ * access:
11
+ * '@/vehicle':
12
+ * add: [sales] # open, a list of teams, or [] for none
13
+ * all: { sales: edit } # a team, or members, to read or edit
14
+ * publicQueries: # what visitors who are not signed in may read
15
+ * '@/vehicle': { whole: true, where: { status: { in: [available, pending] } } }
16
+ * ```
17
+ *
18
+ * ⭐ IT IS THE `backend` SERVICE'S, KEPT IN A FILE OF ITS OWN. A push sends it in that service's
19
+ * row, as `config.blueprint`, beside the rest of what `site.yml::services.backend` asks; a pull
20
+ * lifts it out again and writes it here, and never into `site.yml`. Every other key of the row's
21
+ * `config` round-trips as `services-request.js` says.
22
+ *
23
+ * ⭐ A TYPE IS NAMED AS ITS FOUNDATION NAMES IT — `@/x` for one of the site's foundation's own, a
24
+ * full name for any other, as `data:` and `queries.yml` name types — and a push names each in full
25
+ * by the rule every ref it sends follows (`qualifyRef`, with the scope `siteSelfScope` reads). The
26
+ * backend never resolves an `@/x`. A pull writes `@/x` back, and keeps a name the file already
27
+ * spells another way when it names the same type.
28
+ *
29
+ * ⭐ ITS SHAPE IS THE BACKEND'S, AND THE BACKEND CHECKS IT AT EVERY DOOR THAT WRITES THE ROW. The
30
+ * checks here come earlier — a build, a push, `uniweb doctor`, offline — and refuse no more than
31
+ * the file's shape: its keys, team ids and labels, levels, and a public query's `whole`. Two things
32
+ * are left to a backend that starts from it:
33
+ *
34
+ * - whether a public query's `where`, `sort` and `limit` make a set it can serve, which only it
35
+ * can judge against the types it installs;
36
+ * - a type none of the site's foundations declares: a warning here (`blueprintWarnings`), never a
37
+ * refusal, since a backend started from the site leaves that line out and says so.
38
+ *
39
+ * ⭐ NOTHING OF IT REACHES A PAGE. A static build checks it and writes it nowhere: no page reads how
40
+ * a backend began.
41
+ *
42
+ * Read by the static build (`site/content-collector.js`), the push (`site.js`, `sync-package.js`),
43
+ * the pull (`site-project.js`) and the CLI's `doctor`.
44
+ *
45
+ * @module
46
+ */
47
+
48
+ import { existsSync, readFileSync } from 'node:fs'
49
+ import { join, resolve } from 'node:path'
50
+ import yaml from 'js-yaml'
51
+ import { qualifyRef } from '@uniweb/schemas/refs'
52
+ import { YAML_OPTIONS } from '../utils/yaml-schema.js'
53
+ import { unresolveSelfScope, bareOrg } from './self-scope.js'
54
+ import { writeYamlFile } from './project-writer.js'
55
+ import { detectFoundationType } from '../site/foundation-ref.js'
56
+ import { findSiteExtension, extensionNameOf } from '../site/workspace-extension.js'
57
+ import { resolveFoundationSrcPath } from '../utils/foundation-source-root.js'
58
+ import { buildSchema, readFoundationName } from '../schema.js'
59
+ import { splitFoundationName } from '../foundation-name.js'
60
+ import { BLUEPRINT_FILE, TYPE_KEYS, readBlueprint } from './blueprint-file.js'
61
+
62
+ // The file half — read and checked — is its own light module, so `uniweb dev`'s mock can read the file
63
+ // without the push and the pull (`./blueprint-file.js`, `@uniweb/build/blueprint`).
64
+ export { BLUEPRINT_FILE, BLUEPRINT_KEYS, readBlueprint, blueprintProblems, refuseUnreadableBlueprint } from './blueprint-file.js'
65
+
66
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
67
+
68
+ /** Deterministic JSON: object keys sorted at every depth, arrays left in order. */
69
+ function stable(value) {
70
+ return JSON.stringify(value ?? null, (_k, v) =>
71
+ isMap(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v
72
+ )
73
+ }
74
+
75
+ // ── On the wire ───────────────────────────────────────────────────────────────────
76
+
77
+ /**
78
+ * The blueprint as a push sends it, `config.blueprint` of the `backend` row: the file key for key,
79
+ * each type named in full. Only the names change.
80
+ *
81
+ * @param {object} blueprint - a checked blueprint (`refuseUnreadableBlueprint`)
82
+ * @param {string|null} scope - the scope the site's `@/x` resolve into (`siteSelfScope`); with none,
83
+ * an `@/x` goes as written (`blueprintWarnings` says so)
84
+ * @returns {object}
85
+ * @throws {Error} when two names in one key name the same type
86
+ */
87
+ export function blueprintForWire(blueprint, scope) {
88
+ const out = {}
89
+ for (const [key, value] of Object.entries(blueprint)) {
90
+ out[key] = TYPE_KEYS.includes(key) && isMap(value) ? qualifiedTypes(key, value, scope) : value
91
+ }
92
+ return out
93
+ }
94
+
95
+ /** A map of types with each key in full. ⛔ Two keys for one type cannot both go: refused by name. */
96
+ function qualifiedTypes(key, map, scope) {
97
+ const out = {}
98
+ const from = new Map()
99
+ for (const [type, value] of Object.entries(map)) {
100
+ const full = qualifyRef(type, scope)
101
+ if (from.has(full)) {
102
+ throw new Error(
103
+ `[uniweb] ${BLUEPRINT_FILE}: \`${key}.${from.get(full)}\` and \`${key}.${type}\` name one type, \`${full}\`. Keep one of them.`
104
+ )
105
+ }
106
+ from.set(full, type)
107
+ out[full] = value
108
+ }
109
+ return out
110
+ }
111
+
112
+ /**
113
+ * The blueprint a row holds → the file a pull writes: each type of the site's foundation's own as
114
+ * `@/x` again (`unresolveSelfScope`), or as the file already spells it.
115
+ *
116
+ * @param {object} wire - the row's `config.blueprint`
117
+ * @param {object} [opts]
118
+ * @param {string|null} [opts.scope] - the scope the push qualified with
119
+ * @param {Set<string>|null} [opts.own] - the data schemas the foundation defines, when known
120
+ * @param {object|null} [opts.local] - the file as it stands, whose spelling of a type is kept
121
+ * @returns {object}
122
+ */
123
+ export function blueprintFromWire(wire, { scope = null, own = null, local = null } = {}) {
124
+ const out = {}
125
+ for (const [key, value] of Object.entries(isMap(wire) ? wire : {})) {
126
+ if (!TYPE_KEYS.includes(key) || !isMap(value)) {
127
+ out[key] = value
128
+ continue
129
+ }
130
+ const spelled = spellingsOf(local?.[key], scope)
131
+ out[key] = Object.fromEntries(
132
+ Object.entries(value).map(([type, line]) => [spelled.get(type) ?? unresolveSelfScope(type, scope, own), line])
133
+ )
134
+ }
135
+ return out
136
+ }
137
+
138
+ /** Each type a file's key names, in full → as the file spells it. */
139
+ function spellingsOf(map, scope) {
140
+ const out = new Map()
141
+ if (isMap(map)) for (const type of Object.keys(map)) out.set(qualifyRef(type, scope), type)
142
+ return out
143
+ }
144
+
145
+ // ── A pull ────────────────────────────────────────────────────────────────────────
146
+
147
+ /**
148
+ * The site's `services` rows with the blueprint lifted out of the `backend` row, for `site.yml` —
149
+ * and the blueprint, for its file.
150
+ *
151
+ * @param {object[]} rows - the `services` Section
152
+ * @returns {{ rows: object[], blueprint: object|undefined, backend: boolean }} `backend`: whether
153
+ * the site has a `backend` row at all
154
+ */
155
+ export function liftBlueprint(rows) {
156
+ let blueprint
157
+ let backend = false
158
+ const out = (Array.isArray(rows) ? rows : []).map((row) => {
159
+ if (!isMap(row) || row.name !== 'backend') return row
160
+ backend = true
161
+ if (!isMap(row.config) || !('blueprint' in row.config)) return row
162
+ const { blueprint: held, ...config } = row.config
163
+ blueprint = held
164
+ return { ...row, config }
165
+ })
166
+ return { rows: out, blueprint, backend }
167
+ }
168
+
169
+ /**
170
+ * Write what the site's `backend` row holds to `blueprint.yml` — or leave the file as it is.
171
+ *
172
+ * ⭐ A FILE THAT SAYS WHAT THE ROW SAYS IS LEFT AS WRITTEN: compared as a push would send it, so a
173
+ * pull of what was pushed changes no file. One that differs is edited, its comments kept
174
+ * (`writeYamlFile`).
175
+ *
176
+ * ⭐ A ROW WITH NO BLUEPRINT LEAVES AN EXISTING FILE ALONE, and says so: the file is the author's
177
+ * account of how a backend begins, and a site that holds none has not said otherwise. The next push
178
+ * sends it.
179
+ *
180
+ * @param {object} p
181
+ * @param {string} p.siteRoot
182
+ * @param {object[]} p.rows - the `services` Section
183
+ * @param {string|null} [p.scope] - the scope the push qualified the types with
184
+ * @param {Set<string>|null} [p.own] - the data schemas the foundation defines, when known
185
+ * @returns {{ file: 'updated'|'unchanged'|'kept'|null, note?: string }} `kept`: a file the pull
186
+ * left alone, with the sentence that says why
187
+ */
188
+ export function writePulledBlueprint({ siteRoot, rows, scope = null, own = null }) {
189
+ const { blueprint, backend } = liftBlueprint(rows)
190
+ const path = join(siteRoot, BLUEPRINT_FILE)
191
+ if (blueprint === undefined) {
192
+ if (!existsSync(path)) return { file: null }
193
+ return {
194
+ file: 'kept',
195
+ note: backend
196
+ ? `The site's backend holds no blueprint, so ${BLUEPRINT_FILE} is left as it is. The next push sends it.`
197
+ : `The site asks for no backend, so ${BLUEPRINT_FILE} is left as it is. A push sends it once site.yml asks for one (\`services: { backend: true }\`).`
198
+ }
199
+ }
200
+ let local = null
201
+ try {
202
+ local = readBlueprint(siteRoot)
203
+ } catch {
204
+ local = null // a file a push could not read either: written over with what the site holds
205
+ }
206
+ if (local && saysTheSame(local, blueprint, scope)) return { file: 'unchanged' }
207
+ return { file: writeYamlFile(path, blueprintFromWire(blueprint, { scope, own, local })) }
208
+ }
209
+
210
+ /** Whether the file, as a push would send it, is what the row holds. */
211
+ function saysTheSame(local, wire, scope) {
212
+ try {
213
+ return stable(blueprintForWire(local, scope)) === stable(wire)
214
+ } catch {
215
+ return false
216
+ }
217
+ }
218
+
219
+ // ── What a backend started from the site will leave out ───────────────────────────
220
+
221
+ /**
222
+ * What to tell the author about a blueprint before a backend is started from it — `[]` when there
223
+ * is nothing. Never a refusal: a backend leaves out a line it cannot apply, and says so when it
224
+ * starts. Said here so the author learns of it while still at the file:
225
+ *
226
+ * - a type none of the site's foundations declares, which a backend started from the site does
227
+ * not install. Said only when every foundation the site uses could be read here: one that
228
+ * cannot be — a cataloged foundation, whose data schemas travel as Models — might declare it;
229
+ * - an `@/x` a push cannot name in full, because the foundation has no scope yet — said by a
230
+ * push alone (`sending`): a project's foundation has none until its first `register`, and a
231
+ * build sends nothing.
232
+ *
233
+ * @param {object|null} blueprint - a checked blueprint (`refuseUnreadableBlueprint`)
234
+ * @param {object} p
235
+ * @param {string|null} p.scope - the scope the site's `@/x` resolve into
236
+ * @param {{ types: Set<string>|null }} p.declared - what `siteDeclaredTypes` read
237
+ * @param {boolean} [p.sending] - whether a push is about to send it
238
+ * @returns {string[]}
239
+ */
240
+ export function blueprintWarnings(blueprint, { scope, declared, sending = false }) {
241
+ if (!isMap(blueprint)) return []
242
+ const out = []
243
+ const scoped = Boolean(bareOrg(scope))
244
+ for (const key of TYPE_KEYS) {
245
+ if (!isMap(blueprint[key])) continue
246
+ for (const type of Object.keys(blueprint[key])) {
247
+ const at = `${key}.${type}`
248
+ if (!scoped && type.startsWith('@/')) {
249
+ if (sending) out.push(
250
+ `${BLUEPRINT_FILE}: \`${at}\` is the foundation's own type, and the foundation has no scope yet, ` +
251
+ "so a push sends it as written — the backend never resolves an `@/x`. A foundation's scope is part " +
252
+ "of its name — `name: '@org/<name>'` in its main.js, which `uniweb register` writes."
253
+ )
254
+ continue
255
+ }
256
+ if (declared?.types && !declared.types.has(qualifyRef(type, scope))) {
257
+ out.push(
258
+ `${BLUEPRINT_FILE}: \`${at}\` names a type none of this site's foundations declares, so a backend ` +
259
+ 'started from this site leaves the line out. Check the name against the foundation\'s data schemas.'
260
+ )
261
+ }
262
+ }
263
+ }
264
+ return out
265
+ }
266
+
267
+ /**
268
+ * `blueprintWarnings` for the site at `siteRoot`, reading what it needs: the file, `site.yml` and the
269
+ * site's foundations — `[]` when it has no blueprint, or one that names no type.
270
+ *
271
+ * @param {string} siteRoot
272
+ * @param {object} [opts]
273
+ * @param {string|null} [opts.scope] - the site's foundation's scope (`siteSelfScope`)
274
+ * @param {string} [opts.foundationDir] - the site's foundation, when a push was handed its folder
275
+ * @param {object} [opts.siteYml] - `site.yml`, already read
276
+ * @param {object|null} [opts.primary] - the site's foundation's schema, already read
277
+ * @param {boolean} [opts.sending] - whether a push is about to send it (`blueprintWarnings`)
278
+ * @returns {Promise<string[]>}
279
+ */
280
+ export async function siteBlueprintWarnings(siteRoot, { scope = null, foundationDir, siteYml, primary, sending = false } = {}) {
281
+ const blueprint = readBlueprint(siteRoot)
282
+ if (!isMap(blueprint) || !TYPE_KEYS.some((key) => isMap(blueprint[key]) && Object.keys(blueprint[key]).length)) return []
283
+ const yml = siteYml ?? readSiteYml(siteRoot)
284
+ const declared = await siteDeclaredTypes(siteRoot, yml, { scope, foundationDir, primary })
285
+ return blueprintWarnings(blueprint, { scope, declared, sending })
286
+ }
287
+
288
+ function readSiteYml(siteRoot) {
289
+ try {
290
+ return yaml.load(readFileSync(join(siteRoot, 'site.yml'), 'utf8'), YAML_OPTIONS) || {}
291
+ } catch {
292
+ return {}
293
+ }
294
+ }
295
+
296
+ /**
297
+ * The types a site's foundations declare, each in full — the data schemas a backend started from the
298
+ * site installs: its foundation's and each extension's, the `dataSchemas` `register` registers.
299
+ * `types` is null when any of them cannot be read here, since a type the others do not declare may
300
+ * be that one's; `unread` says which, and why.
301
+ *
302
+ * Read from each foundation's source when it is in the project, so it is the foundation a publish
303
+ * would bring along, and from its build when the source does not load.
304
+ *
305
+ * @param {string} siteRoot
306
+ * @param {object} siteYml
307
+ * @param {object} [opts]
308
+ * @param {string|null} [opts.scope] - the site's foundation's scope (`siteSelfScope`)
309
+ * @param {string} [opts.foundationDir] - the site's foundation, when a push was handed its folder
310
+ * @param {object|null} [opts.primary] - the site's foundation's schema, already read by the caller
311
+ * (the static build's `foundationSections`)
312
+ * @returns {Promise<{ types: Set<string>|null, unread: string[] }>}
313
+ */
314
+ export async function siteDeclaredTypes(siteRoot, siteYml, { scope = null, foundationDir, primary } = {}) {
315
+ const types = new Set()
316
+ const unread = []
317
+ const dir = foundationDir ? resolve(foundationDir) : localFoundationDir(siteRoot, siteYml)
318
+ if (!dir) {
319
+ unread.push(`its foundation${typeof siteYml?.foundation === 'string' ? `, \`${siteYml.foundation}\`,` : ''} is not in this project`)
320
+ } else {
321
+ const schema = primary !== undefined && !foundationDir ? primary : await foundationSchema(dir)
322
+ if (!schema) unread.push('its foundation could not be read')
323
+ else for (const ref of Object.keys(schema.dataSchemas || {})) types.add(qualifyRef(ref, scope))
324
+ }
325
+ for (const entry of Array.isArray(siteYml?.extensions) ? siteYml.extensions : []) {
326
+ const declared = typeof entry === 'string' ? entry : isMap(entry) ? entry.url : null
327
+ const name = workspaceExtensionName(declared, siteYml?.base)
328
+ const extDir = name ? findSiteExtension(name, siteRoot) : null
329
+ if (!extDir) {
330
+ unread.push(`the extension${typeof declared === 'string' ? ` \`${declared}\`` : ''} is not in this project`)
331
+ continue
332
+ }
333
+ const schema = await foundationSchema(extDir)
334
+ if (!schema) {
335
+ unread.push(`the extension \`${name}\` could not be read`)
336
+ continue
337
+ }
338
+ const extScope = await foundationScope(extDir)
339
+ for (const ref of Object.keys(schema.dataSchemas || {})) {
340
+ if (ref.startsWith('@/') && !extScope) {
341
+ unread.push(`the extension \`${name}\` has no scope yet`)
342
+ break
343
+ }
344
+ types.add(qualifyRef(ref, extScope))
345
+ }
346
+ }
347
+ return { types: unread.length ? null : types, unread }
348
+ }
349
+
350
+ /** The site's foundation's folder, when it is in the project — else null (a catalog ref, a URL). */
351
+ function localFoundationDir(siteRoot, siteYml) {
352
+ if (!siteYml?.foundation) return null
353
+ try {
354
+ const info = detectFoundationType(siteYml.foundation, siteRoot)
355
+ return info?.type === 'local' && info.path ? info.path : null
356
+ } catch {
357
+ return null // a declaration the resolver refuses is the build's to report
358
+ }
359
+ }
360
+
361
+ /** A workspace extension's name, from its declaration — a name, or a site-relative URL — or null. */
362
+ function workspaceExtensionName(declared, base) {
363
+ if (typeof declared !== 'string') return null
364
+ if (declared.startsWith('/')) return extensionNameOf(declared, base)?.name ?? null
365
+ return /^[a-z0-9][a-z0-9-]*$/i.test(declared) ? declared : null
366
+ }
367
+
368
+ /** A foundation's schema: from its source, else its build, else null. */
369
+ async function foundationSchema(dir) {
370
+ try {
371
+ return await buildSchema(resolveFoundationSrcPath(dir))
372
+ } catch {
373
+ try {
374
+ return JSON.parse(readFileSync(join(dir, 'dist', 'meta', 'schema.json'), 'utf8')) || null
375
+ } catch {
376
+ return null
377
+ }
378
+ }
379
+ }
380
+
381
+ /** The scope in a foundation's name, or null. */
382
+ async function foundationScope(dir) {
383
+ try {
384
+ return splitFoundationName((await readFoundationName(dir)).name).scope
385
+ } catch {
386
+ return null
387
+ }
388
+ }
package/src/uwx/index.js CHANGED
@@ -141,6 +141,17 @@ export {
141
141
  servicesFromDocument,
142
142
  sameServiceRow,
143
143
  } from './services-request.js'
144
+ // A site's backend blueprint — `blueprint.yml`, beside `site.yml`: how a backend started from the
145
+ // site begins. It rides the `backend` row of the services request.
146
+ export {
147
+ BLUEPRINT_FILE,
148
+ readBlueprint,
149
+ blueprintProblems,
150
+ refuseUnreadableBlueprint,
151
+ blueprintWarnings,
152
+ siteBlueprintWarnings,
153
+ siteDeclaredTypes,
154
+ } from './blueprint.js'
144
155
  export {
145
156
  diffSiteUnits,
146
157
  describeSiteDiff,
@@ -1010,16 +1010,26 @@ export async function buildRecordEntities(siteRoot, opts = {}) {
1010
1010
  // resolves as `@person/2024` — the rule is total, so it is not ambiguous — but an
1011
1011
  // author who meant "records organised by year inside the `person` schema" needs to
1012
1012
  // be told what the build actually read, not only that something failed to resolve.
1013
+ //
1014
+ // ⛔ A resolver that never asks the backend says so (`resolveModel.offline`, set by the
1015
+ // CLI for `-o`, `--dry-run` and `status`), and then the message must not say the backend
1016
+ // has no such Model: it was never asked. Until 2026-11-09 it did, so an offline run that
1017
+ // could not resolve a Model (a query naming a type the site's foundation does not declare,
1018
+ // or `status` in a clone whose kept Models were deleted) said the backend had none.
1013
1019
  const unresolvedExplicit = (modelName, queryName) => {
1014
1020
  const dirs = poolDirsForSchema(modelName)
1015
1021
  const { alternative } = dirs ? poolPathReadings(dirs) : { alternative: null }
1016
1022
  return new Error(
1017
1023
  `uwx/records: Model "${modelName}" (query "${queryName}") could not be ` +
1018
- 'resolved — not defined by a local foundation' +
1019
- (resolveModel
1020
- ? ', and the backend has no such Model (register it first).'
1021
- : '. Run via `uniweb sync` (which fetches non-local Models from the ' +
1022
- 'registry), or provide a local foundation that defines it.') +
1024
+ "resolved — the site's foundation does not define it" +
1025
+ (resolveModel?.offline === true
1026
+ ? '. This run does not ask the backend: `-o`, `--dry-run` and `status` know only ' +
1027
+ 'the Models a push or a pull of this copy read. A push reads it from the backend, ' +
1028
+ 'and stops if the backend has none.'
1029
+ : resolveModel
1030
+ ? ', and the backend has no such Model (register the foundation that defines it first).'
1031
+ : '. Run via `uniweb sync` (which fetches non-local Models from the ' +
1032
+ 'registry), or provide a local foundation that defines it.') +
1023
1033
  (alternative
1024
1034
  ? ` If you meant \`${pool.dir}/${dirs[0]}/\` (${alternative}) organised by ` +
1025
1035
  `\`${dirs[1]}\`, note that a folder inside a schema folder is read as an ` +
@@ -529,6 +529,10 @@ function keepCredentials(entry, local) {
529
529
  /**
530
530
  * The site's rows → the `site.yml::services` map — what a pull writes.
531
531
  *
532
+ * ⭐ `named` lists services written even when off with no settings here: the `backend` row whose
533
+ * blueprint went to its own file (`./blueprint.js`). Without its line, the next push would state it
534
+ * off with no settings, dropping the blueprint the file still holds.
535
+ *
532
536
  * ⭐ AN OFF SERVICE WITH NO SETTINGS IS WRITTEN ONLY WHERE `site.yml` ALREADY NAMES IT
533
537
  * [Diego, 2026-10-07]. Every service is on or off, and off by default, so a `false` line
534
538
  * adds nothing — and writing one for every service switched off in the app, or for each
@@ -546,15 +550,16 @@ function keepCredentials(entry, local) {
546
550
  * @param {object[]} [p.rows] - the `services` Section: the site's rows
547
551
  * @param {object} [p.local] - the `services:` the pull writes over — which services it
548
552
  * names, and the credentials a push never sends (`keepCredentials`)
553
+ * @param {string[]} [p.named] - services written even when off with no settings
549
554
  * @returns {object|null} null when there is nothing to write
550
555
  */
551
- export function servicesFromDocument({ rows, local } = {}) {
556
+ export function servicesFromDocument({ rows, local, named = [] } = {}) {
552
557
  const before = isMap(local) ? local : {}
553
558
  const out = {}
554
559
  for (const row of Array.isArray(rows) ? rows : []) {
555
560
  if (!isMap(row) || typeof row.name !== 'string' || !row.name || row.name in out) continue
556
561
  const entry = entryFromRow(row)
557
- if (entry === false && !(row.name in before)) continue
562
+ if (entry === false && !(row.name in before) && !named.includes(row.name)) continue
558
563
  out[row.name] = keepCredentials(entry, before[row.name])
559
564
  }
560
565
  return Object.keys(out).length ? out : null
@@ -41,6 +41,10 @@ import { mapPageRefs, pageRefIndex, pageRefPages, writtenPageRef } from './page-
41
41
  import { siteFileKeys, siteTree, writtenRefs } from './located-media.js'
42
42
  import { readBackendState, updateBackendState } from './sync-store.js'
43
43
  import { servicesFromDocument, heldServices } from './services-request.js'
44
+ import { liftBlueprint, writePulledBlueprint } from './blueprint.js'
45
+ import { ownSchemaNames } from './self-scope.js'
46
+ import { foundationDataSchemas } from '../site/queries-config.js'
47
+ import { parseCatalogRef } from '../site/foundation-ref.js'
44
48
  import { readFileSync, existsSync, unlinkSync, renameSync, rmSync, readdirSync, statSync, mkdirSync } from 'node:fs'
45
49
  import { isMarkdownFile, isIgnoredFolder } from '../utils/content-files.js'
46
50
  import { createHash } from 'node:crypto'
@@ -235,10 +239,13 @@ function readAuthoredYaml(filePath) {
235
239
  * (`{ info, extensions?, … }`)
236
240
  * @param {string} params.siteRoot
237
241
  * @param {string} [params.sourceLocale] - locale to unwrap localized fields to
238
- * @returns {{ siteConfig: string, theme?: string, headHtml?: string }} per-file
239
- * write status ('updated' | 'unchanged')
242
+ * @param {string|null} [params.scope] - the scope the push qualified the blueprint's types with, so
243
+ * they are written back as `@/x`; by default the pinned foundation's, as for the queries
244
+ * @returns {{ siteConfig: string, theme?: string, headHtml?: string, blueprint?: { file: string|null, note?: string } }}
245
+ * per-file write status ('updated' | 'unchanged'); `blueprint` when the document has a
246
+ * `services` Section (`./blueprint.js`, `writePulledBlueprint`)
240
247
  */
241
- export function siteInfoToConfig({ document, siteRoot, backend = null, sourceLocale = documentSourceLocale(document), collector, keepAuthoredFoundation = false, sameFile = null }) {
248
+ export function siteInfoToConfig({ document, siteRoot, backend = null, sourceLocale = documentSourceLocale(document), collector, keepAuthoredFoundation = false, sameFile = null, scope }) {
242
249
  const info = document?.info || {}
243
250
  const settingsSection = document?.settings || {}
244
251
 
@@ -340,10 +347,15 @@ export function siteInfoToConfig({ document, siteRoot, backend = null, sourceLoc
340
347
  // app, `$id` dropped. ⛔ *Until 2026-10-07 `services` held the rows themselves, the
341
348
  // record a push compared the file against, with `servicesNamed` beside it.*
342
349
  // ⛔ What is held needs a backend: with none there is nowhere coherent to file it.
343
- if (Array.isArray(document?.services)) {
350
+ // ⭐ THE `backend` ROW'S BLUEPRINT GOES TO `blueprint.yml`, NEVER INTO `site.yml` (`./blueprint.js`,
351
+ // written below). A row that carried one keeps its line in `site.yml` even when it is off, so the next
352
+ // push has the row to send the file on.
353
+ const lifted = Array.isArray(document?.services) ? liftBlueprint(document.services) : null
354
+ if (lifted) {
344
355
  siteChanges.services = servicesFromDocument({
345
- rows: document.services,
346
- local: readAuthoredYaml(join(siteRoot, 'site.yml'))?.services
356
+ rows: lifted.rows,
357
+ local: readAuthoredYaml(join(siteRoot, 'site.yml'))?.services,
358
+ named: lifted.blueprint !== undefined ? ['backend'] : []
347
359
  })
348
360
  for (const retired of ['search', 'submit', 'assistant', 'tracking', 'api']) siteChanges[retired] = null
349
361
  }
@@ -372,6 +384,20 @@ export function siteInfoToConfig({ document, siteRoot, backend = null, sourceLoc
372
384
  const written = authoredSite ? keepAuthoredRefs(siteChanges, authoredSite, (a, b) => sameFile(a, b, siteYmlPath)) : siteChanges
373
385
  const result = { siteConfig: writeSiteConfig(siteRoot, written) }
374
386
 
387
+ // `blueprint.yml` — the `backend` row's blueprint, its types of the foundation's own as `@/x` again, by
388
+ // the scope the push qualified them with (`declarationsToQueriesYml` reads it the same way). A
389
+ // document with no `services` Section says nothing of it, and the file is not touched.
390
+ if (lifted) {
391
+ const blueprintScope = scope !== undefined ? scope : (parseCatalogRef(document?.info?.foundation)?.scope ?? null)
392
+ const siteYmlNow = readAuthoredYaml(siteYmlPath)
393
+ result.blueprint = writePulledBlueprint({
394
+ siteRoot,
395
+ rows: document.services,
396
+ scope: blueprintScope,
397
+ own: siteYmlNow ? ownSchemaNames(foundationDataSchemas(siteRoot, siteYmlNow)) : null
398
+ })
399
+ }
400
+
375
401
  // theme (whole object) → theme.yml.
376
402
  if (settingsSection.theme && typeof settingsSection.theme === 'object') {
377
403
  result.theme = writeThemeFile(siteRoot, settingsSection.theme)
@@ -2000,7 +2026,7 @@ export function siteContentDocumentToProject({ document, siteRoot, backend = nul
2000
2026
  // section's writer to make relative to its own file (`located-media.js`).
2001
2027
  const mediaKeys = siteFileKeys(assetMap)
2002
2028
 
2003
- report.config = siteInfoToConfig({ document, siteRoot, backend, sourceLocale, collector, keepAuthoredFoundation, sameFile: sameStoredFile(assetMap, { siteRoot }) })
2029
+ report.config = siteInfoToConfig({ document, siteRoot, backend, sourceLocale, collector, keepAuthoredFoundation, sameFile: sameStoredFile(assetMap, { siteRoot }), scope })
2004
2030
  report.queries = declarationsToQueriesYml({ document, siteRoot, scope })
2005
2031
 
2006
2032
  // The uuid identity index (gitignored `.uniweb/`): read the prior map to anchor
package/src/uwx/site.js CHANGED
@@ -103,6 +103,7 @@ import {
103
103
  refuseRetiredServiceKeys,
104
104
  refuseUnreadableServices
105
105
  } from './services-request.js'
106
+ import { readBlueprint, refuseUnreadableBlueprint, blueprintForWire } from './blueprint.js'
106
107
  import { refuseUnreadableAddress } from '../site/site-address.js'
107
108
  import { resolveQueriesConfig } from './queries-config.js'
108
109
  import { qualifyRef } from '@uniweb/schemas/refs'
@@ -1297,15 +1298,23 @@ function servicesNested(rows) {
1297
1298
  * The `services` Section for this push — the file's services, and the held ones it no
1298
1299
  * longer lists stated off (`statedServices`) — or undefined when there is nothing to state.
1299
1300
  *
1301
+ * ⭐ `blueprint.yml` rides the `backend` row, as its `config.blueprint` (`./blueprint.js`),
1302
+ * whether the row is on or off. A blueprint beside a `site.yml` that names no `backend` was
1303
+ * refused before this (`refuseUnreadableBlueprint`).
1304
+ *
1300
1305
  * @param {object} siteYml
1301
1306
  * @param {object|null} provisioned - the backend's entry in `sync.json`; its `services`
1302
1307
  * is `{ <name>: <$uuid> }`, the services this copy holds
1308
+ * @param {object} [blueprint] - the blueprint as it goes on the wire, types in full
1303
1309
  * @returns {object[]|undefined}
1304
1310
  */
1305
- function requestedServices(siteYml, provisioned) {
1311
+ function requestedServices(siteYml, provisioned, blueprint) {
1306
1312
  const held = provisioned?.services
1313
+ const asks = readServicesRequest(siteYml.services)
1307
1314
  const rows = statedServices(
1308
- readServicesRequest(siteYml.services),
1315
+ blueprint
1316
+ ? (asks || []).map((ask) => (ask.name === 'backend' ? { ...ask, config: { ...ask.config, blueprint } } : ask))
1317
+ : asks,
1309
1318
  held && typeof held === 'object' && !Array.isArray(held) ? held : {}
1310
1319
  )
1311
1320
  // `$uuid` rides beside the payload-local `$id`, as on a query's row.
@@ -1515,6 +1524,9 @@ export async function siteProjectToDocument(siteRoot, opts = {}) {
1515
1524
  refuseRetiredServiceKeys(siteYml)
1516
1525
  refuseUnreadableAddress(siteYml)
1517
1526
  refuseUnreadableServices(siteYml)
1527
+ // How a backend started from this site begins — its own file, checked before anything is read.
1528
+ const blueprint = readBlueprint(siteRoot)
1529
+ refuseUnreadableBlueprint(blueprint, { siteYml })
1518
1530
  const sourceLocale = opts.sourceLocale || resolveDefaultLocale(siteYml)
1519
1531
  if (!siteYml.name) {
1520
1532
  throw new Error('uwx/site: site.yml::name is required')
@@ -1794,7 +1806,8 @@ export async function siteProjectToDocument(siteRoot, opts = {}) {
1794
1806
  // the backend that sold it — and the request is one, in `site.yml`. Push, publish,
1795
1807
  // `status` and a pull's re-bank all build it alike, from the file and `sync.json`.
1796
1808
  const provisioned = opts.backend ? readBackendState(siteRoot, opts.backend) : null
1797
- const services = requestedServices(siteYml, provisioned)
1809
+ // ⭐ The blueprint's types named in full by the scope the records and the queries take.
1810
+ const services = requestedServices(siteYml, provisioned, blueprint ? blueprintForWire(blueprint, scope) : undefined)
1798
1811
  if (services) doc.services = services
1799
1812
  const secrets = secretsNested(provisioned)
1800
1813
  if (secrets) doc.secrets = secrets
@@ -27,6 +27,7 @@ import { fileRecordUploads } from './file-records.js'
27
27
  import { locatedMediaSink } from './located-media.js'
28
28
  import { buildFolderEntity } from './folder.js'
29
29
  import { siteProjectToDocument } from './site.js'
30
+ import { siteBlueprintWarnings } from './blueprint.js'
30
31
  import { siteSourceLocale } from './source-locale.js'
31
32
  import { siteSelfScope, refuseOrgOption } from './self-scope.js'
32
33
  import { stampUnitUuids, collectUnitUuids, computeUnitHashes } from './site-diff.js'
@@ -514,6 +515,9 @@ export async function emitSyncPackages(siteRoot, opts = {}) {
514
515
  // record's, `site.yml`'s — needs a location the entity does not carry, so it is warned
515
516
  // once and skipped. ⛔ Until 2026-10-28 a section's were skipped too.
516
517
  if (media) warnings.push(...media.warnings)
518
+ // ⭐ What a backend started from the site would leave out of its blueprint, said while the author is
519
+ // still at the file. Never a refusal: the backend leaves such a line out and says so (`./blueprint.js`).
520
+ if (includeSite) warnings.push(...(await siteBlueprintWarnings(siteRoot, { scope, foundationDir: opts.foundationDir, sending: true })))
517
521
  const localAssetSet = new Set()
518
522
  const colocatedSeen = new Set()
519
523
  const collectFrom = (doc, taken = null) =>
@@ -91,7 +91,9 @@ export async function validateDataInputs({ siteRoot, foundationPath }) {
91
91
  // that type when no data schema has its name (`uwx/data-key-types.js`).
92
92
  const keyTypes = dataKeyTypes(foundation)
93
93
 
94
- const site = await collectSiteContent(siteRoot, { foundationPath })
94
+ // warnBlueprint: what a backend would leave out of `blueprint.yml` is not this check's to say — the
95
+ // push it gates says it (`uwx/blueprint.js`), and `uniweb doctor` does; said here too, a push said it twice.
96
+ const site = await collectSiteContent(siteRoot, { foundationPath, warnBlueprint: false })
95
97
  const config = site.config || {}
96
98
  const basePath = typeof config.base === 'string' ? config.base : '/'
97
99