htmlhost-cli 1.5.1 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -1
- package/package.json +1 -1
- package/src/api.mjs +77 -34
- package/src/assets.mjs +46 -8
- package/src/cli.mjs +4 -1
- package/src/commands/deploy.mjs +169 -4
package/README.md
CHANGED
|
@@ -38,8 +38,11 @@ Deploy an HTML file — or an entire directory of HTML files — and get live UR
|
|
|
38
38
|
# Single file
|
|
39
39
|
htmlhost deploy index.html
|
|
40
40
|
|
|
41
|
-
# All .html files in the current directory
|
|
41
|
+
# All .html files in the current directory (as separate sites)
|
|
42
42
|
htmlhost deploy .
|
|
43
|
+
|
|
44
|
+
# All .html files as ONE multi-page site
|
|
45
|
+
htmlhost deploy . --pages
|
|
43
46
|
```
|
|
44
47
|
|
|
45
48
|
Local assets (scripts, CSS, images, fonts) referenced in the HTML are
|
|
@@ -51,6 +54,19 @@ deployed as a separate linked site. The mapping is saved to `.htmlhost` so
|
|
|
51
54
|
subsequent `htmlhost deploy .` updates all of them in place. Shared assets
|
|
52
55
|
(e.g. a `styles.css` referenced by multiple pages) are uploaded once and reused.
|
|
53
56
|
|
|
57
|
+
**Multi-page deploy:** Use `--pages` to deploy a directory as a single
|
|
58
|
+
multi-page site. File names map to URL paths:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
index.html → /
|
|
62
|
+
about.html → /about
|
|
63
|
+
contact.html → /contact
|
|
64
|
+
blog/index.html → /blog
|
|
65
|
+
blog/post-1.html → /blog/post-1
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Add a `404.html` file and it will be served automatically for missing pages.
|
|
69
|
+
|
|
54
70
|
| Option | Description |
|
|
55
71
|
|---|---|
|
|
56
72
|
| `--ttl <value>` | Set expiry: `1d`, `7d`, `30d`, `never` |
|
|
@@ -58,6 +74,7 @@ subsequent `htmlhost deploy .` updates all of them in place. Shared assets
|
|
|
58
74
|
| `--title <title>` | Set the site title (single file only) |
|
|
59
75
|
| `--new` | Force new sites (ignore .htmlhost link) |
|
|
60
76
|
| `--no-assets` | Skip automatic asset uploading |
|
|
77
|
+
| `--pages` | Deploy directory as one multi-page site |
|
|
61
78
|
|
|
62
79
|
### `htmlhost list`
|
|
63
80
|
List all your sites with URLs, sizes, and expiry.
|
package/package.json
CHANGED
package/src/api.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* HTTP client wrapper for the htmlhost API.
|
|
3
3
|
*/
|
|
4
4
|
import { getToken, getApi } from "./config.mjs";
|
|
5
|
+
import { dim, yellow } from "./ui.mjs";
|
|
5
6
|
|
|
6
7
|
export class ApiError extends Error {
|
|
7
8
|
constructor(message, status) {
|
|
@@ -10,6 +11,39 @@ export class ApiError extends Error {
|
|
|
10
11
|
}
|
|
11
12
|
}
|
|
12
13
|
|
|
14
|
+
const MAX_RETRIES = 3;
|
|
15
|
+
const BASE_DELAY_MS = 500;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Retry wrapper with exponential backoff.
|
|
19
|
+
* Retries on network errors ("fetch failed", ECONNRESET, etc.)
|
|
20
|
+
* and 5xx server errors. Does NOT retry on 4xx client errors.
|
|
21
|
+
*/
|
|
22
|
+
async function withRetry(fn, label = "request") {
|
|
23
|
+
let lastError;
|
|
24
|
+
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
|
25
|
+
try {
|
|
26
|
+
return await fn();
|
|
27
|
+
} catch (e) {
|
|
28
|
+
lastError = e;
|
|
29
|
+
const isNetworkError =
|
|
30
|
+
!(e instanceof ApiError) ||
|
|
31
|
+
(e.status >= 500 && e.status < 600);
|
|
32
|
+
|
|
33
|
+
if (!isNetworkError || attempt === MAX_RETRIES) {
|
|
34
|
+
throw e;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const delay = BASE_DELAY_MS * Math.pow(2, attempt - 1);
|
|
38
|
+
console.log(
|
|
39
|
+
` ${yellow("↻")} ${label} failed (attempt ${attempt}/${MAX_RETRIES}), retrying in ${delay}ms… ${dim(e.message)}`
|
|
40
|
+
);
|
|
41
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
throw lastError;
|
|
45
|
+
}
|
|
46
|
+
|
|
13
47
|
function headers(extra = {}) {
|
|
14
48
|
const token = getToken();
|
|
15
49
|
if (!token) throw new ApiError("Not logged in. Run: htmlhost login", 0);
|
|
@@ -20,52 +54,61 @@ function headers(extra = {}) {
|
|
|
20
54
|
}
|
|
21
55
|
|
|
22
56
|
export async function get(path) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
57
|
+
return withRetry(async () => {
|
|
58
|
+
const res = await fetch(`${getApi()}${path}`, {
|
|
59
|
+
headers: headers(),
|
|
60
|
+
});
|
|
61
|
+
const data = await res.json();
|
|
62
|
+
if (!res.ok) throw new ApiError(data.error || `HTTP ${res.status}`, res.status);
|
|
63
|
+
return data;
|
|
64
|
+
}, `GET ${path}`);
|
|
29
65
|
}
|
|
30
66
|
|
|
31
67
|
export async function post(path, body) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
68
|
+
return withRetry(async () => {
|
|
69
|
+
const res = await fetch(`${getApi()}${path}`, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: headers({ "Content-Type": "application/json" }),
|
|
72
|
+
body: JSON.stringify(body),
|
|
73
|
+
});
|
|
74
|
+
const data = await res.json();
|
|
75
|
+
if (!res.ok) throw new ApiError(data.error || `HTTP ${res.status}`, res.status);
|
|
76
|
+
return data;
|
|
77
|
+
}, `POST ${path}`);
|
|
40
78
|
}
|
|
41
79
|
|
|
42
80
|
export async function del(path) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
81
|
+
return withRetry(async () => {
|
|
82
|
+
const res = await fetch(`${getApi()}${path}`, {
|
|
83
|
+
method: "DELETE",
|
|
84
|
+
headers: headers(),
|
|
85
|
+
});
|
|
86
|
+
const data = await res.json();
|
|
87
|
+
if (!res.ok) throw new ApiError(data.error || `HTTP ${res.status}`, res.status);
|
|
88
|
+
return data;
|
|
89
|
+
}, `DELETE ${path}`);
|
|
50
90
|
}
|
|
51
91
|
|
|
52
92
|
/**
|
|
53
93
|
* Upload a file via multipart/form-data.
|
|
54
94
|
*/
|
|
55
95
|
export async function uploadFile(path, filePath, fileName, mimeType) {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
96
|
+
return withRetry(async () => {
|
|
97
|
+
const { readFileSync } = await import("node:fs");
|
|
98
|
+
const fileBuffer = readFileSync(filePath);
|
|
99
|
+
const blob = new Blob([fileBuffer], { type: mimeType });
|
|
59
100
|
|
|
60
|
-
|
|
61
|
-
|
|
101
|
+
const form = new FormData();
|
|
102
|
+
form.append("file", blob, fileName);
|
|
62
103
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
104
|
+
const res = await fetch(`${getApi()}${path}`, {
|
|
105
|
+
method: "POST",
|
|
106
|
+
headers: { Authorization: `Bearer ${getToken()}` },
|
|
107
|
+
body: form,
|
|
108
|
+
});
|
|
109
|
+
const data = await res.json();
|
|
110
|
+
if (!res.ok) throw new ApiError(data.error || `HTTP ${res.status}`, res.status);
|
|
111
|
+
return data;
|
|
112
|
+
}, `upload ${fileName}`);
|
|
71
113
|
}
|
|
114
|
+
|
package/src/assets.mjs
CHANGED
|
@@ -137,7 +137,14 @@ async function processCssContent(css, cssDir, sharedCache, urlMap) {
|
|
|
137
137
|
if (sharedCache) sharedCache.set(asset.filePath, hostedUrl);
|
|
138
138
|
ok(` ${cyan(ref)} ${dim(`(${formatBytes(asset.size)})`)} → ${hostedUrl}`);
|
|
139
139
|
} catch (e) {
|
|
140
|
-
|
|
140
|
+
// Fall back to shared cache (which includes persisted entries)
|
|
141
|
+
if (sharedCache && sharedCache.has(asset.filePath)) {
|
|
142
|
+
const fallbackUrl = sharedCache.get(asset.filePath);
|
|
143
|
+
urlMap.set(ref, fallbackUrl);
|
|
144
|
+
warn(` Upload failed for CSS asset ${cyan(ref)}, using cached URL`);
|
|
145
|
+
} else {
|
|
146
|
+
warn(` Failed to upload ${cyan(ref)}: ${e.message}`);
|
|
147
|
+
}
|
|
141
148
|
}
|
|
142
149
|
}
|
|
143
150
|
|
|
@@ -232,12 +239,13 @@ function findAssetRefs(html) {
|
|
|
232
239
|
* @param {string} html The original HTML content
|
|
233
240
|
* @param {string} baseDir Directory the HTML file lives in
|
|
234
241
|
* @param {Map<string, string>} [sharedCache] Optional filePath → hostedUrl cache for batch deploys
|
|
235
|
-
* @
|
|
242
|
+
* @param {Map<string, string>} [persistedCache] Optional filePath → hostedUrl cache from .htmlhost (survives between deploys)
|
|
243
|
+
* @returns {Promise<{html: string, resolvedCache: Map<string, string>}>} Rewritten HTML + cache to persist
|
|
236
244
|
*/
|
|
237
|
-
export async function processAssets(html, baseDir, sharedCache) {
|
|
245
|
+
export async function processAssets(html, baseDir, sharedCache, persistedCache) {
|
|
238
246
|
const entries = findAssetRefs(html);
|
|
239
247
|
|
|
240
|
-
if (entries.length === 0) return html;
|
|
248
|
+
if (entries.length === 0) return { html, resolvedCache: persistedCache || new Map() };
|
|
241
249
|
|
|
242
250
|
const api = getApi();
|
|
243
251
|
|
|
@@ -283,13 +291,25 @@ export async function processAssets(html, baseDir, sharedCache) {
|
|
|
283
291
|
continue;
|
|
284
292
|
}
|
|
285
293
|
|
|
286
|
-
// Check shared cache first
|
|
294
|
+
// Check shared cache first (in-memory, within this deploy)
|
|
287
295
|
if (sharedCache && sharedCache.has(asset.filePath)) {
|
|
288
296
|
urlMap.set(ref, sharedCache.get(asset.filePath));
|
|
289
297
|
ok(`${cyan(ref)} ${dim("(cached)")}`);
|
|
290
298
|
continue;
|
|
291
299
|
}
|
|
292
300
|
|
|
301
|
+
// Check persisted cache (from .htmlhost, across deploys)
|
|
302
|
+
if (persistedCache && persistedCache.has(asset.filePath)) {
|
|
303
|
+
const cached = persistedCache.get(asset.filePath);
|
|
304
|
+
// Invalidate cache if file size changed (file was modified)
|
|
305
|
+
if (cached.size === asset.size) {
|
|
306
|
+
urlMap.set(ref, cached.url);
|
|
307
|
+
if (sharedCache) sharedCache.set(asset.filePath, cached.url);
|
|
308
|
+
ok(`${cyan(ref)} ${dim("(previously uploaded)")}`);
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
293
313
|
const ext = extname(asset.filePath).toLowerCase();
|
|
294
314
|
|
|
295
315
|
// --- CSS file: inline (with nested url() processing) ---
|
|
@@ -325,14 +345,22 @@ export async function processAssets(html, baseDir, sharedCache) {
|
|
|
325
345
|
const hostedUrl = `${api}${data.url}`;
|
|
326
346
|
urlMap.set(ref, hostedUrl);
|
|
327
347
|
if (sharedCache) sharedCache.set(asset.filePath, hostedUrl);
|
|
348
|
+
if (persistedCache) persistedCache.set(asset.filePath, { url: hostedUrl, size: asset.size });
|
|
328
349
|
uploadCount++;
|
|
329
350
|
ok(`${cyan(ref)} ${dim(`(${formatBytes(asset.size)})`)} → ${hostedUrl}`);
|
|
330
351
|
} catch (e) {
|
|
331
|
-
|
|
352
|
+
// Fall back to persisted cache if available — don't lose previously working URLs
|
|
353
|
+
if (persistedCache && persistedCache.has(asset.filePath)) {
|
|
354
|
+
const fallback = persistedCache.get(asset.filePath);
|
|
355
|
+
urlMap.set(ref, fallback.url);
|
|
356
|
+
warn(`Upload failed for ${cyan(ref)}, using cached URL`);
|
|
357
|
+
} else {
|
|
358
|
+
warn(`Failed to upload ${cyan(ref)}: ${e.message}`);
|
|
359
|
+
}
|
|
332
360
|
}
|
|
333
361
|
}
|
|
334
362
|
|
|
335
|
-
if (urlMap.size === 0 && inlineMap.size === 0) return html;
|
|
363
|
+
if (urlMap.size === 0 && inlineMap.size === 0) return { html, resolvedCache: persistedCache || new Map() };
|
|
336
364
|
|
|
337
365
|
// --- Phase 2: Rewrite the HTML ---
|
|
338
366
|
|
|
@@ -385,7 +413,17 @@ export async function processAssets(html, baseDir, sharedCache) {
|
|
|
385
413
|
ok(`Uploaded ${cyan(String(uploadCount))} asset${uploadCount === 1 ? "" : "s"} to media library`);
|
|
386
414
|
}
|
|
387
415
|
|
|
388
|
-
|
|
416
|
+
// Build the final resolved cache — merge persisted + newly uploaded
|
|
417
|
+
const resolvedCache = persistedCache || new Map();
|
|
418
|
+
for (const [ref, hostedUrl] of urlMap) {
|
|
419
|
+
const asset = resolveAsset(baseDir, ref);
|
|
420
|
+
if (asset.filePath && !resolvedCache.has(asset.filePath)) {
|
|
421
|
+
// Only add entries not already set (upload path sets {url, size} directly)
|
|
422
|
+
resolvedCache.set(asset.filePath, { url: hostedUrl, size: asset.size || 0 });
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
return { html: result, resolvedCache };
|
|
389
427
|
}
|
|
390
428
|
|
|
391
429
|
/**
|
package/src/cli.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { bold, dim, cyan, err } from "./ui.mjs";
|
|
5
5
|
import { ApiError } from "./api.mjs";
|
|
6
6
|
|
|
7
|
-
const VERSION = "1.
|
|
7
|
+
const VERSION = "1.7.0";
|
|
8
8
|
|
|
9
9
|
const HELP = `
|
|
10
10
|
${bold("htmlhost")} ${dim(`v${VERSION}`)} — deploy HTML from the terminal
|
|
@@ -24,6 +24,7 @@ const HELP = `
|
|
|
24
24
|
--title <title> Set the site title
|
|
25
25
|
--new Force a new site (ignore .htmlhost link)
|
|
26
26
|
--no-assets Skip auto-uploading local assets
|
|
27
|
+
--pages Deploy directory as one multi-page site
|
|
27
28
|
|
|
28
29
|
${bold("Delete options:")}
|
|
29
30
|
--force, -f Skip confirmation prompt
|
|
@@ -32,6 +33,7 @@ const HELP = `
|
|
|
32
33
|
1st deploy: creates a site, saves slug to ${dim(".htmlhost")}
|
|
33
34
|
2nd deploy: reads ${dim(".htmlhost")}, updates the same site
|
|
34
35
|
Directory: deploys each .html as a separate linked site
|
|
36
|
+
${cyan("--pages")}: deploys all .html as pages within ONE site
|
|
35
37
|
Local scripts, CSS, and images are auto-uploaded
|
|
36
38
|
and rewritten to hosted URLs (files >10 MB are skipped)
|
|
37
39
|
|
|
@@ -39,6 +41,7 @@ const HELP = `
|
|
|
39
41
|
${dim("$")} htmlhost deploy ${dim("# deploys ./index.html")}
|
|
40
42
|
${dim("$")} htmlhost deploy page.html ${dim("# deploys a specific file")}
|
|
41
43
|
${dim("$")} htmlhost deploy . ${dim("# deploys all *.html in dir")}
|
|
44
|
+
${dim("$")} htmlhost deploy . --pages ${dim("# multi-page site from dir")}
|
|
42
45
|
${dim("$")} htmlhost deploy --ttl 30d ${dim("# deploy with 30-day TTL")}
|
|
43
46
|
${dim("$")} htmlhost deploy --new ${dim("# force new sites")}
|
|
44
47
|
${dim("$")} htmlhost upload logo.png
|
package/src/commands/deploy.mjs
CHANGED
|
@@ -50,10 +50,11 @@ function promptChoice(question, options) {
|
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
/**
|
|
53
|
-
* htmlhost deploy [file|dir] [--ttl 7d] [--slug existing-slug] [--title "My Site"] [--new] [--no-assets]
|
|
53
|
+
* htmlhost deploy [file|dir] [--ttl 7d] [--slug existing-slug] [--title "My Site"] [--new] [--no-assets] [--pages]
|
|
54
54
|
*
|
|
55
55
|
* - Defaults to index.html in the current directory
|
|
56
56
|
* - If a directory (or ".") is given, deploys all *.html files as separate linked sites
|
|
57
|
+
* - Use --pages with a directory to deploy all *.html files as pages within ONE multi-page site
|
|
57
58
|
* - Remembers the site(s) via .htmlhost file (auto re-deploy)
|
|
58
59
|
* - Use --new to force fresh deploys
|
|
59
60
|
*/
|
|
@@ -64,6 +65,7 @@ export async function deploy(args) {
|
|
|
64
65
|
const title = getFlag(args, "--title");
|
|
65
66
|
const forceNew = args.includes("--new");
|
|
66
67
|
const skipAssets = args.includes("--no-assets");
|
|
68
|
+
const multiPage = args.includes("--pages");
|
|
67
69
|
|
|
68
70
|
// Check if the target is a directory
|
|
69
71
|
if (file) {
|
|
@@ -71,6 +73,9 @@ export async function deploy(args) {
|
|
|
71
73
|
try {
|
|
72
74
|
const stat = statSync(filePath);
|
|
73
75
|
if (stat.isDirectory()) {
|
|
76
|
+
if (multiPage) {
|
|
77
|
+
return deployMultiPage(filePath, { ttl, title, forceNew, skipAssets });
|
|
78
|
+
}
|
|
74
79
|
return deployDirectory(filePath, { ttl, forceNew, skipAssets });
|
|
75
80
|
}
|
|
76
81
|
} catch {
|
|
@@ -78,6 +83,11 @@ export async function deploy(args) {
|
|
|
78
83
|
}
|
|
79
84
|
}
|
|
80
85
|
|
|
86
|
+
// --pages without explicit dir defaults to cwd
|
|
87
|
+
if (multiPage && !file) {
|
|
88
|
+
return deployMultiPage(resolve("."), { ttl, title, forceNew, skipAssets });
|
|
89
|
+
}
|
|
90
|
+
|
|
81
91
|
// Default to index.html in the current directory
|
|
82
92
|
if (!file) {
|
|
83
93
|
const defaultFile = resolve("index.html");
|
|
@@ -192,7 +202,15 @@ async function deploySingleFile(file, { ttl, title, forceNew, skipAssets, slug }
|
|
|
192
202
|
|
|
193
203
|
// Upload local assets (scripts, css, images) and rewrite references
|
|
194
204
|
if (!skipAssets) {
|
|
195
|
-
|
|
205
|
+
// Load persisted asset cache from .htmlhost
|
|
206
|
+
const existingLink = readLink(projectDir);
|
|
207
|
+
const persistedCache = new Map(Object.entries(existingLink?.assets || {}));
|
|
208
|
+
const result = await processAssets(html, projectDir, undefined, persistedCache);
|
|
209
|
+
html = result.html;
|
|
210
|
+
// Persist the asset cache for next deploy
|
|
211
|
+
const linkData = readLink(projectDir) || {};
|
|
212
|
+
linkData.assets = Object.fromEntries(result.resolvedCache);
|
|
213
|
+
writeLink(projectDir, linkData);
|
|
196
214
|
}
|
|
197
215
|
|
|
198
216
|
info(slug ? `Re-deploying to ${cyan(slug)}…` : "Deploying new site…");
|
|
@@ -317,6 +335,9 @@ async function deployDirectory(dirPath, { ttl, forceNew, skipAssets }) {
|
|
|
317
335
|
// Shared asset cache across all files — avoids re-uploading the same CSS/JS/image
|
|
318
336
|
/** @type {Map<string, string>} absolute file path → hosted URL */
|
|
319
337
|
const assetCache = new Map();
|
|
338
|
+
// Load persisted asset cache from .htmlhost
|
|
339
|
+
const existingAssets = link?.assets || {};
|
|
340
|
+
const persistedCache = new Map(Object.entries(existingAssets));
|
|
320
341
|
|
|
321
342
|
for (const fileName of htmlFiles) {
|
|
322
343
|
const filePath = join(dirPath, fileName);
|
|
@@ -327,9 +348,10 @@ async function deployDirectory(dirPath, { ttl, forceNew, skipAssets }) {
|
|
|
327
348
|
|
|
328
349
|
let html = readFileSync(filePath, "utf8");
|
|
329
350
|
|
|
330
|
-
// Upload local assets with shared cache
|
|
351
|
+
// Upload local assets with shared + persisted cache
|
|
331
352
|
if (!skipAssets) {
|
|
332
|
-
|
|
353
|
+
const result = await processAssets(html, dirPath, assetCache, persistedCache);
|
|
354
|
+
html = result.html;
|
|
333
355
|
}
|
|
334
356
|
|
|
335
357
|
// Determine slug
|
|
@@ -363,6 +385,7 @@ async function deployDirectory(dirPath, { ttl, forceNew, skipAssets }) {
|
|
|
363
385
|
const finalOnRedeploy = freshLink?.onRedeploy || onRedeploy;
|
|
364
386
|
writeLink(dirPath, {
|
|
365
387
|
sites: { ...existingSites, ...results },
|
|
388
|
+
assets: Object.fromEntries(persistedCache),
|
|
366
389
|
...(finalOnRedeploy ? { onRedeploy: finalOnRedeploy } : {}),
|
|
367
390
|
});
|
|
368
391
|
|
|
@@ -381,6 +404,148 @@ async function deployDirectory(dirPath, { ttl, forceNew, skipAssets }) {
|
|
|
381
404
|
console.log("");
|
|
382
405
|
}
|
|
383
406
|
|
|
407
|
+
/**
|
|
408
|
+
* Deploy all *.html files in a directory as pages within a single multi-page site.
|
|
409
|
+
* Uses the --pages flag. File names map to URL paths:
|
|
410
|
+
* index.html → /
|
|
411
|
+
* about.html → /about
|
|
412
|
+
* blog/index.html → /blog
|
|
413
|
+
* blog/post.html → /blog/post
|
|
414
|
+
*/
|
|
415
|
+
async function deployMultiPage(dirPath, { ttl, title, forceNew, skipAssets }) {
|
|
416
|
+
// Find all .html files (recursive) — skip dotfiles
|
|
417
|
+
const htmlFiles = findHtmlFiles(dirPath, dirPath);
|
|
418
|
+
|
|
419
|
+
if (htmlFiles.length === 0) {
|
|
420
|
+
err("No .html files found in this directory.");
|
|
421
|
+
process.exit(1);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// Read existing link data
|
|
425
|
+
const link = readLink(dirPath);
|
|
426
|
+
const existingSlug = (!forceNew && link?.multipage?.slug) || null;
|
|
427
|
+
|
|
428
|
+
console.log("");
|
|
429
|
+
info(`Multi-page deploy: ${cyan(bold(String(htmlFiles.length)))} page${htmlFiles.length > 1 ? "s" : ""} in ${cyan(basename(dirPath) || ".")}`);
|
|
430
|
+
console.log("");
|
|
431
|
+
|
|
432
|
+
// Show page mapping
|
|
433
|
+
for (const { relativePath, pagePath } of htmlFiles) {
|
|
434
|
+
console.log(` ${dim("📄")} ${relativePath} → ${cyan(pagePath)}`);
|
|
435
|
+
}
|
|
436
|
+
console.log("");
|
|
437
|
+
|
|
438
|
+
// If we have a linked slug, confirm overwrite
|
|
439
|
+
if (existingSlug) {
|
|
440
|
+
info(`Linked to ${cyan(existingSlug + ".htmlhost.co")} ${dim("(multi-page)")}`);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// Process assets and build page payloads
|
|
444
|
+
const assetCache = new Map();
|
|
445
|
+
const existingAssets = link?.assets || {};
|
|
446
|
+
const persistedCache = new Map(Object.entries(existingAssets));
|
|
447
|
+
const pagePayloads = [];
|
|
448
|
+
|
|
449
|
+
for (const { filePath, pagePath, relativePath } of htmlFiles) {
|
|
450
|
+
const stat = statSync(filePath);
|
|
451
|
+
info(`${bold(relativePath)} ${dim(`(${formatBytes(stat.size)})`)}`);
|
|
452
|
+
|
|
453
|
+
let html = readFileSync(filePath, "utf8");
|
|
454
|
+
|
|
455
|
+
if (!skipAssets) {
|
|
456
|
+
const result = await processAssets(html, dirname(filePath), assetCache, persistedCache);
|
|
457
|
+
html = result.html;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
pagePayloads.push({
|
|
461
|
+
path: pagePath,
|
|
462
|
+
html,
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// Deploy all pages as one multi-page site
|
|
467
|
+
const body = { pages: pagePayloads };
|
|
468
|
+
if (ttl) body.ttl = ttl;
|
|
469
|
+
if (existingSlug) body.slug = existingSlug;
|
|
470
|
+
if (title) body.title = title;
|
|
471
|
+
|
|
472
|
+
info(existingSlug ? `Re-deploying to ${cyan(existingSlug)}…` : "Deploying new multi-page site…");
|
|
473
|
+
|
|
474
|
+
try {
|
|
475
|
+
const data = await post("/api/sites", body);
|
|
476
|
+
|
|
477
|
+
// Save link
|
|
478
|
+
writeLink(dirPath, {
|
|
479
|
+
multipage: {
|
|
480
|
+
slug: data.slug,
|
|
481
|
+
url: data.url,
|
|
482
|
+
pageCount: data.pageCount || pagePayloads.length,
|
|
483
|
+
},
|
|
484
|
+
assets: Object.fromEntries(persistedCache),
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
console.log("");
|
|
488
|
+
console.log(` ${green("━".repeat(40))}`);
|
|
489
|
+
ok(`${bold("Live")} at ${cyan(`https://${data.url}`)}`);
|
|
490
|
+
console.log(` ${dim(`${data.pageCount || pagePayloads.length} pages · ${data.ttl} TTL`)}`);
|
|
491
|
+
console.log("");
|
|
492
|
+
|
|
493
|
+
for (const { pagePath } of htmlFiles) {
|
|
494
|
+
const urlPath = pagePath === "/" ? "" : pagePath;
|
|
495
|
+
console.log(` ${cyan(`https://${data.url}${urlPath}`)}`);
|
|
496
|
+
}
|
|
497
|
+
console.log("");
|
|
498
|
+
console.log(` ${dim("Linked → .htmlhost (multipage)")}`);
|
|
499
|
+
console.log("");
|
|
500
|
+
} catch (e) {
|
|
501
|
+
err(`Deploy failed: ${e.message}`);
|
|
502
|
+
process.exit(1);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Recursively find all .html files and derive their page paths.
|
|
508
|
+
* Returns [{ filePath, relativePath, pagePath }]
|
|
509
|
+
*/
|
|
510
|
+
function findHtmlFiles(baseDir, currentDir) {
|
|
511
|
+
const entries = readdirSync(currentDir, { withFileTypes: true });
|
|
512
|
+
const results = [];
|
|
513
|
+
|
|
514
|
+
for (const entry of entries) {
|
|
515
|
+
if (entry.name.startsWith(".")) continue;
|
|
516
|
+
|
|
517
|
+
const fullPath = join(currentDir, entry.name);
|
|
518
|
+
|
|
519
|
+
if (entry.isDirectory()) {
|
|
520
|
+
results.push(...findHtmlFiles(baseDir, fullPath));
|
|
521
|
+
} else if (entry.name.endsWith(".html")) {
|
|
522
|
+
const relativePath = fullPath.slice(baseDir.length + 1); // e.g. "about.html" or "blog/post.html"
|
|
523
|
+
|
|
524
|
+
// Derive page path from file path
|
|
525
|
+
let pagePath;
|
|
526
|
+
if (entry.name === "index.html") {
|
|
527
|
+
// index.html → parent directory path (or "/" for root)
|
|
528
|
+
const dirRel = dirname(relativePath);
|
|
529
|
+
pagePath = dirRel === "." ? "/" : `/${dirRel}`;
|
|
530
|
+
} else {
|
|
531
|
+
// about.html → /about, blog/post.html → /blog/post
|
|
532
|
+
pagePath = "/" + relativePath.replace(/\.html$/, "");
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
results.push({ filePath: fullPath, relativePath, pagePath });
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// Sort: root index first, then alphabetical
|
|
540
|
+
results.sort((a, b) => {
|
|
541
|
+
if (a.pagePath === "/") return -1;
|
|
542
|
+
if (b.pagePath === "/") return 1;
|
|
543
|
+
return a.pagePath.localeCompare(b.pagePath);
|
|
544
|
+
});
|
|
545
|
+
|
|
546
|
+
return results;
|
|
547
|
+
}
|
|
548
|
+
|
|
384
549
|
function getFlag(args, flag) {
|
|
385
550
|
const idx = args.indexOf(flag);
|
|
386
551
|
if (idx === -1 || idx >= args.length - 1) return null;
|