@tokenoftrust/cli 7.4.0 → 7.4.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 +1 -1
- package/src/commands/accept.mjs +65 -16
- package/src/redirect-shadows.mjs +261 -0
- package/src/validate.mjs +23 -1
- package/src/viewer-session.mjs +47 -14
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/cli",
|
|
3
|
-
"version": "7.4.
|
|
3
|
+
"version": "7.4.2",
|
|
4
4
|
"description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Token of Trust",
|
package/src/commands/accept.mjs
CHANGED
|
@@ -57,6 +57,7 @@ import { autoSurfaceDoctor } from "../merge-doctor-report.mjs";
|
|
|
57
57
|
import { isJobAccepted, waitForPipelineJob } from "../pipeline-job.mjs";
|
|
58
58
|
|
|
59
59
|
const DEFAULT_STOREFRONT_URL = "https://storefront.tokenoftrust.store";
|
|
60
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
60
61
|
const DEFAULT_MCP_URL = "https://mcp.tokenoftrust.com";
|
|
61
62
|
|
|
62
63
|
// The three refresh strategies `candidate_refresh` accepts, mirroring the admin
|
|
@@ -392,16 +393,54 @@ async function handleNotMergeable(
|
|
|
392
393
|
return { integrate: true, pr: rr.prNumber ?? pr, changeId };
|
|
393
394
|
}
|
|
394
395
|
|
|
396
|
+
/**
|
|
397
|
+
* The waits before asking again about an integrate request whose answer never arrived (the
|
|
398
|
+
* connection dropped, or the store answered 502/503/504). The request may already have created
|
|
399
|
+
* the job, so it is repeated with the SAME `Idempotency-Key`: the store answers the job the
|
|
400
|
+
* first request created, or creates it if that request never landed.
|
|
401
|
+
*/
|
|
402
|
+
export const INTEGRATE_REPEAT_DELAYS_MS = Object.freeze([2_000, 5_000, 10_000, 20_000]);
|
|
403
|
+
const STORE_UNAVAILABLE_STATUSES = new Set([502, 503, 504]);
|
|
404
|
+
|
|
405
|
+
/** An integrate request whose outcome is unknown: it may or may not have queued the job. */
|
|
406
|
+
export class IntegrateUnconfirmedError extends Error {
|
|
407
|
+
/** @param {string} reason */
|
|
408
|
+
constructor(reason) {
|
|
409
|
+
super(reason);
|
|
410
|
+
this.name = "IntegrateUnconfirmedError";
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
395
414
|
/**
|
|
396
415
|
* POST `/api/changes/integrate`, wait on the job it submitted, and normalise the outcome.
|
|
397
|
-
* Returns { res, result } — `res.ok` is the submit's transport verdict.
|
|
416
|
+
* Returns { res, result } — `res.ok` is the submit's transport verdict. A request whose answer
|
|
417
|
+
* was lost is repeated with the same idempotency key (see INTEGRATE_REPEAT_DELAYS_MS), and
|
|
418
|
+
* throws IntegrateUnconfirmedError only when no answer ever arrives.
|
|
398
419
|
*/
|
|
399
|
-
async function postIntegrate({ base, authHeaders, body }, fetchImpl, waitOpts = {}) {
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
420
|
+
async function postIntegrate({ base, authHeaders, body }, fetchImpl, waitOpts = {}, sleep = defaultSleep) {
|
|
421
|
+
const idempotencyKey = globalThis.crypto.randomUUID();
|
|
422
|
+
const send = async () => {
|
|
423
|
+
try {
|
|
424
|
+
const answer = await fetchImpl(`${base}/api/changes/integrate`, {
|
|
425
|
+
method: "POST",
|
|
426
|
+
headers: { "content-type": "application/json", "idempotency-key": idempotencyKey, ...authHeaders },
|
|
427
|
+
body: JSON.stringify(body),
|
|
428
|
+
});
|
|
429
|
+
return STORE_UNAVAILABLE_STATUSES.has(answer.status)
|
|
430
|
+
? { res: null, reason: `the store answered HTTP ${answer.status}` }
|
|
431
|
+
: { res: answer, reason: null };
|
|
432
|
+
} catch (e) {
|
|
433
|
+
return { res: null, reason: String(e?.message || e) };
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
let { res, reason } = await send();
|
|
437
|
+
for (const delay of INTEGRATE_REPEAT_DELAYS_MS) {
|
|
438
|
+
if (res) break;
|
|
439
|
+
console.log(` no answer from the integration queue (${reason}) — it may already have the request; asking again in ${delay / 1000}s…`);
|
|
440
|
+
await sleep(delay);
|
|
441
|
+
({ res, reason } = await send());
|
|
442
|
+
}
|
|
443
|
+
if (!res) throw new IntegrateUnconfirmedError(/** @type {string} */ (reason));
|
|
405
444
|
let data = {};
|
|
406
445
|
try {
|
|
407
446
|
data = await res.json();
|
|
@@ -477,7 +516,7 @@ export function reportIntegrated(result, { tenant, label }) {
|
|
|
477
516
|
* strategy?:string, mcpUrl?:string|null, identity?:string|null, env?:NodeJS.ProcessEnv }} params
|
|
478
517
|
* @param {{ fetch?:typeof fetch, confirmPlan?:typeof printPlanAndConfirm,
|
|
479
518
|
* resolveViewerTransport?:typeof resolveViewerTransport,
|
|
480
|
-
* wait?:Parameters<typeof waitForPipelineJob>[2] }} [deps]
|
|
519
|
+
* wait?:Parameters<typeof waitForPipelineJob>[2], sleep?:(ms:number)=>Promise<void> }} [deps]
|
|
481
520
|
* @returns {Promise<number>} process exit code
|
|
482
521
|
*/
|
|
483
522
|
export async function runIntegrate(
|
|
@@ -595,12 +634,10 @@ export async function runIntegrate(
|
|
|
595
634
|
{ base, authHeaders, body: integrateBody({ tenant, pr: curPr, changeId: curChangeId, headSha: curHead }) },
|
|
596
635
|
fetchImpl,
|
|
597
636
|
deps.wait,
|
|
637
|
+
deps.sleep,
|
|
598
638
|
));
|
|
599
639
|
} catch (e) {
|
|
600
|
-
|
|
601
|
-
fail(`couldn't reach the integration queue at ${base}: ${String(e?.message || e)}`, "check --url / your network, then re-run"),
|
|
602
|
-
);
|
|
603
|
-
return 1;
|
|
640
|
+
return reportIntegrateUnconfirmed(e, { base, tenant });
|
|
604
641
|
}
|
|
605
642
|
|
|
606
643
|
// A pre-flight error (auth, unknown tenant, candidate not found) is an HTTP 4xx
|
|
@@ -633,12 +670,10 @@ export async function runIntegrate(
|
|
|
633
670
|
},
|
|
634
671
|
fetchImpl,
|
|
635
672
|
deps.wait,
|
|
673
|
+
deps.sleep,
|
|
636
674
|
));
|
|
637
675
|
} catch (e) {
|
|
638
|
-
|
|
639
|
-
fail(`couldn't reach the integration queue at ${base}: ${String(e?.message || e)}`, "check --url / your network, then re-run"),
|
|
640
|
-
);
|
|
641
|
-
return 1;
|
|
676
|
+
return reportIntegrateUnconfirmed(e, { base, tenant });
|
|
642
677
|
}
|
|
643
678
|
if (!res.ok) {
|
|
644
679
|
return reportIntegrateHttpError(result, res, { tenant, label });
|
|
@@ -682,6 +717,20 @@ async function preflightMergeable({ base, authHeaders, pr, changeId }, fetchImpl
|
|
|
682
717
|
}
|
|
683
718
|
}
|
|
684
719
|
|
|
720
|
+
/**
|
|
721
|
+
* Surface an integrate request that never got an answer. It may have queued the job, so this
|
|
722
|
+
* never says the queue was unreachable. Returns exit 1.
|
|
723
|
+
*/
|
|
724
|
+
function reportIntegrateUnconfirmed(e, { base, tenant }) {
|
|
725
|
+
console.error(
|
|
726
|
+
fail(
|
|
727
|
+
`couldn't confirm the integration request reached ${base} (${String(e?.message || e)}) — it may already be queued.`,
|
|
728
|
+
`check \`tot pr list --tenant ${tenant}\` before re-running; a change already added reports as such.`,
|
|
729
|
+
),
|
|
730
|
+
);
|
|
731
|
+
return 1;
|
|
732
|
+
}
|
|
733
|
+
|
|
685
734
|
/** Surface an integrate HTTP pre-flight error (4xx, no queue verdict). Returns exit 1. */
|
|
686
735
|
function reportIntegrateHttpError(result, res, { tenant, label }) {
|
|
687
736
|
const msg = result.error || `HTTP ${res.status}`;
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Precedence between the routes a release GENERATES and the redirects its content DECLARES: a route
|
|
4
|
+
* the release generates wins over a declared redirect whose exact source is that route. The redirect
|
|
5
|
+
* is dropped from what the release publishes and reported as a non-blocking warning; it is never a
|
|
6
|
+
* reason to refuse a publish.
|
|
7
|
+
*
|
|
8
|
+
* A redirect declared for a URL that did not exist yet goes stale the day the content grows into it:
|
|
9
|
+
* a leftover `"blog/page/9": "blog"` does nothing while the blog has 8 pages, and would send the 9th
|
|
10
|
+
* page away the day one more post is written. Only EXACT sources yield; a `<dir>/*` rule is a
|
|
11
|
+
* deliberate statement about a whole family of URLs and keeps answering.
|
|
12
|
+
*
|
|
13
|
+
* Pure: callers pass the declaration files they read (`{path, json}`, the shape
|
|
14
|
+
* `declaredRedirectsFromContent` takes) and the route set they know, so the publish, the preview
|
|
15
|
+
* reconcile, the kit and `tot validate` apply one rule.
|
|
16
|
+
* `packages/cli/src/redirect-shadows.mjs` is a byte-identical copy (a test pins it).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** The finding prefix the publish pipeline classifies as non-blocking (`finding-severity`). */
|
|
20
|
+
export const SHADOWED_REDIRECT_PREFIX = "REDIRECT";
|
|
21
|
+
|
|
22
|
+
/** The tenant-wide declaration, and a content collection's slug-rename map. */
|
|
23
|
+
const SITE_REDIRECTS_PATH = "content/redirects.json";
|
|
24
|
+
const COLLECTION_REDIRECTS_PATH = /^content\/([A-Za-z0-9][A-Za-z0-9_-]*)\/redirects\.json$/;
|
|
25
|
+
|
|
26
|
+
/** Posts per collection index page when a collection declares no valid `pageSize`. */
|
|
27
|
+
const DEFAULT_PAGE_SIZE = 12;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The form a route and a redirect source are compared in: root-absolute, no query or fragment, a
|
|
31
|
+
* trailing slash unless the last segment names a file. Null when `raw` is not a same-origin path.
|
|
32
|
+
* The same normalization the redirect contract applies to a declared source.
|
|
33
|
+
* @param {unknown} raw
|
|
34
|
+
* @returns {string | null}
|
|
35
|
+
*/
|
|
36
|
+
export function routeKey(raw) {
|
|
37
|
+
if (typeof raw !== "string") return null;
|
|
38
|
+
const trimmed = raw.trim();
|
|
39
|
+
if (!trimmed.startsWith("/") || trimmed.startsWith("//") || trimmed.includes("*")) return null;
|
|
40
|
+
const path = trimmed.replace(/[?#].*$/, "");
|
|
41
|
+
if (path.includes("..") || path.includes("\\")) return null;
|
|
42
|
+
const collapsed = path.replace(/\/{2,}/g, "/");
|
|
43
|
+
if (collapsed === "/") return "/";
|
|
44
|
+
const segments = collapsed.split("/").filter(Boolean);
|
|
45
|
+
if ((segments[segments.length - 1] ?? "").includes(".")) return collapsed.replace(/\/$/, "");
|
|
46
|
+
return collapsed.endsWith("/") ? collapsed : `${collapsed}/`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A matcher over a list of generated route paths, in any slash form.
|
|
51
|
+
* @param {Iterable<string>} paths
|
|
52
|
+
* @returns {(source: string) => boolean}
|
|
53
|
+
*/
|
|
54
|
+
export function routeMatcher(paths) {
|
|
55
|
+
const keys = new Set();
|
|
56
|
+
for (const path of paths) {
|
|
57
|
+
const key = routeKey(path);
|
|
58
|
+
if (key) keys.add(key);
|
|
59
|
+
}
|
|
60
|
+
return (source) => keys.has(source);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @typedef {{file: string, key: string, value: unknown, source: string}} ShadowedRedirect
|
|
65
|
+
* `file` the declaration it came from, `key`/`value` the entry exactly as written, `source` the
|
|
66
|
+
* generated route it would have redirected.
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Split declaration files into the entries that still apply and the ones a generated route shadows.
|
|
71
|
+
* The files come back with the shadowed entries removed and every other entry untouched, so the
|
|
72
|
+
* caller hands them to the redirect contract exactly as it would have handed the originals; a file
|
|
73
|
+
* that is not a key/value object passes through unchanged for the contract to refuse.
|
|
74
|
+
* @template {{path: string, json: unknown}} T
|
|
75
|
+
* @param {readonly T[]} declarations
|
|
76
|
+
* @param {(source: string) => boolean} isRoute called with a source in `routeKey` form
|
|
77
|
+
* @returns {{declarations: T[], shadowed: ShadowedRedirect[]}}
|
|
78
|
+
*/
|
|
79
|
+
export function redirectsYieldingToRoutes(declarations, isRoute) {
|
|
80
|
+
/** @type {T[]} */
|
|
81
|
+
const kept = [];
|
|
82
|
+
/** @type {ShadowedRedirect[]} */
|
|
83
|
+
const shadowed = [];
|
|
84
|
+
for (const declaration of declarations ?? []) {
|
|
85
|
+
const collection = COLLECTION_REDIRECTS_PATH.exec(declaration?.path ?? "")?.[1];
|
|
86
|
+
const json = declaration?.json;
|
|
87
|
+
if ((declaration?.path !== SITE_REDIRECTS_PATH && !collection) ||
|
|
88
|
+
!json || typeof json !== "object" || Array.isArray(json)) {
|
|
89
|
+
kept.push(declaration);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
/** @type {Record<string, unknown>} */
|
|
93
|
+
const rows = {};
|
|
94
|
+
for (const [key, value] of Object.entries(json)) {
|
|
95
|
+
const source = collection
|
|
96
|
+
? (key ? routeKey(`/${collection}/${key}/`) : null)
|
|
97
|
+
: (key && !key.startsWith("/") ? routeKey(`/${key}`) : null);
|
|
98
|
+
if (source !== null && isRoute(source)) shadowed.push({ file: declaration.path, key, value, source });
|
|
99
|
+
else rows[key] = value;
|
|
100
|
+
}
|
|
101
|
+
kept.push({ ...declaration, json: rows });
|
|
102
|
+
}
|
|
103
|
+
return { declarations: kept, shadowed };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** @param {number} n */
|
|
107
|
+
function ordinal(n) {
|
|
108
|
+
const tens = n % 100;
|
|
109
|
+
const suffix = tens >= 11 && tens <= 13 ? "th" : ({ 1: "st", 2: "nd", 3: "rd" })[n % 10] ?? "th";
|
|
110
|
+
return `${n}${suffix}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** @param {string} collection */
|
|
114
|
+
function collectionName(collection) {
|
|
115
|
+
return collection === "blog" ? "The blog" : `The ${collection} collection`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Why the content now generates `source`, as the start of a sentence.
|
|
120
|
+
* @param {string} source a route in `routeKey` form
|
|
121
|
+
*/
|
|
122
|
+
export function generatedRouteReason(source) {
|
|
123
|
+
const parts = source.split("/").filter(Boolean);
|
|
124
|
+
const [collection, kind, value] = parts;
|
|
125
|
+
if (collection === "blog" || collection === "the-build") {
|
|
126
|
+
if (parts.length === 3 && kind === "page" && /^[1-9][0-9]*$/.test(value ?? "")) {
|
|
127
|
+
return `${collectionName(collection)} now has a ${ordinal(Number(value))} page`;
|
|
128
|
+
}
|
|
129
|
+
if (parts.length === 3 && (kind === "tag" || kind === "category" || kind === "author")) {
|
|
130
|
+
return `${collectionName(collection)} now has a page for the ${kind} "${value}"`;
|
|
131
|
+
}
|
|
132
|
+
if (parts.length === 2) {
|
|
133
|
+
return `${collection === "blog" ? "A blog post" : `A post in the ${collection} collection`} now lives at ${source}`;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return `A page now lives at ${source}`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The plain-language warning for one shadowed redirect: the file, the exact entry, what now
|
|
141
|
+
* generates that page and why, and what to do.
|
|
142
|
+
* @param {ShadowedRedirect} entry
|
|
143
|
+
*/
|
|
144
|
+
export function shadowedRedirectMessage(entry) {
|
|
145
|
+
return `Your ${entry.file} has an old redirect, ${JSON.stringify(entry.key)}: ${JSON.stringify(entry.value)}. ` +
|
|
146
|
+
`${generatedRouteReason(entry.source)}, and that redirect would send it away. ` +
|
|
147
|
+
"The page is served; delete the redirect entry to clear this warning.";
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The warning as a publish finding: `REDIRECT: <message>`. @param {ShadowedRedirect} entry */
|
|
151
|
+
export function shadowedRedirectFinding(entry) {
|
|
152
|
+
return `${SHADOWED_REDIRECT_PREFIX}: ${shadowedRedirectMessage(entry)}`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Is a post listed on the live site's index pages? A missing status is published; a scheduled post
|
|
157
|
+
* counts once its time has come.
|
|
158
|
+
* @param {any} post @param {number} now
|
|
159
|
+
*/
|
|
160
|
+
function listable(post, now) {
|
|
161
|
+
const status = post?.status ?? "published";
|
|
162
|
+
if (status === "published") return true;
|
|
163
|
+
return status === "scheduled" && typeof post?.scheduledAt === "string" && Date.parse(post.scheduledAt) <= now;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** @param {any} post @param {number} now */
|
|
167
|
+
function visible(post, now) {
|
|
168
|
+
return (post?.status ?? "published") === "unlisted" || listable(post, now);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** @param {unknown} value */
|
|
172
|
+
function taxonomySlug(value) {
|
|
173
|
+
return typeof value === "string" ? value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") : "";
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The routes a store's content generates at the default collection bases: each editorial page at
|
|
178
|
+
* its slug, each visible post, each tag and category archive of a listed post, and every index page
|
|
179
|
+
* of a collection. The publish judges against the routes it actually rendered; this is the same
|
|
180
|
+
* question asked of the content, so authoring tools can warn before a publish.
|
|
181
|
+
* @param {{pages?: {slug?: unknown}[], collections?: Record<string, {posts?: {slug: string, post: any}[], settings?: any}>, now?: number}} content
|
|
182
|
+
* @returns {Set<string>} routes in `routeKey` form
|
|
183
|
+
*/
|
|
184
|
+
export function contentGeneratedRoutes({ pages = [], collections = {}, now = Date.now() }) {
|
|
185
|
+
const routes = new Set();
|
|
186
|
+
const add = (/** @type {string} */ path) => {
|
|
187
|
+
const key = routeKey(path);
|
|
188
|
+
if (key) routes.add(key);
|
|
189
|
+
};
|
|
190
|
+
for (const page of pages) if (typeof page?.slug === "string" && page.slug) add(`/${page.slug}`);
|
|
191
|
+
for (const [collection, { posts = [], settings } = {}] of Object.entries(collections)) {
|
|
192
|
+
const pageSize = Number.isInteger(settings?.pageSize) && settings.pageSize > 0 ? settings.pageSize : DEFAULT_PAGE_SIZE;
|
|
193
|
+
let listed = 0;
|
|
194
|
+
for (const { slug, post } of posts) {
|
|
195
|
+
if (visible(post, now)) add(`/${collection}/${slug}`);
|
|
196
|
+
if (!listable(post, now)) continue;
|
|
197
|
+
listed++;
|
|
198
|
+
for (const kind of /** @type {const} */ (["tags", "categories"])) {
|
|
199
|
+
for (const value of Array.isArray(post?.[kind]) ? post[kind] : []) {
|
|
200
|
+
const term = taxonomySlug(value);
|
|
201
|
+
if (term) add(`/${collection}/${kind === "tags" ? "tag" : "category"}/${term}`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (listed > 0) add(`/${collection}`);
|
|
206
|
+
for (let page = 2; page <= Math.ceil(listed / pageSize); page++) add(`/${collection}/page/${page}`);
|
|
207
|
+
}
|
|
208
|
+
return routes;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The collections whose posts the platform renders at their default base. */
|
|
212
|
+
const POST_COLLECTIONS = /^(blog|the-build)\/(?:posts\/([^/]+)\.json|settings\.json)$/;
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Collects, file by file, what the shadowed-redirect check needs from a store's `content/` tree,
|
|
216
|
+
* keeping only the few fields it reads (a slug, a post's status and taxonomy, a page size), so a
|
|
217
|
+
* caller streaming a large tree never holds it. A file that does not parse is skipped: the content
|
|
218
|
+
* validators own that finding.
|
|
219
|
+
*/
|
|
220
|
+
export function createRedirectShadowCollector() {
|
|
221
|
+
/** @type {{slug?: unknown}[]} */
|
|
222
|
+
const pages = [];
|
|
223
|
+
/** @type {Record<string, {posts: {slug: string, post: any}[], settings?: any}>} */
|
|
224
|
+
const collections = {};
|
|
225
|
+
/** @type {{path: string, json: unknown}[]} */
|
|
226
|
+
const declarations = [];
|
|
227
|
+
const collection = (/** @type {string} */ name) => (collections[name] ??= { posts: [] });
|
|
228
|
+
return {
|
|
229
|
+
/**
|
|
230
|
+
* @param {string} rel path under `content/`, e.g. `blog/posts/hello.json`
|
|
231
|
+
* @param {string} text
|
|
232
|
+
*/
|
|
233
|
+
add(rel, text) {
|
|
234
|
+
const declaration = rel === "redirects.json" || COLLECTION_REDIRECTS_PATH.test(`content/${rel}`);
|
|
235
|
+
const html = /^pages-html\/(.+)\.html$/.exec(rel);
|
|
236
|
+
const post = POST_COLLECTIONS.exec(rel);
|
|
237
|
+
if (html) {
|
|
238
|
+
pages.push({ slug: html[1] });
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (!declaration && !post && !/^pages\/[^/]+\.json$/.test(rel)) return;
|
|
242
|
+
let json;
|
|
243
|
+
try {
|
|
244
|
+
json = JSON.parse(text);
|
|
245
|
+
} catch {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (declaration) declarations.push({ path: `content/${rel}`, json });
|
|
249
|
+
else if (!post) pages.push({ slug: json?.slug });
|
|
250
|
+
else if (post[2] === undefined) collection(post[1] ?? "").settings = { pageSize: json?.pageSize };
|
|
251
|
+
else collection(post[1] ?? "").posts.push({ slug: post[2], post: {
|
|
252
|
+
status: json?.status, scheduledAt: json?.scheduledAt, tags: json?.tags, categories: json?.categories,
|
|
253
|
+
} });
|
|
254
|
+
},
|
|
255
|
+
/** The declared redirects the collected content shadows. @param {number} [now] */
|
|
256
|
+
shadowed(now = Date.now()) {
|
|
257
|
+
const routes = contentGeneratedRoutes({ pages, collections, now });
|
|
258
|
+
return redirectsYieldingToRoutes(declarations, (source) => routes.has(source)).shadowed;
|
|
259
|
+
},
|
|
260
|
+
};
|
|
261
|
+
}
|
package/src/validate.mjs
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* point; `validateConfigShape` is exported for focused testing.
|
|
17
17
|
*/
|
|
18
18
|
import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
|
|
19
|
-
import { join, relative } from "node:path";
|
|
19
|
+
import { join, relative, sep } from "node:path";
|
|
20
20
|
import { contrastRatio, declaredObligations, isRegulatedCompliance, validateDeclaredConfig } from "./declared-config.mjs";
|
|
21
21
|
import {
|
|
22
22
|
foreignTenantSegments,
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
workspacePathForTenantRelative,
|
|
25
25
|
} from "./tot-repo-mappings.mjs";
|
|
26
26
|
import { isForbiddenPublicPath, publicBinaryFindings } from "./public-binaries.mjs";
|
|
27
|
+
import { createRedirectShadowCollector, shadowedRedirectMessage } from "./redirect-shadows.mjs";
|
|
27
28
|
import { pageSlugFindings } from "./page-slugs.mjs";
|
|
28
29
|
import { ANALYTICS_DECLARATION_FILE, analyticsDeclarationFindings } from "./analytics-declaration.mjs";
|
|
29
30
|
import { parseSku, skuCollisions, skuFindings } from "./sku.mjs";
|
|
@@ -1206,6 +1207,23 @@ function readJsonSafe(path) {
|
|
|
1206
1207
|
return { value: null, error: /** @type {Error} */ (e).message };
|
|
1207
1208
|
}
|
|
1208
1209
|
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Declared redirects a generated page shadows (the same rule the publish and the preview reconcile
|
|
1212
|
+
* apply), as warnings naming the file, the entry, why, and what to do.
|
|
1213
|
+
* @param {string} contentDir @param {(p: string) => string} rel
|
|
1214
|
+
*/
|
|
1215
|
+
function shadowedRedirectFindings(contentDir, rel) {
|
|
1216
|
+
const collector = createRedirectShadowCollector();
|
|
1217
|
+
for (const p of walk(contentDir, (x) => x.endsWith(".json") || x.endsWith(".html"))) {
|
|
1218
|
+
const path = relative(contentDir, p).split(sep).join("/");
|
|
1219
|
+
if (!/^(redirects\.json|[^/]+\/redirects\.json|pages-html\/.+\.html|pages\/[^/]+\.json|(blog|the-build)\/(settings\.json|posts\/[^/]+\.json))$/.test(path)) continue;
|
|
1220
|
+
collector.add(path, readFileSync(p, "utf8"));
|
|
1221
|
+
}
|
|
1222
|
+
return collector.shadowed().map((entry) => mk(WARN, "redirect-shadowed",
|
|
1223
|
+
rel(join(contentDir, entry.file.slice("content/".length))), shadowedRedirectMessage(entry),
|
|
1224
|
+
`delete ${JSON.stringify(entry.key)} from ${entry.file}`));
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1209
1227
|
function walk(dir, pred) {
|
|
1210
1228
|
const out = [];
|
|
1211
1229
|
if (!existsSync(dir)) return out;
|
|
@@ -1441,6 +1459,10 @@ export function validateTenant(tenantDir, opts = {}) {
|
|
|
1441
1459
|
// 3b. editorial page slugs — every page must be reachable at its slug on the hosted router.
|
|
1442
1460
|
findings.push(...editorialSlugFindings(contentDir, pagesDir, rel));
|
|
1443
1461
|
|
|
1462
|
+
// 3c. a declared redirect whose source the content now generates a page for: the page is served
|
|
1463
|
+
// and the redirect yields, so this warns rather than refuses.
|
|
1464
|
+
findings.push(...shadowedRedirectFindings(contentDir, rel));
|
|
1465
|
+
|
|
1444
1466
|
// 4. raw HTML documents — validate + portability + resolution
|
|
1445
1467
|
const hasChrome = providesChrome(contentDir);
|
|
1446
1468
|
const htmlFiles = walk(contentDir, (p) => p.endsWith(".html"));
|
package/src/viewer-session.mjs
CHANGED
|
@@ -69,8 +69,29 @@ function originOf(url) {
|
|
|
69
69
|
}
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
-
/**
|
|
73
|
-
|
|
72
|
+
/**
|
|
73
|
+
* The waits before each retry of a session mint the store refused because Token of Trust's
|
|
74
|
+
* identity service (MCP) was briefly unavailable. An MCP restart is unreachable for 40-90 s,
|
|
75
|
+
* so the schedule spans about 90 s; the store retries each attempt itself as well.
|
|
76
|
+
*/
|
|
77
|
+
export const MCP_OUTAGE_RETRY_DELAYS_MS = Object.freeze([2_000, 4_000, 8_000, 15_000, 30_000, 30_000]);
|
|
78
|
+
|
|
79
|
+
/** The cli-session codes that mean the MCP was briefly unavailable, not misconfigured. */
|
|
80
|
+
const MCP_OUTAGE_CODES = new Set(["mcp_unreachable", "mcp_unavailable"]);
|
|
81
|
+
const MCP_OUTAGE_STATUSES = new Set([502, 503, 504]);
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Is a cli-session refusal an MCP outage worth waiting out? The store names every seam
|
|
85
|
+
* fault `error: "mcp_unreachable"` and says which in `code`: a lost connection
|
|
86
|
+
* (`mcp_unreachable`), an MCP answering 502/503/504 (`mcp_unavailable`, or `mcp_http_error`
|
|
87
|
+
* with that `upstreamStatus`). A misconfigured or unconfigured seam is never retried.
|
|
88
|
+
* @param {number} status @param {Record<string, unknown>|null} body
|
|
89
|
+
*/
|
|
90
|
+
export function isMcpOutageRefusal(status, body) {
|
|
91
|
+
if ((status !== 502 && status !== 503) || body?.error !== "mcp_unreachable") return false;
|
|
92
|
+
if (typeof body.code === "string" && MCP_OUTAGE_CODES.has(body.code)) return true;
|
|
93
|
+
return body.code === "mcp_http_error" && MCP_OUTAGE_STATUSES.has(Number(body.upstreamStatus));
|
|
94
|
+
}
|
|
74
95
|
|
|
75
96
|
/** A response whose body was already read, re-exposed so the caller can read it again. */
|
|
76
97
|
const replayed = (res, body) => ({
|
|
@@ -108,6 +129,12 @@ export function describeCliSessionRefusal(status, body, signedInMcpUrl) {
|
|
|
108
129
|
const code = body && typeof body.code === "string" ? body.code : null;
|
|
109
130
|
|
|
110
131
|
if (status === 502 || status === 503) {
|
|
132
|
+
if (isMcpOutageRefusal(status, body)) {
|
|
133
|
+
return {
|
|
134
|
+
message: `couldn't verify your session — Token of Trust's identity service (MCP) is unavailable${code ? ` (${code})` : ""}.`,
|
|
135
|
+
hint: "it is usually back within a few minutes; re-run then. if it persists, report it with `tot feedback`.",
|
|
136
|
+
};
|
|
137
|
+
}
|
|
111
138
|
return {
|
|
112
139
|
message: `couldn't verify your session — the store's identity check failed${code ? ` (${code})` : ""}.`,
|
|
113
140
|
hint: "retry shortly; if it persists, report it with `tot feedback`.",
|
|
@@ -136,7 +163,8 @@ export function describeCliSessionRefusal(status, body, signedInMcpUrl) {
|
|
|
136
163
|
*
|
|
137
164
|
* @param {{ tenant:string, env?:NodeJS.ProcessEnv, fetchImpl?:typeof fetch,
|
|
138
165
|
* storefrontUrl?:string|null, resolveDev?:typeof resolveDeveloperSession,
|
|
139
|
-
* verbose?:boolean, log?:(s:string)=>void,
|
|
166
|
+
* verbose?:boolean, log?:(s:string)=>void, notify?:(s:string)=>void,
|
|
167
|
+
* sleep?:(ms:number)=>Promise<void> }} params
|
|
140
168
|
* @returns {Promise<
|
|
141
169
|
* { ok:true, base:string, identity:{ account:string|null, mcp:string|null },
|
|
142
170
|
* authHeaders:Record<string,string> } |
|
|
@@ -151,6 +179,7 @@ export async function resolveViewerTransport({
|
|
|
151
179
|
resolveDev = resolveDeveloperSession,
|
|
152
180
|
verbose = false,
|
|
153
181
|
log = (s) => console.error(`[verbose] ${s}`),
|
|
182
|
+
notify = (s) => console.error(s),
|
|
154
183
|
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
155
184
|
}) {
|
|
156
185
|
// --verbose: request URL + HTTP status + the server's error code only — NEVER
|
|
@@ -204,18 +233,22 @@ export async function resolveViewerTransport({
|
|
|
204
233
|
return { ok: false, message: "your selected MCP issuer isn't trusted by this store.",
|
|
205
234
|
hint: "report it with `tot feedback`; this command keeps your selected issuer." };
|
|
206
235
|
}
|
|
236
|
+
// An MCP outage (a restart leaves it unavailable for 40-90 s) is waited out on the
|
|
237
|
+
// schedule above, then reported naming the MCP. No other refusal is retried.
|
|
207
238
|
let mintedSession = await mintSession(base, dev.token, selectedMcp, fetchImpl, vlog);
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const
|
|
212
|
-
if (
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
239
|
+
let notified = false;
|
|
240
|
+
for (const delay of MCP_OUTAGE_RETRY_DELAYS_MS) {
|
|
241
|
+
if (!mintedSession.ok) break;
|
|
242
|
+
const { status } = mintedSession.response;
|
|
243
|
+
if (status !== 502 && status !== 503) break;
|
|
244
|
+
const refusal = await readJson(mintedSession.response);
|
|
245
|
+
mintedSession = { ok: true, response: replayed(mintedSession.response, refusal) };
|
|
246
|
+
if (!isMcpOutageRefusal(status, refusal)) break;
|
|
247
|
+
if (!notified) notify("Token of Trust's identity service (MCP) is unavailable — retrying for up to 90s…");
|
|
248
|
+
notified = true;
|
|
249
|
+
vlog(`cli-session ${refusal.code} — retrying in ${delay}ms`);
|
|
250
|
+
await sleep(delay);
|
|
251
|
+
mintedSession = await mintSession(base, dev.token, selectedMcp, fetchImpl, vlog);
|
|
219
252
|
}
|
|
220
253
|
if (!mintedSession.ok) return mintedSession.refusal;
|
|
221
254
|
const res = mintedSession.response;
|