goatly 0.1.0 → 0.1.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.
Files changed (161) hide show
  1. package/README.md +874 -1
  2. package/bin/goatly.js +99 -0
  3. package/dist/cli/index.js +234 -0
  4. package/dist/compat/gatsby-node-entry.js +16 -0
  5. package/dist/compat/gatsby-package.json +6 -0
  6. package/dist/compat/md5-file.js +47 -0
  7. package/dist/compat-apis.json +72 -0
  8. package/dist/compat-apis.json.js +62 -0
  9. package/dist/graphql.js +3 -0
  10. package/dist/node/actions/index.js +619 -0
  11. package/dist/node/actions/job-store.js +180 -0
  12. package/dist/node/actions/jobs.js +174 -0
  13. package/dist/node/api-runner.js +258 -0
  14. package/dist/node/bootstrap.js +569 -0
  15. package/dist/node/build/assets.js +110 -0
  16. package/dist/node/build/incremental.js +208 -0
  17. package/dist/node/build/index.js +763 -0
  18. package/dist/node/build/memory-governor.js +450 -0
  19. package/dist/node/build/output-dirs.js +70 -0
  20. package/dist/node/build/page-data.js +40 -0
  21. package/dist/node/build/page-files.js +186 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +626 -0
  24. package/dist/node/build/query-workers.js +863 -0
  25. package/dist/node/build/render-thread.js +103 -0
  26. package/dist/node/build/render-worker.js +162 -0
  27. package/dist/node/build/state.js +24 -0
  28. package/dist/node/build/timing-breakdown.js +216 -0
  29. package/dist/node/build/work-clock.js +75 -0
  30. package/dist/node/build/worker-pool.js +242 -0
  31. package/dist/node/cache-layout.js +99 -0
  32. package/dist/node/cache.js +1430 -0
  33. package/dist/node/compat/chokidar-shim.js +148 -0
  34. package/dist/node/compat/core-utils-lmdb.js +145 -0
  35. package/dist/node/compat/create-node-id-shim.js +1 -0
  36. package/dist/node/compat/module-hooks.js +245 -0
  37. package/dist/node/compat/redux-shim.js +1 -0
  38. package/dist/node/config/index.js +162 -0
  39. package/dist/node/config/not-found-pages.js +95 -0
  40. package/dist/node/datastore/codec.js +144 -0
  41. package/dist/node/datastore/index.js +127 -0
  42. package/dist/node/datastore/logfile/cache.js +89 -0
  43. package/dist/node/datastore/logfile/index.js +1329 -0
  44. package/dist/node/datastore/logfile/record.js +71 -0
  45. package/dist/node/datastore/types.js +1 -0
  46. package/dist/node/develop/express-compat.js +207 -0
  47. package/dist/node/develop/graphiql.js +22 -0
  48. package/dist/node/develop/hydration-report.js +41 -0
  49. package/dist/node/develop/index.js +618 -0
  50. package/dist/node/develop/local-url.js +10 -0
  51. package/dist/node/develop/ssr-runner.js +66 -0
  52. package/dist/node/gql.js +5 -0
  53. package/dist/node/index.js +15 -0
  54. package/dist/node/info.js +270 -0
  55. package/dist/node/internal-plugins/data-bridge.js +196 -0
  56. package/dist/node/internal-plugins/page-creator.js +318 -0
  57. package/dist/node/loader/import-module.js +160 -0
  58. package/dist/node/node-helpers.js +66 -0
  59. package/dist/node/not-found-pages.js +220 -0
  60. package/dist/node/plugins/api-list.js +12 -0
  61. package/dist/node/plugins/load-plugins.js +427 -0
  62. package/dist/node/plugins/resolve-plugin.js +79 -0
  63. package/dist/node/plugins/static-exports.js +64 -0
  64. package/dist/node/query/compile.js +326 -0
  65. package/dist/node/query/dependencies.js +45 -0
  66. package/dist/node/query/execute.js +417 -0
  67. package/dist/node/query/extract.js +372 -0
  68. package/dist/node/query/gql-tada-introspection.js +124 -0
  69. package/dist/node/query/graphql-env.js +231 -0
  70. package/dist/node/query/graphql-runner.js +79 -0
  71. package/dist/node/redux/actions.js +1 -0
  72. package/dist/node/redux/index.js +133 -0
  73. package/dist/node/redux/node-changes.js +128 -0
  74. package/dist/node/redux/reducers.js +193 -0
  75. package/dist/node/redux/state.js +71 -0
  76. package/dist/node/renderer.js +124 -0
  77. package/dist/node/reporter-transports.js +259 -0
  78. package/dist/node/reporter.js +497 -0
  79. package/dist/node/schema/date.js +539 -0
  80. package/dist/node/schema/extensions.js +315 -0
  81. package/dist/node/schema/index.js +542 -0
  82. package/dist/node/schema/infer.js +388 -0
  83. package/dist/node/schema/inline-objects.js +128 -0
  84. package/dist/node/schema/naming.js +20 -0
  85. package/dist/node/schema/node-model.js +207 -0
  86. package/dist/node/schema/query-engine.js +1808 -0
  87. package/dist/node/schema/resolver-kinds.js +7 -0
  88. package/dist/node/schema/resolvers.js +273 -0
  89. package/dist/node/schema/type-builders.js +45 -0
  90. package/dist/node/schema/types.js +241 -0
  91. package/dist/node/serve.js +90 -0
  92. package/dist/node/site-page-nodes.js +277 -0
  93. package/dist/node/types.js +1 -0
  94. package/dist/node/utils/content-digest.js +107 -0
  95. package/dist/node/utils/cpus.js +104 -0
  96. package/dist/node/utils/create-node-id.js +51 -0
  97. package/dist/node/utils/env.js +25 -0
  98. package/dist/node/utils/fs-retry.js +74 -0
  99. package/dist/node/utils/memory-signals.js +441 -0
  100. package/dist/node/utils/memory.js +657 -0
  101. package/dist/node/utils/murmurhash.js +32 -0
  102. package/dist/node/utils/parser.js +33 -0
  103. package/dist/node/utils/partition-hash.js +19 -0
  104. package/dist/node/utils/paths.js +122 -0
  105. package/dist/node/utils/resolver.js +48 -0
  106. package/dist/node/utils/runtime.js +5 -0
  107. package/dist/node/utils/serializable.js +41 -0
  108. package/dist/node/utils/strings.js +41 -0
  109. package/dist/node/vite/config.js +289 -0
  110. package/dist/node/vite/paths.js +12 -0
  111. package/dist/node/vite/plugin-deps.js +232 -0
  112. package/dist/node/vite/plugin.js +283 -0
  113. package/dist/node/vite/react-compiler.js +362 -0
  114. package/dist/node/vite/source-files.js +83 -0
  115. package/dist/node/vite/static-image.js +136 -0
  116. package/dist/node/vite/styled-components.js +73 -0
  117. package/dist/node/vite/transforms.js +330 -0
  118. package/dist/node/wasm-data/host.js +406 -0
  119. package/dist/node/wasm-data/lower.js +406 -0
  120. package/dist/node/wasm-data/runner.js +79 -0
  121. package/dist/node/wasm-data/worker.js +95 -0
  122. package/dist/reporter.js +5 -0
  123. package/dist/runtime/api-runner.js +81 -0
  124. package/dist/runtime/app.js +256 -0
  125. package/dist/runtime/client-entry.js +4 -0
  126. package/dist/runtime/client.js +383 -0
  127. package/dist/runtime/default-html.js +31 -0
  128. package/dist/runtime/head-markup.js +100 -0
  129. package/dist/runtime/head-sync.js +101 -0
  130. package/dist/runtime/head-tags.js +45 -0
  131. package/dist/runtime/hydration-report.js +111 -0
  132. package/dist/runtime/index.js +12 -0
  133. package/dist/runtime/link.js +293 -0
  134. package/dist/runtime/loader.js +449 -0
  135. package/dist/runtime/not-found.js +61 -0
  136. package/dist/runtime/page-renderer.js +35 -0
  137. package/dist/runtime/preamble.js +47 -0
  138. package/dist/runtime/react-compat.js +14 -0
  139. package/dist/runtime/renderer-shared.js +10 -0
  140. package/dist/runtime/renderers/react-client.js +14 -0
  141. package/dist/runtime/renderers/react-server.js +99 -0
  142. package/dist/runtime/renderers/react.js +17 -0
  143. package/dist/runtime/renderers/types.js +1 -0
  144. package/dist/runtime/root-error-handlers.js +29 -0
  145. package/dist/runtime/router/history.js +132 -0
  146. package/dist/runtime/router/index.js +240 -0
  147. package/dist/runtime/router/utils.js +118 -0
  148. package/dist/runtime/script.js +110 -0
  149. package/dist/runtime/scroll.js +40 -0
  150. package/dist/runtime/slice.js +11 -0
  151. package/dist/runtime/ssr.js +240 -0
  152. package/dist/runtime/static-query.js +47 -0
  153. package/dist/utils.js +4 -0
  154. package/package.json +105 -3
  155. package/types/graphql-tada.d.ts +223 -0
  156. package/types/graphql.d.ts +2 -0
  157. package/types/index.d.ts +2287 -0
  158. package/types/node.d.ts +389 -0
  159. package/types/reporter.d.ts +187 -0
  160. package/types/router.d.ts +102 -0
  161. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,103 @@
1
+ import { REPORTER_BRIDGE_ENV } from "../reporter.js";
2
+ import { Worker } from "node:worker_threads";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ // src/node/build/render-thread.ts
6
+ const workerFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "render-worker.js");
7
+ const OOM = "ERR_WORKER_OUT_OF_MEMORY";
8
+ /**
9
+ * Starts a render worker (render-worker.ts) for a query worker: a thread that only holds the SSR
10
+ * bundle and the pages of one batch, so that pages are not rendered in a heap that holds node data
11
+ * – there every garbage collection the rendering causes scans that data, too. Batches are rendered
12
+ * one at a time, as by the query worker itself.
13
+ *
14
+ * Resolves once the SSR bundle is loaded, rejects when that fails. When the thread is gone
15
+ * otherwise – out of memory (`oom`), or it exited – `onDeath` is called: the query worker can't
16
+ * go on, batches in flight never settle.
17
+ */
18
+ function startRenderThread(options, o) {
19
+ return new Promise((resolve, reject) => {
20
+ const worker = new Worker(workerFile, {
21
+ workerData: {
22
+ __goatlyRenderWorker: true,
23
+ options
24
+ },
25
+ env: {
26
+ ...process.env,
27
+ ...REPORTER_BRIDGE_ENV,
28
+ NODE_ENV: "production"
29
+ },
30
+ ...o.limitMb ? { resourceLimits: { maxOldGenerationSizeMb: o.limitMb } } : {}
31
+ });
32
+ let ready = false;
33
+ let closed = false;
34
+ let dead = false;
35
+ let nextId = 0;
36
+ const pending = /* @__PURE__ */ new Map();
37
+ let stats = {
38
+ gcMs: 0,
39
+ cpuMs: void 0
40
+ };
41
+ let taken = {
42
+ gcMs: 0,
43
+ cpuMs: 0
44
+ };
45
+ const die = (error) => {
46
+ if (dead || closed) return;
47
+ dead = true;
48
+ worker.terminate();
49
+ o.onDeath(error, error.code === OOM);
50
+ };
51
+ worker.on("message", (msg) => {
52
+ if (msg?.type === "ready") {
53
+ if (msg.error) {
54
+ closed = true;
55
+ worker.terminate();
56
+ return reject(new Error(msg.error));
57
+ }
58
+ ready = true;
59
+ return resolve(thread);
60
+ }
61
+ const batch = pending.get(msg?.id);
62
+ if (!batch) return;
63
+ pending.delete(msg.id);
64
+ if (msg.stats) stats = msg.stats;
65
+ if (msg.error) batch.reject(new Error(msg.error));
66
+ else batch.resolve(msg.result);
67
+ });
68
+ worker.on("error", (e) => die(e instanceof Error ? e : new Error(String(e))));
69
+ worker.on("exit", (code) => die(/* @__PURE__ */ new Error(`render thread exited with code ${code}${ready ? "" : " while starting"}`)));
70
+ const thread = {
71
+ renderBatch(tasks) {
72
+ return new Promise((done, failed) => {
73
+ const id = nextId++;
74
+ pending.set(id, {
75
+ resolve: done,
76
+ reject: failed
77
+ });
78
+ worker.postMessage({
79
+ id,
80
+ tasks
81
+ });
82
+ });
83
+ },
84
+ takeStats() {
85
+ const cpuMs = stats.cpuMs === void 0 ? void 0 : stats.cpuMs - taken.cpuMs;
86
+ const delta = {
87
+ gcMs: stats.gcMs - taken.gcMs,
88
+ cpuMs
89
+ };
90
+ taken = {
91
+ gcMs: stats.gcMs,
92
+ cpuMs: stats.cpuMs ?? 0
93
+ };
94
+ return delta;
95
+ },
96
+ async close() {
97
+ closed = true;
98
+ await worker.terminate();
99
+ }
100
+ };
101
+ });
102
+ }
103
+ export { startRenderThread };
@@ -0,0 +1,162 @@
1
+ import reporter from "../reporter.js";
2
+ import { threadCpuMs, watchGarbageCollections } from "../utils/memory.js";
3
+ import { pageDataPrefix, readPageDataResult } from "./page-data.js";
4
+ import { createPageWriter } from "./page-files.js";
5
+ import { isMainThread, parentPort, threadId, workerData } from "node:worker_threads";
6
+ import path from "node:path";
7
+ import fs from "node:fs";
8
+ import { pathToFileURL } from "node:url";
9
+ // src/node/build/render-worker.ts
10
+ const cssCache = /* @__PURE__ */ new Map();
11
+ /**
12
+ * Pages are rendered one at a time (also by concurrent batches of the in-process pool): plugins
13
+ * keep per-page state in module scope between rendering and `onRenderBody` – react-helmet's
14
+ * `Helmet.renderStatic()` in gatsby-plugin-react-helmet, a react-helmet-async context created in
15
+ * `wrapRootElement` – and would read another page's state if pages interleaved (Gatsby renders
16
+ * one at a time, too). Rendering is mostly synchronous work in this thread anyway: it costs about
17
+ * 10% of the render step (5,000 pages), and a page that waits (Suspense) holds up the next ones.
18
+ */
19
+ let renderQueue = Promise.resolve();
20
+ function oneAtATime(render) {
21
+ const run = renderQueue.then(render, render);
22
+ renderQueue = run.catch(() => {});
23
+ return run;
24
+ }
25
+ /** Creates the page renderer (used in worker threads and in-process for small sites). */
26
+ async function createRenderer(options) {
27
+ const writer = createPageWriter({ onSlow: (ms) => reporter.verbose(`writing page files several at a time: this disk takes ${ms.toFixed(1)} ms to write one${isMainThread ? "" : ` (thread ${threadId})`}`) });
28
+ const renderPage = (await import(pathToFileURL(options.ssrBundle).href)).renderPage;
29
+ const inlineStyles = async (hrefs) => {
30
+ const out = [];
31
+ for (const href of hrefs) {
32
+ let content = cssCache.get(href);
33
+ if (content === void 0) {
34
+ const rel = href.replace(/^https?:\/\/[^/]+/, "").replace(/^\/+/, "");
35
+ const candidates = [path.join(options.publicDir, rel), path.join(options.publicDir, rel.split("/").slice(1).join("/"))];
36
+ content = "";
37
+ for (const c of candidates) try {
38
+ content = await fs.promises.readFile(c, "utf8");
39
+ break;
40
+ } catch {}
41
+ cssCache.set(href, content);
42
+ }
43
+ out.push({
44
+ href,
45
+ content
46
+ });
47
+ }
48
+ return out;
49
+ };
50
+ /**
51
+ * Renders the page (false: it had no result, see `missing`) and writes its files – `written`:
52
+ * they are being written (a slow disk, see createPageWriter), the page is done when it settles
53
+ */
54
+ async function renderTask(task) {
55
+ let { resultJson, pageDataStaticQueryHashes } = task;
56
+ if (resultJson === void 0) {
57
+ const cached = readPageDataResult(task.pageDataFile, task.componentChunkName, task.pagePath, task.matchPath);
58
+ if (!cached) return false;
59
+ resultJson = cached.resultJson;
60
+ pageDataStaticQueryHashes = cached.staticQueryHashes;
61
+ }
62
+ const json = resultJson;
63
+ const styles = options.inlineCss ? await inlineStyles(task.assets.stylesheets) : void 0;
64
+ const { html, staticQueryHashes } = await oneAtATime(() => renderPage({
65
+ pagePath: task.pagePath,
66
+ pageData: {
67
+ componentChunkName: task.componentChunkName,
68
+ path: task.pagePath,
69
+ ...task.matchPath ? { matchPath: task.matchPath } : {},
70
+ result: JSON.parse(json),
71
+ staticQueryHashes: [],
72
+ slicesMap: {}
73
+ },
74
+ scripts: task.assets.scripts,
75
+ modulePreloads: task.assets.modulePreloads,
76
+ stylesheets: options.inlineCss ? [] : task.assets.stylesheets,
77
+ inlineStyles: styles,
78
+ pageDataUrl: task.pageDataUrl,
79
+ inlinePageData: options.inlinePageData,
80
+ buildHash: options.buildHash,
81
+ generator: options.generator
82
+ }));
83
+ const sq = JSON.stringify(staticQueryHashes);
84
+ const pageData = sq !== pageDataStaticQueryHashes ? writer.write(task.pageDataFile, pageDataPrefix(task.componentChunkName, task.pagePath, task.matchPath) + `${json},"staticQueryHashes":${sq},"slicesMap":{}}`, !!task.filesExist) : void 0;
85
+ const page = writer.write(task.htmlFile, html, !!task.filesExist);
86
+ return {
87
+ staticQueryHashes,
88
+ written: pageData && page ? Promise.all([pageData, page]) : pageData ?? page
89
+ };
90
+ }
91
+ async function renderBatch(tasks) {
92
+ const result = {
93
+ rendered: 0,
94
+ errors: [],
95
+ staticQueryHashes: {},
96
+ missing: []
97
+ };
98
+ const done = (task, staticQueryHashes) => {
99
+ result.staticQueryHashes[task.pagePath] = staticQueryHashes;
100
+ result.rendered++;
101
+ };
102
+ const failed = (task, e) => {
103
+ const err = e;
104
+ result.errors.push({
105
+ pagePath: task.pagePath,
106
+ message: err?.message ?? String(e),
107
+ stack: err?.stack
108
+ });
109
+ };
110
+ /** pages whose files are being written (a slow disk: see createPageWriter) */
111
+ const writing = /* @__PURE__ */ new Set();
112
+ for (const task of tasks) {
113
+ try {
114
+ const page = await renderTask(task);
115
+ if (!page) result.missing.push(task.pagePath);
116
+ else if (!page.written) done(task, page.staticQueryHashes);
117
+ else {
118
+ const settled = page.written.then(() => done(task, page.staticQueryHashes), (e) => failed(task, e)).finally(() => writing.delete(settled));
119
+ writing.add(settled);
120
+ if (writing.size >= writer.window) await Promise.race(writing);
121
+ }
122
+ } catch (e) {
123
+ failed(task, e);
124
+ }
125
+ await new Promise((resolve) => setImmediate(resolve));
126
+ }
127
+ await Promise.all(writing);
128
+ return result;
129
+ }
130
+ return { renderBatch };
131
+ }
132
+ if (!isMainThread && parentPort && workerData?.__goatlyRenderWorker) {
133
+ const port = parentPort;
134
+ const options = workerData.options;
135
+ const rendererPromise = options.renderer ? import("../renderer.js").then(({ useRenderer }) => useRenderer(options.renderer.descriptor, options.renderer.root)).then(() => createRenderer(options)) : createRenderer(options);
136
+ rendererPromise.then(() => port.postMessage({ type: "ready" }), (e) => port.postMessage({
137
+ type: "ready",
138
+ error: e?.stack ?? String(e)
139
+ }));
140
+ let gcMs = 0;
141
+ watchGarbageCollections((collection) => gcMs += collection.ms);
142
+ const stats = () => ({
143
+ gcMs,
144
+ cpuMs: threadCpuMs()
145
+ });
146
+ port.on("message", async (msg) => {
147
+ try {
148
+ const result = await (await rendererPromise).renderBatch(msg.tasks);
149
+ port.postMessage({
150
+ id: msg.id,
151
+ result,
152
+ stats: stats()
153
+ });
154
+ } catch (e) {
155
+ port.postMessage({
156
+ id: msg.id,
157
+ error: e?.stack ?? String(e)
158
+ });
159
+ }
160
+ });
161
+ }
162
+ export { createRenderer };
@@ -0,0 +1,24 @@
1
+ import { BUILD_STATE_PATHS } from "../cache-layout.js";
2
+ import { markHtmlStatePending, readPartitionedHtmlState, readPartitionedQueryState, writePartitionedHtmlState, writePartitionedQueryState } from "./partitioned-state.js";
3
+ import path from "node:path";
4
+ import fs from "node:fs";
5
+ // src/node/build/state.ts
6
+ /** the build state in `cacheDir` */
7
+ function openBuildState(cacheDir) {
8
+ const htmlDir = path.join(cacheDir, BUILD_STATE_PATHS.html);
9
+ const queriesDir = path.join(cacheDir, BUILD_STATE_PATHS.queries);
10
+ return {
11
+ readHtml: () => fs.existsSync(htmlDir) ? readPartitionedHtmlState(htmlDir) : null,
12
+ markHtmlPending: (previous, paths) => markHtmlStatePending(htmlDir, paths.filter((p) => !previous || !(p in previous.pages))),
13
+ writeHtml: (state) => writePartitionedHtmlState(htmlDir, state),
14
+ readQueries: () => readPartitionedQueryState(queriesDir),
15
+ async writeQueries(state, options) {
16
+ writePartitionedQueryState(queriesDir, state, { keepUnlisted: options?.pending });
17
+ },
18
+ writeNodeChanges(state) {
19
+ writePartitionedQueryState(queriesDir, state);
20
+ return true;
21
+ }
22
+ };
23
+ }
24
+ export { openBuildState };
@@ -0,0 +1,216 @@
1
+ import { formatRate } from "../reporter-transports.js";
2
+ import { performance } from "node:perf_hooks";
3
+ // src/node/build/timing-breakdown.ts
4
+ const seconds = (ms) => `${(ms / 1e3).toFixed(3)}s`;
5
+ const plural = (n, word, words = `${word}s`) => `${n} ${n === 1 ? word : words}`;
6
+ /**
7
+ * The fixed segments of the build's timing breakdown (in this order). They cover the build's
8
+ * wall-clock time. Only segments that really ran at the same time overlap (HTML rendering while
9
+ * the page queries still run in the query workers); other work that runs alongside a segment
10
+ * (bundling while the page queries run) only counts where the build waits for it.
11
+ */
12
+ const BUILD_SEGMENTS = [
13
+ {
14
+ key: "config",
15
+ label: "load config and plugins"
16
+ },
17
+ {
18
+ key: "cache",
19
+ label: "initialize cache"
20
+ },
21
+ {
22
+ key: "preBootstrap",
23
+ label: "onPluginInit, onPreBootstrap"
24
+ },
25
+ {
26
+ key: "schemaCustomization",
27
+ label: "createSchemaCustomization"
28
+ },
29
+ {
30
+ key: "sourcing",
31
+ label: "source and transform nodes"
32
+ },
33
+ {
34
+ key: "schema",
35
+ label: "build schema"
36
+ },
37
+ {
38
+ key: "createPages",
39
+ label: "createPages"
40
+ },
41
+ {
42
+ key: "extractQueries",
43
+ label: "extract queries"
44
+ },
45
+ {
46
+ key: "postBootstrap",
47
+ label: "onPostBootstrap"
48
+ },
49
+ {
50
+ key: "staticQueries",
51
+ label: "run static queries"
52
+ },
53
+ {
54
+ key: "queryWorkers",
55
+ label: "start query workers"
56
+ },
57
+ {
58
+ key: "pageQueries",
59
+ label: "run page queries"
60
+ },
61
+ {
62
+ key: "bundle",
63
+ label: "wait for JavaScript bundles"
64
+ },
65
+ {
66
+ key: "render",
67
+ label: "build static HTML"
68
+ },
69
+ {
70
+ key: "postBuild",
71
+ label: "onPostBuild"
72
+ },
73
+ {
74
+ key: "finalize",
75
+ label: "save caches and state"
76
+ }
77
+ ];
78
+ /**
79
+ * Splits the build's wall-clock time into the predefined segments: each `until()` attributes the
80
+ * time since the previous checkpoint to a segment, so the segments cover the whole build. A
81
+ * segment that began earlier, alongside the previous ones, passes `from`.
82
+ */
83
+ var SegmentClock = class {
84
+ last;
85
+ start;
86
+ /** when each segment ran, in ms since the start */
87
+ spans = Object.fromEntries(BUILD_SEGMENTS.map((s) => [s.key, []]));
88
+ constructor(start = performance.now()) {
89
+ this.start = this.last = start;
90
+ }
91
+ /**
92
+ * the time from the previous checkpoint (or from `from`, when the segment began earlier,
93
+ * alongside the previous segments) to `at` (default: now) belongs to `segment`
94
+ */
95
+ until(segment, at = performance.now(), from) {
96
+ const end = Math.max(this.last, at);
97
+ const begin = from === void 0 ? this.last : Math.min(this.last, Math.max(this.start, from));
98
+ this.last = end;
99
+ if (end <= begin) return;
100
+ const spans = this.spans[segment];
101
+ const previous = spans.at(-1);
102
+ const span = [begin - this.start, end - this.start];
103
+ if (previous && previous[1] >= span[0]) previous[1] = Math.max(previous[1], span[1]);
104
+ else spans.push(span);
105
+ }
106
+ /** milliseconds per segment (segments that ran at the same time both count that time) */
107
+ totals() {
108
+ return Object.fromEntries(BUILD_SEGMENTS.map((s) => [s.key, this.spans[s.key].reduce((ms, [a, b]) => ms + b - a, 0)]));
109
+ }
110
+ /** all predefined segments (also the empty ones), in order, with when they ran */
111
+ segments() {
112
+ const totals = this.totals();
113
+ return BUILD_SEGMENTS.map((s) => ({
114
+ key: s.key,
115
+ label: s.label,
116
+ ms: totals[s.key],
117
+ spans: this.spans[s.key].map(([a, b]) => [a, b])
118
+ }));
119
+ }
120
+ };
121
+ /** garbage collection shows in a part's status from this share of the workers' busy time (and 1 s) */
122
+ const NOTABLE_GC_SHARE = .1;
123
+ /** the CPU time shows when the workers were on a CPU for less than this share of their busy time */
124
+ const LOW_CPU_SHARE = .6;
125
+ const NOTABLE_MS = 1e3;
126
+ /**
127
+ * "workers busy 481.633s in total", and where that time went when it was not the work itself:
128
+ * V8's garbage collections (a large heap makes each one slow), or waiting – the threads' CPU time
129
+ * is much less than their busy time when they wait: for a CPU (more workers than CPUs, a CPU
130
+ * quota), for the disk, or for work done elsewhere (jobs in the main thread, a plugin's native
131
+ * code or requests).
132
+ */
133
+ function busyText(span) {
134
+ const parts = [`workers busy ${seconds(span.ms)} in total`];
135
+ const { gcMs = 0, cpuMs } = span;
136
+ if (gcMs >= NOTABLE_MS && gcMs >= NOTABLE_GC_SHARE * span.ms) parts.push(`${seconds(gcMs)} of it collecting garbage`);
137
+ if (cpuMs !== void 0 && span.ms - cpuMs >= NOTABLE_MS && cpuMs < LOW_CPU_SHARE * span.ms) parts.push(`${seconds(cpuMs)} of it on a CPU`);
138
+ return parts.join(", ");
139
+ }
140
+ /**
141
+ * What the query workers' heap guards did, for the step's status: "caches dropped 38 times for
142
+ * memory, 29.702s of forced garbage collection" – the time of all the collections they forced
143
+ * (also those after which the caches stayed; between batches: not part of the workers' busy
144
+ * times), from a second. Empty when they did nothing worth a mention.
145
+ */
146
+ function guardText(guard) {
147
+ if (!guard) return "";
148
+ return [guard.releases > 0 && `caches dropped ${plural(guard.releases, "time")} for memory`, guard.ms >= NOTABLE_MS && `${seconds(guard.ms)} of forced garbage collection`].filter(Boolean).join(", ");
149
+ }
150
+ /**
151
+ * When HTML rendering of the pipelined worker step began (ms since the epoch), or `undefined` when
152
+ * no page was rendered: never before the workers were ready or the bundles existed (the steps
153
+ * before it), so only the page queries overlap it.
154
+ */
155
+ function pipelinedRenderStart(t) {
156
+ if (!(t.render.end >= t.render.start)) return void 0;
157
+ return Math.max(t.ready, t.renderJob, t.render.start);
158
+ }
159
+ /**
160
+ * The parts of the pipelined worker step on its timeline: persisting the data for the workers,
161
+ * starting them (each loads the datastore, e.g. the logfile store's index), running the page
162
+ * queries, waiting for the bundles (when the queries were done first) and building the HTML.
163
+ * The first parts follow one another; HTML rendering starts as soon as the bundles exist, often
164
+ * while queries still run, so its part (with its `offset`) overlaps the queries: its time is the
165
+ * whole time it ran, and its status says how much of it was alongside the queries.
166
+ */
167
+ function pipelineParts(o) {
168
+ const { query, render } = o.timings;
169
+ let last = o.start;
170
+ const until = (at) => {
171
+ const from = last;
172
+ last = Math.min(o.end, Math.max(last, at));
173
+ return (last - from) / 1e3;
174
+ };
175
+ const parts = [{
176
+ text: "persist data for the query workers",
177
+ elapsed: until(o.start + o.persistMs)
178
+ }, {
179
+ text: "start query workers",
180
+ elapsed: until(o.timings.ready),
181
+ status: plural(o.workers, "worker")
182
+ }];
183
+ const queried = query.end >= query.start;
184
+ parts.push({
185
+ text: "run page queries",
186
+ elapsed: until(queried ? query.end : o.timings.ready),
187
+ status: [
188
+ plural(o.queries, "query", "queries"),
189
+ queried && o.queries > 0 && formatRate(o.queries, (query.end - query.start) / 1e3),
190
+ queried && query.ms > 0 && busyText(query)
191
+ ].filter(Boolean).join(", ")
192
+ });
193
+ const queriesEnd = last;
194
+ if (o.timings.renderJob > last) parts.push({
195
+ text: "wait for the JavaScript bundles",
196
+ elapsed: until(o.timings.renderJob)
197
+ });
198
+ const rendering = render.end >= render.start;
199
+ const renderStart = Math.min(o.end, Math.max(o.start, pipelinedRenderStart(o.timings) ?? last));
200
+ const alongside = Math.max(0, queriesEnd - renderStart);
201
+ const after = Math.max(0, o.end - Math.max(renderStart, queriesEnd));
202
+ parts.push({
203
+ text: "build static HTML for pages",
204
+ elapsed: (o.end - renderStart) / 1e3,
205
+ offset: (renderStart - o.start) / 1e3,
206
+ status: [
207
+ plural(o.rendered, "page"),
208
+ rendering && o.rendered > 0 && formatRate(o.rendered, (render.end - render.start) / 1e3),
209
+ o.skipped && `${o.skipped} unchanged`,
210
+ alongside > 0 && `${seconds(alongside)} alongside the queries, ${seconds(after)} after them`,
211
+ rendering && busyText(render)
212
+ ].filter(Boolean).join(", ")
213
+ });
214
+ return parts;
215
+ }
216
+ export { BUILD_SEGMENTS, SegmentClock, busyText, guardText, pipelineParts, pipelinedRenderStart };
@@ -0,0 +1,75 @@
1
+ // src/node/build/work-clock.ts
2
+ /** work that ended is kept for this many more, for the collections reported late */
3
+ const MAX_CLOSED = 256;
4
+ /**
5
+ * Measures the work of a thread by kind (a WorkSpan each): its time, the CPU time the thread used
6
+ * for it, and the time V8 paused the thread for garbage collections during it. Work may contain
7
+ * work of another kind (a page query that runs while a page is rendered): that counts for its own
8
+ * span only.
9
+ *
10
+ * Collections are reported after the fact – Node hands them over when the event loop turns, often
11
+ * after the work they interrupted has ended – so each is matched to the work that ran when it
12
+ * began.
13
+ */
14
+ function createWorkClock(options) {
15
+ /** work in progress, the innermost last */
16
+ const open = [];
17
+ /** work that ended, until no collection can have begun during it any more */
18
+ const closed = [];
19
+ return {
20
+ begin(span) {
21
+ const work = {
22
+ span,
23
+ at: options.epoch(),
24
+ from: options.now(),
25
+ cpu: options.cpu(),
26
+ lessMs: 0,
27
+ lessCpu: 0
28
+ };
29
+ open.push(work);
30
+ return work;
31
+ },
32
+ /** the work ended; `counted: false` leaves it out (it turned out to be none) */
33
+ end(work, counted = true) {
34
+ const index = open.lastIndexOf(work);
35
+ if (index < 0) return;
36
+ open.splice(index, 1);
37
+ if (!counted) return;
38
+ const to = options.now();
39
+ const cpu = options.cpu();
40
+ const ms = to - work.from;
41
+ const cpuMs = work.cpu !== void 0 && cpu !== void 0 ? cpu - work.cpu : void 0;
42
+ const { span } = work;
43
+ span.ms += ms - work.lessMs;
44
+ span.start = Math.min(span.start, work.at);
45
+ span.end = Math.max(span.end, work.at + ms);
46
+ span.gcMs ??= 0;
47
+ if (cpuMs !== void 0) span.cpuMs = (span.cpuMs ?? 0) + cpuMs - work.lessCpu;
48
+ closed.push({
49
+ from: work.from,
50
+ to,
51
+ span
52
+ });
53
+ if (closed.length > MAX_CLOSED) closed.shift();
54
+ const outer = open[index - 1];
55
+ if (outer) {
56
+ outer.lessMs += ms;
57
+ if (cpuMs !== void 0) outer.lessCpu += cpuMs;
58
+ }
59
+ },
60
+ /**
61
+ * A collection that began at `start` (on the thread's clock) paused the thread for `ms`.
62
+ * Collections are reported in the order they ran.
63
+ */
64
+ collected(start, ms) {
65
+ let at = closed.findIndex((work) => work.from <= start && start < work.to);
66
+ let span = at < 0 ? void 0 : closed[at].span;
67
+ if (!span) {
68
+ for (let i = open.length - 1; i >= 0 && !span; i--) if (open[i].from <= start) span = open[i].span;
69
+ }
70
+ if (span) span.gcMs = (span.gcMs ?? 0) + ms;
71
+ for (at = closed.length - 1; at >= 0; at--) if (closed[at].to <= start) closed.splice(at, 1);
72
+ }
73
+ };
74
+ }
75
+ export { createWorkClock };