diff --git a/packages/cli/src/commands/add.test.ts b/packages/cli/src/commands/add.test.ts index bd681c5e76..ce08e1db99 100644 --- a/packages/cli/src/commands/add.test.ts +++ b/packages/cli/src/commands/add.test.ts @@ -1,6 +1,14 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; import { runCommand as runCittyCommand, type CommandDef } from "citty"; -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + existsSync, + linkSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { RegistryItem, RegistryManifest } from "@hyperframes/core"; @@ -16,6 +24,8 @@ import addCommand, { runAdd, tagAddJson, } from "./add.js"; +import { DEFAULT_REGISTRY_URL } from "../registry/index.js"; +import { stagePublishFiles } from "../utils/publishProject.js"; import { trackRegistryItemAdded } from "../telemetry/events.js"; import { trackCommandFailures } from "../utils/command-failure-tracking.js"; @@ -24,6 +34,20 @@ import { trackCommandFailures } from "../utils/command-failure-tracking.js"; // be indistinguishable from no call at all. vi.mock("../telemetry/events.js", () => ({ trackRegistryItemAdded: vi.fn() })); +// A write that fails on every platform: publishing the file whose target ends with `failing` throws. +const failingWrite = vi.hoisted(() => ({ failing: null as string | null })); +vi.mock("../registry/publication.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + publishRegistryFile: (...args: Parameters) => { + if (failingWrite.failing && args[1].endsWith(failingWrite.failing)) + throw new Error(`could not write ${args[1]}`); + return actual.publishRegistryFile(...args); + }, + }; +}); + // ── Fixtures ──────────────────────────────────────────────────────────────── const MANIFEST: RegistryManifest = { @@ -756,3 +780,201 @@ describe("tag installation failures", () => { } }); }); + +describe("installs from the registry a received hyperframes.json names", () => { + let dir: string; + const recordPath = () => join(dir, ".hyperframes", "received-files.json"); + const listed = () => JSON.parse(readFileSync(recordPath(), "utf-8")).files; + const receive = (files: string[]) => { + mkdirSync(join(dir, ".hyperframes")); + writeFileSync(recordPath(), JSON.stringify({ files })); + }; + const writeConfig = (registry: string, name = "hyperframes.json", prefix = "") => + writeFileSync(join(dir, name), prefix + JSON.stringify({ registry })); + + beforeEach(() => { + dir = tmp(); + mockFetch(); + }); + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + rmSync(dir, { recursive: true, force: true }); + }); + + it("lists every file the install writes as received, dependencies included", async () => { + writeConfig(uniqueBase()); + receive(["hyperframes.json"]); + + await runAdd({ name: "dep-block", projectDir: dir, skipClipboard: true }); + + expect(listed()).toEqual([ + "compositions/components/base-component/base-component.css", + "compositions/dep-block.html", + "hyperframes.json", + ]); + }); + + it("keeps a publish from carrying an outside file the installed block names", async () => { + mkdirSync(join(dir, "shared")); + writeFileSync(join(dir, "shared", "logo.png"), "png"); + const project = join(dir, "p"); + mkdirSync(join(project, ".hyperframes"), { recursive: true }); + writeFileSync(join(project, "hyperframes.json"), JSON.stringify({ registry: uniqueBase() })); + writeFileSync( + join(project, ".hyperframes", "received-files.json"), + JSON.stringify({ files: ["hyperframes.json"] }), + ); + writeFileSync(join(project, "index.html"), `
`); + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL) => { + const url = new URL(input); + if (url.pathname.endsWith("/registry.json")) return Response.json(MANIFEST); + if (url.pathname.endsWith("/blocks/my-block/registry-item.json")) + return Response.json(BLOCK_ITEM); + return new Response(`
`); + }), + ); + + await runAdd({ name: "my-block", projectDir: project, skipClipboard: true }); + + const staged = stagePublishFiles(project, Infinity, () => {}); + expect([...staged.keys()].filter((key) => key.startsWith("_ext/"))).toEqual([]); + }); + + it("lists what an install by tag writes", async () => { + writeConfig(uniqueBase()); + receive(["hyperframes.json"]); + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL) => { + const url = new URL(input); + if (url.pathname.endsWith("/registry.json")) return Response.json(MANIFEST); + if (url.pathname.endsWith("/blocks/my-block/registry-item.json")) + return Response.json({ ...BLOCK_ITEM, tags: ["test-tag"] }); + if (url.pathname.endsWith("/blocks/my-block/my-block.html")) + return new Response(FILE_BODIES["my-block.html"]); + return new Response("not found", { status: 404 }); + }), + ); + vi.spyOn(console, "log").mockImplementation(() => {}); + + await runCittyCommand(addCommand, { rawArgs: ["test-tag", "--dir", dir, "--no-clipboard"] }); + + expect(listed()).toEqual(["compositions/my-block.html", "hyperframes.json"]); + }); + + it("reads a received config that starts with a byte-order mark", async () => { + writeConfig(uniqueBase(), "hyperframes.json", "\uFEFF"); + receive(["hyperframes.json"]); + + await runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }); + + expect(listed()).toEqual(["compositions/my-block.html", "hyperframes.json"]); + }); + + it("finds a received config listed under another spelling of the file it opens", async () => { + writeConfig(uniqueBase(), "HyperFrames.json"); + // A disk that tells case apart gets a second name for the same file, as one that ignores case has. + if (!existsSync(join(dir, "hyperframes.json"))) + linkSync(join(dir, "HyperFrames.json"), join(dir, "hyperframes.json")); + receive(["HyperFrames.json"]); + + await runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }); + + expect(listed()).toEqual(["HyperFrames.json", "compositions/my-block.html"]); + }); + + it("leaves what a person's own config installs off the record", async () => { + writeConfig(uniqueBase()); + + await runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }); + + expect(existsSync(join(dir, "compositions/my-block.html"))).toBe(true); + expect(existsSync(recordPath())).toBe(false); + }); + + it("leaves what the public registry installs off the record", async () => { + writeConfig(`${DEFAULT_REGISTRY_URL}/${crypto.randomUUID()}`); + receive(["hyperframes.json"]); + + await runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }); + + expect(existsSync(join(dir, "compositions/my-block.html"))).toBe(true); + expect(listed()).toEqual(["hyperframes.json"]); + }); + + it("takes back what a failed install listed but never wrote", async () => { + writeConfig(uniqueBase()); + receive(["hyperframes.json"]); + failingWrite.failing = "base-component.css"; + try { + await expect( + runAdd({ name: "dep-block", projectDir: dir, skipClipboard: true }), + ).rejects.toThrow(AddError); + } finally { + failingWrite.failing = null; + } + expect(listed()).toEqual(["hyperframes.json"]); + }); + + it("leaves off a file the person edited while the install downloaded", async () => { + writeConfig(uniqueBase()); + await runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }); + receive(["hyperframes.json"]); + const block = join(dir, "compositions", "my-block.html"); + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL) => { + const url = new URL(input); + if (url.pathname.endsWith("/registry.json")) return Response.json(MANIFEST); + if (url.pathname.endsWith("/registry-item.json")) return Response.json(BLOCK_ITEM); + writeFileSync(block, "
the person's edit
"); + return new Response(FILE_BODIES["my-block.html"]); + }), + ); + + const result = await runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }); + + expect(result.preserved).toHaveLength(1); + expect(readFileSync(block, "utf-8")).toBe("
the person's edit
"); + expect(listed()).toEqual(["hyperframes.json"]); + }); + + it("counts a hyperframes.json it cannot parse as received, not as the person's own", async () => { + vi.stubEnv("HYPERFRAMES_CACHE_DIR", tmp()); + writeFileSync(join(dir, "hyperframes.json"), "{ not json"); + + await runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }); + + expect(listed()).toEqual(["compositions/my-block.html"]); + }); + + it("keeps a failed install's files that are on disk listed", async () => { + writeConfig(uniqueBase()); + receive(["hyperframes.json"]); + failingWrite.failing = "dep-block.html"; + try { + await expect( + runAdd({ name: "dep-block", projectDir: dir, skipClipboard: true }), + ).rejects.toThrow(AddError); + } finally { + failingWrite.failing = null; + } + expect(listed()).toEqual([ + "compositions/components/base-component/base-component.css", + "hyperframes.json", + ]); + }); + + it("leaves a record it cannot read as it is", async () => { + writeConfig(uniqueBase()); + mkdirSync(join(dir, ".hyperframes")); + writeFileSync(recordPath(), "{oops"); + + await runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }); + + expect(readFileSync(recordPath(), "utf-8")).toBe("{oops"); + }); +}); diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts index d9b9205222..07ddd12d63 100644 --- a/packages/cli/src/commands/add.ts +++ b/packages/cli/src/commands/add.ts @@ -14,7 +14,7 @@ export const examples: Example[] = [ import { existsSync, readFileSync } from "node:fs"; import { parseHTML } from "linkedom"; -import { resolve, relative } from "node:path"; +import { join, resolve, relative, sep } from "node:path"; import { isProjectRootMissing, ITEM_TYPE_DIRS, @@ -24,11 +24,13 @@ import { import { c } from "../ui/colors.js"; import { DEFAULT_REGISTRY_URL, + isPublicRegistry, prepareItem, publishItem, resolveItemsByTag, type PreparedItem, } from "../registry/index.js"; +import { registryRoot } from "../registry/publication.js"; import { resolveItemWithDependencies } from "../registry/resolver.js"; import { InvalidVariableValuesError } from "../registry/variableDefaults.js"; import { @@ -37,12 +39,19 @@ import { } from "../registry/compatibility.js"; import { DEFAULT_PROJECT_CONFIG, + PROJECT_CONFIG_FILENAME, loadProjectConfig, projectConfigPath, + readProjectConfigWithStatus, recordProjectRegistryItems, createProjectConfig, } from "../utils/projectConfig.js"; import { copyToClipboard } from "../utils/clipboard.js"; +import { + forgetReceivedFiles, + receivedFiles, + recordReceivedFiles, +} from "../utils/privateProjectFile.js"; import { readJsonFlag } from "../utils/jsonFlag.js"; import { trackRegistryItemAdded } from "../telemetry/events.js"; @@ -294,6 +303,34 @@ function assertCompatibleOrThrow(items: RegistryItem[], cliVersion?: string): st } } +// A registry that a received hyperframes.json names serves files that came from its sender; a config that cannot be +// read is not proven to be the person's own. +function fromReceivedRegistry(projectDir: string, registry: string): boolean { + if (readProjectConfigWithStatus(projectDir).status === "unreadable") return true; + return !isPublicRegistry(registry) && receivedFiles(projectDir)(PROJECT_CONFIG_FILENAME); +} + +const PLAIN_WRITES = { guard: (_: string, write: () => void) => write(), undo: () => {} }; + +// Lists each file as received just before it is written; undo() takes back what this install listed that is not on disk. +function receivedWrites(root: string): typeof PLAIN_WRITES { + const listedHere: string[] = []; + return { + guard(destPath: string, write: () => void) { + listedHere.push( + ...recordReceivedFiles(root, [relative(root, destPath).split(sep).join("/")]), + ); + write(); + }, + undo() { + forgetReceivedFiles( + root, + listedHere.filter((path) => !existsSync(join(root, path))), + ); + }, + }; +} + // Install a topologically-ordered plan (dependencies first, requested item // last). Every item is fetched and checked before any is written, so a refusal // or failed fetch anywhere in the plan writes nothing. Returns all written paths. @@ -305,6 +342,7 @@ async function installAll( requestedName: string, variableValues: Record | null, installDirs: string[], + received: boolean, ): Promise<{ written: string[]; preserved: string[]; @@ -315,6 +353,7 @@ async function installAll( const preserved: string[] = []; let variablesApplied: string[] = []; let variablesUnknown: string[] = []; + const writes = received ? receivedWrites(registryRoot(destDir)) : PLAIN_WRITES; try { const prepared: PreparedItem[] = []; for (const planItem of installPlan) { @@ -331,7 +370,7 @@ async function installAll( ); } for (const [i, planItem] of installPlan.entries()) { - const result = publishItem(prepared[i]!); + const result = publishItem(prepared[i]!, writes.guard); written.push(...result.written); preserved.push(...result.preserved); if (planItem.name === requestedName) { @@ -340,6 +379,7 @@ async function installAll( } } } catch (err) { + writes.undo(); if (isProjectRootMissing(err)) throw err; if (err instanceof InvalidVariableValuesError) throw new AddError(err.message, "invalid-vars"); throw new AddError(describeInstallFailure(err, baseUrl), "install-failed"); @@ -449,6 +489,7 @@ export async function addToProject( item.name, variableValues, [config.paths.blocks, config.paths.components, config.paths.assets], + fromReceivedRegistry(projectDir, config.registry), ); // Report what landed, not what was asked for: a failed install throws above, diff --git a/packages/cli/src/registry/index.ts b/packages/cli/src/registry/index.ts index 7e4ab696c4..1775acd84e 100644 --- a/packages/cli/src/registry/index.ts +++ b/packages/cli/src/registry/index.ts @@ -1,7 +1,7 @@ // Only what other modules actually import. Everything else in this folder is // reached through its own module, so re-exporting it here just creates surface // that has to be kept working without anyone depending on it. -export { DEFAULT_REGISTRY_URL } from "./remote.js"; +export { DEFAULT_REGISTRY_URL, isPublicRegistry } from "./remote.js"; export { listRegistryItems, loadAllItems, resolveItemsByTag } from "./resolver.js"; diff --git a/packages/cli/src/registry/installer.ts b/packages/cli/src/registry/installer.ts index 7f61c869c4..16a96f275e 100644 --- a/packages/cli/src/registry/installer.ts +++ b/packages/cli/src/registry/installer.ts @@ -416,7 +416,10 @@ export async function prepareItem( } /** Write a prepared item and record what landed. */ -export function publishItem({ root, outcomes: prepared, force }: PreparedItem): InstallResult { +export function publishItem( + { root, outcomes: prepared, force }: PreparedItem, + guardWrite: (destPath: string, write: () => void) => void = (_, write) => write(), +): InstallResult { // Read now, not at prepare time: another item published in between has recorded its own files. const record = readInstallRecord(root); // Asked again at write time: a save made while the rest of the plan downloaded is still an edit. @@ -425,8 +428,8 @@ export function publishItem({ root, outcomes: prepared, force }: PreparedItem): ? { ...o, preserved: true, hash: null, vars: null, bytes: null } : o, ); - for (const outcome of outcomes) { - if (outcome.bytes) publishRegistryFile(root, outcome.target, outcome.bytes); + for (const { bytes, destPath, target } of outcomes) { + if (bytes) guardWrite(destPath, () => publishRegistryFile(root, target, bytes)); } const written = outcomes.filter((o) => !o.preserved).map((o) => o.destPath); diff --git a/packages/cli/src/registry/remote.test.ts b/packages/cli/src/registry/remote.test.ts index 70ab6a8f90..f65bb5ad51 100644 --- a/packages/cli/src/registry/remote.test.ts +++ b/packages/cli/src/registry/remote.test.ts @@ -18,6 +18,7 @@ const { fetchItemManifest, fetchRegistryManifest, readRegistryManifest, + isPublicRegistry, DEFAULT_REGISTRY_URL, } = await import("./remote.js"); @@ -496,3 +497,22 @@ describe("fetchItemFile retries", () => { expect(fetchSpy).toHaveBeenCalledTimes(3); }); }); + +describe("isPublicRegistry", () => { + it.each([DEFAULT_REGISTRY_URL, `${DEFAULT_REGISTRY_URL}/`, `${DEFAULT_REGISTRY_URL}/blocks`])( + "counts %s as the public registry", + (registry) => expect(isPublicRegistry(registry)).toBe(true), + ); + + it.each([ + "https://registry.example.com", + `${DEFAULT_REGISTRY_URL}-mirror`, + `${DEFAULT_REGISTRY_URL}/../../../../someone/else/main/registry`, + `${DEFAULT_REGISTRY_URL}/%2e%2e/%2e%2e/%2e%2e/%2e%2e/someone/else/main/registry`, + `${DEFAULT_REGISTRY_URL}?from=elsewhere`, + DEFAULT_REGISTRY_URL.replace("https://", "https://user@"), + "not a url", + ])("does not count %s as the public registry", (registry) => + expect(isPublicRegistry(registry)).toBe(false), + ); +}); diff --git a/packages/cli/src/registry/remote.ts b/packages/cli/src/registry/remote.ts index 5154ed8a40..5cb08db3d0 100644 --- a/packages/cli/src/registry/remote.ts +++ b/packages/cli/src/registry/remote.ts @@ -34,6 +34,19 @@ import { export const DEFAULT_REGISTRY_URL = "https://raw.githubusercontent.com/heygen-com/hyperframes/main/registry"; +/** Whether `registry` is the public registry or a folder in it, read the way a fetch reads it. */ +export function isPublicRegistry(registry: string): boolean { + let url: URL; + try { + url = new URL(registry); + } catch { + return false; + } + if (url.username || url.password || url.search || url.hash) return false; + const href = url.href.replace(/\/+$/, ""); + return href === DEFAULT_REGISTRY_URL || href.startsWith(`${DEFAULT_REGISTRY_URL}/`); +} + const FETCH_TIMEOUT_MS = 10_000; const MAX_MANIFEST_BYTES = 10 * 1024 * 1024; diff --git a/packages/cli/src/utils/privateProjectFile.test.ts b/packages/cli/src/utils/privateProjectFile.test.ts index 8b084813fb..7c1741d9ce 100644 --- a/packages/cli/src/utils/privateProjectFile.test.ts +++ b/packages/cli/src/utils/privateProjectFile.test.ts @@ -1,8 +1,23 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + utimesSync, + writeFileSync, +} from "node:fs"; +import { spawn } from "node:child_process"; import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { isEnvOrGitPath, isPrivateCompositionFile, receivedFiles } from "./privateProjectFile.js"; +import { dirname, join } from "node:path"; +import { + isEnvOrGitPath, + isPrivateCompositionFile, + receivedFiles, + recordReceivedFiles, +} from "./privateProjectFile.js"; const zeroFileIds = vi.hoisted(() => ({ on: false })); @@ -82,3 +97,62 @@ describe("receivedFiles", () => { expect(received("mine.html")).toBe(false); }); }); + +describe("recordReceivedFiles", () => { + const record = (root: string) => join(root, ".hyperframes", "received-files.json"); + const lock = (root: string) => `${record(root)}.lock`; + const listed = (root: string) => JSON.parse(readFileSync(record(root), "utf-8")).files; + function project(): string { + dir = mkdtempSync(join(tmpdir(), "hf-received-lock-")); + mkdirSync(join(dir, ".hyperframes")); + writeFileSync(record(dir), JSON.stringify({ files: ["hyperframes.json"] })); + return dir; + } + + it("waits for another writer's lock, so both writers keep their entries", async () => { + const root = project(); + writeFileSync(lock(root), ""); + // Another writer: it read the record, holds the lock, writes its entry, then lets go. + const other = spawn(process.execPath, [ + "-e", + `const fs = require("node:fs"); + const files = JSON.parse(fs.readFileSync(process.argv[1], "utf8")).files; + process.stdout.write("read"); + setTimeout(() => { + fs.writeFileSync(process.argv[1], JSON.stringify({ files: [...files, "theirs.html"] })); + fs.rmSync(process.argv[2]); + }, 300);`, + record(root), + lock(root), + ]); + await new Promise((resolve) => other.stdout.once("data", resolve)); + recordReceivedFiles(root, ["mine.html"]); + await new Promise((resolve) => other.once("exit", resolve)); + expect(listed(root)).toEqual(["hyperframes.json", "mine.html", "theirs.html"]); + }); + + it("takes a project folder however its path is spelled", () => { + const root = join(project(), "Project"); + mkdirSync(root); + const respelled = join(dirname(root), "project"); + const spelled = existsSync(respelled) ? respelled : root; + expect(recordReceivedFiles(spelled, ["mine.html"])).toEqual(["mine.html"]); + expect(listed(root)).toEqual(["mine.html"]); + }); + + it("takes over a lock left behind for more than ten seconds", () => { + const root = project(); + writeFileSync(lock(root), ""); + const old = new Date(Date.now() - 60_000); + utimesSync(lock(root), old, old); + expect(recordReceivedFiles(root, ["mine.html"])).toEqual(["mine.html"]); + expect(listed(root)).toEqual(["hyperframes.json", "mine.html"]); + }); + + it("fails rather than write past a lock that stays held", () => { + const root = project(); + writeFileSync(lock(root), ""); + expect(() => recordReceivedFiles(root, ["mine.html"])).toThrow(/Another program is changing/); + expect(listed(root)).toEqual(["hyperframes.json"]); + }); +}); diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index 91ef85210c..299fa09663 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -1,4 +1,12 @@ -import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs"; +import { + closeSync, + lstatSync, + openSync, + readFileSync, + realpathSync, + rmSync, + statSync, +} from "node:fs"; import { dirname, join, relative, resolve, sep } from "node:path"; import { isEnvOrGitPath, @@ -6,6 +14,8 @@ import { linksOutside, } from "@hyperframes/studio-server/outside-file"; import { isPrivateProjectFile, realFilePath } from "@hyperframes/studio-server/safe-path"; +import { mkdirWithinProject } from "@hyperframes/core"; +import { publishRegistryFile, registryRoot, registryTargetPath } from "../registry/publication.js"; export { isEnvOrGitPath, isPrivateOutsideFile, linksOutside }; @@ -14,6 +24,9 @@ export function linksToPrivateOutsideFile(projectDir: string, filePath: string): } const RECEIVED_RECORD = join(".hyperframes", "received-files.json"); +const RECEIVED_RECORD_LOCK = `${RECEIVED_RECORD}.lock`; +const LOCK_WAIT_MS = 2_000; +const LOCK_STALE_MS = 10_000; interface ReceivedRecord { root: string; @@ -39,6 +52,60 @@ function readRecord(dir: string, ownFolder: boolean): { listed: unknown } | null } } +function sleepSync(ms: number): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} + +function takeRecordLock(lock: string): void { + const deadline = Date.now() + LOCK_WAIT_MS; + for (;;) { + try { + closeSync(openSync(lock, "wx")); + return; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + const heldFor = Date.now() - (statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()); + if (heldFor > LOCK_STALE_MS) rmSync(lock, { force: true }); + else if (Date.now() < deadline) sleepSync(25); + else throw new Error(`Another program is changing ${RECEIVED_RECORD}; try again.`); + } +} + +function changeReceivedRecord(projectDir: string, change: (files: Set) => boolean): void { + const root = registryRoot(projectDir); + const lock = registryTargetPath(root, RECEIVED_RECORD_LOCK); + mkdirWithinProject(root, dirname(lock)); + takeRecordLock(lock); + try { + const record = readRecord(root, true); + if (record && !Array.isArray(record.listed)) return; + const files = new Set(((record?.listed ?? []) as unknown[]).map(String)); + if (!change(files)) return; + publishRegistryFile(root, RECEIVED_RECORD, `${JSON.stringify({ files: [...files].sort() })}\n`); + } finally { + rmSync(lock, { force: true }); + } +} + +export function recordReceivedFiles(root: string, paths: string[]): string[] { + const added: string[] = []; + if (paths.length === 0) return added; + changeReceivedRecord(root, (files) => { + for (const path of paths.map((one) => one.normalize("NFC"))) { + if (!files.has(path)) added.push(path); + files.add(path); + } + return added.length > 0; + }); + return added; +} + +export function forgetReceivedFiles(root: string, paths: string[]): void { + if (paths.length === 0) return; + changeReceivedRecord(root, (files) => paths.map((path) => files.delete(path)).some(Boolean)); +} + function receivedRecordsAtOrAbove(projectDir: string): ReceivedRecord[] { let start: string; try {