@heroiclands/package-build 23.4.1 → 23.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +29 -25
  3. package/assets/images/provenance.yaml +1 -0
  4. package/bin/package-build.mjs +259 -101
  5. package/ci/prettier.mjs +73 -0
  6. package/config.mjs +10 -0
  7. package/container.mjs +232 -1
  8. package/content-config.mjs +5 -1
  9. package/docs/api.md +100 -52
  10. package/docs/authoring/assets.md +16 -1
  11. package/docs/commands.md +154 -51
  12. package/docs/configuration.md +39 -2
  13. package/docs/content-format.md +30 -6
  14. package/docs/diagnostics.md +1 -2
  15. package/docs/guides/e2e.md +38 -0
  16. package/docs/guides/icons.md +5 -0
  17. package/docs/guides/module-project.md +1 -1
  18. package/docs/guides/release-and-deploy.md +36 -1
  19. package/docs/project-setup.md +16 -59
  20. package/docs/reference/format-details.md +180 -34
  21. package/docs/reference/note-types.md +69 -69
  22. package/engine/asset-index.mjs +63 -22
  23. package/engine/asset-references.mjs +355 -0
  24. package/engine/asset-shipping.mjs +363 -0
  25. package/engine/asset-types.mjs +70 -0
  26. package/engine/base-compiler.mjs +24 -1
  27. package/engine/cdn-publish.mjs +643 -0
  28. package/engine/index.mjs +6 -0
  29. package/engine/note-vocabulary.mjs +4 -1
  30. package/engine/pathnames.mjs +21 -10
  31. package/engine/project-init.mjs +4 -29
  32. package/engine/rank-ladder.mjs +40 -16
  33. package/engine/scenes.mjs +1 -1
  34. package/engine/standing-terms.mjs +3 -1
  35. package/package.json +5 -6
  36. package/packagebuild-metadata.jsonl +13 -13
  37. package/release.mjs +69 -7
  38. package/sohl/actors.mjs +12 -4
  39. package/sohl/default-item-art.mjs +23 -19
  40. package/types/config.d.mts +7 -0
  41. package/types/container.d.mts +137 -1
  42. package/types/engine/asset-index.d.mts +3 -2
  43. package/types/engine/asset-references.d.mts +136 -0
  44. package/types/engine/asset-shipping.d.mts +240 -0
  45. package/types/engine/asset-types.d.mts +36 -0
  46. package/types/engine/base-compiler.d.mts +7 -1
  47. package/types/engine/cdn-publish.d.mts +312 -0
  48. package/types/engine/index.d.mts +2 -0
  49. package/types/engine/pathnames.d.mts +2 -1
  50. package/types/engine/rank-ladder.d.mts +25 -6
  51. package/types/release.d.mts +5 -3
  52. package/types/sohl/default-item-art.d.mts +2 -1
  53. package/labels.mjs +0 -191
  54. package/types/labels.d.mts +0 -40
@@ -0,0 +1,643 @@
1
+ /*
2
+ * This file is part of the Song of Heroic Lands (SoHL) system for Foundry VTT.
3
+ * Copyright (c) 2024-2026 Tom Rodriguez ("Toasty") — <toasty@heroiclands.org>
4
+ *
5
+ * This work is licensed under the GNU General Public License v3.0 (GPLv3).
6
+ * You may copy, modify, and distribute it under the terms of that license.
7
+ *
8
+ * For full terms, see the LICENSE.md file in the project root or visit:
9
+ * https://www.gnu.org/licenses/gpl-3.0.html
10
+ *
11
+ * SPDX-License-Identifier: GPL-3.0-or-later
12
+ */
13
+
14
+ /**
15
+ * `package-build cdn publish` — every picture a package has, on the CDN, and
16
+ * the art the package leaves out as a named asset set.
17
+ *
18
+ * **The layout is the deployed one.** Each icon and image is uploaded flat, as
19
+ * `icons/<basename>` or `images/<basename>`, under `<site.assets>/<package>/`
20
+ * — the address {@link module:engine/pathnames.resolvePathname} gives the
21
+ * website for the same file, so the site and the CDN agree by construction.
22
+ * Shipped and excluded pictures both go up: the website shows all of them.
23
+ *
24
+ * **The bucket is served at `site.assets`.** An object's key is its path below
25
+ * that URL, `<package>/images/<basename>`, so the key and the public address
26
+ * differ only by the host.
27
+ *
28
+ * **The bytes are the staged bytes.** The repository's `assetTransform` runs
29
+ * on each file exactly as the stage runs it, so a picture on the CDN and the
30
+ * same picture in the Foundry package are one file.
31
+ *
32
+ * **The set lists only what the package leaves out.** `--set <file>` names it,
33
+ * `<package>/<file>` on the CDN, in the shape
34
+ * {@link module:engine/asset-shipping} describes, with each `source` the
35
+ * file's absolute CDN URL. An address the set does not list resolves to the
36
+ * shipped copy, so listing a shipped picture would only make a world download
37
+ * a file it already has. `default.json` is refused: it is the shipped set's
38
+ * name.
39
+ *
40
+ * **A second run uploads nothing.** A picture whose object already exists at
41
+ * the same size is skipped. The set file is compared byte for byte, since a
42
+ * changed set can keep its length.
43
+ *
44
+ * **A file is refused; a document is reported.** A file under a picture root
45
+ * whose name is no address stops the run before anything is uploaded: the
46
+ * CDN has no key to put it under. A note naming a picture the package does
47
+ * not have, or naming left-out art the CDN does not hold once the run ends, is
48
+ * a warning against the note — the compile draws its default art for the
49
+ * first and the stand-in for the second, so neither stops a publish.
50
+ *
51
+ * Nothing here reads the environment or writes to the console: the command
52
+ * line supplies the credentials, the store and the log.
53
+ *
54
+ * @module
55
+ */
56
+
57
+ import fs from "node:fs";
58
+ import path from "node:path";
59
+
60
+ import { AwsClient } from "aws4fetch";
61
+
62
+ import { artTarget, ART_SLOTS } from "./art-fields.mjs";
63
+ import { collectAssetRecords } from "./asset-index.mjs";
64
+ import { deployedAssetPath, selectStagedAssets, SHIPPED_SET_FILE } from "./asset-shipping.mjs";
65
+ import {
66
+ ASSET_SYSTEM,
67
+ ASSET_TYPE_NAMES,
68
+ DEPLOYED_ASSET_TYPES,
69
+ isAssetType,
70
+ } from "./asset-types.mjs";
71
+ import { renderAddress } from "./address.mjs";
72
+ import { EMBED_DEFAULT_TYPE, embedsIn } from "./content-embeds.mjs";
73
+ import { imagesIn } from "./content-images.mjs";
74
+ import { positionOfFrontmatterPath } from "./diagnostics.mjs";
75
+ import { walkMarkdownTree } from "./helpers.mjs";
76
+ import { resolvePathname } from "./pathnames.mjs";
77
+
78
+ /**
79
+ * The environment variables naming the S3-compatible store behind the CDN.
80
+ *
81
+ * For Cloudflare R2, `CDN_ENDPOINT` is the account's S3 endpoint,
82
+ * `https://<account id>.r2.cloudflarestorage.com`, and the key pair is an R2
83
+ * API token's.
84
+ *
85
+ * @type {Readonly<{endpoint: string, bucket: string, accessKeyId: string, secretAccessKey: string}>}
86
+ */
87
+ export const CDN_ENV = Object.freeze({
88
+ endpoint: "CDN_ENDPOINT",
89
+ bucket: "CDN_BUCKET",
90
+ accessKeyId: "CDN_ACCESS_KEY_ID",
91
+ secretAccessKey: "CDN_SECRET_ACCESS_KEY",
92
+ });
93
+
94
+ /** How many requests run against the store at once. */
95
+ const CONCURRENCY = 8;
96
+
97
+ /**
98
+ * The media type each picture extension is served with. A browser refuses to
99
+ * draw an SVG served as anything but `image/svg+xml`.
100
+ *
101
+ * @type {Readonly<Record<string, string>>}
102
+ */
103
+ const CONTENT_TYPES = Object.freeze({
104
+ ".apng": "image/apng",
105
+ ".avif": "image/avif",
106
+ ".bmp": "image/bmp",
107
+ ".gif": "image/gif",
108
+ ".jpeg": "image/jpeg",
109
+ ".jpg": "image/jpeg",
110
+ ".json": "application/json",
111
+ ".png": "image/png",
112
+ ".svg": "image/svg+xml",
113
+ ".tiff": "image/tiff",
114
+ ".webp": "image/webp",
115
+ });
116
+
117
+ /**
118
+ * The media type a file is uploaded with.
119
+ *
120
+ * @param {string} name - A file name or key.
121
+ * @returns {string} Its media type, `application/octet-stream` when unknown.
122
+ */
123
+ export function contentTypeOf(name) {
124
+ return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? "application/octet-stream";
125
+ }
126
+
127
+ /**
128
+ * Why a `--set` value cannot name a set file, or `""` when it can.
129
+ *
130
+ * @param {unknown} file - The value given.
131
+ * @returns {string} The problem, as a clause, or `""`.
132
+ */
133
+ export function setFileProblem(file) {
134
+ const name = String(file ?? "");
135
+ if (!name) return "`--set` names no file";
136
+ if (name.includes("/") || name.includes("\\")) {
137
+ return `\`--set ${name}\` is a path; a set file sits directly under the package's CDN root, so name a file`;
138
+ }
139
+ if (!name.endsWith(".json")) return `\`--set ${name}\` is not a \`.json\` file`;
140
+ if (name === path.posix.basename(SHIPPED_SET_FILE)) {
141
+ return (
142
+ `\`--set ${name}\` is refused: \`${name}\` is the shipped set's name, the ` +
143
+ "fallback every other set is read against. Name the set for its art"
144
+ );
145
+ }
146
+ return "";
147
+ }
148
+
149
+ /**
150
+ * The store's settings from the environment.
151
+ *
152
+ * @param {Record<string, string|undefined>} env - The environment.
153
+ * @returns {{endpoint: string, bucket: string, accessKeyId: string,
154
+ * secretAccessKey: string}|null} The settings, or `null` when none of the
155
+ * variables is set.
156
+ * @throws {Error} When some are set and others are not, naming the missing
157
+ * ones and never a value.
158
+ */
159
+ export function cdnCredentials(env) {
160
+ const values = Object.fromEntries(
161
+ Object.entries(CDN_ENV).map(([key, name]) => [key, String(env[name] ?? "").trim()]),
162
+ );
163
+ const missing = Object.entries(CDN_ENV)
164
+ .filter(([key]) => !values[key])
165
+ .map(([, name]) => name);
166
+ if (missing.length === Object.keys(CDN_ENV).length) return null;
167
+ if (missing.length) {
168
+ throw new Error(
169
+ `the CDN store is half configured: ${missing.join(", ")} ` +
170
+ `${missing.length === 1 ? "is" : "are"} not set. Set every one of ` +
171
+ `${Object.values(CDN_ENV).join(", ")}, in the environment or \`.env.local\``,
172
+ );
173
+ }
174
+ return /** @type {any} */ (values);
175
+ }
176
+
177
+ /**
178
+ * A store holding the CDN's objects.
179
+ *
180
+ * @typedef {object} CdnStore
181
+ * @property {(key: string) => Promise<number|undefined>} size - An object's
182
+ * size in bytes, `undefined` when there is none or the store does not state
183
+ * it.
184
+ * @property {(key: string) => Promise<Buffer|undefined>} read - An object's
185
+ * bytes, `undefined` when there is none.
186
+ * @property {((key: string, body: Buffer, contentType: string) => Promise<void>)|undefined} write -
187
+ * Store an object; absent on a read-only store.
188
+ * @property {string} describe - What the store is, for the log. Never a
189
+ * secret.
190
+ */
191
+
192
+ /**
193
+ * Request headers that keep the CDN from compressing a HEAD answer: a
194
+ * gzip-encoded answer carries no content-length.
195
+ */
196
+ const IDENTITY = { "accept-encoding": "identity" };
197
+
198
+ /**
199
+ * The object size a HEAD answer states.
200
+ *
201
+ * @param {Response} response - A successful HEAD response.
202
+ * @returns {number|undefined} The content-length, `undefined` when the answer
203
+ * states none.
204
+ */
205
+ function contentLength(response) {
206
+ const header = response.headers.get("content-length");
207
+ if (header === null || header.trim() === "") return undefined;
208
+ const length = Number(header);
209
+ return Number.isFinite(length) && length >= 0 ? length : undefined;
210
+ }
211
+
212
+ /**
213
+ * Throw for a response the store refused.
214
+ *
215
+ * @param {string} what - The request, as `METHOD key`.
216
+ * @param {Response} response - The response.
217
+ * @returns {never}
218
+ */
219
+ function refused(what, response) {
220
+ throw new Error(`${what} answered ${response.status} ${response.statusText}`.trim());
221
+ }
222
+
223
+ /**
224
+ * The S3-compatible store the CDN is served from, signed with AWS SigV4.
225
+ *
226
+ * Addressed path-style, `<endpoint>/<bucket>/<key>`, which R2 and every other
227
+ * S3-compatible server accept.
228
+ *
229
+ * @param {object} opts
230
+ * @param {string} opts.endpoint - The S3 endpoint.
231
+ * @param {string} opts.bucket - The bucket.
232
+ * @param {string} opts.accessKeyId - The access key id.
233
+ * @param {string} opts.secretAccessKey - The secret access key.
234
+ * @param {typeof fetch} [opts.fetch] - The fetch to sign requests for.
235
+ * @returns {CdnStore} The store.
236
+ */
237
+ export function s3Store({ endpoint, bucket, accessKeyId, secretAccessKey, fetch: fetchImpl }) {
238
+ const client = new AwsClient({ accessKeyId, secretAccessKey, service: "s3", region: "auto" });
239
+ const base = `${endpoint.replace(/\/+$/, "")}/${encodeURIComponent(bucket)}`;
240
+ const url = (key) => `${base}/${key.split("/").map(encodeURIComponent).join("/")}`;
241
+ const send = async (key, init) => {
242
+ const request = await client.sign(url(key), init);
243
+ return (fetchImpl ?? fetch)(request);
244
+ };
245
+ return {
246
+ describe: `bucket ${bucket} at ${new URL(endpoint).host}`,
247
+ async size(key) {
248
+ const response = await send(key, { method: "HEAD", headers: IDENTITY });
249
+ if (response.status === 404) return undefined;
250
+ if (!response.ok) refused(`HEAD ${key}`, response);
251
+ return contentLength(response);
252
+ },
253
+ async read(key) {
254
+ const response = await send(key, { method: "GET" });
255
+ if (response.status === 404) return undefined;
256
+ if (!response.ok) refused(`GET ${key}`, response);
257
+ return Buffer.from(await response.arrayBuffer());
258
+ },
259
+ async write(key, body, contentType) {
260
+ const response = await send(key, {
261
+ method: "PUT",
262
+ body,
263
+ headers: { "content-type": contentType, "content-length": String(body.length) },
264
+ });
265
+ if (!response.ok) refused(`PUT ${key}`, response);
266
+ },
267
+ };
268
+ }
269
+
270
+ /**
271
+ * The CDN read through its public address — what a dry run without
272
+ * credentials compares against. It cannot write.
273
+ *
274
+ * @param {string} host - `site.assets`, the URL the bucket is served at.
275
+ * @param {typeof fetch} [fetchImpl] - The fetch to use.
276
+ * @returns {CdnStore} The read-only store.
277
+ */
278
+ export function publicStore(host, fetchImpl) {
279
+ const base = host.replace(/\/+$/, "");
280
+ const get = (key, method) =>
281
+ (fetchImpl ?? fetch)(`${base}/${key}`, {
282
+ method,
283
+ headers: method === "HEAD" ? IDENTITY : undefined,
284
+ });
285
+ return {
286
+ describe: `${base}, read-only`,
287
+ async size(key) {
288
+ const response = await get(key, "HEAD");
289
+ if (response.status === 404 || response.status === 403) return undefined;
290
+ if (!response.ok) refused(`HEAD ${key}`, response);
291
+ return contentLength(response);
292
+ },
293
+ async read(key) {
294
+ const response = await get(key, "GET");
295
+ if (response.status === 404 || response.status === 403) return undefined;
296
+ if (!response.ok) refused(`GET ${key}`, response);
297
+ return Buffer.from(await response.arrayBuffer());
298
+ },
299
+ write: undefined,
300
+ };
301
+ }
302
+
303
+ /**
304
+ * One picture to publish.
305
+ *
306
+ * @typedef {object} CdnUpload
307
+ * @property {object} record - The asset record.
308
+ * @property {string} address - Its canonical address.
309
+ * @property {string} target - `<icons|images>/<basename>`.
310
+ * @property {string} key - The object key, `<package>/<target>`.
311
+ * @property {Buffer} body - The bytes, transformed as the stage transforms
312
+ * them.
313
+ * @property {string} contentType - The media type it is served with.
314
+ * @property {boolean} shipped - Whether the Foundry package ships it.
315
+ */
316
+
317
+ /**
318
+ * Everything a publish uploads, worked out before anything is sent.
319
+ *
320
+ * @typedef {object} CdnPlan
321
+ * @property {object[]} findings - What stops the publish; nothing is planned
322
+ * when non-empty.
323
+ * @property {object[]} records - Every asset record the package has.
324
+ * @property {CdnUpload[]} uploads - One per picture, in key order.
325
+ * @property {{key: string, body: Buffer, set: object}|null} set - The set file.
326
+ * @property {string} cdnRoot - `<site.assets>/<package>/`.
327
+ */
328
+
329
+ /**
330
+ * Work out what a publish uploads.
331
+ *
332
+ * @param {object} opts
333
+ * @param {string} opts.assetsBase - The package's asset directory.
334
+ * @param {string} opts.contentPackage - The content package.
335
+ * @param {string} opts.host - `site.assets`.
336
+ * @param {string} opts.setFile - The set file's name.
337
+ * @param {string} opts.setName - The set's display name.
338
+ * @param {(sourcePath: string) => string|null|undefined} [opts.transform] -
339
+ * The repository's per-file transform.
340
+ * @param {readonly string[]} [opts.shippingLicenses] - The licences the
341
+ * package adds to the shipping list, so the set leaves out what the stage
342
+ * leaves out.
343
+ * @returns {CdnPlan} The plan.
344
+ */
345
+ export function planCdnPublish({
346
+ assetsBase,
347
+ contentPackage,
348
+ host,
349
+ setFile,
350
+ setName,
351
+ transform,
352
+ shippingLicenses = [],
353
+ }) {
354
+ const findings = [];
355
+ const cdnRoot = `${host.replace(/\/+$/, "")}/${contentPackage}/`;
356
+ const records = collectAssetRecords(assetsBase, { contentPackage, problems: findings });
357
+ if (findings.length) return { findings, records, uploads: [], set: null, cdnRoot };
358
+
359
+ const { staged, excluded } = selectStagedAssets(records, shippingLicenses);
360
+ const shipped = new Set(staged);
361
+ const uploads = [...staged, ...excluded.map(({ record }) => record)]
362
+ .map((record) => {
363
+ const from = path.join(assetsBase, ...record.asset.path.split("/"));
364
+ const transformed = transform ? transform(from) : null;
365
+ const body =
366
+ transformed != null ? Buffer.from(transformed, "utf8") : fs.readFileSync(from);
367
+ const target = /** @type {string} */ (deployedAssetPath(record));
368
+ return {
369
+ record,
370
+ address: record.address.canonical,
371
+ target,
372
+ key: `${contentPackage}/${target}`,
373
+ body,
374
+ contentType: contentTypeOf(target),
375
+ shipped: shipped.has(record),
376
+ };
377
+ })
378
+ .sort((a, b) => (a.key < b.key ? -1 : 1));
379
+
380
+ const set = {
381
+ name: setName,
382
+ package: contentPackage,
383
+ assets: uploads
384
+ .filter((upload) => !upload.shipped)
385
+ .map((upload) => ({
386
+ address: upload.address,
387
+ source: `${cdnRoot}${upload.target}`,
388
+ target: upload.target,
389
+ size: upload.body.length,
390
+ }))
391
+ .sort((a, b) => (a.target < b.target ? -1 : 1)),
392
+ };
393
+ return {
394
+ findings,
395
+ records,
396
+ uploads,
397
+ set: {
398
+ key: `${contentPackage}/${setFile}`,
399
+ body: Buffer.from(`${JSON.stringify(set, null, 4)}\n`, "utf8"),
400
+ set,
401
+ },
402
+ cdnRoot,
403
+ };
404
+ }
405
+
406
+ /**
407
+ * Run `work` over `items`, `limit` at a time, in order of completion.
408
+ *
409
+ * @template T
410
+ * @param {readonly T[]} items
411
+ * @param {number} limit
412
+ * @param {(item: T) => Promise<void>} work
413
+ * @returns {Promise<void>}
414
+ */
415
+ async function pooled(items, limit, work) {
416
+ let next = 0;
417
+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
418
+ while (next < items.length) {
419
+ const item = items[next++];
420
+ await work(item);
421
+ }
422
+ });
423
+ await Promise.all(runners);
424
+ }
425
+
426
+ /**
427
+ * Upload a plan.
428
+ *
429
+ * A picture that fails is recorded and the rest carry on, so one refused file
430
+ * costs one file rather than the run. The set file is written only when every
431
+ * picture it lists is on the CDN: a set naming a file the CDN lacks sends a
432
+ * world to fetch nothing.
433
+ *
434
+ * @param {CdnPlan} plan - From {@link planCdnPublish}, with no findings.
435
+ * @param {object} opts
436
+ * @param {CdnStore} opts.store - Where the objects go.
437
+ * @param {boolean} [opts.dryRun] - Compare only; write nothing.
438
+ * @param {(line: string) => void} [opts.log] - One line per object.
439
+ * @returns {Promise<{uploaded: CdnUpload[], skipped: CdnUpload[],
440
+ * failed: {upload: CdnUpload, message: string}[],
441
+ * set: "uploaded"|"skipped"|"withheld", published: Set<string>}>} What was
442
+ * (or, in a dry run, would be) uploaded, skipped and refused; what became of
443
+ * the set file; and every address whose picture is on the CDN at its
444
+ * planned size once the run ends — or would be, in a dry run.
445
+ */
446
+ export async function publishToCdn(plan, { store, dryRun = false, log = () => {} }) {
447
+ if (!dryRun && !store.write) {
448
+ throw new Error(`the store (${store.describe}) is read-only, so it can only be dry-run`);
449
+ }
450
+ const write = /** @type {NonNullable<CdnStore["write"]>} */ (store.write);
451
+ const verb = dryRun ? "would upload" : "uploaded";
452
+ const uploaded = [];
453
+ const skipped = [];
454
+ const failed = [];
455
+ const published = new Set();
456
+ await pooled(plan.uploads, CONCURRENCY, async (upload) => {
457
+ try {
458
+ const size = await store.size(upload.key);
459
+ if (size === upload.body.length) {
460
+ skipped.push(upload);
461
+ } else {
462
+ if (!dryRun) await write(upload.key, upload.body, upload.contentType);
463
+ uploaded.push(upload);
464
+ }
465
+ published.add(upload.address);
466
+ } catch (err) {
467
+ failed.push({ upload, message: err instanceof Error ? err.message : String(err) });
468
+ }
469
+ });
470
+ const byKey = (a, b) => (a.key < b.key ? -1 : 1);
471
+ uploaded.sort(byKey);
472
+ skipped.sort(byKey);
473
+ failed.sort((a, b) => byKey(a.upload, b.upload));
474
+ for (const upload of uploaded) log(`${verb} ${upload.key} (${upload.body.length} bytes)`);
475
+ for (const upload of skipped) log(`skipped ${upload.key}, already present at that size`);
476
+
477
+ const setPlan = /** @type {NonNullable<CdnPlan["set"]>} */ (plan.set);
478
+ if (failed.length) {
479
+ log(`withheld ${setPlan.key}: ${failed.length} of its pictures did not upload`);
480
+ return { uploaded, skipped, failed, set: "withheld", published };
481
+ }
482
+ const current = await store.read(setPlan.key);
483
+ if (current && current.equals(setPlan.body)) {
484
+ log(`skipped ${setPlan.key}, unchanged`);
485
+ return { uploaded, skipped, failed, set: "skipped", published };
486
+ }
487
+ if (!dryRun) await write(setPlan.key, setPlan.body, contentTypeOf(setPlan.key));
488
+ log(`${verb} ${setPlan.key} (${setPlan.set.assets.length} assets)`);
489
+ return { uploaded, skipped, failed, set: "uploaded", published };
490
+ }
491
+
492
+ /**
493
+ * Line and column, 1-based, of an offset inside a note's body.
494
+ *
495
+ * @param {string} body - The body as the walk yields it.
496
+ * @param {number} offset - Where in the body.
497
+ * @param {number} bodyLine - The file line the body starts on.
498
+ * @param {number} bodyColumn - The file column it starts at.
499
+ * @returns {{line: number, column: number}} The file position.
500
+ */
501
+ function bodyPosition(body, offset, bodyLine, bodyColumn) {
502
+ const before = body.slice(0, offset);
503
+ const lines = before.split("\n");
504
+ return lines.length === 1 ?
505
+ { line: bodyLine, column: bodyColumn + offset }
506
+ : { line: bodyLine + lines.length - 1, column: lines[lines.length - 1].length + 1 };
507
+ }
508
+
509
+ /**
510
+ * Every place a package's notes name one of its own pictures, and what each
511
+ * names.
512
+ *
513
+ * Reads the three places a note names art: an art slot under `data:`, an
514
+ * embed (`![[address|label]]`) and a body image whose pathname is the
515
+ * package's own. A reference naming another package, or one that does not
516
+ * parse as an address, is another check's business and is not returned.
517
+ *
518
+ * @param {object} opts
519
+ * @param {string} opts.contentBase - The content tree.
520
+ * @param {readonly string[]} opts.skipDirectories - Directory names the walk
521
+ * ignores.
522
+ * @param {string} opts.contentPackage - The content package.
523
+ * @param {readonly object[]} opts.records - The package's asset records.
524
+ * @returns {Array<{file: string, line?: number, column?: number,
525
+ * written: string, record: object|null}>} One per reference, `record` `null`
526
+ * where the package has no such picture. `file` is relative to the working
527
+ * directory.
528
+ */
529
+ export function noteArtReferences({ contentBase, skipDirectories, contentPackage, records }) {
530
+ const byAddress = new Map(records.map((record) => [record.address.canonical, record]));
531
+ const byPath = new Map(records.map((record) => [record.asset?.path, record]));
532
+ const vocabulary = {
533
+ system: ASSET_SYSTEM,
534
+ package: contentPackage,
535
+ types: ASSET_TYPE_NAMES,
536
+ packages: new Set([contentPackage]),
537
+ };
538
+ /** @returns {string|undefined} The canonical address, when it is this package's. */
539
+ const ownAddress = (value, defaultType, accepts) => {
540
+ const tuple = artTarget(value, defaultType, accepts, vocabulary);
541
+ if (tuple.reason || tuple.package !== contentPackage || !isAssetType(tuple.type)) {
542
+ return undefined;
543
+ }
544
+ return renderAddress(tuple);
545
+ };
546
+
547
+ const out = [];
548
+ for (const note of walkMarkdownTree(contentBase, { skipDirectories })) {
549
+ if (!note.frontmatter) continue;
550
+ const file = path.relative(process.cwd(), note.absPath);
551
+ let raw;
552
+ const rawText = () => (raw ??= fs.readFileSync(note.absPath, "utf8"));
553
+
554
+ for (const slot of ART_SLOTS) {
555
+ const value = note.frontmatter.data?.[slot.key];
556
+ if (typeof value !== "string" || !value || value === slot.declines) continue;
557
+ const address = ownAddress(value, slot.type, slot.accepts);
558
+ if (!address) continue;
559
+ out.push({
560
+ file,
561
+ ...positionOfFrontmatterPath(rawText(), ["data", slot.key]),
562
+ written: value,
563
+ record: byAddress.get(address) ?? null,
564
+ });
565
+ }
566
+
567
+ const body = note.body ?? "";
568
+ const at = (offset) => bodyPosition(body, offset, note.bodyLine ?? 1, note.bodyColumn ?? 1);
569
+ for (const embed of embedsIn(body)) {
570
+ const address = ownAddress(embed.written, EMBED_DEFAULT_TYPE, undefined);
571
+ if (!address) continue;
572
+ out.push({
573
+ file,
574
+ ...at(embed.index),
575
+ written: embed.written,
576
+ record: byAddress.get(address) ?? null,
577
+ });
578
+ }
579
+ for (const image of imagesIn(body)) {
580
+ let forms;
581
+ try {
582
+ forms = resolvePathname(image.src, { contentPackage });
583
+ } catch {
584
+ continue;
585
+ }
586
+ if (forms?.state !== "package" || forms.package !== contentPackage) continue;
587
+ const root = forms.suffix.split("/")[0];
588
+ if (!DEPLOYED_ASSET_TYPES.some((type) => type.root === root)) continue;
589
+ out.push({
590
+ file,
591
+ ...at(image.index),
592
+ written: image.src,
593
+ record: byPath.get(forms.suffix) ?? null,
594
+ });
595
+ }
596
+ }
597
+ return out;
598
+ }
599
+
600
+ /**
601
+ * The findings a publish reports against the package's notes.
602
+ *
603
+ * Both are warnings:
604
+ *
605
+ * - a note names a picture the package does not have, so no address answers
606
+ * it and nothing is published for it;
607
+ * - a note names a picture the package leaves out, and the CDN does not hold
608
+ * it, so a world adding the set gets no file for that document.
609
+ *
610
+ * @param {ReturnType<typeof noteArtReferences>} references - From
611
+ * {@link noteArtReferences}.
612
+ * @param {object} opts
613
+ * @param {string} opts.contentPackage - The content package.
614
+ * @param {ReadonlySet<string>} opts.published - Every address on the CDN at
615
+ * its planned size.
616
+ * @param {ReadonlySet<object>} opts.excluded - The records the package leaves
617
+ * out.
618
+ * @returns {Array<{file: string, line?: number, column?: number,
619
+ * severity: "warning", message: string}>} In note order.
620
+ */
621
+ export function noteArtFindings(references, { contentPackage, published, excluded }) {
622
+ const findings = [];
623
+ for (const { record, written, ...where } of references) {
624
+ if (!record) {
625
+ findings.push({
626
+ ...where,
627
+ severity: "warning",
628
+ message:
629
+ `\`${written}\` names a picture the \`${contentPackage}\` package does not ` +
630
+ "have, so no address answers it and the CDN has nothing to publish for it",
631
+ });
632
+ } else if (excluded.has(record) && !published.has(record.address.canonical)) {
633
+ findings.push({
634
+ ...where,
635
+ severity: "warning",
636
+ message:
637
+ `\`${record.address.canonical}\` is left out of the package and is not on ` +
638
+ "the CDN, so a world adding this set has no file for it",
639
+ });
640
+ }
641
+ }
642
+ return findings;
643
+ }
package/engine/index.mjs CHANGED
@@ -193,6 +193,12 @@ export * as assetTypes from "./asset-types.mjs";
193
193
  /** The asset record: one index line per addressable file, and its provenance. */
194
194
  export * as assetIndex from "./asset-index.mjs";
195
195
 
196
+ /** The deployed layout of a package's pictures, which of them ship, and its asset set. */
197
+ export * as assetShipping from "./asset-shipping.mjs";
198
+
199
+ /** The address every asset reference in a compiled document states. */
200
+ export * as assetReferences from "./asset-references.mjs";
201
+
196
202
  /** The `<package>` segment's registry: the names no repository may claim. */
197
203
  export * as packages from "./packages.mjs";
198
204
 
@@ -1590,7 +1590,10 @@ export const NOTE_VOCABULARY = Object.freeze({
1590
1590
  // its title, ordered by level — the ladder's parallel to
1591
1591
  // `governance.offices`' `roster`.
1592
1592
  ranks: true,
1593
- describe: "The ladder of ranks the body confers — level, title, description.",
1593
+ describe:
1594
+ "The ladder of standings the body confers: level 0 for those it excludes " +
1595
+ "and level 1 for its members, both required, and higher rungs only where " +
1596
+ "the body has them.",
1594
1597
  },
1595
1598
  {
1596
1599
  name: "governance.offices",