@johnhenry/sitefile 0.0.2 → 0.0.4

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 (136) hide show
  1. package/CHANGELOG.md +516 -0
  2. package/README.md +59 -9
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/bake.d.ts +2 -0
  6. package/lib/src/bake.js +30 -1
  7. package/lib/src/bcrypt.d.ts +25 -0
  8. package/lib/src/bcrypt.js +201 -0
  9. package/lib/src/canonical.d.ts +19 -0
  10. package/lib/src/canonical.js +60 -0
  11. package/lib/src/car.d.ts +34 -0
  12. package/lib/src/car.js +203 -0
  13. package/lib/src/checklinks.js +8 -2
  14. package/lib/src/cli/bake.js +4 -3
  15. package/lib/src/cli/build-image.d.ts +1 -0
  16. package/lib/src/cli/build-image.js +1 -0
  17. package/lib/src/cli/common.js +4 -1
  18. package/lib/src/cli/hosts.d.ts +5 -0
  19. package/lib/src/cli/hosts.js +78 -0
  20. package/lib/src/cli/images.js +23 -5
  21. package/lib/src/cli/import-config.d.ts +2 -0
  22. package/lib/src/cli/import-config.js +56 -0
  23. package/lib/src/cli/index.d.ts +6 -1
  24. package/lib/src/cli/index.js +34 -2
  25. package/lib/src/cli/integrity.d.ts +2 -0
  26. package/lib/src/cli/integrity.js +77 -0
  27. package/lib/src/cli/network.d.ts +7 -0
  28. package/lib/src/cli/network.js +14 -3
  29. package/lib/src/cli/serve-keys.d.ts +39 -0
  30. package/lib/src/cli/serve-keys.js +106 -0
  31. package/lib/src/cli/serve-worker.js +119 -8
  32. package/lib/src/cli/servers.d.ts +130 -1
  33. package/lib/src/cli/servers.js +754 -72
  34. package/lib/src/cli/up.d.ts +2 -0
  35. package/lib/src/cli/up.js +193 -0
  36. package/lib/src/cli/watch.d.ts +14 -1
  37. package/lib/src/cli/watch.js +20 -3
  38. package/lib/src/cli.js +138 -18
  39. package/lib/src/csp.d.ts +17 -0
  40. package/lib/src/csp.js +52 -0
  41. package/lib/src/dictionary.d.ts +16 -0
  42. package/lib/src/dictionary.js +89 -0
  43. package/lib/src/epub.d.ts +5 -0
  44. package/lib/src/epub.js +113 -0
  45. package/lib/src/errors.d.ts +22 -9
  46. package/lib/src/errors.js +20 -1
  47. package/lib/src/executor.d.ts +31 -1
  48. package/lib/src/executor.js +231 -24
  49. package/lib/src/explain.js +33 -3
  50. package/lib/src/export-for.d.ts +42 -0
  51. package/lib/src/export-for.js +466 -0
  52. package/lib/src/export-formats.d.ts +2 -2
  53. package/lib/src/export-formats.js +52 -2
  54. package/lib/src/fingerprint.d.ts +3 -1
  55. package/lib/src/fingerprint.js +32 -5
  56. package/lib/src/host-config.d.ts +34 -0
  57. package/lib/src/host-config.js +645 -0
  58. package/lib/src/hosts.d.ts +47 -0
  59. package/lib/src/hosts.js +106 -0
  60. package/lib/src/hreflang.d.ts +25 -0
  61. package/lib/src/hreflang.js +72 -0
  62. package/lib/src/index.d.ts +1 -1
  63. package/lib/src/index.js +1 -1
  64. package/lib/src/integrity.d.ts +115 -0
  65. package/lib/src/integrity.js +273 -0
  66. package/lib/src/language/ast.d.ts +126 -3
  67. package/lib/src/language/ast.js +7 -1
  68. package/lib/src/language/parser.js +189 -7
  69. package/lib/src/language/validate.js +24 -0
  70. package/lib/src/links.d.ts +47 -0
  71. package/lib/src/links.js +289 -3
  72. package/lib/src/lint.d.ts +1 -1
  73. package/lib/src/lint.js +26 -1
  74. package/lib/src/mime-data.d.ts +2 -0
  75. package/lib/src/mime-data.js +92 -0
  76. package/lib/src/oci.d.ts +20 -2
  77. package/lib/src/oci.js +70 -28
  78. package/lib/src/outdated.d.ts +3 -0
  79. package/lib/src/outdated.js +4 -4
  80. package/lib/src/planner.d.ts +87 -2
  81. package/lib/src/planner.js +189 -8
  82. package/lib/src/plugins/cache.d.ts +11 -0
  83. package/lib/src/plugins/cache.js +29 -0
  84. package/lib/src/plugins/host.d.ts +51 -2
  85. package/lib/src/plugins/host.js +141 -16
  86. package/lib/src/plugins/wasm.js +1 -3
  87. package/lib/src/portable.d.ts +8 -0
  88. package/lib/src/portable.js +47 -0
  89. package/lib/src/precache.d.ts +33 -0
  90. package/lib/src/precache.js +75 -0
  91. package/lib/src/precompress.d.ts +19 -0
  92. package/lib/src/precompress.js +35 -0
  93. package/lib/src/qr.d.ts +18 -0
  94. package/lib/src/qr.js +372 -0
  95. package/lib/src/registry-ops.js +4 -2
  96. package/lib/src/reload-client.d.ts +2 -0
  97. package/lib/src/reload-client.js +419 -0
  98. package/lib/src/resources/archive.d.ts +37 -1
  99. package/lib/src/resources/archive.js +353 -71
  100. package/lib/src/resources/convert.js +3 -1
  101. package/lib/src/resources/https.d.ts +9 -1
  102. package/lib/src/resources/https.js +36 -0
  103. package/lib/src/resources/network.d.ts +25 -3
  104. package/lib/src/resources/network.js +77 -6
  105. package/lib/src/secrets.d.ts +12 -3
  106. package/lib/src/secrets.js +18 -5
  107. package/lib/src/serve-auth.d.ts +33 -0
  108. package/lib/src/serve-auth.js +120 -0
  109. package/lib/src/serve-rules.d.ts +83 -7
  110. package/lib/src/serve-rules.js +264 -53
  111. package/lib/src/server.d.ts +529 -11
  112. package/lib/src/server.js +1439 -57
  113. package/lib/src/servers-file.d.ts +36 -0
  114. package/lib/src/servers-file.js +101 -0
  115. package/lib/src/servers.d.ts +115 -7
  116. package/lib/src/servers.js +151 -29
  117. package/lib/src/single-file.d.ts +12 -0
  118. package/lib/src/single-file.js +147 -0
  119. package/lib/src/site.d.ts +58 -0
  120. package/lib/src/site.js +216 -5
  121. package/lib/src/store.js +9 -5
  122. package/lib/src/swbn.d.ts +10 -0
  123. package/lib/src/swbn.js +86 -0
  124. package/lib/src/toml.d.ts +17 -0
  125. package/lib/src/toml.js +323 -0
  126. package/lib/src/wacz.d.ts +6 -0
  127. package/lib/src/wacz.js +96 -0
  128. package/lib/src/warc.d.ts +28 -0
  129. package/lib/src/warc.js +252 -0
  130. package/lib/src/watch.d.ts +12 -1
  131. package/lib/src/watch.js +67 -1
  132. package/lib/src/wbn.d.ts +9 -1
  133. package/lib/src/wbn.js +23 -33
  134. package/lib/src/zstd.d.ts +4 -0
  135. package/lib/src/zstd.js +328 -0
  136. package/package.json +1 -1
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The servers file (issue #223), for `sitefile up`, `down` and `ps`: several detached site servers
3
+ * described in one place, like a Compose file.
4
+ *
5
+ * ```yaml
6
+ * servers:
7
+ * docs:
8
+ * source: ./docs/dist # a directory or archive file (relative to this file), or an image
9
+ * publish: 8081 # [host:]port, as serve -p (default 127.0.0.1, a free port)
10
+ * spa: true # as serve --spa (default false)
11
+ * ```
12
+ *
13
+ * Each key under `servers` is the server's name (as `serve -d --name`).
14
+ */
15
+ export declare const SERVERS_FILES: readonly string[];
16
+ export interface ServerSpec {
17
+ readonly name: string;
18
+ /** As written: `./dir`, `../site.zip`, `/abs`, an image reference or ID, or an archive file name. */
19
+ readonly source: string;
20
+ /** `[host:]port` as written (a number is its decimal form); undefined: 127.0.0.1 and a free port. */
21
+ readonly publish: string | undefined;
22
+ readonly spa: boolean;
23
+ }
24
+ export interface ServersFile {
25
+ /** The file as given (for messages). */
26
+ readonly label: string;
27
+ /** The directory relative sources are resolved against. */
28
+ readonly dir: string;
29
+ readonly servers: readonly ServerSpec[];
30
+ }
31
+ /** `file` when given, else the first of {@link SERVERS_FILES} in the current directory. */
32
+ export declare function findServersFile(file: string | undefined): Promise<string>;
33
+ /** Check the shape of a parsed servers file. */
34
+ export declare function parseServersDefinition(value: unknown, label: string, dir: string): ServersFile;
35
+ /** Read and check a servers file (.yaml, .yml or .json). */
36
+ export declare function loadServersFile(file: string): Promise<ServersFile>;
@@ -0,0 +1,101 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { SitefileError } from './errors.js';
4
+ import { parseYaml } from './yaml.js';
5
+ /**
6
+ * The servers file (issue #223), for `sitefile up`, `down` and `ps`: several detached site servers
7
+ * described in one place, like a Compose file.
8
+ *
9
+ * ```yaml
10
+ * servers:
11
+ * docs:
12
+ * source: ./docs/dist # a directory or archive file (relative to this file), or an image
13
+ * publish: 8081 # [host:]port, as serve -p (default 127.0.0.1, a free port)
14
+ * spa: true # as serve --spa (default false)
15
+ * ```
16
+ *
17
+ * Each key under `servers` is the server's name (as `serve -d --name`).
18
+ */
19
+ export const SERVERS_FILES = ['sitefile.servers.yaml', 'sitefile.servers.yml', 'sitefile.servers.json'];
20
+ const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/;
21
+ const SERVER_KEYS = ['source', 'publish', 'spa'];
22
+ const isMapping = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
23
+ function fail(label, detail) {
24
+ throw new SitefileError('E_DATA', `${label}: ${detail}`);
25
+ }
26
+ /** `file` when given, else the first of {@link SERVERS_FILES} in the current directory. */
27
+ export async function findServersFile(file) {
28
+ if (file !== undefined)
29
+ return file;
30
+ for (const name of SERVERS_FILES) {
31
+ if (await readFile(name).then(() => true, () => false))
32
+ return name;
33
+ }
34
+ throw new SitefileError('E_NOT_FOUND', `no servers file: ${SERVERS_FILES.join(', ')} not found in the current directory (or pass -f)`);
35
+ }
36
+ /** Check the shape of a parsed servers file. */
37
+ export function parseServersDefinition(value, label, dir) {
38
+ if (!isMapping(value))
39
+ fail(label, 'a servers file must be a mapping with a servers key');
40
+ for (const key of Object.keys(value))
41
+ if (key !== 'servers')
42
+ fail(label, `unknown key '${key}' (expected servers)`);
43
+ const raw = value['servers'];
44
+ if (!isMapping(raw) || Object.keys(raw).length === 0)
45
+ fail(label, 'servers must be a non-empty mapping of name: server');
46
+ const servers = [];
47
+ for (const [name, s] of Object.entries(raw)) {
48
+ if (!NAME_RE.test(name))
49
+ fail(label, `'${name}' is not a valid server name (letters, digits, '_', '.', '-'; at most 63)`);
50
+ // A key of digits only would be reordered by JavaScript objects; file order is the start order.
51
+ if (/^[0-9]+$/.test(name))
52
+ fail(label, `'${name}' is not a valid server name here: use at least one letter`);
53
+ const where = `server '${name}'`;
54
+ if (!isMapping(s))
55
+ fail(label, `${where} must be a mapping with a source`);
56
+ for (const key of Object.keys(s)) {
57
+ if (!SERVER_KEYS.includes(key))
58
+ fail(label, `${where}: unknown key '${key}' (expected ${SERVER_KEYS.join(', ')})`);
59
+ }
60
+ const source = s['source'];
61
+ if (typeof source !== 'string' || source === '')
62
+ fail(label, `${where}: source must be a non-empty string`);
63
+ const publish = s['publish'];
64
+ if (publish !== undefined && publish !== null && typeof publish !== 'string' && !(typeof publish === 'number' && Number.isSafeInteger(publish) && publish >= 0)) {
65
+ fail(label, `${where}: publish must be [host:]port (a string or a port number)`);
66
+ }
67
+ const spa = s['spa'];
68
+ if (spa !== undefined && spa !== null && typeof spa !== 'boolean')
69
+ fail(label, `${where}: spa must be true or false`);
70
+ servers.push({ name, source, publish: publish === undefined || publish === null ? undefined : String(publish), spa: spa === true });
71
+ }
72
+ return { label, dir, servers };
73
+ }
74
+ /** Read and check a servers file (.yaml, .yml or .json). */
75
+ export async function loadServersFile(file) {
76
+ const base = path.basename(file).toLowerCase();
77
+ const json = base.endsWith('.json');
78
+ if (!json && !base.endsWith('.yaml') && !base.endsWith('.yml')) {
79
+ throw new SitefileError('E_USAGE', `servers file '${file}': unknown format (use a .yaml, .yml or .json file)`);
80
+ }
81
+ let text;
82
+ try {
83
+ text = await readFile(file, 'utf8');
84
+ }
85
+ catch (e) {
86
+ throw new SitefileError('E_NOT_FOUND', `cannot read servers file '${file}'`, undefined, { cause: e });
87
+ }
88
+ let value;
89
+ if (!json)
90
+ value = parseYaml(text, file);
91
+ else {
92
+ try {
93
+ value = JSON.parse(text.replace(/^/, ''));
94
+ }
95
+ catch (e) {
96
+ throw new SitefileError('E_DATA', `${file} is not valid JSON: ${e.message}`, undefined, { cause: e });
97
+ }
98
+ }
99
+ return parseServersDefinition(value, file, path.dirname(path.resolve(file)));
100
+ }
101
+ //# sourceMappingURL=servers-file.js.map
@@ -1,6 +1,9 @@
1
+ import type { SiteContent } from './server.js';
1
2
  import { type ArchiveLimits } from './resources/types.js';
2
3
  import { Store } from './store.js';
3
4
  import { Tree } from './tree.js';
5
+ import type { CachePreview } from './server.js';
6
+ import type { AuthEntry } from './serve-auth.js';
4
7
  /**
5
8
  * Detached site servers ("containers"). One state file per server:
6
9
  *
@@ -30,6 +33,66 @@ export interface ServerState {
30
33
  readonly path: string;
31
34
  };
32
35
  readonly spa: boolean;
36
+ /** `--spa-exclude`: request paths that never fall back (absent: none). */
37
+ readonly spaExclude?: readonly string[];
38
+ /** `--spa-fallback`: the file every fallback serves (absent: the nearest 200.html or index.html). */
39
+ readonly spaFallback?: string;
40
+ /** `--base`: the path prefix the site is served under, `/repo/` (absent: `/`). */
41
+ readonly base?: string;
42
+ /** `--rewrite-base`: the production URL replaced by the local one in HTML, CSS and XML (absent: none). */
43
+ readonly rewriteBase?: string;
44
+ /** `--host-profile`: netlify, cloudflare, vercel, github-pages or firebase (absent: sitefile's own rules). */
45
+ readonly hostProfile?: 'netlify' | 'cloudflare' | 'vercel' | 'github-pages' | 'firebase';
46
+ /** `--html-handling`: auto, force-slash, drop-slash or none (absent: the profile's). */
47
+ readonly htmlHandling?: 'auto' | 'force-slash' | 'drop-slash' | 'none';
48
+ /** `--keep-os-metadata`: serve a directory's or archive's OS metadata files too (absent: false). */
49
+ readonly keepOsMetadata?: boolean;
50
+ /** `--allowed-host` names (absent: none; localhost names and IP addresses are always allowed). */
51
+ readonly allowedHosts?: readonly string[];
52
+ /** `--cors` (absent: false). */
53
+ readonly cors?: boolean;
54
+ /** `--isolate`: the Cross-Origin-Embedder-Policy sent with COOP and CORP (absent: not isolated). */
55
+ readonly isolate?: 'require-corp' | 'credentialless';
56
+ /** `--max-age`, `--immutable`, `--max-age-html` (absent: every response keeps `no-cache`). */
57
+ readonly cache?: CachePreview;
58
+ /** `--log-format json` (absent: text). */
59
+ readonly logFormat?: 'json';
60
+ /** `--log-ip` (absent: false). */
61
+ readonly logIp?: boolean;
62
+ /** `--quiet` (absent: false). */
63
+ readonly quiet?: boolean;
64
+ /** `--auth`, `SITEFILE_SERVE_AUTH`: users and password verifiers (never passwords; absent: none). */
65
+ readonly auth?: readonly AuthEntry[];
66
+ /** `--auth-file`: an htpasswd file, read at every start (absent: none). */
67
+ readonly authFile?: string;
68
+ /** `--max-connections-per-ip` (absent: no limit). */
69
+ readonly maxConnectionsPerIp?: number;
70
+ /** `--random-route`: `base` is a secret, so `/` is a plain 404 (absent: false). */
71
+ readonly hideBase?: boolean;
72
+ /** `--allow-ip` / `--deny-ip` blocks as given (absent: none). */
73
+ readonly allowIp?: readonly string[];
74
+ readonly denyIp?: readonly string[];
75
+ /** `--stop-after`: when the server stops itself (ISO time; absent: never). */
76
+ readonly expires?: string;
77
+ /** `--tls-cert`, `--tls-key`: HTTPS with these PEM files, read at every start (absent: HTTP). */
78
+ readonly tlsCert?: string;
79
+ readonly tlsKey?: string;
80
+ /** `--compress` (absent: false). */
81
+ readonly compress?: boolean;
82
+ /** `--throttle` as given (absent: none). */
83
+ readonly throttle?: string;
84
+ /** `--mime`, `--mime-file`: extension → content type (absent: the built-in table only). */
85
+ readonly mime?: Readonly<Record<string, string>>;
86
+ /** `--country`: what `_redirects` `Country=` conditions match (absent: none matches). */
87
+ readonly country?: string;
88
+ /** `--strict-site-files`: an ignored `_redirects`/`_headers` line stops the server from starting (absent: false). */
89
+ readonly strictSiteFiles?: boolean;
90
+ /** `-d --watch` (a directory only): re-read the directory on change and live-reload open pages (absent: false). */
91
+ readonly watch?: boolean;
92
+ /** `--poll`, `--poll-interval` with `-d --watch`: poll every this many milliseconds instead of file system events (absent: events). */
93
+ readonly pollMs?: number;
94
+ /** `--sync` with `-d --watch`: pages report where they are and follow each other (`scroll`: their scrolling too) (absent: off). */
95
+ readonly sync?: 'nav' | 'scroll';
33
96
  /** The requested bind address (port 0 = pick a free port). */
34
97
  readonly bind: {
35
98
  readonly host: string;
@@ -42,6 +105,8 @@ export interface ServerState {
42
105
  readonly logFile: string;
43
106
  readonly ready: boolean;
44
107
  readonly error?: string;
108
+ /** The servers file (`sitefile up`) that started it, by real path; absent for `serve -d`. */
109
+ readonly project?: string;
45
110
  }
46
111
  export interface ServerView extends ServerState {
47
112
  readonly status: 'running' | 'exited';
@@ -71,15 +136,58 @@ export declare class ServerRegistry {
71
136
  export declare function pidAlive(pid: number): boolean;
72
137
  /** Alive AND answering on its port with its own id header (guards against pid and port reuse). */
73
138
  export declare function isRunning(s: ServerState): Promise<boolean>;
74
- /** Load a directory into a Tree through the sandboxed local reader; hidden files (except .well-known) are not served. */
75
- export declare function loadDirectoryTree(dir: string): Promise<Tree>;
139
+ /** How a directory or archive is read for serving. */
140
+ export interface ServedTreeOptions {
141
+ /** Serve OS metadata files (`__MACOSX/`, `._*`, `Thumbs.db`, `desktop.ini`, ...) too; default false. */
142
+ readonly keepOsMetadata?: boolean;
143
+ /** Told how many OS metadata files were skipped. */
144
+ readonly warn?: (message: string) => void;
145
+ }
146
+ /**
147
+ * Load a directory into a Tree through the sandboxed local reader; hidden files (except .well-known)
148
+ * and OS metadata files are not served.
149
+ */
150
+ export declare function loadDirectoryTree(dir: string, options?: ServedTreeOptions): Promise<Tree>;
76
151
  /**
77
152
  * Load an archive file into a Tree. The format comes from the bytes, never the name: zip, tar, tar.gz,
78
153
  * a Web Bundle, or an OCI image archive (a tar holding an OCI layout, as `build -o x.oci.tar` and `save`
79
154
  * write it). A zip, tar or Web Bundle is extracted with `limits` (unsafe entries are refused) and served
80
- * like a directory, without hidden files except `.well-known`; an OCI archive serves its first image's
81
- * files, like that image from the store, after checking every blob's digest and its site layer against `limits`.
155
+ * like a directory, without hidden files except `.well-known` and without OS metadata files (unless
156
+ * `options.keepOsMetadata`); an OCI archive serves its first image's files, like that image from the
157
+ * store, after checking every blob's digest and its site layer against `limits`.
158
+ * `hidden` keeps hidden files and OS metadata (verify and diff compare every file).
159
+ */
160
+ export declare function loadArchiveTree(file: string, limits?: ArchiveLimits, options?: ServedTreeOptions & {
161
+ readonly hidden?: boolean;
162
+ }): Promise<Tree>;
163
+ /** What a server serves: the tree and, for a zip served in place, where its contents come from. */
164
+ export interface ServedSite {
165
+ readonly tree: Tree;
166
+ readonly content?: SiteContent;
167
+ /** Release the open zip file, if any. */
168
+ close(): void;
169
+ }
170
+ /**
171
+ * A zip archive file opened for serving in place (#213): its entries are checked and indexed at
172
+ * start (each inflated once, one at a time, for its CRC-32 and digest) and read from the file on
173
+ * each request, so memory does not grow with the archive. The tree is the one {@link loadArchiveTree}
174
+ * serves, with the same errors. Undefined for anything that is not a zip (or a zip holding an OCI layout).
175
+ */
176
+ export declare function openZipArchive(file: string, limits?: ArchiveLimits, options?: ServedTreeOptions): Promise<ServedSite | undefined>;
177
+ /** {@link loadServedTree}, serving a zip archive in place ({@link openZipArchive}). */
178
+ export declare function loadServedSite(store: Store, source: ServerState['source'], options?: ServedTreeOptions): Promise<ServedSite>;
179
+ /** The tree a server state serves (`options` apply to a directory or archive). */
180
+ export declare function loadServedTree(store: Store, source: ServerState['source'], options?: ServedTreeOptions): Promise<Tree>;
181
+ /**
182
+ * Warn about every `_redirects`/`_headers` line `serve` ignores; with `strict` (`--strict-site-files`)
183
+ * any such line is then an error.
184
+ */
185
+ export declare function checkSiteFiles(tree: Tree, strict: boolean, warn: (m: string) => void, content?: SiteContent): void;
186
+ /**
187
+ * When a server's files last changed, in Unix seconds (`Last-Modified`): for an image, when it was
188
+ * first stored (never older than its files, unlike the config's `created`, which is the Unix epoch
189
+ * unless SOURCE_DATE_EPOCH is set); for a directory, the newest modification time of the files it
190
+ * serves (hidden entries but `.well-known` are skipped, symbolic links to files followed); for an
191
+ * archive, the file's modification time. Undefined when there is none.
82
192
  */
83
- export declare function loadArchiveTree(file: string, limits?: ArchiveLimits): Promise<Tree>;
84
- /** The tree a server state serves. */
85
- export declare function loadServedTree(store: Store, source: ServerState['source']): Promise<Tree>;
193
+ export declare function servedLastModified(store: Store, source: ServerState['source']): Promise<number | undefined>;
@@ -1,11 +1,14 @@
1
+ import { looksLikeWarc, readWarc } from './warc.js';
1
2
  import { randomBytes } from 'node:crypto';
2
3
  import { promises as fs } from 'node:fs';
3
4
  import http from 'node:http';
5
+ import https from 'node:https';
4
6
  import path from 'node:path';
5
7
  import { sha256 } from './digest.js';
6
8
  import { SitefileError } from './errors.js';
7
- import { blobPathOf, decodeIndex, extractImageFiles, MEDIA, parseConfig, parseManifest, siteLayerIndex } from './oci.js';
8
- import { extractArchive } from './resources/archive.js';
9
+ import { siteFileWarnings } from './serve-rules.js';
10
+ import { blobPathOf, decodeIndex, extractImageFiles, MEDIA, parseConfig, parseManifest, siteLayerIndices } from './oci.js';
11
+ import { extractArchive, openZipFile, osMetadataWarning, withoutOsMetadata } from './resources/archive.js';
9
12
  import { LocalContext } from './resources/local.js';
10
13
  import { DEFAULT_ARCHIVE_LIMITS } from './resources/types.js';
11
14
  import { Store } from './store.js';
@@ -96,12 +99,12 @@ export class ServerRegistry {
96
99
  }
97
100
  async view(s) {
98
101
  const running = await isRunning(s);
99
- return { ...s, status: running ? 'running' : 'exited', url: s.ready ? urlOf(s) : '' };
102
+ return { ...s, status: running ? 'running' : 'exited', url: s.ready ? urlOf(s) + (s.base ?? '/').slice(1) : '' };
100
103
  }
101
104
  }
102
105
  function urlOf(s) {
103
106
  const shown = s.host === '0.0.0.0' ? '127.0.0.1' : s.host === '::' ? '::1' : s.host;
104
- return `http://${shown.includes(':') ? `[${shown}]` : shown}:${s.port}/`;
107
+ return `${s.tlsCert !== undefined ? 'https' : 'http'}://${shown.includes(':') ? `[${shown}]` : shown}:${s.port}/`;
105
108
  }
106
109
  export function pidAlive(pid) {
107
110
  if (!Number.isInteger(pid) || pid <= 0)
@@ -120,7 +123,9 @@ export async function isRunning(s) {
120
123
  return false;
121
124
  const host = s.host === '0.0.0.0' ? '127.0.0.1' : s.host === '::' ? '::1' : s.host;
122
125
  return new Promise((resolve) => {
123
- const req = http.request({ host, port: s.port, method: 'HEAD', path: '/', headers: { 'x-sitefile-probe': s.id }, timeout: 1500, agent: false }, (res) => {
126
+ // Over HTTPS the probe skips certificate checks: it only reads this server's own id header.
127
+ const request = s.tlsCert !== undefined ? (o, cb) => https.request({ ...o, rejectUnauthorized: false }, cb) : http.request;
128
+ const req = request({ host, port: s.port, method: 'HEAD', path: '/', headers: { 'x-sitefile-probe': s.id }, timeout: 1500, agent: false }, (res) => {
124
129
  res.resume();
125
130
  resolve(res.headers['x-sitefile-server'] === s.id);
126
131
  });
@@ -133,34 +138,97 @@ export async function isRunning(s) {
133
138
  function visible(tree) {
134
139
  return Tree.fromFiles(tree.entries().filter(([p]) => p.split('/').every((seg) => !seg.startsWith('.') || seg === '' || seg === '.well-known')));
135
140
  }
136
- /** Load a directory into a Tree through the sandboxed local reader; hidden files (except .well-known) are not served. */
137
- export async function loadDirectoryTree(dir) {
141
+ /** `tree` as served: without OS metadata (unless kept; with a warning naming `origin`) and hidden files except `.well-known`. */
142
+ function served(tree, origin, options) {
143
+ if (!options.keepOsMetadata) {
144
+ const r = withoutOsMetadata(tree);
145
+ if (r.skipped > 0)
146
+ options.warn?.(osMetadataWarning(origin, r.skipped));
147
+ tree = r.tree;
148
+ }
149
+ return visible(tree);
150
+ }
151
+ /**
152
+ * Load a directory into a Tree through the sandboxed local reader; hidden files (except .well-known)
153
+ * and OS metadata files are not served.
154
+ */
155
+ export async function loadDirectoryTree(dir, options = {}) {
138
156
  const ctx = await LocalContext.open(dir, { sitefileignore: false });
139
157
  const { tree } = await ctx.readTree('', 'serve');
140
- return visible(tree);
158
+ return served(tree, dir, options);
141
159
  }
142
160
  /**
143
161
  * Load an archive file into a Tree. The format comes from the bytes, never the name: zip, tar, tar.gz,
144
162
  * a Web Bundle, or an OCI image archive (a tar holding an OCI layout, as `build -o x.oci.tar` and `save`
145
163
  * write it). A zip, tar or Web Bundle is extracted with `limits` (unsafe entries are refused) and served
146
- * like a directory, without hidden files except `.well-known`; an OCI archive serves its first image's
147
- * files, like that image from the store, after checking every blob's digest and its site layer against `limits`.
164
+ * like a directory, without hidden files except `.well-known` and without OS metadata files (unless
165
+ * `options.keepOsMetadata`); an OCI archive serves its first image's files, like that image from the
166
+ * store, after checking every blob's digest and its site layer against `limits`.
167
+ * `hidden` keeps hidden files and OS metadata (verify and diff compare every file).
148
168
  */
149
- export async function loadArchiveTree(file, limits = DEFAULT_ARCHIVE_LIMITS) {
169
+ export async function loadArchiveTree(file, limits = DEFAULT_ARCHIVE_LIMITS, options = {}) {
150
170
  const origin = file;
151
- const unreadable = () => new SitefileError('E_ARCHIVE', `cannot read '${origin}'`);
171
+ const unreadable = await checkArchiveFile(file, limits);
172
+ const bytes = new Uint8Array(await fs.readFile(file).catch(() => { throw unreadable(); }));
173
+ const warc = looksLikeWarc(bytes);
174
+ const tree = warc ? readWarc(bytes, origin, limits) : await extractArchive(bytes, origin, limits);
175
+ if (!warc && tree.get('/oci-layout'))
176
+ return ociArchiveTree(tree, origin, limits);
177
+ return options.hidden ? tree : served(tree, origin, options);
178
+ }
179
+ /** The checks every archive file gets before it is read; returns the error for an unreadable file. */
180
+ async function checkArchiveFile(file, limits) {
181
+ const unreadable = () => new SitefileError('E_ARCHIVE', `cannot read '${file}'`);
152
182
  const st = await fs.stat(file).catch((e) => {
153
- throw e.code === 'ENOENT' ? new SitefileError('E_NOT_FOUND', `'${origin}' does not exist`) : unreadable();
183
+ throw e.code === 'ENOENT' ? new SitefileError('E_NOT_FOUND', `'${file}' does not exist`) : unreadable();
154
184
  });
155
185
  if (!st.isFile())
156
- throw new SitefileError('E_TYPE', `'${origin}' is not a file`);
186
+ throw new SitefileError('E_TYPE', `'${file}' is not a file`);
157
187
  // The archive is at most its expanded size plus tar framing for every entry.
158
188
  if (st.size > limits.maxTotalBytes + (limits.maxEntries + 2) * 4 * 512) {
159
- throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: archive expands beyond ${limits.maxTotalBytes} bytes`);
189
+ throw new SitefileError('E_ARCHIVE_LIMIT', `${file}: archive expands beyond ${limits.maxTotalBytes} bytes`);
160
190
  }
161
- const bytes = new Uint8Array(await fs.readFile(file).catch(() => { throw unreadable(); }));
162
- const tree = await extractArchive(bytes, origin, limits);
163
- return tree.get('/oci-layout') ? ociArchiveTree(tree, origin, limits) : visible(tree);
191
+ return unreadable;
192
+ }
193
+ /**
194
+ * A zip archive file opened for serving in place (#213): its entries are checked and indexed at
195
+ * start (each inflated once, one at a time, for its CRC-32 and digest) and read from the file on
196
+ * each request, so memory does not grow with the archive. The tree is the one {@link loadArchiveTree}
197
+ * serves, with the same errors. Undefined for anything that is not a zip (or a zip holding an OCI layout).
198
+ */
199
+ export async function openZipArchive(file, limits = DEFAULT_ARCHIVE_LIMITS, options = {}) {
200
+ const unreadable = await checkArchiveFile(file, limits);
201
+ const head = Buffer.alloc(4);
202
+ try {
203
+ const fh = await fs.open(file, 'r');
204
+ try {
205
+ await fh.read(head, 0, 4, 0);
206
+ }
207
+ finally {
208
+ await fh.close();
209
+ }
210
+ }
211
+ catch {
212
+ throw unreadable();
213
+ }
214
+ const zip = head[0] === 0x50 && head[1] === 0x4b && ((head[2] === 3 && head[3] === 4) || (head[2] === 5 && head[3] === 6));
215
+ if (!zip)
216
+ return undefined;
217
+ const z = await openZipFile(file, file, limits);
218
+ if (z.tree.get('/oci-layout')) {
219
+ z.close();
220
+ return undefined;
221
+ }
222
+ return { tree: served(z.tree, file, options), content: z, close: () => z.close() };
223
+ }
224
+ /** {@link loadServedTree}, serving a zip archive in place ({@link openZipArchive}). */
225
+ export async function loadServedSite(store, source, options = {}) {
226
+ if (source.kind === 'archive') {
227
+ const site = await openZipArchive(source.path, DEFAULT_ARCHIVE_LIMITS, options);
228
+ if (site)
229
+ return site;
230
+ }
231
+ return { tree: await loadServedTree(store, source, options), close: () => undefined };
164
232
  }
165
233
  /** The files of the first image in an extracted OCI layout. */
166
234
  async function ociArchiveTree(layout, origin, limits) {
@@ -202,24 +270,78 @@ async function ociArchiveTree(layout, origin, limits) {
202
270
  catch {
203
271
  throw bad("OCI archive's image config is corrupt");
204
272
  }
205
- const layer = m.layers[siteLayerIndex(m, cfg)];
206
- let layerBytes = new Uint8Array(0); // extractImageFiles reports "not a Sitefile image"
207
- if (layer && (layer.mediaType === MEDIA.layer || layer.mediaType === MEDIA.layerTar)) {
208
- layerBytes = blob(layer.digest, layer.size);
209
- // Hold the site layer to the archive limits before it is fully decoded.
210
- await extractArchive(layerBytes, origin, limits);
273
+ const layers = siteLayerIndices(m, cfg).map((i) => m.layers[i]);
274
+ // An empty list makes extractImageFiles report "not a Sitefile image".
275
+ const blobs = [];
276
+ if (layers.every((l) => l.mediaType === MEDIA.layer || l.mediaType === MEDIA.layerTar)) {
277
+ for (const l of layers) {
278
+ const b = blob(l.digest, l.size);
279
+ // Hold each site layer to the archive limits before it is fully decoded.
280
+ await extractArchive(b, origin, limits);
281
+ blobs.push(b);
282
+ }
211
283
  }
212
- return extractImageFiles(m, cfg, layerBytes, origin);
284
+ return extractImageFiles(m, cfg, layers.length ? blobs : [new Uint8Array(0)], origin);
213
285
  }
214
- /** The tree a server state serves. */
215
- export async function loadServedTree(store, source) {
286
+ /** The tree a server state serves (`options` apply to a directory or archive). */
287
+ export async function loadServedTree(store, source, options = {}) {
216
288
  switch (source.kind) {
217
289
  case 'image':
218
290
  return store.loadTree(source.imageId);
219
291
  case 'dir':
220
- return loadDirectoryTree(source.path);
292
+ return loadDirectoryTree(source.path, options);
221
293
  case 'archive':
222
- return loadArchiveTree(source.path);
294
+ return loadArchiveTree(source.path, DEFAULT_ARCHIVE_LIMITS, options);
295
+ }
296
+ }
297
+ /**
298
+ * Warn about every `_redirects`/`_headers` line `serve` ignores; with `strict` (`--strict-site-files`)
299
+ * any such line is then an error.
300
+ */
301
+ export function checkSiteFiles(tree, strict, warn, content) {
302
+ const ignored = siteFileWarnings(tree, content);
303
+ for (const m of ignored)
304
+ warn(m);
305
+ if (strict && ignored.length > 0) {
306
+ const n = ignored.length;
307
+ throw new SitefileError('E_VALIDATION', `${n} line${n === 1 ? '' : 's'} of _redirects/_headers ${n === 1 ? 'is' : 'are'} ignored (--strict-site-files)`);
308
+ }
309
+ }
310
+ /**
311
+ * When a server's files last changed, in Unix seconds (`Last-Modified`): for an image, when it was
312
+ * first stored (never older than its files, unlike the config's `created`, which is the Unix epoch
313
+ * unless SOURCE_DATE_EPOCH is set); for a directory, the newest modification time of the files it
314
+ * serves (hidden entries but `.well-known` are skipped, symbolic links to files followed); for an
315
+ * archive, the file's modification time. Undefined when there is none.
316
+ */
317
+ export async function servedLastModified(store, source) {
318
+ const secs = (ms) => Math.floor(ms / 1000);
319
+ switch (source.kind) {
320
+ case 'image': {
321
+ const ms = Date.parse((await store.details(source.imageId)).created);
322
+ return Number.isNaN(ms) ? undefined : secs(ms);
323
+ }
324
+ case 'archive':
325
+ return secs((await fs.stat(source.path)).mtimeMs);
326
+ case 'dir': {
327
+ let newest;
328
+ const walk = async (dir) => {
329
+ for (const e of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
330
+ if (e.name.startsWith('.') && e.name !== '.well-known')
331
+ continue;
332
+ const p = path.join(dir, e.name);
333
+ if (e.isDirectory())
334
+ await walk(p);
335
+ else if (e.isFile() || e.isSymbolicLink()) {
336
+ const st = await fs.stat(p).catch(() => undefined);
337
+ if (st?.isFile())
338
+ newest = Math.max(newest ?? 0, secs(st.mtimeMs));
339
+ }
340
+ }
341
+ };
342
+ await walk(source.path);
343
+ return newest;
344
+ }
223
345
  }
224
346
  }
225
347
  //# sourceMappingURL=servers.js.map
@@ -0,0 +1,12 @@
1
+ import type { Tree } from './tree.js';
2
+ /** `EXPORT … AS html`: the page with every asset inlined as a data: URI. */
3
+ export declare function writeSingleFile(tree: Tree, page?: string): Uint8Array;
4
+ /** The default MHTML base URL (no EXPORT BASE or --base-url). */
5
+ export declare const MHTML_DEFAULT_BASE = "https://site.invalid/";
6
+ /**
7
+ * `EXPORT … AS mhtml [BASE <url>]`: the page and its assets as MHTML (RFC 2557 multipart/related, as
8
+ * Chrome saves "Webpage, Single File"): each part base64 with its Content-Type and an absolute
9
+ * Content-Location under the base URL (default `https://site.invalid/`), the page first. References
10
+ * are kept as written; the browser resolves them against the page's Content-Location.
11
+ */
12
+ export declare function writeMhtml(tree: Tree, page?: string, baseUrl?: string): Uint8Array;