@uniweb/build 1.23.8 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniweb/build",
3
- "version": "1.23.8",
3
+ "version": "1.24.0",
4
4
  "description": "Build tooling for the Uniweb Component Web Platform",
5
5
  "type": "module",
6
6
  "exports": {
@@ -57,11 +57,11 @@
57
57
  "js-yaml": "^4.3.2",
58
58
  "sharp": "^0.35.5",
59
59
  "yaml": "^2.5.0",
60
- "@uniweb/content-reader": "~1.5.10",
60
+ "@uniweb/content-reader": "~1.5.11",
61
61
  "@uniweb/content-writer": "~1.3.2",
62
- "@uniweb/schemas": "~1.7.4",
63
- "@uniweb/semantic-parser": "~1.13.5",
64
62
  "@uniweb/projections": "~1.2.17",
63
+ "@uniweb/semantic-parser": "~1.13.5",
64
+ "@uniweb/schemas": "~1.7.4",
65
65
  "@uniweb/theming": "~1.3.2"
66
66
  },
67
67
  "optionalDependencies": {
@@ -0,0 +1,132 @@
1
+ import { PUBLISHED_MOUNT } from '../site/published.js'
2
+
3
+ /**
4
+ * `uniweb dev --published` — the dev server answers a published site's services at addresses of
5
+ * its own and forwards each request to the published address (`../site/published.js` has the
6
+ * contract and how the addresses are made).
7
+ *
8
+ * ⭐ Same-origin on purpose, as `mountDevApi` is. The page asks the dev server, so a session
9
+ * cookie the published site's backend sets is first-party on the dev server's origin, and nothing
10
+ * exercises CORS or third-party-cookie rules the published site does not have. A cookie is kept
11
+ * on the dev server's origin, for its whole path, and loses `Secure` over plain http, where a
12
+ * browser could drop it — except a `__Host-` or `__Secure-` cookie, whose name requires it.
13
+ *
14
+ * ⭐ The request goes as the published page would send it: its method, body and headers, with the
15
+ * published page's origin as its `Origin`, since that is the page a visitor's request comes from.
16
+ * The dev server's own `Host` and `Referer` stay behind, and so does `Accept-Encoding`, because
17
+ * the answer is read whole and handed on decoded. A redirect is handed to the browser as it came.
18
+ *
19
+ * ⚠️ The answer is read whole before it is sent on, so a streamed one arrives at its end.
20
+ *
21
+ * ⛔ Registered SYNCHRONOUSLY, like `mountDevApi`: Vite runs the middleware registered before
22
+ * `configureServer` returns ahead of its SPA fallback, which would answer every address with
23
+ * `index.html`.
24
+ *
25
+ * @param {import('vite').ViteDevServer} server
26
+ * @param {object} options
27
+ * @param {Record<string, string>} options.targets - service → the origin it forwards to (`localServices`)
28
+ * @param {string} options.site - the published page's address
29
+ * @param {string} [options.base] - the dev site's base path, which a request may still carry
30
+ * @param {typeof fetch} [options.fetch] - injected in tests
31
+ * @param {(line: string) => void} [options.log]
32
+ */
33
+ export function mountPublished(server, { targets, site, base = '/', fetch: send = globalThis.fetch, log = console.log }) {
34
+ const siteOrigin = new URL(site).origin
35
+
36
+ server.middlewares.use(async (req, res, next) => {
37
+ const url = withoutBase(req.url || '', base)
38
+ if (!url.startsWith(`${PUBLISHED_MOUNT}/`)) return next()
39
+ const after = url.slice(PUBLISHED_MOUNT.length + 1)
40
+ const cut = after.search(/[/?]/)
41
+ const name = cut === -1 ? after : after.slice(0, cut)
42
+ const rest = cut === -1 ? '/' : after[cut] === '?' ? `/${after.slice(cut)}` : after.slice(cut)
43
+ const origin = targets[name]
44
+ if (!origin) {
45
+ return problem(res, 404, 'No Such Service', `The site published at ${siteOrigin} offers no ${name} service.`)
46
+ }
47
+
48
+ const headers = new Headers()
49
+ for (const [key, value] of Object.entries(req.headers)) {
50
+ if (value === undefined || NOT_SENT.has(key)) continue
51
+ headers.set(key, Array.isArray(value) ? value.join(', ') : value)
52
+ }
53
+ if (headers.has('origin')) headers.set('origin', siteOrigin)
54
+ const init = { method: req.method, headers, redirect: 'manual' }
55
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
56
+ const chunks = []
57
+ for await (const chunk of req) chunks.push(chunk)
58
+ if (chunks.length) init.body = Buffer.concat(chunks)
59
+ }
60
+
61
+ let response
62
+ try {
63
+ response = await send(`${origin}${rest}`, init)
64
+ } catch (err) {
65
+ return problem(res, 502, 'Published Site Unreachable', `Could not reach ${origin}: ${err?.cause?.message || err.message}`)
66
+ }
67
+ res.statusCode = response.status
68
+ response.headers.forEach((value, key) => {
69
+ if (key !== 'set-cookie' && !NOT_RETURNED.has(key)) res.setHeader(key, value)
70
+ })
71
+ const cookies = response.headers.getSetCookie?.() ?? []
72
+ if (cookies.length) {
73
+ const secure = Boolean(req.socket?.encrypted)
74
+ res.setHeader('set-cookie', cookies.map((cookie) => firstPartyCookie(cookie, { secure })))
75
+ }
76
+ // Bytes, never text: an answer may be an image or a file.
77
+ const bytes = Buffer.from(await response.arrayBuffer())
78
+ res.end(bytes.length ? bytes : undefined)
79
+ })
80
+
81
+ const names = Object.keys(targets)
82
+ log(
83
+ names.length
84
+ ? `[dev-published] ${names.map((n) => `${PUBLISHED_MOUNT}/${n}`).join(', ')} → the site as published at ${siteOrigin}`
85
+ : `[dev-published] the site published at ${siteOrigin} offers no service with an address`
86
+ )
87
+ }
88
+
89
+ /**
90
+ * A cookie the published site set, for the dev server's origin: no `Domain`, the whole path, and,
91
+ * over plain http, no `Secure` — so `SameSite=None`, which needs it, becomes `Lax`, the
92
+ * first-party default — unless its name requires `Secure`.
93
+ *
94
+ * @param {string} cookie - one `Set-Cookie` value
95
+ * @param {{ secure: boolean }} options - whether the dev server is reached over https
96
+ * @returns {string}
97
+ */
98
+ export function firstPartyCookie(cookie, { secure }) {
99
+ const [pair, ...attributes] = cookie.split(';')
100
+ const name = pair.split('=')[0].trim()
101
+ const keepSecure = secure || /^__(Host|Secure)-/.test(name)
102
+ const kept = []
103
+ for (const raw of attributes) {
104
+ const attribute = raw.trim()
105
+ const key = attribute.split('=')[0].trim().toLowerCase()
106
+ if (!attribute || key === 'domain' || key === 'path') continue
107
+ if (!keepSecure && (key === 'secure' || key === 'partitioned')) continue
108
+ if (!keepSecure && key === 'samesite' && /=\s*none\s*$/i.test(attribute)) {
109
+ kept.push('SameSite=Lax')
110
+ continue
111
+ }
112
+ kept.push(attribute)
113
+ }
114
+ return [pair.trim(), 'Path=/', ...kept].join('; ')
115
+ }
116
+
117
+ const HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']
118
+ const NOT_SENT = new Set([...HOP_BY_HOP, 'host', 'referer', 'content-length', 'accept-encoding'])
119
+ // `fetch` hands the body on decoded, so its length and encoding are no longer the answer's.
120
+ const NOT_RETURNED = new Set([...HOP_BY_HOP, 'content-length', 'content-encoding'])
121
+
122
+ function problem(res, status, title, detail) {
123
+ res.statusCode = status
124
+ res.setHeader('content-type', 'application/problem+json')
125
+ res.end(JSON.stringify({ status, title, detail }))
126
+ }
127
+
128
+ /** A request may still carry the site's base path; the address is the dev server's own. */
129
+ function withoutBase(url, base) {
130
+ const prefix = String(base || '/').replace(/\/+$/, '')
131
+ return prefix && (url === prefix || url.startsWith(`${prefix}/`)) ? url.slice(prefix.length) || '/' : url
132
+ }
@@ -24,6 +24,13 @@
24
24
  * A dev rebuild never ships: it empties `dist/` and writes no `entry-ssr.js`,
25
25
  * so `register` builds again before it uploads (`foundationNeedsBuild`).
26
26
  *
27
+ * ⭐ The one working copy that talks to a real backend is one served by
28
+ * `uniweb dev --published` (`../site/published.js`): it is answered by the
29
+ * published site's own services, which hold the types as `register` stored
30
+ * them, so it is stamped as a build is and sends `@acme/x` as the published
31
+ * site does [Diego, 2026-11-15]. It still ships nothing: a dev rebuild stays
32
+ * one.
33
+ *
27
34
  * An author's own `define` for the key wins: it is left untouched.
28
35
  */
29
36
 
@@ -33,6 +40,7 @@ import { loadFoundationConfig } from '../schema.js'
33
40
  import { foundationNameOf, splitFoundationName } from '../foundation-name.js'
34
41
  import { resolveFoundationSrcDir } from '../utils/foundation-source-root.js'
35
42
  import { hasDevRebuildMarker } from './dev-rebuild.js'
43
+ import { PUBLISHED_ENV } from '../site/published.js'
36
44
 
37
45
  export const FOUNDATION_SCOPE_KEY = '__FOUNDATION_SCOPE__'
38
46
 
@@ -48,7 +56,7 @@ export function foundationScopeDefine({ foundationDir } = {}) {
48
56
  name: 'uniweb:foundation-scope',
49
57
  async config(config, { command }) {
50
58
  if (config.define && FOUNDATION_SCOPE_KEY in config.define) return
51
- const workingCopy = command === 'serve' || hasDevRebuildMarker(config)
59
+ const workingCopy = (command === 'serve' || hasDevRebuildMarker(config)) && !process.env[PUBLISHED_ENV]
52
60
  const scope = workingCopy ? null : await foundationScope(foundationDir ?? config.root ?? process.cwd())
53
61
  return { define: { [FOUNDATION_SCOPE_KEY]: JSON.stringify(scope) } }
54
62
  },
@@ -42,6 +42,7 @@ import { libraryImports } from '../foundation/library-imports.js'
42
42
  import { copiedLibraries, copiedLibrariesWarning } from '../foundation/libraries.js'
43
43
  import { workspaceRootOf } from './workspace-extension.js'
44
44
  import { readPreview, PREVIEW_ENV } from './preview.js'
45
+ import { PUBLISHED_ENV } from './published.js'
45
46
  import { previewMediaPlugin } from './preview-media.js'
46
47
  import { previewDirectoryIndexPlugin } from './preview-directory-index.js'
47
48
  import { devServerRecordPlugin, requestedDevPort } from './dev-server.js'
@@ -439,6 +440,22 @@ export async function defineSiteConfig(options = {}) {
439
440
  }))
440
441
  }
441
442
 
443
+ if (process.env[PUBLISHED_ENV]) {
444
+ // ⛔ NOR DOES A PUBLISHED SITE'S. `uniweb dev --published` hands its dev server the
445
+ // services a published page carries, for that server alone (`./published.js`).
446
+ plugins.push({
447
+ name: 'uniweb:published-only',
448
+ config(_config, env) {
449
+ if (env.command === 'build') {
450
+ throw new Error(
451
+ `[site] ${PUBLISHED_ENV} is what \`uniweb dev --published\` read from a published ` +
452
+ 'site, for one dev server, and a build does not take it. Unset it to build.'
453
+ )
454
+ }
455
+ }
456
+ })
457
+ }
458
+
442
459
  if (preview) {
443
460
  // ⛔ A PREVIEW'S ANSWER NEVER REACHES A BUILT ARTIFACT. Where the backend serves a
444
461
  // version is decided at publish and read for one preview (`./preview.js`); written into
package/src/site/index.js CHANGED
@@ -10,6 +10,7 @@ export { siteContentPlugin } from './plugin.js'
10
10
  export { defineSiteConfig, readSiteConfig, default } from './config.js'
11
11
  // What `uniweb dev` hands the dev server of a site a backend holds (`./preview.js`).
12
12
  export { PREVIEW_ENV, encodePreview, readPreview } from './preview.js'
13
+ export { PUBLISHED_ENV, encodePublished, readPublished } from './published.js'
13
14
  // Where a site's dev server listens, as it states it, for `uniweb dev` (`./dev-server.js`).
14
15
  export { DEV_PORT_ENV, DEV_RECORD_ENV, runningDevServer, stopDevServer } from './dev-server.js'
15
16
  // Where a statically built site lives, as its deploy target or author states it (`./site-address.js`).
@@ -244,6 +244,9 @@ import { dataBlockModels, NO_DATA_MODELS } from '../i18n/data-models.js'
244
244
  import { refuseSearchOption } from './search-declared.js'
245
245
  import { mountDevApi } from '../dev/api-mount.js'
246
246
  import { mountDevSubmit } from '../dev/submit-mount.js'
247
+ import { mountPublished } from '../dev/published-mount.js'
248
+ import { readPublished, localServices, queriesInFull } from './published.js'
249
+ import { foundationScope } from '../foundation/scope-define.js'
247
250
 
248
251
  /**
249
252
  * A shell carrying the page's look by the runtime's own rule (`@uniweb/runtime/ssr`, which a
@@ -402,12 +405,24 @@ export function siteContentPlugin(options = {}) {
402
405
  // never in a build.
403
406
  let devApiAddress = null
404
407
  let devSubmitAddress = null
408
+ // Under `uniweb dev --published`, the published site's services instead, at the dev server's
409
+ // own addresses (`./published.js`): the host tier, as the published page carries it.
410
+ let publishedServices = null
411
+ // ...and the scope of the foundation's name, which names the site's queries in full there.
412
+ let publishedScope = null
405
413
  /**
406
414
  * The dev payload names those addresses as the site's `backend` and `submit` services:
407
415
  * the site tier, which `resolveService` reads when no host speaks. A build never gets
408
- * here with one.
416
+ * here with one. Under `--published` the dev server is the host, and its payload carries
417
+ * the host's block, as a published page does, and its queries with their types named in
418
+ * full, as the published page holds them (`queriesInFull`).
409
419
  */
410
420
  const withDevServices = (content) => {
421
+ if (publishedServices && content?.config) {
422
+ content.config.services = publishedServices
423
+ content.config.queries = queriesInFull(content.config.queries, publishedScope)
424
+ return content
425
+ }
411
426
  if (devApiAddress && content?.config) content.config.backend = devApiAddress
412
427
  if (devSubmitAddress && content?.config) content.config.submit = devSubmitAddress
413
428
  return content
@@ -659,6 +674,7 @@ export function siteContentPlugin(options = {}) {
659
674
  viteRoot = config.root
660
675
  isProduction = config.command === 'build'
661
676
  basePath = config.base || '/'
677
+ if (!isProduction && foundationPath && readPublished()) publishedScope = await foundationScope(foundationPath)
662
678
 
663
679
  // In dev mode, process collections early so JSON files exist before server starts
664
680
  // This runs before configureServer, ensuring data is available immediately
@@ -756,20 +772,32 @@ export function siteContentPlugin(options = {}) {
756
772
  // ⚠️ Synchronous on purpose — see mountDevApi. An await here and the
757
773
  // middleware lands after Vite's SPA fallback, which answers the API with
758
774
  // index.html and says nothing about why.
759
- try {
760
- devApiAddress = mountDevApi(devServer, { root: resolvedSitePath })
761
- } catch (err) {
762
- console.error(`[dev-api] ${err.message}`)
763
- }
775
+ //
776
+ // ⭐ `uniweb dev --published` answers every service the published site has with that
777
+ // site's own, forwarded (`../dev/published-mount.js`), so neither the mock nor the
778
+ // local form handler is mounted: the page talks to what visitors of the published site
779
+ // talk to. A handed value that says nothing usable stops the server here.
780
+ const published = readPublished()
781
+ if (published) {
782
+ const { services, targets } = localServices(published)
783
+ publishedServices = services
784
+ mountPublished(devServer, { targets, site: published.site, base: basePath })
785
+ } else {
786
+ try {
787
+ devApiAddress = mountDevApi(devServer, { root: resolvedSitePath })
788
+ } catch (err) {
789
+ console.error(`[dev-api] ${err.message}`)
790
+ }
764
791
 
765
- // A site's forms, taken locally in development when site.yml asks its host for
766
- // them (`services: { submit: true }`): the dev server is that host here, so a form
767
- // shows and can be sent before the site is published. Synchronous for the same
768
- // reason as the mount above.
769
- try {
770
- devSubmitAddress = mountDevSubmit(devServer, { root: resolvedSitePath, base: basePath })
771
- } catch (err) {
772
- console.error(`[dev-submit] ${err.message}`)
792
+ // A site's forms, taken locally in development when site.yml asks its host for
793
+ // them (`services: { submit: true }`): the dev server is that host here, so a form
794
+ // shows and can be sent before the site is published. Synchronous for the same
795
+ // reason as the mount above.
796
+ try {
797
+ devSubmitAddress = mountDevSubmit(devServer, { root: resolvedSitePath, base: basePath })
798
+ } catch (err) {
799
+ console.error(`[dev-submit] ${err.message}`)
800
+ }
773
801
  }
774
802
 
775
803
  // A site-relative workspace extension (`/effects/entry.js`) is served from
@@ -0,0 +1,162 @@
1
+ /**
2
+ * THE SITE AS PUBLISHED — what `uniweb dev --published` read from a published site, handed to the
3
+ * one dev server it starts.
4
+ *
5
+ * A site's services — its own `backend`, its `records`, its forms — are its host's to answer once
6
+ * the site is published, at addresses the host chooses. `uniweb dev --published` serves the working
7
+ * copy, its foundation and pages with live reload, against those services. `uniweb dev` reads the
8
+ * host's answer from the published page itself (`__DATA__`, `content.config.services`) and passes
9
+ * it in `UNIWEB_PUBLISHED`, as JSON:
10
+ *
11
+ * { site: 'https://…/', the published page the services were read from
12
+ * backend: 'https://…', the backend the site is published from
13
+ * base: '/' | null, that page's `config.base`
14
+ * services: { backend: '/_api', … } } the host's block, as the page carries it
15
+ *
16
+ * The dev server then plays the host (`../dev/published-mount.js`): its payload carries that block
17
+ * with each address replaced by one of its own, under `PUBLISHED_MOUNT`, and it forwards a request
18
+ * for one of those to the published address. The page sees one origin, so a sign-in cookie is
19
+ * first-party, as it is on the published site, and a query is answered by the site's records
20
+ * service, the entries its public queries open included, as a visitor's is.
21
+ *
22
+ * ⭐ Read, never composed. A host owns its services' addresses and states them in the page it
23
+ * serves (`@uniweb/core/services`), so one is resolved as the published page's runtime resolves it
24
+ * (`resolveServiceUrl`, with that page's base) and against that page's address, and nothing here
25
+ * knows a route.
26
+ *
27
+ * ⛔ Nothing keeps it. It lives as long as the dev server, as a preview does (`./preview.js`), and a
28
+ * build handed it refuses it (`./config.js`), so a published site's addresses never reach a built
29
+ * artifact.
30
+ */
31
+ import { readEndpoint, resolveServiceUrl } from '@uniweb/core/services'
32
+
33
+ /** The variable `uniweb dev --published` sets for the dev server it starts. */
34
+ export const PUBLISHED_ENV = 'UNIWEB_PUBLISHED'
35
+
36
+ /** Where the dev server answers the published site's services: `/_published/<service>/…`. */
37
+ export const PUBLISHED_MOUNT = '/_published'
38
+
39
+ /**
40
+ * The variable's value.
41
+ *
42
+ * @param {{ site: string, backend: string, base?: string|null, services: object }} published
43
+ * @returns {string}
44
+ */
45
+ export function encodePublished({ site, backend, base = null, services }) {
46
+ return JSON.stringify({ site, backend, base: typeof base === 'string' ? base : null, services })
47
+ }
48
+
49
+ /**
50
+ * What a dev server was handed, or null when it was handed nothing.
51
+ *
52
+ * @param {Record<string, string|undefined>} [env]
53
+ * @returns {{ site: string, backend: string, base: string|null, services: object }|null}
54
+ * @throws {Error} when the variable is set and says nothing usable: a dev server told to use a
55
+ * published site's services must not start on its own mock instead
56
+ */
57
+ export function readPublished(env = process.env) {
58
+ const raw = env[PUBLISHED_ENV]
59
+ if (!raw) return null
60
+ let given = null
61
+ try {
62
+ given = JSON.parse(raw)
63
+ } catch {
64
+ // reported below
65
+ }
66
+ if (!isHttpUrl(given?.site) || !isHttpUrl(given?.backend) || !isPlainObject(given?.services)) {
67
+ throw new Error(
68
+ `${PUBLISHED_ENV} holds no published site (${JSON.stringify(raw).slice(0, 120)}). ` +
69
+ 'It is set by `uniweb dev --published`; run that rather than setting it.'
70
+ )
71
+ }
72
+ return {
73
+ site: new URL(given.site).href,
74
+ backend: new URL(given.backend).origin,
75
+ base: typeof given.base === 'string' ? given.base : null,
76
+ services: given.services,
77
+ }
78
+ }
79
+
80
+ /**
81
+ * The services block the dev payload carries — the host's, each address replaced by one of the dev
82
+ * server's — and the origin each service forwards to.
83
+ *
84
+ * An address keeps everything after its origin as written, a `{locale}` slot included, under
85
+ * `/_published/<service>`: the published `records` at `/_query/{locale}` becomes
86
+ * `/_published/records/_query/{locale}`, and a request for `/_published/records/_query/fr` goes to
87
+ * `<its origin>/_query/fr`. A service the host names with no address is carried as it is: the host
88
+ * answered, and offered none.
89
+ *
90
+ * @param {{ site: string, base?: string|null, services: object }} published - from `readPublished`
91
+ * @returns {{ services: object, targets: Record<string, string> }} targets: service → origin
92
+ */
93
+ export function localServices({ site, base = null, services }) {
94
+ const local = {}
95
+ const targets = {}
96
+ for (const [name, value] of Object.entries(services)) {
97
+ const endpoint = readEndpoint(value)
98
+ if (!endpoint || !SERVICE_NAME.test(name)) {
99
+ local[name] = value
100
+ continue
101
+ }
102
+ const { origin, rest } = splitAddress(resolveServiceUrl(endpoint, base || ''), site)
103
+ targets[name] = origin
104
+ const address = `${PUBLISHED_MOUNT}/${name}${rest}`
105
+ local[name] = typeof value === 'string' ? address : { ...value, endpoint: address }
106
+ }
107
+ return { services: local, targets }
108
+ }
109
+
110
+ /**
111
+ * The site's queries as the published page carries them: each `schema` the copy spells `@/x` named
112
+ * in full, `<scope>/x`, with the scope of the foundation's name. A backend matches a type's name
113
+ * exactly, and a published page holds its queries as the backend registered them, so a records ask
114
+ * for `@/course` finds nothing there. Every other value is left as written, and so is every query
115
+ * when the foundation's name has no scope.
116
+ *
117
+ * @param {object|undefined} queries - the payload's `config.queries`
118
+ * @param {string|null} scope - `@acme` for `@acme/courses`
119
+ * @returns {object|undefined}
120
+ */
121
+ export function queriesInFull(queries, scope) {
122
+ if (!isPlainObject(queries) || typeof scope !== 'string' || !scope.startsWith('@')) return queries
123
+ const full = {}
124
+ for (const [name, query] of Object.entries(queries)) {
125
+ const schema = query?.schema
126
+ full[name] =
127
+ isPlainObject(query) && typeof schema === 'string' && schema.startsWith('@/')
128
+ ? { ...query, schema: `${scope}/${schema.slice(2)}` }
129
+ : query
130
+ }
131
+ return full
132
+ }
133
+
134
+ // A segment of the dev server's own address, so only a name that is one.
135
+ const SERVICE_NAME = /^[A-Za-z0-9_-]+$/
136
+
137
+ /**
138
+ * An address the runtime would ask, split into the origin it goes to and the rest, kept as written
139
+ * so a `{locale}` slot survives: `new URL` would encode the braces.
140
+ */
141
+ function splitAddress(address, site) {
142
+ const absolute = /^((?:[a-z][a-z0-9+.-]*:)?\/\/[^/?#]*)(.*)$/i.exec(address)
143
+ if (absolute) {
144
+ const [, head, tail] = absolute
145
+ const origin = new URL(head.startsWith('//') ? `${new URL(site).protocol}${head}` : head).origin
146
+ return { origin, rest: tail.startsWith('/') ? tail : `/${tail}` }
147
+ }
148
+ return { origin: new URL(site).origin, rest: address.startsWith('/') ? address : `/${address}` }
149
+ }
150
+
151
+ // ⛔ `new URL('localhost:8080')` parses — as the scheme `localhost:` — so a URL is http(s) or nothing.
152
+ function isHttpUrl(value) {
153
+ try {
154
+ return /^https?:$/.test(new URL(value).protocol)
155
+ } catch {
156
+ return false
157
+ }
158
+ }
159
+
160
+ function isPlainObject(value) {
161
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
162
+ }
@@ -157,9 +157,10 @@ const looksLikeAddress = (v) => v.startsWith('/') || /^https?:\/\//i.test(v)
157
157
 
158
158
  /**
159
159
  * Whether two references name the same stored file: the same string, or two references the map gives
160
- * one asset id. A backend keeps a file by its bytes, so two files with the same bytes are one asset, with
161
- * one id and one served address. A stored reference to it says nothing of which path it came from, and
162
- * `restoreAssetRefs` gives it the first path the map lists.
160
+ * one asset id — a path it keeps, or the address the host serves one at. A backend keeps a file by its
161
+ * bytes, so two files with the same bytes are one asset, with one id and one served address. A stored
162
+ * reference to it says nothing of which path it came from, and `restoreAssetRefs` gives it the first
163
+ * path the map lists.
163
164
  *
164
165
  * A relative reference is read from the file it is written in (`fromFile`), as the push keyed it
165
166
  * (`located-media.js::siteFileKey`).
@@ -174,10 +175,23 @@ const looksLikeAddress = (v) => v.startsWith('/') || /^https?:\/\//i.test(v)
174
175
  * @returns {(a: string, b: string, fromFile?: string|null) => boolean}
175
176
  */
176
177
  export function sameStoredFile(map, { siteRoot = null, tree = () => [] } = {}) {
178
+ const byServed = new Map()
179
+ for (const v of Object.values(map || {})) {
180
+ if (v?.served && v?.id && !byServed.has(v.served)) byServed.set(v.served, v.id)
181
+ }
177
182
  const idOf = (ref, fromFile) => {
178
183
  if (typeof ref !== 'string' || !ref) return null
179
184
  const own = map?.[ref]?.id
180
185
  if (own) return own
186
+ // ⭐ An address the host serves a stored file at names that file, by the fingerprint a push
187
+ // recorded for it (`servedFingerprint`), as `restoreAssetRefs` reads it. ⛔ Until 2026-11-16
188
+ // only a path did, so a `site.yml` naming its favicon by the host's address came back as the
189
+ // path of a file of the same bytes the site had just begun to use (`/favicon.svg`), and
190
+ // `uniweb status` called that a change on the backend (measured on a site, 2026-11-16).
191
+ if (looksLikeAddress(ref)) {
192
+ const served = byServed.get(servedFingerprint(ref))
193
+ if (served) return served
194
+ }
181
195
  if (!siteRoot || !fromFile || ref.startsWith('/') || /^[a-z][a-z0-9+.-]*:/i.test(ref)) return null
182
196
  const key = siteFileKey(siteRoot, resolve(dirname(fromFile), ref), tree())
183
197
  return (key && map?.[key]?.id) || null
package/src/uwx/folder.js CHANGED
@@ -159,8 +159,19 @@ function recordOf(item) {
159
159
 
160
160
  /**
161
161
  * Walk a folder document's `contents` tree, visiting every item with the keys that
162
- * address it: its slash-joined `name` chain, whether that chain is UNIQUE among its
163
- * siblings, and — for a leaf — the uuid of the record it references.
162
+ * address it: its slash-joined `name` chain, whether that chain names it alone
163
+ * (`unique`), and — for a leaf — the uuid of the record it references.
164
+ *
165
+ * ⭐ A SUB-FOLDER'S CHAIN NAMES IT WHATEVER RECORDS SIT BESIDE IT. `folder.yml` refuses two
166
+ * sub-folders of one name at one level (`site/records-config.js::resolveFolder`), so a branch
167
+ * is counted among the branches beside it. A leaf's chain names it only when nothing beside
168
+ * it, branch or leaf, has its name: a leaf has its record's key, and never takes a branch's.
169
+ * ⛔ Until 2026-11-16 a branch was counted among every item beside it, so a record named like
170
+ * a sub-folder (`template/blog` at the top, beside the sub-folder `blog`) left the sub-folder
171
+ * with no key. A key an earlier push had banked kept it bound while the map was merged; once
172
+ * the map was written whole (2026-11-13), the next push sent the sub-folder with no `$uuid`,
173
+ * as a new item, and the backend refused it: "409 Conflict — another item already has this
174
+ * name" (measured on a site, 2026-11-15).
164
175
  *
165
176
  * ⛔ IT MUST RECURSE INTO `$children`. `contents` is SELF-NESTING: a walk of the
166
177
  * top level sees the branches and misses every record under them — which is 6 of
@@ -170,13 +181,17 @@ function recordOf(item) {
170
181
  function walkFolderItems(contents, cb, prefix = '') {
171
182
  const items = (contents || []).filter((item) => item && typeof item === 'object')
172
183
  const count = new Map()
184
+ const branches = new Map()
173
185
  for (const item of items) {
174
- if (typeof item.name === 'string') count.set(item.name, (count.get(item.name) || 0) + 1)
186
+ if (typeof item.name !== 'string') continue
187
+ count.set(item.name, (count.get(item.name) || 0) + 1)
188
+ if (item.kind === 'branch') branches.set(item.name, (branches.get(item.name) || 0) + 1)
175
189
  }
176
190
  for (const item of items) {
177
191
  const seg = typeof item.name === 'string' ? item.name : null
178
192
  const path = seg ? (prefix ? `${prefix}/${seg}` : seg) : prefix
179
- if (seg) cb({ path, unique: count.get(seg) === 1, record: recordOf(item) }, item)
193
+ const unique = item.kind === 'branch' ? branches.get(seg) === 1 : count.get(seg) === 1
194
+ if (seg) cb({ path, unique, record: recordOf(item) }, item)
180
195
  walkFolderItems(item.$children, cb, path)
181
196
  }
182
197
  }
@@ -186,8 +201,9 @@ function walkFolderItems(contents, cb, prefix = '') {
186
201
  *
187
202
  * ⭐ A PLACEMENT IS KEYED BY THE RECORD IT REFERENCES — `@<record uuid>` — because a
188
203
  * record has one placement, so that key is unique in the folder whatever the names
189
- * are. A branch, and a leaf whose name no sibling shares, is ALSO keyed by its `name`
190
- * chain, which is what every placement map banked before 2026-09-21 holds.
204
+ * are. A branch is keyed by its `name` chain, and so is a leaf whose name nothing beside
205
+ * it shares (`walkFolderItems`), which is what every placement map banked before
206
+ * 2026-09-21 holds.
191
207
  *
192
208
  * ⛔ The chain alone assumed no two siblings share a name. Two records of different
193
209
  * schemas can (`article/intro`, `person/intro`), and keyed by `intro` both would
@@ -240,7 +256,8 @@ export function collectFolderRecordTypes(doc) {
240
256
  * by a comment in this file that was true of the entity and false of its contents.
241
257
  *
242
258
  * ⭐ A leaf takes the uuid banked under its record (`@<record uuid>`) first, and its
243
- * `name` chain only when no sibling shares the name — the one key an older map has.
259
+ * `name` chain only when no sibling shares the name — the one key an older map has. A
260
+ * branch takes its chain's, which no other branch beside it has.
244
261
  * ⛔ No uuid is stamped twice: two items claiming one row is the failure the record
245
262
  * key exists to prevent, so a second claimant goes out without one, as a new row.
246
263
  *
package/src/uwx/index.js CHANGED
@@ -50,14 +50,18 @@ export {
50
50
  extensionDeclaration,
51
51
  isExtensionUrl,
52
52
  isSiteRelativeExtensionUrl,
53
+ buildRouteOf,
53
54
  } from './site.js'
55
+ // A `page:` reference read as the runtime reads one — a page's id, else its route — over pages a
56
+ // caller lists (`uniweb promote` names a post's page so, on the site as pushed).
57
+ export { pageRefIndex } from './page-refs.js'
54
58
  export {
55
59
  resolveQueriesConfig,
56
60
  queriesYmlPath,
57
61
  QUERIES_YML_RELPATH,
58
62
  } from './queries-config.js'
59
63
  // Edits to a YAML file an author wrote — the one editor; files are written through project-writer.js.
60
- export { editYamlText, setYamlKey, replaceInYamlList } from './yaml-edit.js'
64
+ export { editYamlText, setYamlKey, setYamlKeyFirst, replaceInYamlList } from './yaml-edit.js'
61
65
  export { buildFolderEntity,
62
66
  collectFolderItemUuids,
63
67
  collectFolderRecordTypes,
@@ -313,8 +313,9 @@ function loadYamlFile(filePath) {
313
313
  // rewritten, and every comment, blank line and list the author wrote stays (`editYamlText`). ⛔ Until then
314
314
  // every writer here dumped the whole file — a pull that changed one key of `site.yml` left the Starter
315
315
  // template's 93 lines as 10, and a `pull --merge` conflicted on the whole commented header. The whole dump
316
- // remains for a file with nothing to keep (none yet, unreadable) and one the editor declines (an alias or a
317
- // `<<` merge key, or a result that would read differently).
316
+ // remains for a file with nothing to keep (none yet, unreadable) and one the editor declines (a `<<` merge
317
+ // key in the file's own map, or a result that would read differently). An anchor and its aliases no longer
318
+ // stop an edit (2026-11-16).
318
319
  function writeYamlIfChanged(filePath, value, prior) {
319
320
  if (prior.read && canonicalJson(value) === canonicalJson(prior.value)) return 'unchanged'
320
321
  const edited = prior.read ? editYamlText(prior.text, prior.value, value, YAML_DUMP_OPTS) : null
@@ -20,7 +20,7 @@
20
20
  // beside a comment, a new key PREPENDED above a file's header comments.*
21
21
 
22
22
  import yaml from 'js-yaml'
23
- import { parseDocument, isMap, isSeq, isScalar, Scalar, visit } from 'yaml'
23
+ import { parseDocument, isAlias, isMap, isSeq, isScalar, Scalar } from 'yaml'
24
24
  import { YAML_OPTIONS } from '../utils/yaml-schema.js'
25
25
 
26
26
  /** js-yaml's options for every value the framework writes into YAML, so output is byte-stable. */
@@ -48,7 +48,8 @@ function columnOf(text, key) {
48
48
  /**
49
49
  * Where a pair's text ends: after its value, its trailing comment and its newline.
50
50
  *
51
- * ⛔ A SCALAR ENDS WHERE ITS OWN TEXT DOES — `range[1]`, then the rest of that line. Its
51
+ * ⛔ A SCALAR ENDS WHERE ITS OWN TEXT DOES — `range[1]`, then the rest of that line, and so
52
+ * does an alias (`*persona`). Its
52
53
  * `range[2]` also spans the comment lines that follow it, and for an empty value (`team:`)
53
54
  * every comment and blank line up to the next key, at any indentation: those belong to what
54
55
  * comes next. ⛔ Until 2026-10-08 this read `range[2]`, and a pull that gave a bare `team:` its
@@ -56,7 +57,7 @@ function columnOf(text, key) {
56
57
  */
57
58
  function pairEnd(text, pair) {
58
59
  const node = pair.value ?? pair.key
59
- let end = isScalar(node) ? node.range[1] : node.range[2]
60
+ let end = isScalar(node) || isAlias(node) ? node.range[1] : node.range[2]
60
61
  if (text[end - 1] !== '\n') {
61
62
  const nl = text.indexOf('\n', end)
62
63
  const rest = nl === -1 ? text.slice(end) : text.slice(end, nl)
@@ -75,22 +76,69 @@ function indented(text, col, first) {
75
76
  .join('\n')
76
77
  }
77
78
 
78
- /** An alias or a `<<` merge key: one edit could change what another place says. */
79
- function usesReferences(doc) {
80
- let found = false
81
- visit(doc, {
82
- Alias() {
83
- found = true
84
- return visit.BREAK
85
- },
86
- Pair(_, pair) {
87
- if (isScalar(pair.key) && pair.key.value === '<<') {
88
- found = true
89
- return visit.BREAK
79
+ /** A map that merges another into it (`<<: *base`): some of what it says is not its own to edit. */
80
+ const holdsMergeKey = (map) => map.items.some((pair) => isScalar(pair.key) && pair.key.value === '<<')
81
+
82
+ /** What a value read from YAML holds at `path` (keys and list indexes); undefined where it holds nothing. */
83
+ function valueAt(value, path) {
84
+ let v = value
85
+ for (const step of path) {
86
+ if (v === null || typeof v !== 'object') return undefined
87
+ v = v[step]
88
+ }
89
+ return v
90
+ }
91
+
92
+ /**
93
+ * Every place whose value another place gives it: each alias (`*persona`), with the path of the
94
+ * anchor it names (`&persona`), and each map that merges another into it (`<<`). Walked in the
95
+ * file's order, so an alias names the last anchor of its name before it, as YAML reads it.
96
+ */
97
+ function referencesOf(root) {
98
+ const places = []
99
+ const anchorPathOf = new Map()
100
+ const anchors = new Map()
101
+ const walk = (node, path) => {
102
+ if (!node) return
103
+ if (isAlias(node)) {
104
+ places.push({ node, path })
105
+ if (anchors.has(node.source)) anchorPathOf.set(node, anchors.get(node.source))
106
+ return
107
+ }
108
+ if (node.anchor) anchors.set(node.anchor, path)
109
+ if (isMap(node)) {
110
+ if (holdsMergeKey(node)) places.push({ node, path })
111
+ for (const pair of node.items) {
112
+ if (!isScalar(pair.key) || pair.key.value === '<<') continue
113
+ walk(pair.value, [...path, String(pair.key.value)])
90
114
  }
115
+ } else if (isSeq(node)) {
116
+ node.items.forEach((item, i) => walk(item, [...path, i]))
91
117
  }
92
- })
93
- return found
118
+ }
119
+ walk(root, [])
120
+ return { places, anchorPathOf }
121
+ }
122
+
123
+ /** Whether an alias, left as it is, says `value`: whether its anchor's place is to say it. */
124
+ function aliasHolds(cx, alias, value) {
125
+ const at = cx.anchorPathOf.get(alias)
126
+ return at !== undefined && sameValue(valueAt(cx.after, at), value)
127
+ }
128
+
129
+ /** Whether `node`, or anything in it, is a place that must be written as its own value. */
130
+ function holdsForced(cx, node) {
131
+ if (!cx.force.size || !node) return false
132
+ if (cx.force.has(node)) return true
133
+ if (isMap(node)) return node.items.some((pair) => holdsForced(cx, pair.value))
134
+ if (isSeq(node)) return node.items.some((item) => holdsForced(cx, item))
135
+ return false
136
+ }
137
+
138
+ /** `key: value` as js-yaml writes it, with the value's anchor kept: `key: &persona value`. */
139
+ function anchored(whole, key, anchor, dump) {
140
+ const head = dump({ [key]: null }).replace(/ null\n$/, '')
141
+ return whole.startsWith(head) ? `${head} &${anchor}${whole.slice(head.length)}` : whole
94
142
  }
95
143
 
96
144
  /**
@@ -117,15 +165,20 @@ function scalarText(text, node, value, dump, inFlow) {
117
165
  /**
118
166
  * Make one list say `after` — `before` is what it says now, the same length — by
119
167
  * rewriting each changed entry where it stands. False for anything else (a list that
120
- * grew or shrank, an entry that is not a one-line scalar): the caller writes it whole.
168
+ * grew or shrank, an entry that is not a one-line scalar, an alias that would no longer
169
+ * say its entry): the caller writes it whole.
121
170
  */
122
- function editSeq(text, seq, before, after, edits, dump) {
171
+ function editSeq(cx, seq, before, after, edits) {
123
172
  if (seq.items.length !== before.length || before.length !== after.length) return false
124
173
  const inner = []
125
174
  for (let i = 0; i < after.length; i++) {
126
- if (sameValue(before[i], after[i])) continue
127
175
  const node = seq.items[i]
128
- const now = isScalar(node) ? scalarText(text, node, after[i], dump, seq.flow) : null
176
+ if (isAlias(node)) {
177
+ if (!cx.force.has(node) && aliasHolds(cx, node, after[i])) continue
178
+ return false
179
+ }
180
+ if (sameValue(before[i], after[i]) && !holdsForced(cx, node)) continue
181
+ const now = isScalar(node) ? scalarText(cx.text, node, after[i], cx.dump, seq.flow) : null
129
182
  if (now === null) return false
130
183
  inner.push({ start: node.range[0], end: node.range[1], text: now })
131
184
  }
@@ -137,11 +190,14 @@ function editSeq(text, seq, before, after, edits, dump) {
137
190
  * Make one block map say `after` — `before` is what it says now — by edits to its own
138
191
  * entries: a removed key's lines go, a changed scalar is rewritten where it stands, a
139
192
  * changed map or same-length list is edited the same way one level down, anything else
140
- * is written whole in its place, and a new key goes after the last one. False when the
141
- * map is not one this can edit (a key that is not a plain scalar, or not first on its line).
193
+ * is written whole in its place, and a new key goes after the last one. An alias stays
194
+ * where its anchor's place is to say what it says, and is written as its own value where
195
+ * not; a value written whole keeps its anchor. False when the map is not one this can edit
196
+ * (a key that is not a plain scalar, or not first on its line, or a `<<` merge key).
142
197
  */
143
- function editMap(text, map, before, after, edits, dump) {
144
- if (!map.items.length || !map.items[0].key?.range) return false
198
+ function editMap(cx, map, before, after, edits) {
199
+ const { text, dump } = cx
200
+ if (!map.items.length || !map.items[0].key?.range || holdsMergeKey(map)) return false
145
201
  const col = columnOf(text, map.items[0].key)
146
202
  if (col === null) return false
147
203
  const seen = new Set()
@@ -158,44 +214,49 @@ function editMap(text, map, before, after, edits, dump) {
158
214
  edits.push({ start: lineStart(text, pair.key.range[0]), end: stop, text: '' })
159
215
  continue
160
216
  }
161
- if (Object.hasOwn(before, key) && sameValue(before[key], after[key])) continue
162
217
  const next = after[key]
163
- const inner = []
164
- if (isMap(value) && !value.flow && isPlainObject(before[key]) && isPlainObject(next)) {
165
- if (editMap(text, value, before[key], next, inner, dump)) {
166
- edits.push(...inner)
167
- continue
218
+ if (isAlias(value)) {
219
+ // ⭐ An alias stays where its anchor's place is to say what this one says; written whole
220
+ // below where it is not, as its own value.
221
+ if (!cx.force.has(value) && aliasHolds(cx, value, next)) continue
222
+ } else {
223
+ if (Object.hasOwn(before, key) && sameValue(before[key], next) && !holdsForced(cx, value)) continue
224
+ const inner = []
225
+ if (isMap(value) && !value.flow && isPlainObject(before[key]) && isPlainObject(next)) {
226
+ if (editMap(cx, value, before[key], next, inner)) {
227
+ edits.push(...inner)
228
+ continue
229
+ }
230
+ } else if (isSeq(value) && Array.isArray(before[key]) && Array.isArray(next)) {
231
+ if (editSeq(cx, value, before[key], next, inner)) {
232
+ edits.push(...inner)
233
+ continue
234
+ }
235
+ } else if (isScalar(value)) {
236
+ const now = scalarText(text, value, next, dump, false)
237
+ if (now !== null) {
238
+ edits.push({ start: value.range[0], end: value.range[1], text: now })
239
+ continue
240
+ }
168
241
  }
169
- } else if (isSeq(value) && Array.isArray(before[key]) && Array.isArray(next)) {
170
- if (editSeq(text, value, before[key], next, inner, dump)) {
171
- edits.push(...inner)
172
- continue
173
- }
174
- } else if (isScalar(value)) {
175
- const now = scalarText(text, value, next, dump, false)
176
- if (now !== null) {
177
- edits.push({ start: value.range[0], end: value.range[1], text: now })
178
- continue
242
+ // ⭐ A BARE KEY GIVEN A VALUE KEEPS ITS LINE — and any comment the author wrote on it — and
243
+ // the value goes under it: `team: # the people` gains ` schema: '@/team'` beneath.
244
+ const bare = isScalar(value) && value.value === null && value.range[0] === value.range[1]
245
+ if (bare && (isPlainObject(next) || Array.isArray(next))) {
246
+ const whole = indented(dump({ [key]: next }), col, false)
247
+ const nl = whole.indexOf('\n')
248
+ if (nl !== -1 && nl < whole.length - 1) {
249
+ edits.push({ start: stop, end: stop, text: (text[stop - 1] === '\n' ? '' : '\n') + whole.slice(nl + 1) })
250
+ continue
251
+ }
179
252
  }
180
253
  }
181
- // ⭐ A BARE KEY GIVEN A VALUE KEEPS ITS LINE — and any comment the author wrote on it — and
182
- // the value goes under it: `team: # the people` gains ` schema: '@/team'` beneath.
183
- const bare = isScalar(value) && value.value === null && value.range[0] === value.range[1]
184
- if (bare && (isPlainObject(next) || Array.isArray(next))) {
185
- const whole = indented(dump({ [key]: next }), col, false)
186
- const nl = whole.indexOf('\n')
187
- if (nl !== -1 && nl < whole.length - 1) {
188
- edits.push({ start: stop, end: stop, text: (text[stop - 1] === '\n' ? '' : '\n') + whole.slice(nl + 1) })
189
- continue
190
- }
191
- }
192
- // Written whole — in flow style when the author wrote it that way (`tags: [a, b]`).
254
+ // Written whole — in flow style when the author wrote it that way (`tags: [a, b]`), and
255
+ // with its anchor, so an alias that names it still does.
193
256
  const flow = (isMap(value) || isSeq(value)) && value.flow
194
- edits.push({
195
- start: pair.key.range[0],
196
- end: stop,
197
- text: indented(dump({ [key]: next }, flow ? { flowLevel: 1 } : {}), col, false)
198
- })
257
+ let whole = dump({ [key]: next }, flow ? { flowLevel: 1 } : {})
258
+ if (!isAlias(value) && value?.anchor) whole = anchored(whole, key, value.anchor, dump)
259
+ edits.push({ start: pair.key.range[0], end: stop, text: indented(whole, col, false) })
199
260
  }
200
261
  for (const key of Object.keys(after)) {
201
262
  if (seen.has(key) || after[key] === undefined) continue
@@ -224,12 +285,24 @@ function editMap(text, map, before, after, edits, dump) {
224
285
  * of `site.yml` left the Starter template's 93 lines as 10 — every comment gone — and a
225
286
  * `pull --merge` then conflicted on the whole commented header (F1, F12).*
226
287
  *
288
+ * ⭐ AN ANCHOR AND ITS ALIASES STAY. A value written once and named again (`&persona` …
289
+ * `*persona`) is edited where its anchor is, and an alias stays wherever its anchor's place
290
+ * is to say what it says. Where it is not (the app changed one of the two places), the
291
+ * alias's place is written as its own value: an edit that changed what an alias says is
292
+ * found by the read back, and made again with that place written whole. ⛔ Until 2026-11-16
293
+ * any alias or `<<` merge key made the engine decline the file, and the writer then dumped
294
+ * it whole: a pull that changed one key of a docs site's `site.yml` took all its comments,
295
+ * turned its anchor into two copies and a folded `>` block into `|` (measured on a site,
296
+ * 2026-11-16). A map that merges another into it (`<<`) is still written whole by the map it
297
+ * is in, and the file whole when it is the file's own.
298
+ *
227
299
  * @param {string} text - the file as it is
228
300
  * @param {object} before - what it says, read by the build's reader
229
301
  * @param {object} after - what it must say
230
302
  * @param {object} [dumpOptions] - js-yaml's, for what is written
231
303
  * @returns {string|null} the edited text; null when the file cannot be edited in place —
232
- * not a map, an alias or merge key, a parse error, or a result that reads differently
304
+ * not a map, a `<<` merge key in the file's own map, a parse error, or a result that
305
+ * reads differently
233
306
  */
234
307
  export function editYamlText(text, before, after, dumpOptions = YAML_DUMP_OPTS) {
235
308
  if (typeof text !== 'string' || !isPlainObject(before) || !isPlainObject(after)) return null
@@ -239,29 +312,51 @@ export function editYamlText(text, before, after, dumpOptions = YAML_DUMP_OPTS)
239
312
  } catch {
240
313
  return null
241
314
  }
242
- if (doc.errors.length || usesReferences(doc)) return null
315
+ if (doc.errors.length) return null
243
316
  const dump = (value, extra = {}) => yaml.dump(value, { ...dumpOptions, ...extra })
244
- const edits = []
245
317
  if (doc.contents === null || doc.contents === undefined) {
246
318
  // Comments and nothing else: what the file says goes after them.
247
- const lead = text && !text.endsWith('\n') ? '\n' : ''
248
- edits.push({ start: text.length, end: text.length, text: lead + dump(after) })
249
- } else if (!isMap(doc.contents) || doc.contents.flow || !editMap(text, doc.contents, before, after, edits, dump)) {
250
- return null
319
+ const out = text + (text && !text.endsWith('\n') ? '\n' : '') + dump(after)
320
+ return sameValue(readOrUndefined(out), after) ? out : null
251
321
  }
252
- // Last first, so an offset is never moved by an edit before it. At one offset: a removal
253
- // before an insertion, and the outer map's new keys before the inner map's, so the inner
254
- // map's land first in the text.
322
+ if (!isMap(doc.contents) || doc.contents.flow) return null
323
+ const { places, anchorPathOf } = referencesOf(doc.contents)
324
+ const cx = { text, dump, after, anchorPathOf, force: new Set() }
325
+ // Each round writes at least one more place as its own value, so there are at most as many
326
+ // rounds as places.
327
+ for (;;) {
328
+ const edits = []
329
+ if (!editMap(cx, doc.contents, before, after, edits)) return null
330
+ const out = applyEdits(text, edits)
331
+ const read = readOrUndefined(out)
332
+ if (read !== undefined && sameValue(read, after)) return out
333
+ // A place another gives its value to that does not say what `after` says there — or every
334
+ // one, when an anchor was lost and the text no longer reads — is written as its own value.
335
+ const wrong = places.filter(
336
+ (p) => !cx.force.has(p.node) && (read === undefined || !sameValue(valueAt(read, p.path), valueAt(after, p.path)))
337
+ )
338
+ if (!wrong.length) return null
339
+ for (const p of wrong) cx.force.add(p.node)
340
+ }
341
+ }
342
+
343
+ // Last first, so an offset is never moved by an edit before it. At one offset: a removal
344
+ // before an insertion, and the outer map's new keys before the inner map's, so the inner
345
+ // map's land first in the text.
346
+ function applyEdits(text, edits) {
255
347
  const order = edits.map((e, i) => ({ ...e, i })).sort((a, b) => b.start - a.start || b.end - a.end || b.i - a.i)
256
348
  let out = text
257
349
  for (const e of order) out = out.slice(0, e.start) + e.text + out.slice(e.end)
258
- let read
350
+ return out
351
+ }
352
+
353
+ /** What `text` says, as the build reads it — undefined when it does not read. */
354
+ function readOrUndefined(text) {
259
355
  try {
260
- read = yaml.load(out, YAML_OPTIONS) ?? {}
356
+ return yaml.load(text, YAML_OPTIONS) ?? {}
261
357
  } catch {
262
- return null
358
+ return undefined
263
359
  }
264
- return sameValue(read, after) ? out : null
265
360
  }
266
361
 
267
362
  /** What `text` says, as the build reads it — null when it is not YAML, or not a map. */
@@ -301,7 +396,8 @@ export function setYamlKey(text, key, value) {
301
396
  * @param {string} key
302
397
  * @param {*} value
303
398
  * @returns {string|null} the new contents; null when the text cannot be edited in place — not a
304
- * block map, an alias or merge key, a parse error, or a result that reads differently
399
+ * block map, a parse error, or a result that reads differently. A line before the first key
400
+ * changes nothing an anchor or an alias says, so neither stops it.
305
401
  */
306
402
  export function setYamlKeyFirst(text, key, value) {
307
403
  const before = readMap(text)
@@ -313,7 +409,7 @@ export function setYamlKeyFirst(text, key, value) {
313
409
  } catch {
314
410
  return null
315
411
  }
316
- if (doc.errors.length || usesReferences(doc)) return null
412
+ if (doc.errors.length) return null
317
413
  const line = yaml.dump({ [key]: value }, YAML_DUMP_OPTS)
318
414
  let out
319
415
  if (doc.contents === null || doc.contents === undefined) {