@plitzi/sdk-server 0.39.4 → 0.39.7

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 (43) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -1
  3. package/dist/adapters/cloudAdapters.d.ts +7 -0
  4. package/dist/adapters/space/index.d.ts +2 -0
  5. package/dist/adapters/space/resolvers.d.ts +14 -3
  6. package/dist/adapters/space/snapshotPreview.d.ts +45 -0
  7. package/dist/adapters/space/types.d.ts +4 -1
  8. package/dist/cache.js +1 -1
  9. package/dist/chunks/{buildBody-BSC0UbjP.js → buildBody-Bm398uxH.js} +600 -63
  10. package/dist/chunks/{core-w7FIMpgv.js → core-CoKORAOg.js} +149 -23
  11. package/dist/chunks/{createServer-BQ0KE0Qu.js → createServer-BSmQqzwb.js} +31 -607
  12. package/dist/chunks/{platform-C0AVlwpB.js → platform-BTssQQXp.js} +1 -1
  13. package/dist/chunks/sdkAssets-CXGoc_WE.js +60 -0
  14. package/dist/chunks/{token-CBUubxtm.js → token-XEz1n4jp.js} +1 -1
  15. package/dist/chunks/views/template.ejs +5 -0
  16. package/dist/core/services/robotsTxt.d.ts +3 -1
  17. package/dist/deploy/aws/s3.d.ts +51 -0
  18. package/dist/deploy/aws/sigv4.d.ts +33 -0
  19. package/dist/deploy/contentType.d.ts +2 -0
  20. package/dist/deploy/fingerprint.d.ts +18 -0
  21. package/dist/deploy/folder.d.ts +6 -0
  22. package/dist/deploy/ftp.d.ts +27 -0
  23. package/dist/deploy/sdkFiles.d.ts +11 -0
  24. package/dist/deploy/spaShell.d.ts +35 -0
  25. package/dist/deploy/staticSite.d.ts +44 -0
  26. package/dist/deploy/types.d.ts +58 -0
  27. package/dist/deploy/zip.d.ts +8 -0
  28. package/dist/deploy.d.ts +24 -0
  29. package/dist/deploy.js +938 -0
  30. package/dist/handlers.js +1 -1
  31. package/dist/helpers/ownVersion.d.ts +1 -0
  32. package/dist/index.js +3 -3
  33. package/dist/oauth.js +1 -1
  34. package/dist/platform.js +1 -1
  35. package/dist/project.js +3 -3
  36. package/dist/spaces.d.ts +2 -2
  37. package/dist/spaces.js +1 -1
  38. package/dist/ssr.d.ts +1 -1
  39. package/dist/ssr.js +1 -1
  40. package/package.json +15 -13
  41. package/skills/plitzi-authoring/reference/authoring-errors.md +8 -4
  42. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  43. package/skills/plitzi-authoring/reference/layouts.md +2 -1
package/dist/deploy.js ADDED
@@ -0,0 +1,938 @@
1
+ import { r as resolveSdkAssetsDir } from "./chunks/sdkAssets-CXGoc_WE.js";
2
+ import { K as escapeJson, b as escapeHtml, v as ownVersion } from "./chunks/core-CoKORAOg.js";
3
+ import { createRequire } from "node:module";
4
+ import { mkdir, writeFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
7
+ import { createHash, createHmac } from "node:crypto";
8
+ import { readFileSync, readdirSync } from "node:fs";
9
+ import { connect } from "node:net";
10
+ import { connect as connect$1 } from "node:tls";
11
+ // src/deploy/aws/sigv4.ts
12
+ var sha256 = (data) => createHash("sha256").update(data).digest("hex");
13
+ var hmac = (key, data) => createHmac("sha256", key).update(data).digest();
14
+ /** RFC 3986's unreserved characters left as they are, everything else percent-encoded — what SigV4 asks. */
15
+ var awsEncode = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
16
+ /** The path as SigV4 reads it: each segment encoded once (S3's rule, and the same for the paths other services use). */
17
+ var canonicalPath = (url) => url.pathname.split("/").map((segment) => awsEncode(decodeURIComponent(segment))).join("/") || "/";
18
+ var canonicalQuery = (url) => [...url.searchParams.entries()].map(([key, value]) => [awsEncode(key), awsEncode(value)]).sort(([a, x], [b, y]) => a === b ? x < y ? -1 : 1 : a < b ? -1 : 1).map(([key, value]) => `${key}=${value}`).join("&");
19
+ /** `20261116T183000Z` and `20261116`. */
20
+ var stamps = (now) => {
21
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
22
+ return {
23
+ amzDate,
24
+ day: amzDate.slice(0, 8)
25
+ };
26
+ };
27
+ /** The headers a request is sent with, signed: its own, plus `host`, `x-amz-date`, the payload's digest and `authorization`. */
28
+ var signAws = ({ method, url, headers = {}, body = "", region, service, credentials, now = /* @__PURE__ */ new Date() }) => {
29
+ const { amzDate, day } = stamps(now);
30
+ const payloadHash = sha256(body);
31
+ const signed = {
32
+ ...Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value.trim()])),
33
+ host: url.host,
34
+ "x-amz-date": amzDate,
35
+ ...service === "s3" ? { "x-amz-content-sha256": payloadHash } : {},
36
+ ...credentials.sessionToken ? { "x-amz-security-token": credentials.sessionToken } : {}
37
+ };
38
+ const names = Object.keys(signed).sort();
39
+ const canonicalRequest = [
40
+ method.toUpperCase(),
41
+ canonicalPath(url),
42
+ canonicalQuery(url),
43
+ names.map((name) => `${name}:${signed[name].replace(/\s+/g, " ")}\n`).join(""),
44
+ names.join(";"),
45
+ payloadHash
46
+ ].join("\n");
47
+ const scope = `${day}/${region}/${service}/aws4_request`;
48
+ const toSign = [
49
+ "AWS4-HMAC-SHA256",
50
+ amzDate,
51
+ scope,
52
+ sha256(canonicalRequest)
53
+ ].join("\n");
54
+ const key = hmac(hmac(hmac(hmac(`AWS4${credentials.secretAccessKey}`, day), region), service), "aws4_request");
55
+ const signature = createHmac("sha256", key).update(toSign).digest("hex");
56
+ return {
57
+ ...signed,
58
+ authorization: `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(";")}, Signature=${signature}`
59
+ };
60
+ };
61
+ /** What AWS answered when it refused, in its own words — the `<Message>` of its XML, or the `message` of its JSON. */
62
+ var awsRefusal = async (response, doing) => {
63
+ const text = await response.text().catch(() => "");
64
+ const said = /<Message>([^<]*)<\/Message>/.exec(text)?.[1] ?? /"message"\s*:\s*"([^"]*)"/i.exec(text)?.[1] ?? text.slice(0, 200);
65
+ return /* @__PURE__ */ new Error(`${doing} was refused (${String(response.status)})${said ? `: ${said}` : ""}`);
66
+ };
67
+ /** A signed request, sent. */
68
+ var awsFetch = async (request) => {
69
+ const sent = Object.fromEntries(Object.entries(signAws(request)).filter(([name]) => name !== "host"));
70
+ return fetch(request.url, {
71
+ method: request.method,
72
+ headers: sent,
73
+ ...request.body === void 0 || request.method === "GET" || request.method === "HEAD" ? {} : { body: typeof request.body === "string" ? request.body : Buffer.from(request.body) },
74
+ ...request.signal ? { signal: request.signal } : {}
75
+ });
76
+ };
77
+ // src/deploy/aws/s3.ts
78
+ /** How many files go up at once. */
79
+ var PARALLEL = 8;
80
+ var CACHE_CONTROL = {
81
+ immutable: "public, max-age=31536000, immutable",
82
+ revalidate: "public, max-age=0, must-revalidate"
83
+ };
84
+ var joinKey = (...parts) => parts.filter((part) => Boolean(part)).map((part) => part.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
85
+ /** The address of an object, virtual-hosted on AWS and path-style elsewhere. */
86
+ var objectUrl = ({ bucket, region, endpoint }, key) => {
87
+ const path = key.split("/").map(awsEncode).join("/");
88
+ return endpoint ? new URL(`${endpoint.replace(/\/+$/, "")}/${bucket}/${path}`) : new URL(`https://${bucket}.s3.${region}.amazonaws.com/${path}`);
89
+ };
90
+ /** Writes one object. */
91
+ var putObject = async (target, key, file, signal) => {
92
+ const response = await awsFetch({
93
+ method: "PUT",
94
+ url: objectUrl(target, key),
95
+ headers: {
96
+ "content-type": file.type,
97
+ "cache-control": CACHE_CONTROL[file.cache]
98
+ },
99
+ body: file.body,
100
+ region: target.region,
101
+ service: "s3",
102
+ credentials: target.credentials,
103
+ ...signal ? { signal } : {}
104
+ });
105
+ if (!response.ok) throw await awsRefusal(response, `Writing ${key} to the bucket ${target.bucket}`);
106
+ };
107
+ /** Whether an object is there already: an immutable file — named by its content — is never written twice. */
108
+ var exists = async (target, key, signal) => {
109
+ return (await awsFetch({
110
+ method: "HEAD",
111
+ url: objectUrl(target, key),
112
+ region: target.region,
113
+ service: "s3",
114
+ credentials: target.credentials,
115
+ ...signal ? { signal } : {}
116
+ })).ok;
117
+ };
118
+ /** Every file written under `prefix`, a few at a time; the immutable ones a bucket already holds are left as they are. */
119
+ var putFiles = async (target, prefix, files, log, signal) => {
120
+ let written = 0;
121
+ let kept = 0;
122
+ let bytes = 0;
123
+ const queue = [...files];
124
+ const work = async () => {
125
+ for (let file = queue.shift(); file; file = queue.shift()) {
126
+ signal?.throwIfAborted();
127
+ const key = joinKey(target.prefix, prefix, file.path);
128
+ if (file.cache === "immutable" && await exists(target, key, signal)) {
129
+ kept += 1;
130
+ continue;
131
+ }
132
+ await putObject(target, key, file, signal);
133
+ written += 1;
134
+ bytes += file.body.byteLength;
135
+ }
136
+ };
137
+ await Promise.all(Array.from({ length: Math.min(PARALLEL, files.length) }, work));
138
+ log(`Wrote ${String(written)} files (${String(Math.round(bytes / 1024))} KB) to ${target.bucket}${kept ? `; ${String(kept)} were there already` : ""}`);
139
+ return {
140
+ written,
141
+ kept,
142
+ bytes
143
+ };
144
+ };
145
+ var CLOUDFRONT = "https://cloudfront.amazonaws.com/2020-05-31";
146
+ /** Asks CloudFront to forget what it keeps of `paths` (`/*`: everything), so the next visitor gets the new site. */
147
+ var invalidateCloudFront = async ({ distributionId, credentials, endpoint = CLOUDFRONT }, paths, reference, signal) => {
148
+ const items = paths.map((path) => `<Path>${path.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</Path>`).join("");
149
+ const body = `<?xml version="1.0" encoding="UTF-8"?><InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><Paths><Quantity>${String(paths.length)}</Quantity><Items>${items}</Items></Paths><CallerReference>${reference}</CallerReference></InvalidationBatch>`;
150
+ const response = await awsFetch({
151
+ method: "POST",
152
+ url: new URL(`${endpoint}/distribution/${encodeURIComponent(distributionId)}/invalidation`),
153
+ headers: { "content-type": "application/xml" },
154
+ body,
155
+ region: "us-east-1",
156
+ service: "cloudfront",
157
+ credentials,
158
+ ...signal ? { signal } : {}
159
+ });
160
+ if (!response.ok) throw await awsRefusal(response, `Clearing CloudFront's copy (${distributionId})`);
161
+ };
162
+ /**
163
+ * Points the distribution's origin for `bucket` at `originPath`: what makes a deploy written under its own prefix the
164
+ * site, in one step. The rest of the distribution's configuration is sent back as CloudFront gave it.
165
+ */
166
+ var pointCloudFront = async ({ distributionId, credentials, endpoint = CLOUDFRONT }, bucket, originPath, signal) => {
167
+ const url = new URL(`${endpoint}/distribution/${encodeURIComponent(distributionId)}/config`);
168
+ const read = await awsFetch({
169
+ method: "GET",
170
+ url,
171
+ region: "us-east-1",
172
+ service: "cloudfront",
173
+ credentials,
174
+ ...signal ? { signal } : {}
175
+ });
176
+ if (!read.ok) throw await awsRefusal(read, `Reading the CloudFront distribution ${distributionId}`);
177
+ const etag = read.headers.get("etag") ?? "";
178
+ const config = await read.text();
179
+ const origins = [...config.matchAll(/<Origin>([\s\S]*?)<\/Origin>/g)];
180
+ const origin = origins.find(([, inner]) => new RegExp(`<DomainName>${bucket.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.`).test(inner)) ?? (origins.length === 1 ? origins[0] : void 0);
181
+ if (!origin) throw new Error(`The distribution ${distributionId} has no origin for the bucket ${bucket}: add it as an origin there, or name the bucket it serves`);
182
+ const [whole, inner] = origin;
183
+ const previous = /<OriginPath>([^<]*)<\/OriginPath>/.exec(inner)?.[1] ?? "";
184
+ const pointed = /<OriginPath>[^<]*<\/OriginPath>|<OriginPath\/>/.test(inner) ? inner.replace(/<OriginPath>[^<]*<\/OriginPath>|<OriginPath\/>/, `<OriginPath>${originPath}</OriginPath>`) : inner.replace(/(<DomainName>[^<]*<\/DomainName>)/, `$1<OriginPath>${originPath}</OriginPath>`);
185
+ const write = await awsFetch({
186
+ method: "PUT",
187
+ url,
188
+ headers: {
189
+ "content-type": "application/xml",
190
+ "if-match": etag
191
+ },
192
+ body: config.replace(whole, `<Origin>${pointed}</Origin>`),
193
+ region: "us-east-1",
194
+ service: "cloudfront",
195
+ credentials,
196
+ ...signal ? { signal } : {}
197
+ });
198
+ if (!write.ok) throw await awsRefusal(write, `Pointing the CloudFront distribution ${distributionId} at ${originPath || "the bucket root"}`);
199
+ return { previous };
200
+ };
201
+ /**
202
+ * An uploader for a bucket: with a distribution, every deploy under `deploys/<reference>` and the distribution switched
203
+ * to it; without one, the files written over the site's.
204
+ */
205
+ var s3Uploader = (target, options) => ({
206
+ name: `${target.endpoint ? "Bucket" : "S3 bucket"} ${target.bucket}${options.cloudFront ? ` behind CloudFront ${options.cloudFront.distributionId}` : ""}`,
207
+ atomic: Boolean(options.cloudFront),
208
+ upload: async (files, log, signal) => {
209
+ const { cloudFront, reference } = options;
210
+ if (!cloudFront) {
211
+ log(`No CloudFront distribution: the files are replaced one by one, so for a few seconds a visitor may get some of each version`, "warn");
212
+ const { written, kept, bytes } = await putFiles(target, "", files, log, signal);
213
+ return {
214
+ files: written + kept,
215
+ bytes,
216
+ reference: joinKey(target.prefix) || "/"
217
+ };
218
+ }
219
+ const prefix = joinKey("deploys", reference);
220
+ const { written, kept, bytes } = await putFiles(target, prefix, files, log, signal);
221
+ const originPath = `/${joinKey(target.prefix, prefix)}`;
222
+ const { previous } = await pointCloudFront(cloudFront, target.bucket, originPath, signal);
223
+ log(`CloudFront ${cloudFront.distributionId} serves ${originPath} now (it served ${previous || "the bucket root"})`);
224
+ await invalidateCloudFront(cloudFront, ["/*"], reference, signal);
225
+ log("Asked CloudFront to drop its copies: visitors get the new site within a few minutes");
226
+ return {
227
+ files: written + kept,
228
+ bytes,
229
+ reference: originPath
230
+ };
231
+ }
232
+ });
233
+ // src/deploy/contentType.ts
234
+ /** The media types a site's files are served as, by extension: what a static host is told for each upload. */
235
+ var TYPES = {
236
+ html: "text/html; charset=utf-8",
237
+ css: "text/css; charset=utf-8",
238
+ js: "text/javascript; charset=utf-8",
239
+ mjs: "text/javascript; charset=utf-8",
240
+ json: "application/json; charset=utf-8",
241
+ map: "application/json; charset=utf-8",
242
+ txt: "text/plain; charset=utf-8",
243
+ xml: "application/xml; charset=utf-8",
244
+ svg: "image/svg+xml",
245
+ png: "image/png",
246
+ jpg: "image/jpeg",
247
+ jpeg: "image/jpeg",
248
+ gif: "image/gif",
249
+ webp: "image/webp",
250
+ avif: "image/avif",
251
+ ico: "image/x-icon",
252
+ woff: "font/woff",
253
+ woff2: "font/woff2",
254
+ ttf: "font/ttf",
255
+ otf: "font/otf",
256
+ webmanifest: "application/manifest+json",
257
+ wasm: "application/wasm",
258
+ pdf: "application/pdf",
259
+ mp4: "video/mp4",
260
+ webm: "video/webm"
261
+ };
262
+ /** A file's media type from its path; one this list does not know is served as bytes, never guessed as a page. */
263
+ var contentTypeOf = (path) => {
264
+ return TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream";
265
+ };
266
+ // src/deploy/fingerprint.ts
267
+ /**
268
+ * Does this publish need a deploy? A build is described part by part — the SDK it loads, the fonts it
269
+ * links, the environment it names — each a digest, computed without building anything, so a target's last deploy and
270
+ * the revision about to be published can be compared before the person confirms, and the parts that differ said.
271
+ */
272
+ /** A digest of anything JSON can say, the same for the same value whatever the order of its keys. */
273
+ var digestOf = (value) => createHash("sha256").update(stableJson(value)).digest("hex").slice(0, 16);
274
+ var stableJson = (value) => {
275
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
276
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, inner]) => inner !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, inner]) => `${JSON.stringify(key)}:${stableJson(inner)}`).join(",")}}`;
277
+ return value === void 0 || typeof value === "function" ? "null" : JSON.stringify(value);
278
+ };
279
+ /** The fingerprint of a build, whole: one digest of every part. */
280
+ var fingerprintOf = (parts) => ({
281
+ digest: digestOf(parts),
282
+ parts
283
+ });
284
+ /**
285
+ * The parts of `next` that differ from `deployed` — what a deploy would change, by name, in the order `next` lists
286
+ * them. A part only one side has is a difference too: a build that bakes something new in has changed.
287
+ */
288
+ var fingerprintChanges = (deployed, next) => [...Object.keys(next).filter((part) => deployed[part] !== next[part]), ...Object.keys(deployed).filter((part) => !(part in next))];
289
+ // src/deploy/folder.ts
290
+ /**
291
+ * A site written into a folder of this machine — what `plitzi build --spa|--static` leaves for a customer's own CI to
292
+ * ship, and the simplest provider to try a build with. A path that would leave the folder is refused, never written.
293
+ */
294
+ var folderUploader = (folder) => ({
295
+ name: `the folder ${folder}`,
296
+ atomic: false,
297
+ upload: async (files, log, signal) => {
298
+ const root = path.resolve(folder);
299
+ let bytes = 0;
300
+ for (const file of files) {
301
+ signal?.throwIfAborted();
302
+ const target = path.resolve(root, file.path);
303
+ if (!target.startsWith(`${root}${path.sep}`)) throw new Error(`${file.path} would be written outside ${folder}`);
304
+ await mkdir(path.dirname(target), { recursive: true });
305
+ await writeFile(target, file.body);
306
+ bytes += file.body.byteLength;
307
+ }
308
+ log(`Wrote ${String(files.length)} files (${String(Math.round(bytes / 1024))} KB) to ${folder}`);
309
+ return {
310
+ files: files.length,
311
+ bytes,
312
+ reference: root
313
+ };
314
+ }
315
+ });
316
+ // src/deploy/ftp.ts
317
+ /** One control connection: commands sent, answers read whole (a multi-line answer is one). */
318
+ var Control = class {
319
+ socket;
320
+ timeoutMs;
321
+ buffer = "";
322
+ waiting = [];
323
+ replies = [];
324
+ failure;
325
+ constructor(socket, timeoutMs) {
326
+ this.socket = socket;
327
+ this.timeoutMs = timeoutMs;
328
+ this.listen(socket);
329
+ }
330
+ listen(socket) {
331
+ this.socket = socket;
332
+ socket.setEncoding("utf8");
333
+ socket.on("data", (chunk) => this.read(chunk));
334
+ socket.on("error", (error) => {
335
+ this.failure = error;
336
+ });
337
+ }
338
+ read(chunk) {
339
+ this.buffer += chunk;
340
+ for (;;) {
341
+ const match = /^(\d{3}) [^\r\n]*\r?\n/m.exec(this.buffer);
342
+ if (!match) return;
343
+ const end = match.index + match[0].length;
344
+ const reply = {
345
+ code: Number(match[1]),
346
+ text: this.buffer.slice(0, end).trim()
347
+ };
348
+ this.buffer = this.buffer.slice(end);
349
+ const next = this.waiting.shift();
350
+ if (next) next(reply);
351
+ else this.replies.push(reply);
352
+ }
353
+ }
354
+ next() {
355
+ const ready = this.replies.shift();
356
+ if (ready) return Promise.resolve(ready);
357
+ if (this.failure) return Promise.reject(this.failure);
358
+ return new Promise((resolve, reject) => {
359
+ const timer = setTimeout(() => reject(/* @__PURE__ */ new Error("The FTP host stopped answering")), this.timeoutMs);
360
+ this.waiting.push((reply) => {
361
+ clearTimeout(timer);
362
+ resolve(reply);
363
+ });
364
+ });
365
+ }
366
+ async send(command, expect, said = command.split(" ")[0]) {
367
+ this.socket.write(`${command}\r\n`);
368
+ const reply = await this.next();
369
+ if (!expect.includes(reply.code)) throw new Error(`The FTP host refused ${said}: ${reply.text}`);
370
+ return reply;
371
+ }
372
+ };
373
+ var opened = (socket, event, timeoutMs) => new Promise((resolve, reject) => {
374
+ const timer = setTimeout(() => {
375
+ socket.destroy();
376
+ reject(/* @__PURE__ */ new Error("The FTP host did not answer"));
377
+ }, timeoutMs);
378
+ socket.once(event, () => {
379
+ clearTimeout(timer);
380
+ resolve();
381
+ });
382
+ socket.once("error", (error) => {
383
+ clearTimeout(timer);
384
+ reject(error);
385
+ });
386
+ });
387
+ /** The data address a `227 Entering Passive Mode (h1,h2,h3,h4,p1,p2)` answer names. */
388
+ var passiveAddress = (text) => {
389
+ const numbers = /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/.exec(text);
390
+ if (!numbers) throw new Error(`The FTP host answered PASV with no address: ${text}`);
391
+ const [, a, b, c, d, high, low] = numbers;
392
+ return {
393
+ host: `${a}.${b}.${c}.${d}`,
394
+ port: Number(high) * 256 + Number(low)
395
+ };
396
+ };
397
+ var ftpUploader = (target) => {
398
+ const secure = target.secure ?? "explicit";
399
+ const port = target.port ?? (secure === "implicit" ? 990 : 21);
400
+ const timeoutMs = target.timeoutMs ?? 3e4;
401
+ const folder = (target.folder ?? "").replace(/^\/+|\/+$/g, "");
402
+ const tlsOptions = {
403
+ servername: target.host,
404
+ rejectUnauthorized: !target.allowSelfSigned
405
+ };
406
+ return {
407
+ name: `FTP ${target.user}@${target.host}${folder ? `/${folder}` : ""}`,
408
+ atomic: false,
409
+ upload: async (files, log, signal) => {
410
+ log("FTP replaces the files one by one: while they go up, a visitor may get some of each version", "warn");
411
+ if (secure === "none") log("This FTP host is reached without TLS: its password and the site travel in the clear", "warn");
412
+ if (target.allowSelfSigned) log("The host’s certificate is accepted without an authority vouching for it", "warn");
413
+ const socket = secure === "implicit" ? connect$1({
414
+ host: target.host,
415
+ port,
416
+ ...tlsOptions
417
+ }) : connect({
418
+ host: target.host,
419
+ port
420
+ });
421
+ await opened(socket, secure === "implicit" ? "secureConnect" : "connect", timeoutMs);
422
+ const control = new Control(socket, timeoutMs);
423
+ let session;
424
+ const abort = () => control.socket.destroy(/* @__PURE__ */ new Error("Canceled"));
425
+ signal?.addEventListener("abort", abort, { once: true });
426
+ try {
427
+ await control.next().then((reply) => {
428
+ if (reply.code !== 220) throw new Error(`The FTP host did not greet: ${reply.text}`);
429
+ });
430
+ if (secure === "explicit") {
431
+ await control.send("AUTH TLS", [234]);
432
+ control.socket.removeAllListeners("data");
433
+ const upgraded = connect$1({
434
+ socket: control.socket,
435
+ ...tlsOptions
436
+ });
437
+ await opened(upgraded, "secureConnect", timeoutMs);
438
+ control.listen(upgraded);
439
+ }
440
+ if (secure !== "none") {
441
+ session = control.socket.getSession();
442
+ await control.send("PBSZ 0", [200]);
443
+ await control.send("PROT P", [200]);
444
+ }
445
+ await control.send(`USER ${target.user}`, [230, 331], "the user");
446
+ await control.send(`PASS ${target.password}`, [230, 202], "the password");
447
+ await control.send("TYPE I", [200]);
448
+ const made = /* @__PURE__ */ new Set();
449
+ const makeFolders = async (path) => {
450
+ const parts = path.split("/").slice(0, -1);
451
+ for (let depth = 1; depth <= parts.length; depth += 1) {
452
+ const dir = parts.slice(0, depth).join("/");
453
+ if (!made.has(dir)) {
454
+ made.add(dir);
455
+ await control.send(`MKD ${dir}`, [
456
+ 257,
457
+ 550,
458
+ 521
459
+ ]);
460
+ }
461
+ }
462
+ };
463
+ let bytes = 0;
464
+ for (const file of files) {
465
+ signal?.throwIfAborted();
466
+ const path = folder ? `${folder}/${file.path}` : file.path;
467
+ await makeFolders(path);
468
+ const address = passiveAddress((await control.send("PASV", [227])).text);
469
+ const host = /^(10|127|192\.168|172\.(1[6-9]|2\d|3[01]))\./.test(address.host) ? target.host : address.host;
470
+ const raw = connect({
471
+ host,
472
+ port: address.port
473
+ });
474
+ await opened(raw, "connect", timeoutMs);
475
+ const data = secure === "none" ? raw : connect$1({
476
+ socket: raw,
477
+ ...tlsOptions,
478
+ ...session ? { session } : {}
479
+ });
480
+ if (secure !== "none") await opened(data, "secureConnect", timeoutMs);
481
+ control.socket.write(`STOR ${path}\r\n`);
482
+ const started = await control.next();
483
+ if (started.code !== 150 && started.code !== 125) {
484
+ data.destroy();
485
+ throw new Error(`The FTP host refused to store ${path}: ${started.text}`);
486
+ }
487
+ await new Promise((resolve, reject) => {
488
+ data.once("error", reject);
489
+ data.end(Buffer.from(file.body), () => resolve());
490
+ });
491
+ const stored = await control.next();
492
+ if (stored.code !== 226 && stored.code !== 250) throw new Error(`The FTP host did not keep ${path}: ${stored.text}`);
493
+ bytes += file.body.byteLength;
494
+ }
495
+ await control.send("QUIT", [221, 200]).catch(() => void 0);
496
+ log(`Stored ${String(files.length)} files (${String(Math.round(bytes / 1024))} KB) on ${target.host}`);
497
+ return {
498
+ files: files.length,
499
+ bytes,
500
+ reference: folder || "/"
501
+ };
502
+ } finally {
503
+ signal?.removeEventListener("abort", abort);
504
+ control.socket.destroy();
505
+ }
506
+ }
507
+ };
508
+ };
509
+ // src/deploy/sdkFiles.ts
510
+ /**
511
+ * The SDK's files a site served off this server loads — the bundle, React and its kin (the vendor bundle), the
512
+ * stylesheets, the icon fonts and the chunks the bundle imports — read from the installed `@plitzi/plitzi-sdk`, so a
513
+ * site carries its own copy instead of asking a third-party CDN for React at run time. Kept under a folder named by
514
+ * their digest: immutable, and a deploy with a newer SDK is a new folder, never a file changed in place.
515
+ */
516
+ /** What a browser never asks for: the development builds, source maps, the pre-compressed copies, the package's own. */
517
+ var LEFT_OUT = /(\.gz|\.map|\.d\.ts)$|^(index\.html|robots\.txt|build\.json)$|dev-vendor/;
518
+ var read;
519
+ var walk = (dir, prefix = "") => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
520
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
521
+ if (entry.isDirectory()) return entry.name === "webfonts" ? walk(path.join(dir, entry.name), relative) : [];
522
+ return LEFT_OUT.test(entry.name) ? [] : [relative];
523
+ });
524
+ /** The SDK's files, read once a process — the installed SDK cannot change while it runs. */
525
+ var sdkFiles = () => {
526
+ if (read) return read;
527
+ const dir = resolveSdkAssetsDir();
528
+ if (!dir) throw new Error("@plitzi/plitzi-sdk is not installed beside @plitzi/sdk-server: a site served off it has no SDK to load");
529
+ const names = walk(dir).sort();
530
+ const bodies = names.map((name) => readFileSync(path.join(dir, name)));
531
+ const hash = createHash("sha256");
532
+ names.forEach((name, index) => hash.update(name).update(bodies[index]));
533
+ const digest = hash.digest("hex").slice(0, 12);
534
+ const folder = `_plitzi/sdk-${digest}`;
535
+ read = {
536
+ folder,
537
+ digest,
538
+ files: names.map((name, index) => ({
539
+ path: `${folder}/${name}`,
540
+ body: new Uint8Array(bodies[index]),
541
+ type: contentTypeOf(name),
542
+ cache: "immutable"
543
+ }))
544
+ };
545
+ return read;
546
+ };
547
+ var versionOf = (manifest) => {
548
+ try {
549
+ const parsed = JSON.parse(readFileSync(manifest, "utf8"));
550
+ return parsed !== null && typeof parsed === "object" && "version" in parsed && typeof parsed.version === "string" ? parsed.version : "unknown";
551
+ } catch {
552
+ return "unknown";
553
+ }
554
+ };
555
+ var versions;
556
+ /** The versions a build made here bakes in (§5.2): the SDK beside this server, its React, and this server. */
557
+ var buildVersions = () => {
558
+ if (versions) return versions;
559
+ const dir = resolveSdkAssetsDir();
560
+ const require = createRequire(import.meta.url);
561
+ let react = "unknown";
562
+ try {
563
+ react = versionOf(require.resolve("react/package.json"));
564
+ } catch {}
565
+ versions = {
566
+ sdk: dir ? versionOf(path.join(dir, "..", "package.json")) : "unknown",
567
+ react,
568
+ sdkServer: ownVersion()
569
+ };
570
+ return versions;
571
+ };
572
+ // src/deploy/spaShell.ts
573
+ /**
574
+ * A space as a single-page app: an `index.html` that loads the SDK from beside it and asks the page
575
+ * server for the space, and the SDK's files under a folder named by their digest. Hosted anywhere that serves files.
576
+ *
577
+ * The shell names the environment it serves and never a revision: the page server answers the revision the site's own
578
+ * domain is published at (`renderGrant`'s `served`), so publishing to an SPA target is a pointer move, as it is on
579
+ * Plitzi, and a deploy is needed only when the shell itself changed — its fingerprint says which part did.
580
+ */
581
+ /** Changed when the shell's markup changes: every SPA built before needs a deploy to get it. */
582
+ var SHELL_VERSION = "1";
583
+ var normalizeBase = (basePath) => {
584
+ const trimmed = (basePath ?? "/").trim().replace(/^\/*/, "/").replace(/\/*$/, "/");
585
+ return trimmed === "//" ? "/" : trimmed;
586
+ };
587
+ var fontsMarkup = ({ preconnect, links, faces }) => [
588
+ ...preconnect.map(({ href, crossorigin }) => `<link rel="preconnect" href="${escapeHtml(href)}"${crossorigin ? " crossorigin" : ""}>`),
589
+ ...links.map(({ href, rel, as, type, crossorigin }) => `<link rel="${rel}" href="${escapeHtml(href)}"${as ? ` as="${as}"` : ""}${type ? ` type="${escapeHtml(type)}"` : ""}${crossorigin ? " crossorigin" : ""}>`),
590
+ ...faces ? [`<style data-plitzi-fonts>${faces.replace(/<\//g, "<\\/")}</style>`] : []
591
+ ].join("\n ");
592
+ /** The shell's `index.html`. */
593
+ var shellHtml = (input, base, sdkFolder) => {
594
+ const sdk = `${base}${sdkFolder}`;
595
+ const imports = {
596
+ react: `${sdk}/plitzi-sdk-vendor.js`,
597
+ "react-dom": `${sdk}/plitzi-sdk-vendor.js`,
598
+ "react-dom/client": `${sdk}/plitzi-sdk-vendor.js`,
599
+ "react/jsx-runtime": `${sdk}/plitzi-sdk-vendor.js`,
600
+ "react/compiler-runtime": `${sdk}/plitzi-sdk-vendor.js`,
601
+ "@plitzi/plitzi-sdk": `${sdk}/plitzi-sdk.js`
602
+ };
603
+ const props = {
604
+ webKey: input.webKey,
605
+ environment: input.environment,
606
+ renderMode: "raw",
607
+ server: {
608
+ ...input.servers,
609
+ basePath: base
610
+ },
611
+ state: {}
612
+ };
613
+ return `<!doctype html>
614
+ <html lang="${escapeHtml(input.head.lang)}">
615
+ <head>
616
+ <meta charset="utf-8">
617
+ <meta name="viewport" content="width=device-width, initial-scale=1">
618
+ <title>${escapeHtml(input.head.title)}</title>
619
+ <link rel="icon" href="${escapeHtml(input.head.favicon)}">
620
+ <link rel="preconnect" href="${escapeHtml(input.servers.ssrServer)}" crossorigin>
621
+ ${fontsMarkup(input.head.fonts)}
622
+ <script type="importmap">${escapeJson(JSON.stringify({ imports }))}<\/script>
623
+ <link rel="modulepreload" href="${escapeHtml(imports.react)}">
624
+ <link rel="modulepreload" href="${escapeHtml(imports["@plitzi/plitzi-sdk"])}">
625
+ <link rel="stylesheet" href="${escapeHtml(sdk)}/plitzi-sdk.css">
626
+ <link rel="stylesheet" href="${escapeHtml(sdk)}/plitzi-sdk-icons.css">
627
+ </head>
628
+ <body>
629
+ <noscript>This site needs JavaScript to show its pages.</noscript>
630
+ <div id="plitzi" class="plitzi-root-container"></div>
631
+ <script type="module">
632
+ import { render } from '@plitzi/plitzi-sdk';
633
+
634
+ render('plitzi', ${escapeJson(JSON.stringify(props))}, {}, false);
635
+ <\/script>
636
+ </body>
637
+ </html>
638
+ `;
639
+ };
640
+ /** What an SPA bakes in, part by part (§5.1): what its fingerprint is made of, and the reasons a deploy is needed. */
641
+ var spaFingerprintParts = (input, sdkDigest = sdkFiles().digest) => ({
642
+ shell: SHELL_VERSION,
643
+ sdk: sdkDigest,
644
+ environment: input.environment,
645
+ fonts: digestOf(input.head.fonts),
646
+ head: digestOf({
647
+ title: input.head.title,
648
+ lang: input.head.lang,
649
+ favicon: input.head.favicon
650
+ }),
651
+ key: digestOf(input.webKey),
652
+ servers: digestOf({
653
+ ...input.servers,
654
+ basePath: normalizeBase(input.basePath)
655
+ })
656
+ });
657
+ /**
658
+ * The SPA, built: `index.html`, the same page as `404.html` — a static host answers an address it has no file for with
659
+ * it, so a link into the site opens its page instead of the host's error — and the SDK's files.
660
+ */
661
+ var buildSpaShell = (input) => {
662
+ const sdk = sdkFiles();
663
+ const html = new TextEncoder().encode(shellHtml(input, normalizeBase(input.basePath), sdk.folder));
664
+ const page = (path) => ({
665
+ path,
666
+ body: html,
667
+ type: "text/html; charset=utf-8",
668
+ cache: "revalidate"
669
+ });
670
+ return {
671
+ files: [
672
+ page("index.html"),
673
+ page("404.html"),
674
+ ...sdk.files
675
+ ],
676
+ fingerprint: fingerprintOf(spaFingerprintParts(input, sdk.digest)),
677
+ versions: buildVersions()
678
+ };
679
+ };
680
+ // src/deploy/staticSite.ts
681
+ var DEFAULT_MAX_PAGES = 500;
682
+ /** An address the site has no page for: its 404 page, kept as `404.html`. */
683
+ var NOT_FOUND_PROBE = "/__plitzi-not-found__";
684
+ var decoder = new TextDecoder();
685
+ /** An address of the same origin, without its fragment; nothing for another origin, a `data:` or a `mailto:`. */
686
+ var sameOrigin = (raw) => {
687
+ const value = raw.trim().replace(/&amp;/g, "&");
688
+ if (!value.startsWith("/") || value.startsWith("//")) return;
689
+ return value.split("#")[0] || void 0;
690
+ };
691
+ /** The file a path is kept as: `/` → `index.html`, `/menu` → `menu/index.html`, `/a.js?v=1` → `a.js`. */
692
+ var fileOf = (path, html) => {
693
+ const clean = decodeURIComponent(path.split("?")[0]).replace(/^\/+/, "");
694
+ if (!html) return clean;
695
+ return clean === "" ? "index.html" : clean.endsWith(".html") ? clean : `${clean.replace(/\/+$/, "")}/index.html`;
696
+ };
697
+ /** The first group of a match that took part in it: `(?:"(a)"|'(b)')` is either. */
698
+ var firstGroup = (match) => match.slice(1).find((group) => typeof group === "string");
699
+ /** The pages an HTML document links to, and the files it loads (scripts, stylesheets, images, the import map's). */
700
+ var linksOf = (html) => {
701
+ const pages = /* @__PURE__ */ new Set();
702
+ const files = /* @__PURE__ */ new Set();
703
+ const add = (into, raw) => {
704
+ const path = sameOrigin(raw ?? "");
705
+ if (path) into.add(path);
706
+ };
707
+ for (const match of html.matchAll(/<a\b[^>]*?\shref=(?:"([^"]*)"|'([^']*)')/gi)) add(pages, firstGroup(match));
708
+ for (const match of html.matchAll(/<link\b[^>]*?\shref=(?:"([^"]*)"|'([^']*)')/gi)) add(files, firstGroup(match));
709
+ for (const match of html.matchAll(/\s(?:src|poster|data-src)=(?:"([^"]*)"|'([^']*)')/gi)) add(files, firstGroup(match));
710
+ for (const match of html.matchAll(/\ssrcset=(?:"([^"]*)"|'([^']*)')/gi)) for (const candidate of (firstGroup(match) ?? "").split(",")) add(files, candidate.trim().split(/\s+/)[0]);
711
+ for (const match of html.matchAll(/<script type="importmap"[^>]*>([\s\S]*?)<\/script>/gi)) for (const value of match[1].matchAll(/"(\/[^"]+)"/g)) add(files, value[1]);
712
+ for (const match of html.matchAll(/["'](\/_plitzi\/[\w./-]+\.(?:json|css|js))["']/g)) add(files, match[1]);
713
+ return {
714
+ pages: [...pages],
715
+ files: [...files]
716
+ };
717
+ };
718
+ /** The files a stylesheet loads (`url(...)`, `@import`), resolved against where it is. */
719
+ var cssFilesOf = (css, at) => {
720
+ const base = new URL(at, "https://site.invalid");
721
+ const found = /* @__PURE__ */ new Set();
722
+ for (const match of css.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)|@import\s+(['"])([^'"]+)\3/g)) {
723
+ const raw = ([match[2], match[4]].find((group) => typeof group === "string") ?? "").trim();
724
+ if (!raw || raw.startsWith("data:") || /^[a-z]+:/i.test(raw) || raw.startsWith("//")) continue;
725
+ const resolved = new URL(raw, base);
726
+ found.add(`${resolved.pathname}${resolved.search}`);
727
+ }
728
+ return [...found];
729
+ };
730
+ var isPattern = (route) => /[:*]/.test(route);
731
+ var buildStaticSite = async ({ fetchPage, routes, extraPaths = [], maxPages = DEFAULT_MAX_PAGES, log, signal, version }) => {
732
+ const files = /* @__PURE__ */ new Map();
733
+ const pagesSeen = /* @__PURE__ */ new Set();
734
+ const filesSeen = /* @__PURE__ */ new Set();
735
+ const queue = [.../* @__PURE__ */ new Set([
736
+ "/",
737
+ ...routes.filter((route) => !isPattern(route)),
738
+ ...extraPaths
739
+ ])];
740
+ const patterns = routes.filter(isPattern);
741
+ const reached = [];
742
+ const failed = [];
743
+ const keepFile = async (path) => {
744
+ if (filesSeen.has(path)) return;
745
+ filesSeen.add(path);
746
+ signal?.throwIfAborted();
747
+ const answer = await fetchPage(path);
748
+ if (answer.status !== 200) {
749
+ failed.push(`${path} (${String(answer.status)})`);
750
+ return;
751
+ }
752
+ const name = fileOf(path, false);
753
+ files.set(name, {
754
+ path: name,
755
+ body: answer.body,
756
+ type: answer.type || contentTypeOf(name),
757
+ cache: path.includes("?") || /[.-][0-9a-f]{8,}\./i.test(name) ? "immutable" : "revalidate"
758
+ });
759
+ if (answer.type.includes("css")) for (const inner of cssFilesOf(decoder.decode(answer.body), path)) await keepFile(inner);
760
+ };
761
+ while (queue.length > 0) {
762
+ const page = (queue.shift() ?? "/").split("?")[0];
763
+ if (pagesSeen.has(page)) continue;
764
+ if (pagesSeen.size >= maxPages) {
765
+ log(`Stopped at ${String(maxPages)} pages: the rest of the site was not prerendered`, "warn");
766
+ break;
767
+ }
768
+ pagesSeen.add(page);
769
+ signal?.throwIfAborted();
770
+ const answer = await fetchPage(page);
771
+ if (answer.status !== 200 || !answer.type.includes("html")) {
772
+ failed.push(`${page} (${String(answer.status)})`);
773
+ continue;
774
+ }
775
+ const html = decoder.decode(answer.body);
776
+ files.set(fileOf(page, true), {
777
+ path: fileOf(page, true),
778
+ body: answer.body,
779
+ type: "text/html; charset=utf-8",
780
+ cache: "revalidate"
781
+ });
782
+ reached.push(page);
783
+ const links = linksOf(html);
784
+ for (const file of links.files) await keepFile(file);
785
+ for (const link of links.pages) {
786
+ const target = link.split("?")[0];
787
+ if (!pagesSeen.has(target) && !/\.[a-z0-9]{1,5}$/i.test(target)) queue.push(target);
788
+ }
789
+ }
790
+ const notFound = await fetchPage(NOT_FOUND_PROBE);
791
+ if (notFound.type.includes("html")) {
792
+ files.set("404.html", {
793
+ path: "404.html",
794
+ body: notFound.body,
795
+ type: "text/html; charset=utf-8",
796
+ cache: "revalidate"
797
+ });
798
+ for (const file of linksOf(decoder.decode(notFound.body)).files) await keepFile(file);
799
+ }
800
+ const unreached = patterns.filter((pattern) => {
801
+ const matcher = new RegExp(`^${pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/:[^/]+/g, "[^/]+").replace(/\*/g, ".*")}$`);
802
+ return !reached.some((path) => matcher.test(path));
803
+ });
804
+ log(`Prerendered ${String(reached.length)} pages and ${String(files.size - reached.length)} files they load`);
805
+ if (unreached.length > 0) log(`Not prerendered — no page links to an address of: ${unreached.join(", ")}. List the addresses to prerender in the target’s settings`, "warn");
806
+ if (failed.length > 0) log(`The page server did not answer: ${failed.slice(0, 10).join(", ")}${failed.length > 10 ? "…" : ""}`, "warn");
807
+ const sorted = [...files.values()].sort((a, b) => a.path < b.path ? -1 : 1);
808
+ return {
809
+ files: sorted,
810
+ fingerprint: fingerprintOf({
811
+ version,
812
+ content: digestOf(sorted.map((file) => [file.path, digestOf(decoder.decode(file.body))]))
813
+ }),
814
+ versions: buildVersions(),
815
+ unreached
816
+ };
817
+ };
818
+ // src/deploy/zip.ts
819
+ /**
820
+ * A site as one zip and back (PKWARE APPNOTE, the subset every unzip reads): what a person downloads to host by hand,
821
+ * what Amplify takes as a deploy, and how a deploy's artifact is kept for a rollback that ships it again (§7). Deflated
822
+ * where that saves bytes, stored where it does not (images and fonts are compressed already). No ZIP64: a site past
823
+ * 4 GB or 65,535 files is refused with why, never written broken.
824
+ */
825
+ var LOCAL_HEADER = 67324752;
826
+ var CENTRAL_HEADER = 33639248;
827
+ var END_OF_CENTRAL = 101010256;
828
+ var STORED = 0;
829
+ var DEFLATED = 8;
830
+ /** "Version needed to extract": 2.0, deflate. */
831
+ var ZIP_VERSION = 20;
832
+ /** Bit 11: names are UTF-8. */
833
+ var UTF8 = 2048;
834
+ var MAX_FILES = 65535;
835
+ var MAX_BYTES = 4294967295;
836
+ /** 1980-01-01 00:00 in DOS time: every entry carries the same, so the same site is always the same zip. */
837
+ var DOS_DATE = 33;
838
+ /** A site's files as one zip, the same bytes for the same files. */
839
+ var zipFiles = (files) => {
840
+ if (files.length > MAX_FILES) throw new Error(`A zip holds at most ${String(MAX_FILES)} files; this site has ${String(files.length)}`);
841
+ const locals = [];
842
+ const centrals = [];
843
+ let offset = 0;
844
+ for (const file of files) {
845
+ const name = Buffer.from(file.path, "utf8");
846
+ const raw = Buffer.from(file.body);
847
+ const deflated = deflateRawSync(raw);
848
+ const method = deflated.length < raw.length ? DEFLATED : STORED;
849
+ const data = method === DEFLATED ? deflated : raw;
850
+ const checksum = crc32(raw);
851
+ if (offset + 30 + name.length + data.length > MAX_BYTES) throw new Error("A zip holds at most 4 GB; this site is larger");
852
+ const local = Buffer.alloc(30);
853
+ local.writeUInt32LE(LOCAL_HEADER, 0);
854
+ local.writeUInt16LE(ZIP_VERSION, 4);
855
+ local.writeUInt16LE(UTF8, 6);
856
+ local.writeUInt16LE(method, 8);
857
+ local.writeUInt16LE(0, 10);
858
+ local.writeUInt16LE(DOS_DATE, 12);
859
+ local.writeUInt32LE(checksum, 14);
860
+ local.writeUInt32LE(data.length, 18);
861
+ local.writeUInt32LE(raw.length, 22);
862
+ local.writeUInt16LE(name.length, 26);
863
+ local.writeUInt16LE(0, 28);
864
+ const central = Buffer.alloc(46);
865
+ central.writeUInt32LE(CENTRAL_HEADER, 0);
866
+ central.writeUInt16LE(788, 4);
867
+ central.writeUInt16LE(ZIP_VERSION, 6);
868
+ central.writeUInt16LE(UTF8, 8);
869
+ central.writeUInt16LE(method, 10);
870
+ central.writeUInt16LE(0, 12);
871
+ central.writeUInt16LE(DOS_DATE, 14);
872
+ central.writeUInt32LE(checksum, 16);
873
+ central.writeUInt32LE(data.length, 20);
874
+ central.writeUInt32LE(raw.length, 24);
875
+ central.writeUInt16LE(name.length, 28);
876
+ central.writeUInt32LE(33188 << 16 >>> 0, 38);
877
+ central.writeUInt32LE(offset, 42);
878
+ locals.push(local, name, data);
879
+ centrals.push(central, name);
880
+ offset += local.length + name.length + data.length;
881
+ }
882
+ const directory = Buffer.concat(centrals);
883
+ const end = Buffer.alloc(22);
884
+ end.writeUInt32LE(END_OF_CENTRAL, 0);
885
+ end.writeUInt16LE(files.length, 8);
886
+ end.writeUInt16LE(files.length, 10);
887
+ end.writeUInt32LE(directory.length, 12);
888
+ end.writeUInt32LE(offset, 16);
889
+ return new Uint8Array(Buffer.concat([
890
+ ...locals,
891
+ directory,
892
+ end
893
+ ]));
894
+ };
895
+ /**
896
+ * The files of a zip this module wrote (or any zip of the same subset: no ZIP64, no encryption, stored or deflated).
897
+ * Anything else is refused with what it is, never read half.
898
+ */
899
+ var unzipFiles = (zip, cache = () => "revalidate") => {
900
+ const bytes = Buffer.from(zip);
901
+ const endAt = bytes.lastIndexOf(Buffer.from([
902
+ 80,
903
+ 75,
904
+ 5,
905
+ 6
906
+ ]));
907
+ if (endAt < 0) throw new Error("Not a zip: it has no central directory");
908
+ const count = bytes.readUInt16LE(endAt + 10);
909
+ let at = bytes.readUInt32LE(endAt + 16);
910
+ const files = [];
911
+ for (let index = 0; index < count; index += 1) {
912
+ if (bytes.readUInt32LE(at) !== CENTRAL_HEADER) throw new Error(`The zip's directory is broken at entry ${String(index + 1)}`);
913
+ const flags = bytes.readUInt16LE(at + 8);
914
+ const method = bytes.readUInt16LE(at + 10);
915
+ const size = bytes.readUInt32LE(at + 20);
916
+ const nameLength = bytes.readUInt16LE(at + 28);
917
+ const extraLength = bytes.readUInt16LE(at + 30);
918
+ const commentLength = bytes.readUInt16LE(at + 32);
919
+ const localAt = bytes.readUInt32LE(at + 42);
920
+ const path = bytes.subarray(at + 46, at + 46 + nameLength).toString("utf8");
921
+ if (flags & 1) throw new Error(`${path} is encrypted, and a site's files never are`);
922
+ const dataAt = localAt + 30 + bytes.readUInt16LE(localAt + 26) + bytes.readUInt16LE(localAt + 28);
923
+ const data = bytes.subarray(dataAt, dataAt + size);
924
+ if (method !== STORED && method !== DEFLATED) throw new Error(`${path} is compressed with method ${String(method)}, which only stored and deflated zips use`);
925
+ if (!path.endsWith("/")) {
926
+ const body = method === DEFLATED ? inflateRawSync(data) : data;
927
+ files.push({
928
+ path,
929
+ body: new Uint8Array(body),
930
+ type: contentTypeOf(path),
931
+ cache: cache(path)
932
+ });
933
+ }
934
+ at += 46 + nameLength + extraLength + commentLength;
935
+ }
936
+ return files;
937
+ };
938
+ export { awsEncode, awsFetch, awsRefusal, buildSpaShell, buildStaticSite, buildVersions, contentTypeOf, cssFilesOf, digestOf, fileOf, fingerprintChanges, fingerprintOf, folderUploader, ftpUploader, invalidateCloudFront, linksOf, objectUrl, passiveAddress, pointCloudFront, putFiles, putObject, s3Uploader, sdkFiles, signAws, spaFingerprintParts, unzipFiles, zipFiles };