@opentf/afw-cli 0.0.0-stage → 1.31.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Open Tech Foundation and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,100 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @opentf/afw-cli
4
+
5
+ ***Static generation for AFW apps, run as an `esdev build` step***
6
+
7
+ [Static generation guide](https://afw.opentechf.org/docs/deployment/static-generation) | [Changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw-cli/CHANGELOG.md) | [GitHub](https://github.com/Open-Tech-Foundation/afw)
8
+
9
+ </div>
10
+
11
+ <div align="right">
12
+
13
+ *An [Open Tech Foundation](https://opentechf.org/) project*
14
+
15
+ </div>
16
+
17
+ > Your project owns its build. This package supplies the pieces a prerender step
18
+ > needs: route and loader discovery, page rendering, API and loader bundles, plus a
19
+ > release hook that writes search indexes, feeds and `llms.txt`.
20
+
21
+ ```json
22
+ {
23
+ "plugins": [
24
+ { "module": "@opentf/esdev-plugin-afw", "options": { "mode": "ssg" } },
25
+ { "module": "@opentf/afw-cli/ssg", "export": "siteOutputPlugin",
26
+ "options": { "target": "web", "prerenderTarget": "site-ssg", "root": "." } }
27
+ ],
28
+ "build": {
29
+ "targets": {
30
+ "web": { "entry": "index.html", "outdir": "dist" },
31
+ "site-ssg": { "entry": "ssg.js", "out": ".ssg/ssg.js", "then": "run" }
32
+ }
33
+ }
34
+ }
35
+ ```
36
+
37
+ `esdev build` bundles the site, then runs `ssg.js`, which prerenders every route
38
+ into the staged output. Only when every step succeeds does the new site replace the
39
+ old one.
40
+
41
+ > [!NOTE]
42
+ > **Alpha.** The package keeps its historical name; the old `afw` executable and
43
+ > its `dev` / `build` / `serve` commands are retired in favour of `esdev`.
44
+
45
+ ## Install
46
+
47
+ ```sh
48
+ pnpm add -D @opentf/afw-cli @opentf/esdev-plugin-afw
49
+ pnpm add @opentf/afw
50
+ ```
51
+
52
+ Requires esdev 0.16 or newer. `esdev create my-site --template=docs` generates a
53
+ project with the prerender target, `ssg.js` and the release hook already in place.
54
+
55
+ ## The prerender step
56
+
57
+ `ssg.js` is a short script you own. It uses this package to:
58
+
59
+ | Step | Helpers |
60
+ | --- | --- |
61
+ | Find pages and loaders under `app/` | `discoverPages`, `discoverLoaders`, `assertNoRouteConflicts` |
62
+ | Read `afw.config.js` | `loadConfig` |
63
+ | Render each route into the shell `index.html` | `runPrerender`, `stampHydrateSentinel` |
64
+ | Bundle server code for a deploy adapter | `emitLoaderBundle`, `emitApiBundle` |
65
+ | Hand results to the release hook | `writePrerenderReport` |
66
+
67
+ Pages with dynamic segments are skipped unless they export `getStaticPaths()`.
68
+ The [static generation guide](https://afw.opentechf.org/docs/deployment/static-generation)
69
+ walks through a complete `ssg.js`.
70
+
71
+ ## The release hook
72
+
73
+ `siteOutputPlugin` runs in the staging area after prerendering and before the
74
+ site is published:
75
+
76
+ | Output | Source |
77
+ | --- | --- |
78
+ | Search index | `afwc docs index` over the prerendered HTML |
79
+ | RSS / Atom feeds | The blog section, when `afw.config.js` has one |
80
+ | `llms.txt`, `llms-full.txt` | Page titles and descriptions, for LLM context |
81
+
82
+ | Option | Purpose |
83
+ | --- | --- |
84
+ | `target` | The browser build target to post-process (e.g. `"web"`) |
85
+ | `prerenderTarget` | The prerender target that must run first |
86
+ | `root` | The site's source folder, relative to the working directory |
87
+
88
+ The hook never runs under `esdev start`. If indexing fails, the build fails and the
89
+ previous deployment stays live.
90
+
91
+ ## Environment
92
+
93
+ | Variable | Effect |
94
+ | --- | --- |
95
+ | `AFWC_BIN` | Use this `afwc` executable for compilation and indexing |
96
+ | `EXCLUDE_ROUTES` | Comma-separated route folders the release hook skips (the starter `ssg.js` honours it too) |
97
+
98
+ ## License
99
+
100
+ MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@opentf/afw-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.31.0",
4
+ "description": "Static generation for AFW apps, run as an esdev build step.",
5
+ "type": "module",
6
+ "scripts": {
7
+ "build": "cp ../../LICENSE LICENSE"
8
+ },
9
+ "exports": {
10
+ "./ssg": "./src/ssg.js"
11
+ },
12
+ "files": [
13
+ "src"
14
+ ],
15
+ "engines": {
16
+ "esdev": ">=0.16.0"
17
+ },
18
+ "dependencies": {
19
+ "@opentf/esdev-plugin-afw": "0.5.0"
20
+ },
21
+ "peerDependencies": {
22
+ "@opentf/afw": "0.33.0"
23
+ },
24
+ "keywords": [
25
+ "afw",
26
+ "opentf",
27
+ "ssg",
28
+ "static-site-generator",
29
+ "prerender",
30
+ "esdev"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/Open-Tech-Foundation/afw.git",
35
+ "directory": "packages/afw-cli"
36
+ },
37
+ "homepage": "https://afw.opentechf.org/docs/deployment/static-generation",
38
+ "bugs": "https://github.com/Open-Tech-Foundation/afw/issues",
39
+ "license": "MIT",
40
+ "publishConfig": {
41
+ "access": "public"
42
+ }
43
+ }
package/src/output.js ADDED
@@ -0,0 +1,63 @@
1
+ // Release-only output work, after every target and prerender step has finished.
2
+ import { file, remove } from "runtime:fs";
3
+ import { join, resolve } from "runtime:path";
4
+ import { cwd, env } from "runtime:process";
5
+ import { exists, writeFile } from "./runtime.js";
6
+ import { discoverPages, loadConfig, resolveCompiler, runBlogFeed, runDocsSearchIndex, runLlmsFiles, searchProviderWarning } from "./shared.js";
7
+ import { step } from "./reporter.js";
8
+
9
+ const REPORT = ".afw-prerender.json";
10
+
11
+ /** Hand resolved render metadata to the finish hook without recompiling pages. */
12
+ export async function writePrerenderReport(outDir, result) {
13
+ await writeFile(join(outDir, REPORT), JSON.stringify({ siteDescription: result.siteDescription ?? "" }));
14
+ }
15
+
16
+ /** esdev project plugin (release-only `finish` hook); output paths come from staging, never from config. */
17
+ export function siteOutputPlugin({ root = ".", target = "web", prerenderTarget, exclude = [] } = {}) {
18
+ const siteRoot = resolve(cwd(), root);
19
+ return {
20
+ name: "afw-site-output",
21
+ finish: {
22
+ async handler(targets) {
23
+ const output = targets[target];
24
+ if (!output) return;
25
+ // A selected browser-only build has no prerender step and must not index CSR.
26
+ if (prerenderTarget && !targets[prerenderTarget]) return;
27
+ if (output.platform !== "browser") throw new Error(`Site output target "${target}" must be a browser target`);
28
+ const siteDir = output.outDir;
29
+ const reportPath = join(siteDir, REPORT);
30
+ let siteDescription = "";
31
+ if (await exists(reportPath)) {
32
+ ({ siteDescription } = await file(reportPath).json());
33
+ await remove(reportPath);
34
+ } else if (prerenderTarget) {
35
+ throw new Error(`Prerender target "${prerenderTarget}" must call writePrerenderReport(outDir, result)`);
36
+ }
37
+ const config = await loadConfig(siteRoot);
38
+ const appDir = join(siteRoot, "app");
39
+ const excluded = new Set([...exclude, ...(env.EXCLUDE_ROUTES ?? "").split(",").filter(Boolean)]);
40
+ const baseUrl = String(config?.site?.url ?? "").replace(/\/+$/, "");
41
+ const searchWarning = searchProviderWarning(config);
42
+ if (searchWarning) console.warn(searchWarning);
43
+ if (config?.docs?.search?.provider === "afw") {
44
+ const progress = step("Building search index");
45
+ const { afwc } = await resolveCompiler();
46
+ const search = await runDocsSearchIndex(siteRoot, config, siteDir, afwc);
47
+ progress.done(`Search index — ${search?.pages ?? 0} page(s)`);
48
+ }
49
+ if (config?.blog) {
50
+ const progress = step("Generating blog feeds");
51
+ const feed = await runBlogFeed(siteRoot, appDir, config, siteDir, baseUrl, excluded);
52
+ progress.done(feed ? `Blog feeds — ${feed.count} post(s) → ${feed.paths.join(", ")}` : "Blog feeds — skipped");
53
+ }
54
+ if (config?.docs || config?.blog) {
55
+ const progress = step("Generating LLM context");
56
+ const pages = await discoverPages(appDir, excluded);
57
+ const llms = await runLlmsFiles(siteRoot, appDir, pages, config, siteDir, baseUrl, { siteDescription });
58
+ progress.done(llms ? `LLM context — ${llms.paths.join(", ")}` : "LLM context — skipped");
59
+ }
60
+ },
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,220 @@
1
+ // SSG pre-render (ARCHITECTURE.md §6): build a *server* bundle of the app with the
2
+ // compiler's SSG backend (HTML-string renderers), then run it in-process to
3
+ // render each route to a static HTML file. No DOM — the SSG output is pure string
4
+ // concatenation, so no effects/lifecycle run.
5
+
6
+ import { dirname, join } from "runtime:path";
7
+
8
+ import { exists, writeFile } from "./runtime.js";
9
+
10
+ import {
11
+ DATA_FILE,
12
+ buildServerBundle,
13
+ injectHead,
14
+ injectHydrationData,
15
+ injectMarkup,
16
+ injectRouteData,
17
+ modulepreloadTags,
18
+ stampRenderedPath,
19
+ withHtmlLang,
20
+ } from "./shared.js";
21
+
22
+ // "/" → dist/index.html, "/post/1" → dist/post/1/index.html, "/fr/about" → dist/fr/about/index.html.
23
+ function htmlPathFor(outDir, route) {
24
+ return route === "/" ? join(outDir, "index.html") : join(outDir, route, "index.html");
25
+ }
26
+
27
+ // Prefix a locale-agnostic route with `locale` (bare for the default) — the URL form
28
+ // that both selects the output file and, passed to renderRoute, pins router.locale.
29
+ function localizeFor(path, locale, defaultLocale) {
30
+ if (!locale || locale === defaultLocale) return path;
31
+ return path === "/" ? `/${locale}` : `/${locale}${path}`;
32
+ }
33
+
34
+ // `rel="alternate" hreflang` descriptors for a route across all locales (+ x-default),
35
+ // merged into metadata.links so renderHead emits them (docs/I18N.md §6).
36
+ function alternatesFor(path, locales, defaultLocale) {
37
+ const links = locales.map((l) => ({
38
+ rel: "alternate",
39
+ hreflang: l,
40
+ href: localizeFor(path, l, defaultLocale),
41
+ }));
42
+ links.push({ rel: "alternate", hreflang: "x-default", href: localizeFor(path, defaultLocale, defaultLocale) });
43
+ return links;
44
+ }
45
+
46
+ // Absolute URL for sitemap/robots; "" if no base URL configured.
47
+ function absoluteUrl(baseUrl, path) {
48
+ if (!baseUrl) return "";
49
+ return baseUrl.replace(/\/+$/, "") + (path === "/" ? "/" : path);
50
+ }
51
+
52
+ // Emit sitemap.xml (absolute <loc> per rendered path, with <lastmod> where the
53
+ // last-updated map knows the path) — requires a base URL. A project-supplied
54
+ // public/sitemap.xml takes precedence (it overwrites ours on copy).
55
+ async function writeSitemap(outDir, publicDir, baseUrl, paths, lastUpdated = {}) {
56
+ if (await exists(join(publicDir, "sitemap.xml"))) return false;
57
+ if (!baseUrl) {
58
+ console.warn("⚠ sitemap.xml skipped: no site URL (pass --base-url or set afw.config)");
59
+ return false;
60
+ }
61
+ const urls = paths
62
+ .map((p) => {
63
+ const lastmod = lastUpdated[p] ? `<lastmod>${escapeXml(lastUpdated[p])}</lastmod>` : "";
64
+ return ` <url><loc>${escapeXml(absoluteUrl(baseUrl, p))}</loc>${lastmod}</url>`;
65
+ })
66
+ .join("\n");
67
+ const xml =
68
+ `<?xml version="1.0" encoding="UTF-8"?>\n` +
69
+ `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`;
70
+ await writeFile(join(outDir, "sitemap.xml"), xml);
71
+ return true;
72
+ }
73
+
74
+ // Emit a permissive robots.txt referencing the sitemap (honor a public/ override).
75
+ async function writeRobots(outDir, publicDir, baseUrl, hasSitemap) {
76
+ if (await exists(join(publicDir, "robots.txt"))) return false;
77
+ let body = "User-agent: *\nAllow: /\n";
78
+ if (baseUrl && hasSitemap) body += `Sitemap: ${absoluteUrl(baseUrl, "/sitemap.xml")}\n`;
79
+ await writeFile(join(outDir, "robots.txt"), body);
80
+ return true;
81
+ }
82
+
83
+ function escapeXml(s) {
84
+ return String(s).replace(/[&<>'"]/g, (c) =>
85
+ c === "&" ? "&amp;" : c === "<" ? "&lt;" : c === ">" ? "&gt;" : c === "'" ? "&apos;" : "&quot;",
86
+ );
87
+ }
88
+
89
+ /**
90
+ * Pre-render the app to static HTML files under `outDir`. Returns
91
+ * `{ count, skipped, failed, siteDescription }` — `siteDescription` is the site's own
92
+ * `<meta name="description">` text (home route, falling back to the root layout's
93
+ * route-independent metadata), which `llms.txt` uses for its summary line.
94
+ */
95
+ export async function runPrerender({ root, pages, afwEntry, afwc, shellHtml, outDir, baseUrl = "", docsPlugins = [], lastUpdated = {}, i18n = null, loaders = null, chunkManifest = null, onCompile, onRender }) {
96
+ const { mod, cleanup } = await buildServerBundle({ root, pages, afwEntry, afwc, docsPlugins, i18n, onCompile });
97
+
98
+ // i18n (docs/I18N.md §6): pre-render each route once per locale. The default
99
+ // locale is emitted bare (dist/<route>/index.html), others under their prefix
100
+ // (dist/<locale>/<route>/index.html). A single `[null]` means i18n is off — the
101
+ // loop collapses to the original one-render-per-route behavior.
102
+ const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
103
+ const locales = i18nOn ? i18n.locales : [null];
104
+ const defaultLocale = i18nOn ? i18n.defaultLocale : null;
105
+
106
+ const { paths, skipped } = await mod.collectRoutePaths();
107
+
108
+ // `<link rel="modulepreload">` for the page + layout chunks this route will import,
109
+ // so the browser fetches them in parallel with `bundle.js` rather than after it.
110
+ const preloadFor = (route) => modulepreloadTags(chunkManifest?.routes?.[route]);
111
+ const failed = [];
112
+ const rendered = []; // concrete paths that produced an HTML file (for the sitemap)
113
+ let renderedCount = 0;
114
+ let siteDescription = ""; // the home route's resolved description (see the JSDoc above)
115
+ for (const { path, params, route } of paths) {
116
+ onRender?.(++renderedCount, paths.length);
117
+ for (const locale of locales) {
118
+ const urlPath = localizeFor(path, locale, defaultLocale);
119
+ try {
120
+ // Route loader (docs/DATA.md): run it at build time with no `request` and
121
+ // an empty query (a query-dependent loader needs a request server). The result
122
+ // is threaded into the render (`router.data`), inlined into the HTML, and
123
+ // written as a sibling `__data.json` — per locale, since a localized
124
+ // loader can return locale-dependent data.
125
+ const m = loaders?.match(urlPath);
126
+ let data;
127
+ let dataJson = "";
128
+ if (m) ({ data, json: dataJson } = await loaders.loadSerialized(m, { query: {} }));
129
+
130
+ // Passing the localized URL pins router.locale (resolveLocale) and still
131
+ // matches the locale-agnostic route table, so `t()` renders in `locale`.
132
+ const { html, metadata, hydration } =
133
+ (await mod.renderRoute(urlPath, params, "", { data })) ?? { html: "", metadata: {}, hydration: "" };
134
+ const meta = i18nOn
135
+ ? { ...metadata, links: [...(metadata.links || []), ...alternatesFor(path, locales, defaultLocale)] }
136
+ : metadata;
137
+ if (path === "/" && (!locale || locale === defaultLocale) && typeof metadata?.description === "string") {
138
+ siteDescription = metadata.description;
139
+ }
140
+ let head = mod.renderHead(meta, { path: urlPath, baseUrl, managed: true });
141
+ const preload = preloadFor(route);
142
+ if (preload) head += `\n${preload}`;
143
+ // SEO: expose the page's last-updated time (git/frontmatter) as Open Graph's
144
+ // article:modified_time so crawlers see when the content actually changed,
145
+ // and a frontmatter `date` as article:published_time (blog posts).
146
+ // Article tags only on an article: `og:type` "article", or a page with a publish
147
+ // `date`. An index or a landing page is a website; a modified time there
148
+ // describes nothing.
149
+ const published = typeof metadata?.date === "string" ? metadata.date.trim() : "";
150
+ const article = metadata?.openGraph?.type === "article" || Boolean(published);
151
+ const iso = article ? lastUpdated[path] : null;
152
+ if (iso) head += `\n<meta data-afw-head="" property="article:modified_time" content="${escapeXml(iso)}">`;
153
+ if (published) head += `\n<meta data-afw-head="" property="article:published_time" content="${escapeXml(published)}">`;
154
+ // Static hosts decode requested URLs when locating files. Decode generated
155
+ // segments once; leave literal static folder names unchanged.
156
+ const outputPath = Object.keys(params).length
157
+ ? urlPath.split("/").map(decodeURIComponent).join("/") : urlPath;
158
+ const file = htmlPathFor(outDir, outputPath);
159
+ await writeFile(
160
+ file,
161
+ injectRouteData(
162
+ injectHydrationData(
163
+ injectMarkup(injectHead(withHtmlLang(stampRenderedPath(shellHtml, urlPath), locale), head), html),
164
+ hydration,
165
+ ),
166
+ dataJson,
167
+ ),
168
+ );
169
+ if (m) {
170
+ // The static data file SPA navigation fetches on a plain static host —
171
+ // byte-identical to the inline payload ("null" when the loader returned
172
+ // undefined, so a 200 still parses as JSON).
173
+ const dataFile = join(dirname(file), DATA_FILE);
174
+ await writeFile(dataFile, dataJson || "null");
175
+ }
176
+ rendered.push(urlPath);
177
+ } catch (e) {
178
+ failed.push(urlPath);
179
+ const why = e?.afwNotFound ? "loader called notFound()" : (e?.message ?? e);
180
+ console.error(`✗ pre-render failed for ${urlPath}: ${why}`);
181
+ }
182
+ }
183
+ }
184
+
185
+ // 404: any unmatched path resolves to the registered 404 page. Mark noindex so
186
+ // crawlers don't index the error page, and keep it out of the sitemap.
187
+ try {
188
+ const result = await mod.renderRoute("/__afw_404__");
189
+ if (result) {
190
+ let head = mod.renderHead({ robots: "noindex", ...result.metadata }, { baseUrl, managed: true });
191
+ const preload = modulepreloadTags(chunkManifest?.notFound);
192
+ if (preload) head += `\n${preload}`;
193
+ await writeFile(
194
+ join(outDir, "404.html"),
195
+ injectHydrationData(injectMarkup(injectHead(shellHtml, head), result.html), result.hydration),
196
+ );
197
+ }
198
+ } catch {
199
+ /* no 404 page */
200
+ }
201
+
202
+ // Crawl infrastructure: sitemap.xml + robots.txt (honoring public/ overrides).
203
+ const publicDir = join(root, "public");
204
+ const hasSitemap = await writeSitemap(outDir, publicDir, baseUrl, rendered, lastUpdated);
205
+ await writeRobots(outDir, publicDir, baseUrl, hasSitemap);
206
+
207
+ // No "/" route (or it declared no description): fall back to the layout chain's
208
+ // route-independent metadata — the site-wide description every route inherits.
209
+ if (!siteDescription) {
210
+ try {
211
+ const siteMeta = await mod.resolveMetadata({ route: "/", entry: null });
212
+ if (typeof siteMeta?.description === "string") siteDescription = siteMeta.description;
213
+ } catch {
214
+ /* no root layout metadata */
215
+ }
216
+ }
217
+
218
+ cleanup();
219
+ return { count: rendered.length, skipped, failed, siteDescription };
220
+ }
@@ -0,0 +1,103 @@
1
+ // Build reporter. Each phase is a "step" that announces itself, then collapses to a
2
+ // green ✅ line with the elapsed time when done.
3
+ //
4
+ // On a terminal the announcement is a spinner that stays on one line and shows what
5
+ // the phase is working on. Anywhere else — CI, a piped log, a file — there is nothing
6
+ // to animate and no width to fit into, so the step prints one line when it starts and
7
+ // one when it ends, which is what a log wants to hold anyway.
8
+
9
+ // `stdout` is esdev's, not esrun's: naming it in a static import is a load-time
10
+ // SyntaxError under the runtime a released CLI would run on. Reached through the
11
+ // namespace it is simply absent there, which is the same answer as "no terminal".
12
+ const { stdout } = await import("runtime:process");
13
+
14
+ const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
15
+ const FRAME_IN = "•";
16
+ const INTERVAL = 80;
17
+
18
+ const animated = () => Boolean(stdout?.isTTY);
19
+ const width = () => stdout?.columns ?? 80;
20
+
21
+ /** Humanize a millisecond duration: 940ms, 5.2s. */
22
+ export function fmtMs(n) {
23
+ return n < 1000 ? `${Math.round(n)}ms` : `${(n / 1000).toFixed(1)}s`;
24
+ }
25
+
26
+ /** Cut `s` to the terminal width, so a long path cannot wrap and orphan a line. */
27
+ function fit(s) {
28
+ const max = width() - 1;
29
+ return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}…`;
30
+ }
31
+
32
+ // The step currently drawing, if any. A spinner owns the last line of the terminal,
33
+ // so anything else that prints has to take the line back first — see `quiet`.
34
+ let live = null;
35
+
36
+ /**
37
+ * Stop whatever is spinning and clear its line, so a diagnostic printed from deep
38
+ * inside a build starts on a clean one. `console` is read-only here, so this is a
39
+ * call the printer makes rather than something the reporter can arrange for it.
40
+ */
41
+ export function quiet() {
42
+ live?.stop();
43
+ }
44
+
45
+ class Step {
46
+ constructor(label) {
47
+ this.label = label;
48
+ this.detail = "";
49
+ this.t0 = performance.now();
50
+ this.frame = 0;
51
+ this.timer = null;
52
+
53
+ if (!animated()) return void console.log(` ${FRAME_IN} ${label}…`);
54
+ live = this;
55
+ this.draw();
56
+ this.timer = setInterval(() => {
57
+ this.frame = (this.frame + 1) % FRAMES.length;
58
+ this.draw();
59
+ }, INTERVAL);
60
+ }
61
+
62
+ draw() {
63
+ const detail = this.detail ? ` ${this.detail}` : "";
64
+ stdout.write(`\r${fit(` ${FRAMES[this.frame]} ${this.label}…${detail}`)}`);
65
+ }
66
+
67
+ /**
68
+ * Record the live detail (the current file, an `N/total` count). On a terminal it
69
+ * rides along on the spinner's line; elsewhere nothing is printed — that would be
70
+ * one line per compiled module — but the last value is kept so a failure can say
71
+ * how far the phase got.
72
+ */
73
+ update(detail) {
74
+ this.detail = detail || "";
75
+ if (this.timer) this.draw();
76
+ }
77
+
78
+ /** Finish the step: green ✅ with `msg` (defaults to the label) and elapsed time. */
79
+ done(msg) {
80
+ this.stop();
81
+ console.log(` ✅ ${msg || this.label} ${fmtMs(performance.now() - this.t0)}`);
82
+ }
83
+
84
+ /** Mark the step failed: red ✗ with `msg`, plus how far it had got. */
85
+ fail(msg) {
86
+ const where = this.detail ? ` (at ${this.detail})` : "";
87
+ this.stop();
88
+ console.log(` ✗ ${msg || this.label}${where}`);
89
+ }
90
+
91
+ stop() {
92
+ if (!this.timer) return;
93
+ clearInterval(this.timer);
94
+ this.timer = null;
95
+ stdout.write("\r");
96
+ live = null;
97
+ }
98
+ }
99
+
100
+ /** Start a build phase. Returns a `Step` you drive with `.update()` then `.done()`. */
101
+ export function step(label) {
102
+ return new Step(label);
103
+ }