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.
- package/README.md +874 -1
- package/bin/goatly.js +99 -0
- package/dist/cli/index.js +234 -0
- package/dist/compat/gatsby-node-entry.js +16 -0
- package/dist/compat/gatsby-package.json +6 -0
- package/dist/compat/md5-file.js +47 -0
- package/dist/compat-apis.json +72 -0
- package/dist/compat-apis.json.js +62 -0
- package/dist/graphql.js +3 -0
- package/dist/node/actions/index.js +619 -0
- package/dist/node/actions/job-store.js +180 -0
- package/dist/node/actions/jobs.js +174 -0
- package/dist/node/api-runner.js +258 -0
- package/dist/node/bootstrap.js +569 -0
- package/dist/node/build/assets.js +110 -0
- package/dist/node/build/incremental.js +208 -0
- package/dist/node/build/index.js +763 -0
- package/dist/node/build/memory-governor.js +450 -0
- package/dist/node/build/output-dirs.js +70 -0
- package/dist/node/build/page-data.js +40 -0
- package/dist/node/build/page-files.js +186 -0
- package/dist/node/build/partitioned-state.js +258 -0
- package/dist/node/build/query-worker.js +626 -0
- package/dist/node/build/query-workers.js +863 -0
- package/dist/node/build/render-thread.js +103 -0
- package/dist/node/build/render-worker.js +162 -0
- package/dist/node/build/state.js +24 -0
- package/dist/node/build/timing-breakdown.js +216 -0
- package/dist/node/build/work-clock.js +75 -0
- package/dist/node/build/worker-pool.js +242 -0
- package/dist/node/cache-layout.js +99 -0
- package/dist/node/cache.js +1430 -0
- package/dist/node/compat/chokidar-shim.js +148 -0
- package/dist/node/compat/core-utils-lmdb.js +145 -0
- package/dist/node/compat/create-node-id-shim.js +1 -0
- package/dist/node/compat/module-hooks.js +245 -0
- package/dist/node/compat/redux-shim.js +1 -0
- package/dist/node/config/index.js +162 -0
- package/dist/node/config/not-found-pages.js +95 -0
- package/dist/node/datastore/codec.js +144 -0
- package/dist/node/datastore/index.js +127 -0
- package/dist/node/datastore/logfile/cache.js +89 -0
- package/dist/node/datastore/logfile/index.js +1329 -0
- package/dist/node/datastore/logfile/record.js +71 -0
- package/dist/node/datastore/types.js +1 -0
- package/dist/node/develop/express-compat.js +207 -0
- package/dist/node/develop/graphiql.js +22 -0
- package/dist/node/develop/hydration-report.js +41 -0
- package/dist/node/develop/index.js +618 -0
- package/dist/node/develop/local-url.js +10 -0
- package/dist/node/develop/ssr-runner.js +66 -0
- package/dist/node/gql.js +5 -0
- package/dist/node/index.js +15 -0
- package/dist/node/info.js +270 -0
- package/dist/node/internal-plugins/data-bridge.js +196 -0
- package/dist/node/internal-plugins/page-creator.js +318 -0
- package/dist/node/loader/import-module.js +160 -0
- package/dist/node/node-helpers.js +66 -0
- package/dist/node/not-found-pages.js +220 -0
- package/dist/node/plugins/api-list.js +12 -0
- package/dist/node/plugins/load-plugins.js +427 -0
- package/dist/node/plugins/resolve-plugin.js +79 -0
- package/dist/node/plugins/static-exports.js +64 -0
- package/dist/node/query/compile.js +326 -0
- package/dist/node/query/dependencies.js +45 -0
- package/dist/node/query/execute.js +417 -0
- package/dist/node/query/extract.js +372 -0
- package/dist/node/query/gql-tada-introspection.js +124 -0
- package/dist/node/query/graphql-env.js +231 -0
- package/dist/node/query/graphql-runner.js +79 -0
- package/dist/node/redux/actions.js +1 -0
- package/dist/node/redux/index.js +133 -0
- package/dist/node/redux/node-changes.js +128 -0
- package/dist/node/redux/reducers.js +193 -0
- package/dist/node/redux/state.js +71 -0
- package/dist/node/renderer.js +124 -0
- package/dist/node/reporter-transports.js +259 -0
- package/dist/node/reporter.js +497 -0
- package/dist/node/schema/date.js +539 -0
- package/dist/node/schema/extensions.js +315 -0
- package/dist/node/schema/index.js +542 -0
- package/dist/node/schema/infer.js +388 -0
- package/dist/node/schema/inline-objects.js +128 -0
- package/dist/node/schema/naming.js +20 -0
- package/dist/node/schema/node-model.js +207 -0
- package/dist/node/schema/query-engine.js +1808 -0
- package/dist/node/schema/resolver-kinds.js +7 -0
- package/dist/node/schema/resolvers.js +273 -0
- package/dist/node/schema/type-builders.js +45 -0
- package/dist/node/schema/types.js +241 -0
- package/dist/node/serve.js +90 -0
- package/dist/node/site-page-nodes.js +277 -0
- package/dist/node/types.js +1 -0
- package/dist/node/utils/content-digest.js +107 -0
- package/dist/node/utils/cpus.js +104 -0
- package/dist/node/utils/create-node-id.js +51 -0
- package/dist/node/utils/env.js +25 -0
- package/dist/node/utils/fs-retry.js +74 -0
- package/dist/node/utils/memory-signals.js +441 -0
- package/dist/node/utils/memory.js +657 -0
- package/dist/node/utils/murmurhash.js +32 -0
- package/dist/node/utils/parser.js +33 -0
- package/dist/node/utils/partition-hash.js +19 -0
- package/dist/node/utils/paths.js +122 -0
- package/dist/node/utils/resolver.js +48 -0
- package/dist/node/utils/runtime.js +5 -0
- package/dist/node/utils/serializable.js +41 -0
- package/dist/node/utils/strings.js +41 -0
- package/dist/node/vite/config.js +289 -0
- package/dist/node/vite/paths.js +12 -0
- package/dist/node/vite/plugin-deps.js +232 -0
- package/dist/node/vite/plugin.js +283 -0
- package/dist/node/vite/react-compiler.js +362 -0
- package/dist/node/vite/source-files.js +83 -0
- package/dist/node/vite/static-image.js +136 -0
- package/dist/node/vite/styled-components.js +73 -0
- package/dist/node/vite/transforms.js +330 -0
- package/dist/node/wasm-data/host.js +406 -0
- package/dist/node/wasm-data/lower.js +406 -0
- package/dist/node/wasm-data/runner.js +79 -0
- package/dist/node/wasm-data/worker.js +95 -0
- package/dist/reporter.js +5 -0
- package/dist/runtime/api-runner.js +81 -0
- package/dist/runtime/app.js +256 -0
- package/dist/runtime/client-entry.js +4 -0
- package/dist/runtime/client.js +383 -0
- package/dist/runtime/default-html.js +31 -0
- package/dist/runtime/head-markup.js +100 -0
- package/dist/runtime/head-sync.js +101 -0
- package/dist/runtime/head-tags.js +45 -0
- package/dist/runtime/hydration-report.js +111 -0
- package/dist/runtime/index.js +12 -0
- package/dist/runtime/link.js +293 -0
- package/dist/runtime/loader.js +449 -0
- package/dist/runtime/not-found.js +61 -0
- package/dist/runtime/page-renderer.js +35 -0
- package/dist/runtime/preamble.js +47 -0
- package/dist/runtime/react-compat.js +14 -0
- package/dist/runtime/renderer-shared.js +10 -0
- package/dist/runtime/renderers/react-client.js +14 -0
- package/dist/runtime/renderers/react-server.js +99 -0
- package/dist/runtime/renderers/react.js +17 -0
- package/dist/runtime/renderers/types.js +1 -0
- package/dist/runtime/root-error-handlers.js +29 -0
- package/dist/runtime/router/history.js +132 -0
- package/dist/runtime/router/index.js +240 -0
- package/dist/runtime/router/utils.js +118 -0
- package/dist/runtime/script.js +110 -0
- package/dist/runtime/scroll.js +40 -0
- package/dist/runtime/slice.js +11 -0
- package/dist/runtime/ssr.js +240 -0
- package/dist/runtime/static-query.js +47 -0
- package/dist/utils.js +4 -0
- package/package.json +105 -3
- package/types/graphql-tada.d.ts +223 -0
- package/types/graphql.d.ts +2 -0
- package/types/index.d.ts +2287 -0
- package/types/node.d.ts +389 -0
- package/types/reporter.d.ts +187 -0
- package/types/router.d.ts +102 -0
- package/types/vendor/gql-tada.d.ts +2529 -0
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import reporter, { REPORTER_BRIDGE_ENV } from "../reporter.js";
|
|
2
|
+
import { cpuCount } from "../utils/cpus.js";
|
|
3
|
+
import { outOfMemoryHint, planWorkerHeap, workerLimitMb } from "../utils/memory.js";
|
|
4
|
+
import { createRenderer } from "./render-worker.js";
|
|
5
|
+
import { Worker } from "node:worker_threads";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
// src/node/build/worker-pool.ts
|
|
9
|
+
const workerFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "render-worker.js");
|
|
10
|
+
/**
|
|
11
|
+
* The most worker threads of a build: `renderWorkers` in gatsby-config, GOATLY_RENDER_WORKERS, else
|
|
12
|
+
* one less than the CPUs it may use (see cpuCount: GOATLY_CPU_COUNT or Gatsby's GATSBY_CPU_COUNT,
|
|
13
|
+
* else the CPUs the process may run on, within its cgroups' CPU quota), at most 16 – like Gatsby,
|
|
14
|
+
* whose worker pool has one process less than its CPU count.
|
|
15
|
+
*/
|
|
16
|
+
function defaultWorkerCount(configured) {
|
|
17
|
+
if (configured && configured > 0) return configured;
|
|
18
|
+
const env = Number(process.env.GOATLY_RENDER_WORKERS);
|
|
19
|
+
if (env > 0) return env;
|
|
20
|
+
const cpus = cpuCount({ warn: (message) => reporter.warn(message) });
|
|
21
|
+
return Math.max(1, Math.min(cpus - 1, 16));
|
|
22
|
+
}
|
|
23
|
+
/** GOATLY_WORKERS=<n>: a fixed number of workers instead of the adaptive pool */
|
|
24
|
+
function fixedWorkerCount() {
|
|
25
|
+
const raw = process.env.GOATLY_WORKERS;
|
|
26
|
+
if (raw === void 0 || raw.trim() === "") return void 0;
|
|
27
|
+
const n = Number(raw);
|
|
28
|
+
if (Number.isInteger(n) && n > 0) return n;
|
|
29
|
+
reporter.warn(`GOATLY_WORKERS=${raw} is not a positive whole number – ignored`);
|
|
30
|
+
}
|
|
31
|
+
/** Renders in-process (small sites – avoids worker start-up cost). */
|
|
32
|
+
async function createInProcessPool(options) {
|
|
33
|
+
const renderer = await createRenderer(options);
|
|
34
|
+
return {
|
|
35
|
+
size: 1,
|
|
36
|
+
render: (tasks) => renderer.renderBatch(tasks),
|
|
37
|
+
close: async () => {}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** tasks per message by attempt: a page whose worker ran out of memory is tried at most 3 times */
|
|
41
|
+
const RETRY_BATCH = [
|
|
42
|
+
1e400,
|
|
43
|
+
4,
|
|
44
|
+
1
|
|
45
|
+
];
|
|
46
|
+
const OOM = "ERR_WORKER_OUT_OF_MEMORY";
|
|
47
|
+
const pageList = (tasks) => tasks.slice(0, 5).map((t) => t.pagePath).join(", ") + (tasks.length > 5 ? ` and ${tasks.length - 5} more` : "");
|
|
48
|
+
/**
|
|
49
|
+
* A pool of worker threads, each holding the SSR bundle. Batches are dispatched to idle workers. A
|
|
50
|
+
* worker that runs out of memory is replaced (with a higher heap limit, unless the user chose one)
|
|
51
|
+
* and its batch is rendered again in smaller batches. Any other death of a worker fails the pool:
|
|
52
|
+
* its batches, later render() calls and – when nothing else reported it – close().
|
|
53
|
+
*/
|
|
54
|
+
function createWorkerPool(options, count, heap = planWorkerHeap({ workers: count })) {
|
|
55
|
+
const top = heap.ladder.length - 1;
|
|
56
|
+
const slots = [];
|
|
57
|
+
const queue = [];
|
|
58
|
+
const live = () => slots.filter((s) => !s.dead);
|
|
59
|
+
let respawnsLeft = 2 * count + 2;
|
|
60
|
+
let nextId = 0;
|
|
61
|
+
let closed = false;
|
|
62
|
+
/** the pool failed (a worker died, not out of memory, or none is left) */
|
|
63
|
+
let failure;
|
|
64
|
+
/** …and no batch was rejected with that error yet: close() throws it */
|
|
65
|
+
let unreported;
|
|
66
|
+
const fail = (group, error) => {
|
|
67
|
+
if (group.settled) return;
|
|
68
|
+
group.settled = true;
|
|
69
|
+
if (error === unreported) unreported = void 0;
|
|
70
|
+
group.reject(error);
|
|
71
|
+
};
|
|
72
|
+
const settle = (group, result) => {
|
|
73
|
+
if (group.settled) return;
|
|
74
|
+
group.result.rendered += result.rendered;
|
|
75
|
+
group.result.errors.push(...result.errors);
|
|
76
|
+
group.result.missing.push(...result.missing);
|
|
77
|
+
Object.assign(group.result.staticQueryHashes, result.staticQueryHashes);
|
|
78
|
+
if (--group.pending === 0) {
|
|
79
|
+
group.settled = true;
|
|
80
|
+
group.resolve(group.result);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* fails every batch, queued or in flight (`reported`: the death that caused it already failed a
|
|
85
|
+
* batch with its own error – close() doesn't throw this one over it)
|
|
86
|
+
*/
|
|
87
|
+
const stop = (error, reported = false) => {
|
|
88
|
+
if (failure) return;
|
|
89
|
+
failure = error;
|
|
90
|
+
unreported = reported ? void 0 : error;
|
|
91
|
+
for (const job of queue.splice(0)) fail(job.group, error);
|
|
92
|
+
for (const slot of slots) {
|
|
93
|
+
if (!slot.job) continue;
|
|
94
|
+
const { group } = slot.job;
|
|
95
|
+
slot.job = void 0;
|
|
96
|
+
fail(group, error);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const dispatch = () => {
|
|
100
|
+
if (failure || closed) return;
|
|
101
|
+
for (const slot of slots) {
|
|
102
|
+
if (slot.dead || !slot.ready || slot.job) continue;
|
|
103
|
+
const i = queue.findIndex((j) => !j.group.settled && (j.attempt <= slot.rung || !live().some((o) => o.rung >= j.attempt)));
|
|
104
|
+
if (i < 0) continue;
|
|
105
|
+
const [job] = queue.splice(i, 1);
|
|
106
|
+
slot.job = job;
|
|
107
|
+
slot.messageId = nextId++;
|
|
108
|
+
slot.worker.postMessage({
|
|
109
|
+
id: slot.messageId,
|
|
110
|
+
tasks: job.tasks
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].group.settled) queue.splice(i, 1);
|
|
114
|
+
};
|
|
115
|
+
const spawn = (rung) => {
|
|
116
|
+
const limitMb = workerLimitMb(heap, rung);
|
|
117
|
+
const worker = new Worker(workerFile, {
|
|
118
|
+
workerData: {
|
|
119
|
+
__goatlyRenderWorker: true,
|
|
120
|
+
options
|
|
121
|
+
},
|
|
122
|
+
env: {
|
|
123
|
+
...process.env,
|
|
124
|
+
...REPORTER_BRIDGE_ENV,
|
|
125
|
+
NODE_ENV: "production"
|
|
126
|
+
},
|
|
127
|
+
...limitMb && !heap.soft ? { resourceLimits: { maxOldGenerationSizeMb: limitMb } } : {}
|
|
128
|
+
});
|
|
129
|
+
const slot = {
|
|
130
|
+
rung,
|
|
131
|
+
limitMb,
|
|
132
|
+
worker,
|
|
133
|
+
ready: false,
|
|
134
|
+
dead: false
|
|
135
|
+
};
|
|
136
|
+
worker.on("message", (msg) => {
|
|
137
|
+
if (slot.dead) return;
|
|
138
|
+
if (msg?.type === "ready") {
|
|
139
|
+
slot.ready = true;
|
|
140
|
+
return dispatch();
|
|
141
|
+
}
|
|
142
|
+
const job = slot.job;
|
|
143
|
+
if (!job || msg?.id !== slot.messageId) return;
|
|
144
|
+
slot.job = void 0;
|
|
145
|
+
if (msg.error) fail(job.group, new Error(msg.error));
|
|
146
|
+
else settle(job.group, msg.result);
|
|
147
|
+
dispatch();
|
|
148
|
+
});
|
|
149
|
+
const die = (error) => {
|
|
150
|
+
if (slot.dead) return;
|
|
151
|
+
slot.dead = true;
|
|
152
|
+
const job = slot.job;
|
|
153
|
+
slot.job = void 0;
|
|
154
|
+
if (closed) return;
|
|
155
|
+
worker.terminate();
|
|
156
|
+
const loading = !slot.ready ? " while loading the SSR bundle" : "";
|
|
157
|
+
if (error.code !== OOM) {
|
|
158
|
+
error.message += job ? ` (while rendering ${pageList(job.tasks)})` : loading && ` (${loading.trim()})`;
|
|
159
|
+
const reported = !!job && !job.group.settled;
|
|
160
|
+
if (job) fail(job.group, error);
|
|
161
|
+
return stop(error, reported);
|
|
162
|
+
}
|
|
163
|
+
let replacement;
|
|
164
|
+
if (respawnsLeft > 0) {
|
|
165
|
+
respawnsLeft--;
|
|
166
|
+
let next = Math.min(rung + 1, top);
|
|
167
|
+
if (next === top && top > 0 && live().some((s) => s.rung === top)) next = top - 1;
|
|
168
|
+
replacement = spawn(next);
|
|
169
|
+
}
|
|
170
|
+
let again = false;
|
|
171
|
+
/** the page failed the build (its own error, not "No render worker is left") */
|
|
172
|
+
let pageFailed = false;
|
|
173
|
+
if (job && !job.group.settled) {
|
|
174
|
+
const tried = limitMb ? [...job.tried, limitMb] : job.tried;
|
|
175
|
+
const attempt = Math.min(job.attempt + 1, RETRY_BATCH.length - 1);
|
|
176
|
+
if (job.attempt + 1 >= RETRY_BATCH.length && job.tasks.length === 1) {
|
|
177
|
+
const list = [...new Set(tried)].join(", ");
|
|
178
|
+
fail(job.group, /* @__PURE__ */ new Error(`The page "${job.tasks[0].pagePath}" ran out of memory while it was rendered in a worker thread${list ? ` (heap limits tried: ${list} MB)` : ""}. ${outOfMemoryHint(heap, Math.max(0, ...tried))}`));
|
|
179
|
+
pageFailed = true;
|
|
180
|
+
} else {
|
|
181
|
+
const size = RETRY_BATCH[attempt];
|
|
182
|
+
const parts = [];
|
|
183
|
+
for (let i = 0; i < job.tasks.length; i += size) parts.push({
|
|
184
|
+
tasks: job.tasks.slice(i, i + size),
|
|
185
|
+
attempt,
|
|
186
|
+
group: job.group,
|
|
187
|
+
tried
|
|
188
|
+
});
|
|
189
|
+
job.group.pending += parts.length - 1;
|
|
190
|
+
queue.unshift(...parts);
|
|
191
|
+
again = true;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const left = live().length > 0;
|
|
195
|
+
reporter.warn(`A render worker ran out of memory (heap limit ${limitMb ? `${limitMb} MB` : "none"})` + (job ? ` while rendering ${pageList(job.tasks)}` : loading) + (again && left ? ` – rendering ${job.tasks.length === 1 ? "it" : "them"} again` : "") + "." + (replacement?.limitMb ? ` Starting a new worker with a heap limit of ${replacement.limitMb} MB.` : ""));
|
|
196
|
+
if (!left) stop(/* @__PURE__ */ new Error(`No render worker is left: the last one ran out of memory${loading} (heap limit ${limitMb ? `${limitMb} MB` : "none"}). ${outOfMemoryHint(heap, limitMb)}`), pageFailed);
|
|
197
|
+
dispatch();
|
|
198
|
+
};
|
|
199
|
+
worker.on("error", (e) => die(e instanceof Error ? e : new Error(String(e))));
|
|
200
|
+
worker.on("exit", (code) => die(/* @__PURE__ */ new Error(`render worker exited with code ${code}`)));
|
|
201
|
+
slots.push(slot);
|
|
202
|
+
return slot;
|
|
203
|
+
};
|
|
204
|
+
reporter.receiveWorkerOutput();
|
|
205
|
+
for (let i = 0; i < count; i++) spawn(0);
|
|
206
|
+
return {
|
|
207
|
+
size: count,
|
|
208
|
+
render(tasks) {
|
|
209
|
+
return new Promise((resolve, reject) => {
|
|
210
|
+
if (failure || closed) return reject(failure ?? /* @__PURE__ */ new Error("the render pool was closed"));
|
|
211
|
+
const group = {
|
|
212
|
+
pending: 1,
|
|
213
|
+
settled: false,
|
|
214
|
+
resolve,
|
|
215
|
+
reject,
|
|
216
|
+
result: {
|
|
217
|
+
rendered: 0,
|
|
218
|
+
errors: [],
|
|
219
|
+
staticQueryHashes: {},
|
|
220
|
+
missing: []
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
queue.push({
|
|
224
|
+
tasks,
|
|
225
|
+
attempt: 0,
|
|
226
|
+
group,
|
|
227
|
+
tried: []
|
|
228
|
+
});
|
|
229
|
+
dispatch();
|
|
230
|
+
});
|
|
231
|
+
},
|
|
232
|
+
async close() {
|
|
233
|
+
closed = true;
|
|
234
|
+
const error = /* @__PURE__ */ new Error("the render pool was closed");
|
|
235
|
+
for (const job of queue.splice(0)) fail(job.group, error);
|
|
236
|
+
for (const slot of slots) if (slot.job) fail(slot.job.group, error);
|
|
237
|
+
await Promise.all(slots.map((s) => s.worker.terminate()));
|
|
238
|
+
if (unreported) throw unreported;
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
export { createInProcessPool, createWorkerPool, defaultWorkerCount, fixedWorkerCount };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { renameSync, retrySync } from "./utils/fs-retry.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
// src/node/cache-layout.ts
|
|
5
|
+
/**
|
|
6
|
+
* How `.cache` is laid out on disk: for caches that travel as container image layers (Docker /
|
|
7
|
+
* BuildKit, a `FROM <previous image>` build) or any other file-level diff or sync. An incremental
|
|
8
|
+
* build creates new files and rewrites only the small files whose content changed, instead of
|
|
9
|
+
* changing a few large files: overlayfs copies a whole file up into the new layer when any byte of
|
|
10
|
+
* it changes. The node datastore writes immutable segment files, the plugin cache writes a SQLite
|
|
11
|
+
* file per run (merged in size tiers), and the build state partition files that are only written
|
|
12
|
+
* when their content changed.
|
|
13
|
+
*/
|
|
14
|
+
/** the directory of the plugin cache (`<cacheDir>/caches-lsm`) */
|
|
15
|
+
const PLUGIN_CACHE_DIR = "caches-lsm";
|
|
16
|
+
/** the build state in `cacheDir` (see `openBuildState`) */
|
|
17
|
+
const BUILD_STATE_PATHS = {
|
|
18
|
+
html: "html-state",
|
|
19
|
+
queries: path.join("data", "query-state")
|
|
20
|
+
};
|
|
21
|
+
/** the prefix of `writeFileIfChanged`'s temporary files (`atomic`) */
|
|
22
|
+
const TMP_PREFIX = ".tmp-";
|
|
23
|
+
let tmpCounter = 0;
|
|
24
|
+
/** whether `file` has exactly these bytes (`sizeOnly`: as many) */
|
|
25
|
+
function sameBytes(file, data, sizeOnly = false) {
|
|
26
|
+
try {
|
|
27
|
+
const stat = fs.statSync(file);
|
|
28
|
+
const size = typeof data === "string" ? Buffer.byteLength(data) : data.length;
|
|
29
|
+
if (!stat.isFile() || stat.size !== size) return false;
|
|
30
|
+
return sizeOnly || fs.readFileSync(file).equals(typeof data === "string" ? Buffer.from(data) : data);
|
|
31
|
+
} catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Writes `data` to `file` unless the file already has exactly these bytes: a rewrite with the same
|
|
37
|
+
* content still changes the file for a layer diff (overlayfs copies it up).
|
|
38
|
+
* - `atomic`: via a temporary file and a rename, `file` has either its old or its new content
|
|
39
|
+
* - `contentAddressed`: the name has a hash of the content, so the same size is the same content
|
|
40
|
+
*/
|
|
41
|
+
function writeFileIfChanged(file, data, options = {}) {
|
|
42
|
+
if (sameBytes(file, data, options.contentAddressed)) return;
|
|
43
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
44
|
+
if (!options.atomic) return fs.writeFileSync(file, data);
|
|
45
|
+
const tmp = path.join(path.dirname(file), `${TMP_PREFIX}${process.pid}-${tmpCounter++}`);
|
|
46
|
+
fs.writeFileSync(tmp, data);
|
|
47
|
+
renameSync(tmp, file);
|
|
48
|
+
}
|
|
49
|
+
/** where the SSR bundle is built before `syncDirectory` moves it to page-ssr */
|
|
50
|
+
const SSR_BUILD_DIR = "page-ssr.next";
|
|
51
|
+
/** the files under `dir` (relative paths), none when it is missing */
|
|
52
|
+
function listFiles(dir) {
|
|
53
|
+
let entries;
|
|
54
|
+
try {
|
|
55
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
56
|
+
} catch {
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
return entries.flatMap((e) => e.isDirectory() ? listFiles(path.join(dir, e.name)).map((f) => path.join(e.name, f)) : [e.name]);
|
|
60
|
+
}
|
|
61
|
+
/** removes the empty directories under `dir` (not `dir` itself); returns whether it is empty */
|
|
62
|
+
function pruneEmpty(dir, root = dir) {
|
|
63
|
+
let entries;
|
|
64
|
+
try {
|
|
65
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
let empty = true;
|
|
70
|
+
for (const e of entries) if (!e.isDirectory() || !pruneEmpty(path.join(dir, e.name), root)) empty = false;
|
|
71
|
+
if (empty && dir !== root) fs.rmdirSync(dir);
|
|
72
|
+
return empty;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Makes `dest` hold the files of `src` and removes `src`. Files with the same bytes are left as
|
|
76
|
+
* they are (a rewrite would put them into the next layer), the others are moved, and files `src`
|
|
77
|
+
* doesn't have are deleted.
|
|
78
|
+
*/
|
|
79
|
+
function syncDirectory(src, dest) {
|
|
80
|
+
const wanted = new Set(listFiles(src));
|
|
81
|
+
for (const rel of listFiles(dest)) if (!wanted.has(rel)) fs.rmSync(path.join(dest, rel), { force: true });
|
|
82
|
+
for (const rel of wanted) {
|
|
83
|
+
const from = path.join(src, rel);
|
|
84
|
+
const to = path.join(dest, rel);
|
|
85
|
+
if (sameBytes(to, fs.readFileSync(from))) continue;
|
|
86
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
87
|
+
retrySync(() => fs.rmSync(to, {
|
|
88
|
+
recursive: true,
|
|
89
|
+
force: true
|
|
90
|
+
}));
|
|
91
|
+
renameSync(from, to);
|
|
92
|
+
}
|
|
93
|
+
pruneEmpty(dest);
|
|
94
|
+
fs.rmSync(src, {
|
|
95
|
+
recursive: true,
|
|
96
|
+
force: true
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
export { BUILD_STATE_PATHS, PLUGIN_CACHE_DIR, SSR_BUILD_DIR, TMP_PREFIX, syncDirectory, writeFileIfChanged };
|