@hyperframes/share 0.9.104 → 0.9.107

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 CHANGED
@@ -109,7 +109,14 @@ Hosts with their own file inventory can instead read `readSourceIgnore(projectPa
109
109
  once per capture. Pass the resulting `ignored` function to the inventory walk as
110
110
  `ignored(relativePath, entry.isDirectory())` and reuse it for
111
111
  `listReferencedHiddenSourceAssets(projectPath, observed, { ignored })`. Private-path rules apply
112
- even when an ignore rule re-includes a path.
112
+ even when an ignore rule re-includes a path. The gitignore reader accepts 256 active rules of 256 UTF-16 code units each. A rule can have
113
+ up to four wildcard components with one star apiece, including one recursive globstar.
114
+ Two stars within a filename pattern, such as `*draft*` or `*.min.*`, are supported when the
115
+ other components are literal or the filename is prefixed with `**/`. A recursive contents rule such as `**/cache/**` is supported
116
+ with literal components between the globstars. Avoid bracket expressions and backslash escapes
117
+ in rules containing multiple stars. With active rules, capture stops if a path exceeds 64
118
+ components or 1024 UTF-16 code units. For a path-limit failure, `SourceIgnoreError.relativePath`
119
+ provides an abbreviated project-relative path for local display. Simplify the rules or shorten the path to resume.
113
120
 
114
121
  Editable source includes referenced WOFF, WOFF2, TTF and OTF files with dot-prefixed names, such as
115
122
  `.brand/.Atlas.woff2`. The same private-path and ignore rules apply to these fonts. Preview and render servers can call
@@ -4,11 +4,13 @@ export function referencedHiddenDigest(paths: readonly string[]): string;
4
4
  export function contentKey(html: string): string;
5
5
  /** @typedef {Map<string, unknown>} Snapshot */
6
6
  /** @typedef {{ lenientIgnore?: boolean }} IgnoreOptions */
7
- /** @param {string} dir @param {{ byContent?: boolean, followSymlinks?: boolean } & IgnoreOptions} [options]
7
+ /** @param {string} dir
8
+ * @param {{ byContent?: boolean, followSymlinks?: boolean, progress?: () => void } & IgnoreOptions} [options]
8
9
  * @returns {Promise<Snapshot>} */
9
- export function snapshotProject(dir: string, { byContent, followSymlinks, lenientIgnore }?: {
10
+ export function snapshotProject(dir: string, { byContent, followSymlinks, lenientIgnore, progress }?: {
10
11
  byContent?: boolean;
11
12
  followSymlinks?: boolean;
13
+ progress?: () => void;
12
14
  } & IgnoreOptions): Promise<Snapshot>;
13
15
  /** What an export's sidecar records of the project, from a snapshot already taken.
14
16
  * @param {Snapshot} snapshot */
@@ -13,7 +13,16 @@ export function readSourceIgnore(root: string, { syntax }?: {
13
13
  * @returns {Promise<(path: string) => boolean>} */
14
14
  export function readChangeIgnore(root: string): Promise<(path: string) => boolean>;
15
15
  export class SourceIgnoreError extends Error {
16
+ /** @param {string} [message] @param {ErrorOptions & {reason?: "rule" | "file" | "read" | "path", relativePath?: string | undefined}} [options] */
17
+ constructor(message?: string, options?: ErrorOptions & {
18
+ reason?: "rule" | "file" | "read" | "path";
19
+ relativePath?: string | undefined;
20
+ });
21
+ reason: "file" | "rule" | "read" | "path";
22
+ /** A relative path for local display, kept out of the message and enumerable error fields. */
23
+ get relativePath(): string | undefined;
16
24
  code: string;
25
+ #private;
17
26
  }
18
27
  export type SourceIgnoreSyntax = "gitignore";
19
28
  export type SourceIgnore = (path: string, directory?: boolean) => boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/share",
3
- "version": "0.9.104",
3
+ "version": "0.9.107",
4
4
  "description": "Shared review identity, version upload and sharing state for HyperFrames hosts",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -113,7 +113,7 @@
113
113
  "css-tree": "^3.2.1",
114
114
  "ignore": "^5.3.2",
115
115
  "linkedom": "^0.18.12",
116
- "@hyperframes/parsers": "0.9.104"
116
+ "@hyperframes/parsers": "0.9.107"
117
117
  },
118
118
  "devDependencies": {
119
119
  "@types/css-tree": "^3.2.0",
@@ -29,32 +29,65 @@ export function contentKey(html) {
29
29
  return sha256(html.replace(HF_ID_ATTRIBUTE, ""));
30
30
  }
31
31
 
32
+ const noTick = () => {};
33
+
34
+ /** A throw from the caller's `progress`, carried past the catches that skip one unreadable entry. */
35
+ class ProgressThrew {
36
+ /** @param {unknown} cause */
37
+ constructor(cause) {
38
+ this.cause = cause;
39
+ }
40
+ }
41
+
32
42
  /** A file renamed away between readdir and stat (atomic writes), or one the app may not read, is simply not there
33
- * (undefined): one unreadable entry must not blind the whole scan. @param {string} full @param {boolean} byContent */
34
- async function snapshotKey(full, byContent) {
43
+ * (undefined): one unreadable entry must not blind the whole scan. @param {string} full @param {boolean} byContent
44
+ * @param {() => void} [progress] */
45
+ async function snapshotKey(full, byContent, progress) {
46
+ const tick = progress ?? noTick;
35
47
  const resolved = await fs.realpath(full).catch(() => null);
36
48
  if (!resolved) return undefined;
49
+ tick();
37
50
  const handle = await fs
38
51
  .open(resolved, constants.O_RDONLY | constants.O_NOFOLLOW)
39
52
  .catch(() => null);
40
53
  if (!handle) return undefined;
41
54
  try {
42
55
  const stat = await handle.stat();
56
+ tick();
43
57
  if (!stat.isFile()) return undefined;
44
- if (full.endsWith(".html")) return contentKey(await handle.readFile("utf8"));
45
- if (byContent) return await hashFile(handle);
58
+ if (full.endsWith(".html")) return contentKey(await readText(handle, progress));
59
+ if (byContent) return await hashFile(handle, progress);
46
60
  return `${stat.mtimeMs}:${stat.size}`;
47
- } catch {
61
+ } catch (error) {
62
+ if (error instanceof ProgressThrew) throw error;
48
63
  return undefined;
49
64
  } finally {
50
65
  await handle.close();
51
66
  }
52
67
  }
53
68
 
54
- /** @param {import("node:fs/promises").FileHandle} handle */
55
- async function hashFile(handle) {
69
+ // Measured when the read starts and bounded as readFile bounds it, so both paths key the same bytes.
70
+ /** @param {import("node:fs/promises").FileHandle} handle @param {() => void} [progress] */
71
+ async function readText(handle, progress) {
72
+ if (!progress) return handle.readFile("utf8");
73
+ const { size } = await handle.stat();
74
+ const extent = size > 0 ? { end: size - 1 } : {};
75
+ const chunks = [];
76
+ const stream = handle.createReadStream({ encoding: "utf8", autoClose: false, ...extent });
77
+ for await (const chunk of stream) {
78
+ chunks.push(chunk);
79
+ progress();
80
+ }
81
+ return chunks.join("");
82
+ }
83
+
84
+ /** @param {import("node:fs/promises").FileHandle} handle @param {() => void} [progress] */
85
+ async function hashFile(handle, progress) {
56
86
  const hash = createHash("sha256");
57
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash.update(chunk);
87
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
88
+ hash.update(chunk);
89
+ progress?.();
90
+ }
58
91
  return hash.digest("hex");
59
92
  }
60
93
 
@@ -70,19 +103,24 @@ async function entryKind(entry, full, followSymlinks) {
70
103
  // A `.hyperframesignore` this package can't read makes the snapshot throw, so a caller that picks files to send never
71
104
  // sends one the file meant to exclude. Change detection passes `lenientIgnore`: it then sees more files, never fewer.
72
105
  /** @typedef {{ lenientIgnore?: boolean }} IgnoreOptions */
73
- /** @param {string} dir @param {{ byContent?: boolean, followSymlinks?: boolean } & IgnoreOptions} [options]
106
+ // `progress` is called as the read moves, so a caller timing it out can tell a slow disk from a stuck one.
107
+ /** @param {string} dir
108
+ * @param {{ byContent?: boolean, followSymlinks?: boolean, progress?: () => void } & IgnoreOptions} [options]
74
109
  * @returns {Promise<Snapshot>} */
75
110
  export async function snapshotProject(
76
111
  dir,
77
- { byContent = false, followSymlinks = false, lenientIgnore = false } = {},
112
+ { byContent = false, followSymlinks = false, lenientIgnore = false, progress } = {},
78
113
  ) {
79
114
  /** @type {Snapshot} */
80
115
  const result = new Map();
81
116
  const ignored = await ignoreFor(dir, lenientIgnore);
117
+ const tick = progress ? () => callProgress(progress) : noTick;
118
+ const fileTick = progress && tick;
82
119
  /** @param {string} current @param {Set<string>} ancestors */
83
120
  async function walk(current, ancestors) {
84
121
  const real = await fs.realpath(current).catch(() => null);
85
122
  if (!real || ancestors.has(real)) return;
123
+ tick();
86
124
  const parents = new Set([...ancestors, real]);
87
125
  /** @type {import("node:fs").Dirent[]} */
88
126
  let entries;
@@ -91,21 +129,35 @@ export async function snapshotProject(
91
129
  } catch {
92
130
  return;
93
131
  }
132
+ tick();
94
133
  for (const entry of entries) {
95
134
  const full = path.join(current, entry.name);
96
135
  if (excludedFromSnapshot(dir, full, ignored)) continue;
97
136
  const kind = await entryKind(entry, full, followSymlinks);
98
137
  if (kind?.isDirectory()) await walk(full, parents);
99
138
  else if (kind?.isFile()) {
100
- const key = await snapshotKey(full, byContent);
139
+ const key = await snapshotKey(full, byContent, fileTick);
101
140
  if (key !== undefined) result.set(path.relative(dir, full), key);
102
141
  }
103
142
  }
104
143
  }
105
- await walk(dir, new Set());
144
+ try {
145
+ await walk(dir, new Set());
146
+ } catch (error) {
147
+ throw error instanceof ProgressThrew ? error.cause : error;
148
+ }
106
149
  return result;
107
150
  }
108
151
 
152
+ /** @param {() => void} progress */
153
+ function callProgress(progress) {
154
+ try {
155
+ progress();
156
+ } catch (cause) {
157
+ throw new ProgressThrew(cause);
158
+ }
159
+ }
160
+
109
161
  /** What an export's sidecar records of the project, from a snapshot already taken.
110
162
  * @param {Snapshot} snapshot */
111
163
  export function snapshotFingerprint(snapshot) {
@@ -4,6 +4,22 @@ import { lstat, open } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
 
6
6
  export class SourceIgnoreError extends Error {
7
+ #relativePath;
8
+
9
+ /** @param {string} [message] @param {ErrorOptions & {reason?: "rule" | "file" | "read" | "path", relativePath?: string | undefined}} [options] */
10
+ constructor(message, options) {
11
+ super(message, options);
12
+ this.reason = options?.reason ?? "rule";
13
+ this.#relativePath = options?.relativePath ? localPathLabel(options.relativePath) : undefined;
14
+ }
15
+
16
+ /** A relative path for local display, kept out of the message and enumerable error fields. */
17
+ // Package hosts read this field when presenting a capture failure.
18
+ // fallow-ignore-next-line unused-class-member
19
+ get relativePath() {
20
+ return this.#relativePath;
21
+ }
22
+
7
23
  code = "invalid_source_ignore";
8
24
  }
9
25
  const scratch = (/** @type {string} */ path) => /(?:^|\/)[^/]+\.(?:log|swp)$/.test(path);
@@ -18,13 +34,23 @@ export async function readSourceIgnore(root, { syntax } = {}) {
18
34
  const text = await readIgnoreText(root);
19
35
  if (!text) return scratch;
20
36
  if (syntax === "gitignore") {
37
+ const lines = boundedGitignoreRules(text);
38
+ if (!lines.length) return scratch;
21
39
  const { default: ignore } = await import("ignore");
22
- const rules = ignore({ allowRelativePaths: true }).add(text);
40
+ const rules = ignore({ allowRelativePaths: true }).add(lines);
23
41
  if (rules.ignores("index.html"))
24
42
  throw new SourceIgnoreError(
25
43
  ".hyperframesignore must include index.html at the project root.",
26
44
  );
27
- return (path, directory) => scratch(path) || rules.ignores(directory ? `${path}/` : path);
45
+ return (path, directory) => {
46
+ // The matcher checks each ancestor. Bound that work before entering it, including on a cold cache.
47
+ if (path.length > 1024 || path.split("/").length > 64)
48
+ throw new SourceIgnoreError(
49
+ ".hyperframesignore supports paths up to 1024 characters and 64 components.",
50
+ { reason: "path", relativePath: path },
51
+ );
52
+ return scratch(path) || rules.ignores(directory ? `${path}/` : path);
53
+ };
28
54
  }
29
55
  const paths = text
30
56
  .split(/\r?\n/)
@@ -34,9 +60,72 @@ export async function readSourceIgnore(root, { syntax } = {}) {
34
60
  return (path) => scratch(path) || entries.some((entry) => entry.test(path));
35
61
  }
36
62
 
63
+ /** @param {string} path */
64
+ function localPathLabel(path) {
65
+ if (/^(?:\/|[a-z]:)|\\|(?:^|\/)\.\.(?:\/|$)/i.test(path)) return undefined;
66
+ const brief = path.length > 160 ? path.slice(0, 60) + "…" + path.slice(-96) : path;
67
+ return JSON.stringify(brief)
68
+ .slice(1, -1)
69
+ .replace(/[\u202a-\u202e\u2066-\u2069]/g, "�");
70
+ }
71
+
72
+ /** @param {string} pattern */
73
+ function checkWildcardComponents(pattern) {
74
+ const wildcardParts = pattern.split("/").filter((part) => part.includes("*"));
75
+ if (wildcardParts.length > 4)
76
+ throw new SourceIgnoreError(
77
+ ".hyperframesignore allows up to four wildcard path components per rule.",
78
+ );
79
+ const ordinary = wildcardParts.filter((part) => part !== "**");
80
+ const globstars = wildcardParts.length - ordinary.length;
81
+ // A trailing /** only tests for contents. Keep the common **/folder/** form.
82
+ const contentsOnly =
83
+ wildcardParts.length === 2 && /(?:^|\/)\*\*\/(?:[^*?/]+\/)+\*\*$/.test(pattern);
84
+ if (globstars > 1 && !contentsOnly)
85
+ throw new SourceIgnoreError(
86
+ ".hyperframesignore allows one recursive wildcard and an optional trailing /**.",
87
+ );
88
+ // A two-star filename such as *.min.* is confined to one component. Keep the remaining
89
+ // components literal so matching one filename cannot multiply work in another.
90
+ const maxStars = wildcardParts.length === 1 ? 2 : 1;
91
+ if (ordinary.some((part) => part.split("*").length - 1 > maxStars))
92
+ throw new SourceIgnoreError(
93
+ ".hyperframesignore allows a two-star filename with otherwise literal components.",
94
+ );
95
+ }
96
+
97
+ /** @param {string} line */
98
+ function boundedGitignoreRule(line) {
99
+ if (line.length > 256)
100
+ throw new SourceIgnoreError(".hyperframesignore rules may contain up to 256 characters.");
101
+ const pattern = line.replace(/^!/, "");
102
+ // A leading **/ before a single filename is the ordinary basename match. Only
103
+ // simplify validation; pass the original rule to the matcher to preserve its semantics.
104
+ const basename = /^\*\*\/([^/]+)$/.exec(pattern)?.[1];
105
+ checkWildcardComponents(basename && basename !== "**" ? basename : pattern);
106
+ // Count stars before interpreting escapes and classes, which can change component boundaries.
107
+ if (pattern.indexOf("*") !== pattern.lastIndexOf("*") && /[\\[]/.test(pattern))
108
+ throw new SourceIgnoreError(
109
+ ".hyperframesignore rule combines unsupported wildcards or escapes.",
110
+ );
111
+ // A standalone globstar has no adjacent path component to span.
112
+ return /^!?\/?\*\*\/?$/.test(line) ? line.replace("**", "*") : line;
113
+ }
114
+
115
+ /** @param {string} text */
116
+ function boundedGitignoreRules(text) {
117
+ const lines = text.split(/\r?\n/).filter((line) => !line.startsWith("#") && line.trim());
118
+ if (lines.length > 256) throw new SourceIgnoreError(".hyperframesignore allows up to 256 rules.");
119
+ return lines.map(boundedGitignoreRule);
120
+ }
121
+
122
+ const unreadableIgnoreFile = () =>
123
+ new SourceIgnoreError(".hyperframesignore could not be read.", { reason: "read" });
124
+
37
125
  const invalidIgnoreFile = () =>
38
126
  new SourceIgnoreError(
39
127
  ".hyperframesignore must be a regular file inside the project, smaller than 64 KiB.",
128
+ { reason: "file" },
40
129
  );
41
130
 
42
131
  /** @param {string} file */
@@ -45,11 +134,12 @@ async function openIgnoreFile(file) {
45
134
  file,
46
135
  constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
47
136
  ).catch(async (/** @type {NodeJS.ErrnoException} */ error) => {
48
- if (error.code !== "ENOENT") throw invalidIgnoreFile();
137
+ if (error.code === "ELOOP" || error.code === "EMLINK") throw invalidIgnoreFile();
138
+ if (error.code !== "ENOENT") throw unreadableIgnoreFile();
49
139
  // An absent file means no exclusions; a dangling symlink is invalid.
50
140
  const named = await lstat(file).catch((/** @type {NodeJS.ErrnoException} */ missing) => {
51
141
  if (missing.code === "ENOENT") return null;
52
- throw invalidIgnoreFile();
142
+ throw unreadableIgnoreFile();
53
143
  });
54
144
  if (named) throw invalidIgnoreFile();
55
145
  return null;