@hyperframes/core 0.9.64 → 0.9.65

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.
@@ -1,6 +1,8 @@
1
1
  type ScopeOptions = {
2
2
  compoundAuthoredRoot?: boolean;
3
3
  scopeRootSelectors?: boolean;
4
+ /** Told the sheet's size, an upper bound for each rule before it is scoped, then the correction. */
5
+ charge?: (bytes: number) => void;
4
6
  };
5
7
  export declare function scopeCssToComposition(css: string, compositionId: string, scopeSelectorOverride?: string, authoredRootId?: string | null, options?: ScopeOptions): string;
6
8
  /** `scopeCssToComposition` for sheets mounted many times: each sheet is scoped once around a
@@ -151,7 +151,21 @@ export function scopeCssToComposition(css, compositionId, scopeSelectorOverride,
151
151
  const scope = scopeSelectorOverride ||
152
152
  `[data-composition-id="${escapeCssAttributeValue(trimmedCompositionId)}"]`;
153
153
  const root = parseCss(css);
154
- return root ? scopeParsedCss(root, scope, trimmedCompositionId, authoredRootId, options) : "";
154
+ return root
155
+ ? scopeParsedCss(root, css.length, scope, trimmedCompositionId, authoredRootId, options)
156
+ : "";
157
+ }
158
+ /** Up to two forms per selector, each with the scope per id mention plus twice, and an attribute per `#`. */
159
+ function scopedSelectorsBound(selectors, scope, authoredRootId) {
160
+ const authoredAttribute = 26 + 2 * (authoredRootId?.trim().length ?? 0);
161
+ let bound = 0;
162
+ for (const selector of selectors) {
163
+ const mentions = selector.split("data-composition-id").length - 1;
164
+ const hashes = selector.split("#").length - 1;
165
+ const form = selector.length + hashes * authoredAttribute + (mentions + 2) * scope.length + 64;
166
+ bound += 2 * form + 2;
167
+ }
168
+ return bound;
155
169
  }
156
170
  function parseCss(css) {
157
171
  try {
@@ -170,9 +184,20 @@ function forEachScopedRule(root, visit) {
170
184
  visit(rule);
171
185
  });
172
186
  }
173
- function scopeParsedCss(root, scope, compositionId, authoredRootId, options) {
187
+ function scopeParsedCss(root, cssLength, scope, compositionId, authoredRootId, options) {
188
+ const charge = options?.charge;
189
+ charge?.(cssLength);
174
190
  forEachScopedRule(root, (rule) => {
175
- rule.selectors = rule.selectors.map((selector) => scopeSelector(selector, scope, compositionId, authoredRootId, options?.compoundAuthoredRoot, options?.scopeRootSelectors));
191
+ const authored = rule.selector.length;
192
+ const selectors = rule.selectors;
193
+ // postcss re-joins the list with the first separator in the authored selector.
194
+ const separator = selectors.length > 1 ? (rule.selector.match(/,\s*/)?.[0].length ?? 1) : 0;
195
+ const reserved = charge
196
+ ? scopedSelectorsBound(selectors, scope, authoredRootId) + (selectors.length - 1) * separator
197
+ : 0;
198
+ charge?.(reserved);
199
+ rule.selectors = selectors.map((selector) => scopeSelector(selector, scope, compositionId, authoredRootId, options?.compoundAuthoredRoot, options?.scopeRootSelectors));
200
+ charge?.(rule.selector.length - authored - reserved);
176
201
  });
177
202
  return root.toResult({ map: false }).css;
178
203
  }
@@ -208,9 +233,12 @@ export function createCompositionCssScoper() {
208
233
  template = scopeTemplate(css, trimmedId, authoredRootId, options);
209
234
  templates.set(key, template);
210
235
  }
211
- return template === null
212
- ? scopeCssToComposition(css, compositionId, scopeSelectorOverride, authoredRootId, options)
213
- : template.split(PLACEHOLDER_SCOPE).join(scope);
236
+ if (template === null) {
237
+ return scopeCssToComposition(css, compositionId, scopeSelectorOverride, authoredRootId, options);
238
+ }
239
+ const pieces = template.split(PLACEHOLDER_SCOPE);
240
+ options?.charge?.(template.length + (pieces.length - 1) * (scope.length - PLACEHOLDER_SCOPE.length));
241
+ return pieces.join(scope);
214
242
  };
215
243
  }
216
244
  /** Null when the placeholder is already in the sheet, or a selector keeps its raw text (it holds a comment). */
@@ -228,7 +256,8 @@ function scopeTemplate(css, compositionId, authoredRootId, options) {
228
256
  });
229
257
  return rawSelector
230
258
  ? null
231
- : scopeParsedCss(root, PLACEHOLDER_SCOPE, compositionId, authoredRootId, options);
259
+ : // The cached template stays in memory for the render, so it is charged as well as each join.
260
+ scopeParsedCss(root, css.length, PLACEHOLDER_SCOPE, compositionId, authoredRootId, options);
232
261
  }
233
262
  function isFontFaceAtRule(node) {
234
263
  return node.type === "atrule" && node.name.toLowerCase() === "font-face";
@@ -100,6 +100,11 @@ export interface InlineSubCompositionsOptions {
100
100
  /** Tag each top-level host with `data-hf-scene` and report every part's scene, for preview swaps. */
101
101
  tagScenes?: boolean;
102
102
  readProjectScript?: (path: string) => string | null;
103
+ /**
104
+ * Told the size of each script and stylesheet generated for a mount: each wrapped script once
105
+ * built, and each scoped sheet rule by rule as `scopeCssToComposition` reports it. May throw.
106
+ */
107
+ chargeEmitted?: (srcPath: string, bytes: number) => void;
103
108
  }
104
109
  export interface ExternalLink {
105
110
  href: string;
@@ -195,7 +195,7 @@ function defaultBuildScopeSelector(compId) {
195
195
  */
196
196
  // fallow-ignore-next-line complexity
197
197
  export function inlineSubCompositions(document, hosts, options) {
198
- const { resolveHtml, parseHtml, hostIdentityMap, rewriteInlineStyles = false, flattenInnerRoot, compoundAuthoredRoot, readVariableDefaults, parseHostVariables, buildScopeSelector = defaultBuildScopeSelector, scriptErrorLabel = "[HyperFrames] composition script error:", onMissingComposition, assetExists, tagScenes = false, readProjectScript, } = options;
198
+ const { resolveHtml, parseHtml, hostIdentityMap, rewriteInlineStyles = false, flattenInnerRoot, compoundAuthoredRoot, readVariableDefaults, parseHostVariables, buildScopeSelector = defaultBuildScopeSelector, scriptErrorLabel = "[HyperFrames] composition script error:", onMissingComposition, assetExists, tagScenes = false, readProjectScript, chargeEmitted, } = options;
199
199
  const rootStyles = [...document.querySelectorAll("style")];
200
200
  const styles = [];
201
201
  const styleScenes = [];
@@ -361,12 +361,15 @@ export function inlineSubCompositions(document, hosts, options) {
361
361
  css = rewriteCssAssetUrls(raw, src, assetExists);
362
362
  sheetsWithAssetUrls.set(sheetKey, css);
363
363
  }
364
- return scopeCompId
365
- ? scopeCssToComposition(css, scopeCompId, runtimeScope || undefined, authoredRootId, {
366
- compoundAuthoredRoot: compoundAuthoredRoot === true,
367
- scopeRootSelectors: true,
368
- })
369
- : css;
364
+ if (!scopeCompId) {
365
+ chargeEmitted?.(src, css.length);
366
+ return css;
367
+ }
368
+ return scopeCssToComposition(css, scopeCompId, runtimeScope || undefined, authoredRootId, {
369
+ compoundAuthoredRoot: compoundAuthoredRoot === true,
370
+ scopeRootSelectors: true,
371
+ ...(chargeEmitted ? { charge: (bytes) => chargeEmitted(src, bytes) } : {}),
372
+ });
370
373
  };
371
374
  // <link> hoisting is unconditional. A templated sub-composition's webfont
372
375
  // link is as load-bearing as a non-templated one's, and the mount path has
@@ -432,7 +435,9 @@ export function inlineSubCompositions(document, hosts, options) {
432
435
  const prelude = scriptCompositionId
433
436
  ? scopedModulePrelude(runtimeCompId || scopeCompId || scriptCompositionId, src)
434
437
  : "";
435
- moduleScripts.push(`${prelude}${AUTHORED_SOURCE_BEGIN}\n${scriptEl.textContent || ""}\n${AUTHORED_SOURCE_END}`);
438
+ const moduleScript = `${prelude}${AUTHORED_SOURCE_BEGIN}\n${scriptEl.textContent || ""}\n${AUTHORED_SOURCE_END}`;
439
+ chargeEmitted?.(src, moduleScript.length);
440
+ moduleScripts.push(moduleScript);
436
441
  }
437
442
  else if (externalSrc) {
438
443
  if (!externalScriptSrcs.includes(externalSrc)) {
@@ -449,6 +454,7 @@ export function inlineSubCompositions(document, hosts, options) {
449
454
  const wrappedScript = scriptCompositionId
450
455
  ? wrapScopedCompositionScript(scriptEl.textContent || "", scriptCompositionId, scriptErrorLabel, runtimeScope || undefined, runtimeCompId || scopeCompId || scriptCompositionId, authoredRootId, src)
451
456
  : wrapInlineScriptWithErrorBoundary(scriptEl.textContent || "", scriptErrorLabel);
457
+ chargeEmitted?.(src, wrappedScript.length);
452
458
  scripts.push(wrappedScript);
453
459
  scriptItems.push({ kind: "inline", content: wrappedScript, ...(scene ? { scene } : {}) });
454
460
  }
@@ -7,10 +7,11 @@
7
7
  * a missed link bakes a correct literal; a wrong link silently changes
8
8
  * color at the next brand refresh. Never match by value or name.
9
9
  */
10
- import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
11
10
  import { join } from "node:path";
11
+ import { replaceFileAtomically } from "../atomicFile.js";
12
12
  import { readJsonlValues } from "./jsonl.js";
13
- import { mediaDir } from "./manifest.js";
13
+ import { mediaDir, ownMediaDir } from "./manifest.js";
14
+ import { appendWithoutFollowing } from "./projectFiles.js";
14
15
  const BINDINGS_FILE = "figma-bindings.jsonl";
15
16
  function bindingsPath(projectDir) {
16
17
  return join(mediaDir(projectDir), BINDINGS_FILE);
@@ -36,8 +37,8 @@ function readLines(projectDir) {
36
37
  return readJsonlValues(bindingsPath(projectDir));
37
38
  }
38
39
  function appendLine(projectDir, record) {
39
- mkdirSync(mediaDir(projectDir), { recursive: true });
40
- appendFileSync(bindingsPath(projectDir), JSON.stringify(record) + "\n");
40
+ ownMediaDir(projectDir);
41
+ appendWithoutFollowing(bindingsPath(projectDir), JSON.stringify(record) + "\n");
41
42
  }
42
43
  export function readBindings(projectDir) {
43
44
  return readLines(projectDir).filter(isBindingRecord);
@@ -54,9 +55,9 @@ export function appendBinding(projectDir, record) {
54
55
  export function upsertBindings(projectDir, records) {
55
56
  const incoming = new Set(records.map((r) => r.figmaId));
56
57
  const survivors = readLines(projectDir).filter((line) => !(isBindingRecord(line) && incoming.has(line.figmaId)));
57
- mkdirSync(mediaDir(projectDir), { recursive: true });
58
+ ownMediaDir(projectDir);
58
59
  const lines = [...survivors, ...records].map((r) => JSON.stringify(r)).join("\n");
59
- writeFileSync(bindingsPath(projectDir), lines.length > 0 ? lines + "\n" : "");
60
+ replaceFileAtomically(bindingsPath(projectDir), lines.length > 0 ? lines + "\n" : "");
60
61
  }
61
62
  /** Exact-ID lookup, checking alias chains too. Never value/name matching. */
62
63
  export function findBindingByFigmaId(projectDir, figmaId) {
@@ -3,8 +3,9 @@ export { createFigmaClient, FigmaClientError } from "./client.js";
3
3
  export type { FigmaClient, FigmaClientErrorCode, FigmaClientOptions, FigmaFetch, FigmaFileVersion, FigmaNodeDocument, FigmaStyleMeta, FigmaVariablePayload, FigmaVariablesResult, RenderedNode, RenderNodeOptions, } from "./client.js";
4
4
  export { parseFigmaRef } from "./parseFigmaRef.js";
5
5
  export { MAX_FREEZE_BYTES, exceedsFreezeCap, freezeBytes, freezeUrl, freezeLocalFile, } from "./freeze.js";
6
- export { mediaDir, manifestPath, typeDirPath, updateRecord, isFigmaManifestRecord, readManifest, appendRecord, findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest.js";
6
+ export { mediaDir, manifestPath, typeDirPath, ownTypeDir, updateRecord, isFigmaManifestRecord, readManifest, appendRecord, findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest.js";
7
7
  export { regenerateIndex } from "./mediaIndex.js";
8
+ export { ownProjectDir } from "./projectFiles.js";
8
9
  export { buildAssetSnippet } from "./assetSnippet.js";
9
10
  export { sanitizeSvg } from "./sanitizeSvg.js";
10
11
  export { appendBinding, upsertBindings, findBindingByFigmaId, readBindings, readLibraryMap, recordLibraryFile, } from "./bindings.js";
@@ -1,8 +1,9 @@
1
1
  export { createFigmaClient, FigmaClientError } from "./client.js";
2
2
  export { parseFigmaRef } from "./parseFigmaRef.js";
3
3
  export { MAX_FREEZE_BYTES, exceedsFreezeCap, freezeBytes, freezeUrl, freezeLocalFile, } from "./freeze.js";
4
- export { mediaDir, manifestPath, typeDirPath, updateRecord, isFigmaManifestRecord, readManifest, appendRecord, findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest.js";
4
+ export { mediaDir, manifestPath, typeDirPath, ownTypeDir, updateRecord, isFigmaManifestRecord, readManifest, appendRecord, findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest.js";
5
5
  export { regenerateIndex } from "./mediaIndex.js";
6
+ export { ownProjectDir } from "./projectFiles.js";
6
7
  export { buildAssetSnippet } from "./assetSnippet.js";
7
8
  export { sanitizeSvg } from "./sanitizeSvg.js";
8
9
  export { appendBinding, upsertBindings, findBindingByFigmaId, readBindings, readLibraryMap, recordLibraryFile, } from "./bindings.js";
@@ -2,6 +2,8 @@ import type { FigmaManifestRecord } from "./types.js";
2
2
  export declare function mediaDir(projectDir: string): string;
3
3
  export declare function manifestPath(projectDir: string): string;
4
4
  export declare function typeDirPath(projectDir: string, type: FigmaManifestRecord["type"]): string;
5
+ export declare function ownMediaDir(projectDir: string): string;
6
+ export declare function ownTypeDir(projectDir: string, type: FigmaManifestRecord["type"]): string;
5
7
  /**
6
8
  * Guards figma-OWNED rows only — media-use rows (bgm/sfx/icon, no
7
9
  * provenance.source) legitimately fail this and are filtered out of
@@ -1,6 +1,8 @@
1
- import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { replaceFileAtomically } from "../atomicFile.js";
3
4
  import { readJsonlValues } from "./jsonl.js";
5
+ import { appendWithoutFollowing, ownProjectDir } from "./projectFiles.js";
4
6
  const MANIFEST_FILE = "manifest.jsonl";
5
7
  // Mirrors the media-use `.media/` layout for interop (one shared inventory).
6
8
  const TYPE_DIRS = {
@@ -16,6 +18,12 @@ export function manifestPath(projectDir) {
16
18
  export function typeDirPath(projectDir, type) {
17
19
  return join(mediaDir(projectDir), TYPE_DIRS[type]);
18
20
  }
21
+ export function ownMediaDir(projectDir) {
22
+ return ownProjectDir(projectDir, mediaDir(projectDir));
23
+ }
24
+ export function ownTypeDir(projectDir, type) {
25
+ return ownProjectDir(projectDir, typeDirPath(projectDir, type));
26
+ }
19
27
  /**
20
28
  * Guards figma-OWNED rows only — media-use rows (bgm/sfx/icon, no
21
29
  * provenance.source) legitimately fail this and are filtered out of
@@ -49,8 +57,8 @@ export function readManifest(projectDir) {
49
57
  return readJsonlValues(manifestPath(projectDir)).filter(isFigmaManifestRecord);
50
58
  }
51
59
  export function appendRecord(projectDir, record) {
52
- mkdirSync(typeDirPath(projectDir, record.type), { recursive: true });
53
- appendFileSync(manifestPath(projectDir), JSON.stringify(record) + "\n");
60
+ ownTypeDir(projectDir, record.type);
61
+ appendWithoutFollowing(manifestPath(projectDir), JSON.stringify(record) + "\n");
54
62
  }
55
63
  export function findByFigmaNode(projectDir, fileKey, nodeId) {
56
64
  return findAllByFigmaNode(projectDir, fileKey, nodeId)[0] ?? null;
@@ -81,7 +89,8 @@ export function updateRecord(projectDir, record) {
81
89
  }
82
90
  return line;
83
91
  });
84
- writeFileSync(p, out.join("\n"));
92
+ ownMediaDir(projectDir);
93
+ replaceFileAtomically(p, out.join("\n"));
85
94
  }
86
95
  export function nextId(projectDir, type) {
87
96
  const re = new RegExp(`^${type}_(\\d+)$`);
@@ -2,9 +2,8 @@
2
2
  * Regenerate .media/index.md — the agent-readable inventory table — after a
3
3
  * figma import, exactly the way media-use does after a resolve. Both writers
4
4
  * regenerate the SAME file from the manifest's current rows (all writers'), so the
5
- * output format AND row selection here must stay byte-identical with
6
- * skills/media-use/scripts/lib/index-gen.mjs — including rendering every
7
- * JSON-parseable row (no shape filtering), or the file would flip-flop
5
+ * output format AND row selection (every JSON-parseable row, no shape filtering) must stay
6
+ * byte-identical with skills/media-use/scripts/lib/index-gen.mjs, or the file would flip-flop
8
7
  * depending on which writer ran last.
9
8
  */
10
9
  type IndexRow = Record<string, unknown>;
@@ -2,23 +2,25 @@
2
2
  * Regenerate .media/index.md — the agent-readable inventory table — after a
3
3
  * figma import, exactly the way media-use does after a resolve. Both writers
4
4
  * regenerate the SAME file from the manifest's current rows (all writers'), so the
5
- * output format AND row selection here must stay byte-identical with
6
- * skills/media-use/scripts/lib/index-gen.mjs — including rendering every
7
- * JSON-parseable row (no shape filtering), or the file would flip-flop
5
+ * output format AND row selection (every JSON-parseable row, no shape filtering) must stay
6
+ * byte-identical with skills/media-use/scripts/lib/index-gen.mjs, or the file would flip-flop
8
7
  * depending on which writer ran last.
9
8
  */
10
- import { mkdirSync, writeFileSync } from "node:fs";
11
- import { dirname, join } from "node:path";
9
+ import { join } from "node:path";
10
+ import { replaceFileAtomically } from "../atomicFile.js";
12
11
  import { readJsonlValues } from "./jsonl.js";
13
- import { manifestPath, mediaDir } from "./manifest.js";
12
+ import { manifestPath, mediaDir, ownMediaDir } from "./manifest.js";
14
13
  function isRow(value) {
15
14
  return typeof value === "object" && value !== null;
16
15
  }
17
16
  export function indexPath(projectDir) {
18
17
  return join(mediaDir(projectDir), "index.md");
19
18
  }
19
+ function singleLineCell(value) {
20
+ return String(value ?? "").replace(/\s*[\r\n]+\s*/g, " ");
21
+ }
20
22
  function pad(str, len) {
21
- return String(str ?? "").padEnd(len);
23
+ return singleLineCell(str).padEnd(len);
22
24
  }
23
25
  function formatDur(r) {
24
26
  if (r.duration == null)
@@ -32,9 +34,6 @@ function formatDims(r) {
32
34
  return "svg";
33
35
  return "—";
34
36
  }
35
- function len(value) {
36
- return String(value ?? "").length;
37
- }
38
37
  export function generateIndexContent(records) {
39
38
  const count = records.length;
40
39
  const header = `# .media · ${count} asset${count === 1 ? "" : "s"}\n`;
@@ -42,11 +41,11 @@ export function generateIndexContent(records) {
42
41
  return header;
43
42
  const cols = { id: 4, type: 5, dur: 4, dims: 5, path: 5 };
44
43
  for (const r of records) {
45
- cols.id = Math.max(cols.id, len(r.id));
46
- cols.type = Math.max(cols.type, len(r.type));
44
+ cols.id = Math.max(cols.id, singleLineCell(r.id).length);
45
+ cols.type = Math.max(cols.type, singleLineCell(r.type).length);
47
46
  cols.dur = Math.max(cols.dur, formatDur(r).length);
48
47
  cols.dims = Math.max(cols.dims, formatDims(r).length);
49
- cols.path = Math.max(cols.path, len(r.path));
48
+ cols.path = Math.max(cols.path, singleLineCell(r.path).length);
50
49
  }
51
50
  const heading = pad("id", cols.id + 2) +
52
51
  pad("type", cols.type + 2) +
@@ -61,7 +60,7 @@ export function generateIndexContent(records) {
61
60
  pad(formatDur(r), cols.dur + 2) +
62
61
  pad(formatDims(r), cols.dims + 2) +
63
62
  pad(r.path, cols.path + 2) +
64
- String(r.description ?? ""));
63
+ singleLineCell(r.description));
65
64
  }
66
65
  return lines.join("\n") + "\n";
67
66
  }
@@ -71,8 +70,7 @@ export function regenerateIndex(projectDir) {
71
70
  const last = new Map(rows.map((row, index) => [row.path, index]));
72
71
  const records = rows.filter((row, index) => !row.path || last.get(row.path) === index);
73
72
  const content = generateIndexContent(records);
74
- const p = indexPath(projectDir);
75
- mkdirSync(dirname(p), { recursive: true });
76
- writeFileSync(p, content);
73
+ ownMediaDir(projectDir);
74
+ replaceFileAtomically(indexPath(projectDir), content);
77
75
  return content;
78
76
  }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Folders and appends for figma's project writes that never follow a link out
3
+ * of the project. Whole-file rewrites use `replaceFileAtomically`, whose rename
4
+ * replaces a link instead of writing through it.
5
+ */
6
+ /**
7
+ * Creates `dir` under `projectDir` one folder at a time and returns it. Throws
8
+ * when any folder on the way is a link or not a folder.
9
+ */
10
+ export declare function ownProjectDir(projectDir: string, dir: string): string;
11
+ /**
12
+ * Throws on a link at `path` instead of appending through it. Opened first, then
13
+ * written only when `lstat` finds the same single-link plain file at the path, as
14
+ * projectRecords' appendRecord does; O_NOFOLLOW is undefined on Windows.
15
+ */
16
+ export declare function appendWithoutFollowing(path: string, text: string): void;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Folders and appends for figma's project writes that never follow a link out
3
+ * of the project. Whole-file rewrites use `replaceFileAtomically`, whose rename
4
+ * replaces a link instead of writing through it.
5
+ */
6
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, realpathSync, statSync, writeSync, } from "node:fs";
7
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ function leadsOutside(dir) {
9
+ return new Error(`${dir} leads outside the project folder; nothing was written there`);
10
+ }
11
+ /**
12
+ * Creates `dir` under `projectDir` one folder at a time and returns it. Throws
13
+ * when any folder on the way is a link or not a folder.
14
+ */
15
+ export function ownProjectDir(projectDir, dir) {
16
+ const root = resolve(projectDir);
17
+ const target = resolve(dir);
18
+ const rel = relative(root, target);
19
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
20
+ throw leadsOutside(target);
21
+ mkdirSync(root, { recursive: true });
22
+ let current = root;
23
+ // The JS realpathSync, not .native: it keeps the case asked for, as `expected` does.
24
+ let expected = realpathSync(root);
25
+ for (const segment of rel.split(sep).filter(Boolean)) {
26
+ current = join(current, segment);
27
+ expected = join(expected, segment);
28
+ try {
29
+ mkdirSync(current);
30
+ }
31
+ catch (error) {
32
+ if (error.code !== "EEXIST")
33
+ throw error;
34
+ }
35
+ if (lstatSync(current).isSymbolicLink() || realpathSync(current) !== expected) {
36
+ throw leadsOutside(current);
37
+ }
38
+ if (!statSync(current).isDirectory()) {
39
+ throw new Error(`${current} is not a folder; nothing was written there`);
40
+ }
41
+ }
42
+ return target;
43
+ }
44
+ function notPlainFile(path) {
45
+ return new Error(`${path} is a link or not a plain file; nothing was written through it`);
46
+ }
47
+ /**
48
+ * Throws on a link at `path` instead of appending through it. Opened first, then
49
+ * written only when `lstat` finds the same single-link plain file at the path, as
50
+ * projectRecords' appendRecord does; O_NOFOLLOW is undefined on Windows.
51
+ */
52
+ export function appendWithoutFollowing(path, text) {
53
+ let fd;
54
+ try {
55
+ fd = openSync(path, constants.O_WRONLY |
56
+ constants.O_APPEND |
57
+ constants.O_CREAT |
58
+ (constants.O_NOFOLLOW ?? 0) |
59
+ (constants.O_NONBLOCK ?? 0), 0o666);
60
+ }
61
+ catch (error) {
62
+ if (error.code === "ELOOP")
63
+ throw notPlainFile(path);
64
+ throw error;
65
+ }
66
+ try {
67
+ const opened = fstatSync(fd);
68
+ const named = lstatSync(path);
69
+ const samePlainFile = opened.isFile() &&
70
+ named.isFile() &&
71
+ opened.nlink === 1 &&
72
+ named.ino === opened.ino &&
73
+ named.dev === opened.dev;
74
+ if (!samePlainFile)
75
+ throw notPlainFile(path);
76
+ writeSync(fd, text);
77
+ }
78
+ finally {
79
+ closeSync(fd);
80
+ }
81
+ }