mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-19 19:36:04 +00:00
fix(share): clarify updates and avoid scratch-file rerenders
This commit is contained in:
@@ -43,7 +43,8 @@ scratch/
|
||||
|
||||
Each line excludes that file or folder and its contents from source capture and
|
||||
sharing change detection. Blank lines and lines starting with `#` are ignored.
|
||||
Use literal paths with `/` separators; wildcards, negation, absolute paths, and
|
||||
Use paths with `/` separators or a single `*` wildcard (for example, `*.log`
|
||||
or `scratch/*.json`). Basename patterns apply in every folder. Negation, absolute paths, and
|
||||
excluding `index.html` are rejected. Do not exclude assets your composition uses.
|
||||
These rules can only exclude files, never re-include credentials or other files
|
||||
blocked by the portable project policy.
|
||||
@@ -123,3 +124,8 @@ modify Desktop's application data directory.
|
||||
|
||||
- [CLI reference](/packages/cli#share) — audiences, updates, and processing status.
|
||||
- [CLI guide](/developers/cli) — choose the command for your task.
|
||||
|
||||
Sharing excludes scratch `*.log` and `*.swp` files by default, both from render
|
||||
change detection and uploaded project files. Other files remain inputs because
|
||||
compositions can load them dynamically. Invalid rules report
|
||||
`invalid_source_ignore`; sharing stops rather than silently uploading excluded files.
|
||||
|
||||
@@ -3074,7 +3074,9 @@ audience flag (for example, `share --public`) changes an existing share’s audi
|
||||
without uploading a version, just like Studio’s audience selector. Without an
|
||||
audience flag, access stays unchanged. Use
|
||||
`--update` to publish a new rendered version. If nothing changed, the command says
|
||||
“Already up to date” (`upToDate: true` in JSON). The previous ready version remains
|
||||
“Already up to date” (`upToDate: true` in JSON). A successful new version
|
||||
sets `updated: true`; Studio confirms “Shared version updated.” Status reads
|
||||
omit `upToDate` because they do not render or compare all inputs. The previous ready version remains
|
||||
visible while an update processes. Interrupted first uploads can resume when
|
||||
the source is unchanged; if it changed, explicitly use `--update`. If the
|
||||
project's review or audience changes while rendering, check the current share
|
||||
@@ -3114,3 +3116,6 @@ OAuth client. Storage URLs outside the selected origins are rejected.
|
||||
|
||||
Existing `/p/...` publications remain separate and reachable. Sharing does not
|
||||
convert a legacy publication or change its URL, visibility or ownership.
|
||||
|
||||
Share renders keep warnings and failures visible. Routine compiler, browser-launch,
|
||||
and runtime-FPS diagnostics require `HF_DEBUG_RENDER=1`.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReviewFailed } from "@hyperframes/share";
|
||||
import { SourceIgnoreError, ReviewFailed } from "@hyperframes/share";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { runCommand } from "citty";
|
||||
import { consumeCommandResult } from "../utils/commandResult.js";
|
||||
@@ -133,3 +133,13 @@ it("reports an unchanged update in human and JSON output", async () => {
|
||||
upToDate: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a specific code for an invalid ignore file", async () => {
|
||||
mocks.run.mockRejectedValue(new SourceIgnoreError("Invalid ignore pattern"));
|
||||
const out = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
await runCommand(command, { rawArgs: ["--public", "--json"] });
|
||||
expect(JSON.parse(String(out.mock.calls[0]?.[0]))).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "invalid_source_ignore" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ export function presentShare(value: ShareState): LocalShareState {
|
||||
value.share?.sharingState?.state === "subscription_required";
|
||||
return {
|
||||
upToDate: value.upToDate,
|
||||
updated: value.updated,
|
||||
state: presentedState(value, Boolean(held)),
|
||||
url: held ? null : (value.url ?? value.previousUrl),
|
||||
failure: value.state === "failed" ? value.version.failure : null,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ownerOf, ReviewFailed, reviewSentence } from "@hyperframes/share";
|
||||
import { SourceIgnoreError, ownerOf, ReviewFailed, reviewSentence } from "@hyperframes/share";
|
||||
import { ShareSourceError } from "./sources.js";
|
||||
import { isAuthError } from "../auth/errors.js";
|
||||
import { CliUsageError } from "../utils/commandResult.js";
|
||||
@@ -20,6 +20,7 @@ const HINTS: Record<string, string> = {
|
||||
"This project has no shared review yet. Run hyperframes share with an explicit audience.",
|
||||
};
|
||||
export function shareError(error: unknown): { code: string; message: string; owner?: string } {
|
||||
if (error instanceof SourceIgnoreError) return { code: error.code, message: error.message };
|
||||
if (error instanceof CliUsageError) return { code: error.code, message: error.message };
|
||||
if (error instanceof ShareSourceError)
|
||||
return { code: "source_unavailable", message: error.message };
|
||||
|
||||
@@ -72,3 +72,18 @@ describe("local sharing render boundary", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("reuses the video when only a scratch log is added", async () => {
|
||||
const dir = folder();
|
||||
writeFileSync(join(dir, "index.html"), "<html></html>");
|
||||
rendering.execute.mockImplementation(async ({ output }: { output: string }) =>
|
||||
writeFileSync(output, "video"),
|
||||
);
|
||||
await prepareShareRender(dir);
|
||||
const original = latestShareRender(dir);
|
||||
rendering.execute.mockClear();
|
||||
writeFileSync(join(dir, "other.log"), "scratch output");
|
||||
await prepareShareRender(dir);
|
||||
expect(rendering.execute).not.toHaveBeenCalled();
|
||||
expect(latestShareRender(dir)?.id).toBe(original?.id);
|
||||
});
|
||||
|
||||
@@ -453,12 +453,23 @@ it("does not label a newly published version as already up to date", async () =>
|
||||
onAdded();
|
||||
return null;
|
||||
});
|
||||
expect((await createShareService("/project").run({ action: "update" })).upToDate).toBe(false);
|
||||
expect(await createShareService("/project").run({ action: "update" })).toMatchObject({
|
||||
upToDate: false,
|
||||
});
|
||||
});
|
||||
it("does not label a still-processing update as already up to date", async () => {
|
||||
mocks.status.mockResolvedValue(shared);
|
||||
mocks.version.mockResolvedValue({ last: { current: true }, source: "ready" });
|
||||
mocks.pending.mockResolvedValue({ projectId: "project" });
|
||||
mocks.add.mockResolvedValue(null);
|
||||
expect((await createShareService("/project").run({ action: "update" })).upToDate).toBe(false);
|
||||
expect(await createShareService("/project").run({ action: "update" })).toMatchObject({
|
||||
upToDate: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not claim to check freshness in status", async () => {
|
||||
mocks.status.mockResolvedValue(shared);
|
||||
expect(await createShareService("/project").run({ action: "status" })).not.toHaveProperty(
|
||||
"upToDate",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -64,7 +64,6 @@ async function readStatus(
|
||||
const failed = hasFailedVersion(version);
|
||||
const ready = Boolean(activeUrl && latest && !processing && !failed);
|
||||
return {
|
||||
upToDate: false,
|
||||
share,
|
||||
version,
|
||||
pending,
|
||||
@@ -179,7 +178,7 @@ export function createShareService(
|
||||
const dir = bindCliShareProject(projectPath);
|
||||
const auth = createShareAccess(options.pinIdentity);
|
||||
const client = reviewClient(auth);
|
||||
const status = async (expectedProjectId?: string) => {
|
||||
const status = async (expectedProjectId?: string): Promise<ShareState> => {
|
||||
await auth.access();
|
||||
return readStatus(dir, client, expectedProjectId);
|
||||
};
|
||||
@@ -220,6 +219,7 @@ export function createShareService(
|
||||
return {
|
||||
...result,
|
||||
upToDate: isUnchangedUpdate(input, added, result),
|
||||
updated: input.action === "update" && added,
|
||||
};
|
||||
};
|
||||
const uploadTarget = async (current: ReviewShare | null, input: ShareAction, space?: string) => {
|
||||
@@ -251,7 +251,7 @@ export function createShareService(
|
||||
audience: target.audience,
|
||||
});
|
||||
};
|
||||
const mutate = async (input: ShareAction, attempt: ShareAttempt) => {
|
||||
const mutate = async (input: ShareAction, attempt: ShareAttempt): Promise<ShareState> => {
|
||||
await auth.access();
|
||||
attempt.authenticated();
|
||||
let current = await readStatus(dir, client, undefined, attempt.recover);
|
||||
@@ -312,7 +312,10 @@ export function createShareService(
|
||||
};
|
||||
}
|
||||
export type ShareService = ReturnType<typeof createShareService>;
|
||||
export type ShareState = Awaited<ReturnType<typeof readStatus>>;
|
||||
export type ShareState = Awaited<ReturnType<typeof readStatus>> & {
|
||||
upToDate?: boolean;
|
||||
updated?: boolean;
|
||||
};
|
||||
|
||||
function hasFailedVersion(version: Awaited<ReturnType<typeof reviewVersion>>): boolean {
|
||||
return Boolean(version.failure && !version.held);
|
||||
|
||||
@@ -1624,22 +1624,28 @@ describe("browser pool", () => {
|
||||
_setPuppeteerForTests(undefined);
|
||||
});
|
||||
|
||||
it("keeps the launch diagnostic on stderr when a command emits JSON", async () => {
|
||||
const stdout = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
const stderr = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
try {
|
||||
const result = await acquireBrowser(["--no-sandbox"], poolCfg);
|
||||
await result.release();
|
||||
it.each([undefined, "1"])(
|
||||
"emits the launch diagnostic only in debug mode (%s)",
|
||||
async (debug) => {
|
||||
vi.stubEnv("HF_DEBUG_RENDER", debug);
|
||||
const stdout = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
const stderr = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
try {
|
||||
const result = await acquireBrowser(["--no-sandbox"], poolCfg);
|
||||
await result.release();
|
||||
|
||||
expect(stderr).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/^\[BrowserManager\] Browser launched/),
|
||||
);
|
||||
expect(stdout).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
stdout.mockRestore();
|
||||
stderr.mockRestore();
|
||||
}
|
||||
});
|
||||
const launches = stderr.mock.calls.filter(([line]) =>
|
||||
String(line).startsWith("[BrowserManager] Browser launched"),
|
||||
);
|
||||
expect(launches.length).toBe(debug ? 1 : 0);
|
||||
expect(stdout).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
stdout.mockRestore();
|
||||
stderr.mockRestore();
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("sequential acquires with pool enabled return the same browser", async () => {
|
||||
const first = await acquireBrowser(["--no-sandbox"], poolCfg);
|
||||
|
||||
@@ -955,9 +955,10 @@ async function launchBrowser(
|
||||
const gpuFlags = fingerprint.args.filter(
|
||||
(a) => a.startsWith("--use-gl=") || a.startsWith("--use-angle="),
|
||||
);
|
||||
console.error(
|
||||
`[BrowserManager] Browser launched (${browserVersion}, ${captureMode}, gl=${gpuFlags.join(" ") || "default"}, headlessShell=${!!fingerprint.executablePath}, platform=${process.platform})`,
|
||||
);
|
||||
if (process.env.HF_DEBUG_RENDER === "1")
|
||||
console.error(
|
||||
`[BrowserManager] Browser launched (${browserVersion}, ${captureMode}, gl=${gpuFlags.join(" ") || "default"}, headlessShell=${!!fingerprint.executablePath}, platform=${process.platform})`,
|
||||
);
|
||||
|
||||
if (captureMode === "beginframe") {
|
||||
let result = await probe(browser);
|
||||
|
||||
@@ -203,7 +203,6 @@ describe("classifyPageError", () => {
|
||||
emit("error", "Failed to load resource", "https://fonts.gstatic.com/font.woff2");
|
||||
|
||||
expect(stderr.mock.calls).toEqual([
|
||||
["[HyperFrames] render runtime fps"],
|
||||
["[Browser:WARN] GPU readback warning"],
|
||||
["[Browser:ERROR] [HyperFrames] composition script error: scene TypeError: x"],
|
||||
]);
|
||||
|
||||
@@ -3068,7 +3068,11 @@ export async function initializeSession(session: CaptureSession): Promise<void>
|
||||
const text = msg.text();
|
||||
const locationUrl = msg.location()?.url ?? "";
|
||||
const diagnostic = formatConsoleDiagnostic(type, text, locationUrl);
|
||||
if (!diagnostic.suppressHostLog && !loggedEarlierInRender(session, text)) {
|
||||
if (
|
||||
!diagnostic.suppressHostLog &&
|
||||
!quietRuntimeDetail(text) &&
|
||||
!loggedEarlierInRender(session, text)
|
||||
) {
|
||||
console.error(diagnostic.text);
|
||||
}
|
||||
appendBrowserDiagnostic(session, diagnostic.text);
|
||||
@@ -5937,3 +5941,7 @@ export function getCapturePerfSummary(session: CaptureSession): CapturePerfSumma
|
||||
deFrameTimeouts: session.deFrameTimeouts ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
function quietRuntimeDetail(text: string): boolean {
|
||||
return process.env.HF_DEBUG_RENDER !== "1" && text.startsWith("[hyperframes] render runtime fps");
|
||||
}
|
||||
|
||||
@@ -92,4 +92,6 @@ export function createConsoleLogger(level: LogLevel = "info"): ProducerLogger {
|
||||
}
|
||||
|
||||
/** Default logger singleton (level: "info"). */
|
||||
export const defaultLogger: ProducerLogger = createConsoleLogger("info");
|
||||
export const defaultLogger: ProducerLogger = createConsoleLogger(
|
||||
process.env.HF_DEBUG_RENDER === "1" ? "debug" : "info",
|
||||
);
|
||||
|
||||
@@ -1461,16 +1461,16 @@ describe("local font embedding", () => {
|
||||
</body></html>`,
|
||||
);
|
||||
|
||||
const originalInfo = defaultLogger.info;
|
||||
const originalDebug = defaultLogger.debug;
|
||||
const embeddedMessages: string[] = [];
|
||||
defaultLogger.info = (message) => {
|
||||
defaultLogger.debug = (message) => {
|
||||
if (message.includes("Embedded local font file")) embeddedMessages.push(message);
|
||||
};
|
||||
|
||||
try {
|
||||
await compileForRender(projectDir, join(projectDir, "index.html"), projectDir);
|
||||
} finally {
|
||||
defaultLogger.info = originalInfo;
|
||||
defaultLogger.debug = originalDebug;
|
||||
}
|
||||
|
||||
expect(embeddedMessages).toHaveLength(1);
|
||||
@@ -1550,9 +1550,9 @@ describe("local font embedding", () => {
|
||||
</body></html>`,
|
||||
);
|
||||
|
||||
const originalInfo = defaultLogger.info;
|
||||
const originalDebug = defaultLogger.debug;
|
||||
const fileBackedMessages: string[] = [];
|
||||
defaultLogger.info = (message) => {
|
||||
defaultLogger.debug = (message) => {
|
||||
if (message.includes("Kept large local font file-backed")) {
|
||||
fileBackedMessages.push(message);
|
||||
}
|
||||
@@ -1562,7 +1562,7 @@ describe("local font embedding", () => {
|
||||
try {
|
||||
compiled = await compileForRender(projectDir, join(projectDir, "index.html"), projectDir);
|
||||
} finally {
|
||||
defaultLogger.info = originalInfo;
|
||||
defaultLogger.debug = originalDebug;
|
||||
}
|
||||
|
||||
expect(compiled.html).toContain('url("assets/large.ttc")');
|
||||
|
||||
@@ -109,7 +109,7 @@ import { assertAssetMediaTypeProfile } from "./assetMediaType.js";
|
||||
import { withMediaProbeSlot } from "../utils/mediaProbeConcurrency.js";
|
||||
|
||||
function logRemoteDownloadTelemetry(event: UrlDownloadTelemetry): void {
|
||||
defaultLogger.info("[Compiler] Remote asset download integrity", { ...event });
|
||||
defaultLogger.debug("[Compiler] Remote asset download integrity", { ...event });
|
||||
}
|
||||
|
||||
export interface CompiledComposition {
|
||||
@@ -1332,7 +1332,7 @@ export async function inlineExternalScripts(html: string): Promise<string> {
|
||||
}
|
||||
inlineScript.textContent = `/* inlined: ${src} */\n${safeText}\n//# sourceURL=${new URL(src).href}\n`;
|
||||
el.replaceWith(inlineScript);
|
||||
defaultLogger.info(`[Compiler] Inlined CDN script: ${src}`);
|
||||
defaultLogger.debug(`[Compiler] Inlined CDN script: ${src}`);
|
||||
} else {
|
||||
// A verified mismatch must never fall back to an executable external tag:
|
||||
// browser support for integrity metadata (including casing) can differ.
|
||||
@@ -1415,7 +1415,7 @@ export function collectExternalAssets(
|
||||
}
|
||||
|
||||
if (externalAssets.size > 0) {
|
||||
defaultLogger.info(
|
||||
defaultLogger.debug(
|
||||
`[Compiler] Found ${externalAssets.size} asset(s) outside project directory, will copy to render output`,
|
||||
);
|
||||
}
|
||||
@@ -1499,7 +1499,7 @@ async function downloadAndRewriteUrls(
|
||||
if (extraRewrite) result = extraRewrite(result, url, relPath);
|
||||
}
|
||||
|
||||
defaultLogger.info(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
|
||||
defaultLogger.debug(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
|
||||
return { html: result, remoteMediaAssets };
|
||||
}
|
||||
|
||||
@@ -1754,7 +1754,7 @@ async function inlineExternalFontStylesheets(html: string): Promise<string> {
|
||||
const identity = safeDownloadUrlIdentity(href);
|
||||
const inlineStyle = `<style>/* Inlined external font stylesheet */\n${fontFaceBlocks.join("\n")}\n</style>`;
|
||||
result = result.replace(fullMatch, inlineStyle);
|
||||
defaultLogger.info("[Compiler] Inlined external @font-face rule(s)", {
|
||||
defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
|
||||
count: fontFaceBlocks.length,
|
||||
urlFingerprint: identity.urlFingerprint,
|
||||
host: identity.host,
|
||||
@@ -1924,7 +1924,7 @@ async function embedLocalFontFaces(html: string, projectDir: string): Promise<st
|
||||
const font = await readLocalFont(absPath);
|
||||
if (font.kind === "file-backed") {
|
||||
fileBackedAbsolutePaths.add(absPath);
|
||||
defaultLogger.info(
|
||||
defaultLogger.debug(
|
||||
`[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`,
|
||||
);
|
||||
embeddedPaths.add(localPath);
|
||||
@@ -1932,7 +1932,7 @@ async function embedLocalFontFaces(html: string, projectDir: string): Promise<st
|
||||
}
|
||||
dataUri = await toDataUri(font.buffer, ext, { compressToWoff2: false });
|
||||
dataUriByAbsolutePath.set(absPath, dataUri);
|
||||
defaultLogger.info(
|
||||
defaultLogger.debug(
|
||||
`[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB → data URI)`,
|
||||
);
|
||||
}
|
||||
@@ -2033,7 +2033,7 @@ function rewriteUnresolvableGsapToCdn(
|
||||
if (/^https?:\/\//i.test(src)) return full;
|
||||
if (exists(compSrcPath ? rewriteAssetPath(compSrcPath, src, exists) : src)) return full;
|
||||
gsapDist ??= renderGsapDist();
|
||||
defaultLogger.info(`[Compiler] Rewriting missing gsap script: ${src} → ${gsapDist}${file}`);
|
||||
defaultLogger.debug(`[Compiler] Rewriting missing gsap script: ${src} → ${gsapDist}${file}`);
|
||||
return `${prefix}${gsapDist}${file}${suffix}`;
|
||||
},
|
||||
);
|
||||
@@ -2233,7 +2233,7 @@ export async function compileForRender(
|
||||
timeoutMs: options.ffmpegProcessTimeout,
|
||||
});
|
||||
if (preparedHeifImages.length > 0) {
|
||||
defaultLogger.info(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
|
||||
defaultLogger.debug(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
|
||||
}
|
||||
|
||||
const gifSourceAssets = new Map<string, string>(remoteImageAssets);
|
||||
@@ -2249,7 +2249,7 @@ export async function compileForRender(
|
||||
timeoutMs: options.ffmpegProcessTimeout,
|
||||
});
|
||||
if (preparedGifs.length > 0) {
|
||||
defaultLogger.info(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
|
||||
defaultLogger.debug(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
|
||||
}
|
||||
|
||||
const embeddedHtml = await embedLocalFontFaces(htmlWithPreparedGifs, projectDir);
|
||||
|
||||
@@ -86,3 +86,5 @@ export {
|
||||
shareSourceFingerprint,
|
||||
createProjectShareSourceStore,
|
||||
} from "./shareSources.mjs";
|
||||
|
||||
export { SourceIgnoreError } from "./sourceIgnore.mjs";
|
||||
|
||||
@@ -3,12 +3,19 @@ import { constants } from "node:fs";
|
||||
import { lstat, open } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
export class SourceIgnoreError extends Error {
|
||||
code = "invalid_source_ignore";
|
||||
}
|
||||
const scratch = (/** @type {string} */ path) => /(?:^|\/)[^/]+\.(?:log|swp)$/.test(path);
|
||||
|
||||
/** Explicit, project-relative exclusions. This only removes files; it cannot override safety exclusions.
|
||||
* @param {string} root @returns {Promise<(path: string) => boolean>} */
|
||||
export async function readSourceIgnore(root) {
|
||||
const file = join(root, ".hyperframesignore");
|
||||
const invalid = () =>
|
||||
new Error(".hyperframesignore must be a regular file inside the project, smaller than 64 KiB.");
|
||||
new SourceIgnoreError(
|
||||
".hyperframesignore must be a regular file inside the project, smaller than 64 KiB.",
|
||||
);
|
||||
const handle = await open(
|
||||
file,
|
||||
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
|
||||
@@ -22,7 +29,7 @@ export async function readSourceIgnore(root) {
|
||||
if (named) throw invalid();
|
||||
return null;
|
||||
});
|
||||
if (!handle) return () => false;
|
||||
if (!handle) return scratch;
|
||||
let text;
|
||||
try {
|
||||
// Validate the opened descriptor before reading. lstat additionally rejects links on
|
||||
@@ -52,18 +59,34 @@ export async function readSourceIgnore(root) {
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && !line.startsWith("#"));
|
||||
const entries = paths.map((entry) => {
|
||||
const path = entry.replace(/\/$/, "");
|
||||
if (
|
||||
path === "index.html" ||
|
||||
/[\\*?![\]:]/.test(path) ||
|
||||
path.includes("\0") ||
|
||||
path.split("/").some((part) => !part || part === "." || part === "..")
|
||||
)
|
||||
throw new Error(
|
||||
".hyperframesignore accepts literal project-relative file or folder paths, one per line. Wildcards and excluding index.html are not supported.",
|
||||
);
|
||||
return path;
|
||||
});
|
||||
return (path) => entries.some((entry) => path === entry || path.startsWith(`${entry}/`));
|
||||
const entries = paths.map(ignorePattern);
|
||||
return (path) => scratch(path) || entries.some((entry) => entry.test(path));
|
||||
}
|
||||
|
||||
/** @param {string} entry */
|
||||
function ignorePattern(entry) {
|
||||
const path = entry.replace(/\/$/, "");
|
||||
const invalid = () =>
|
||||
new SourceIgnoreError(
|
||||
".hyperframesignore accepts project-relative paths or patterns with one * wildcard. Negation, traversal, and excluding index.html are not supported.",
|
||||
);
|
||||
if (!validPatternPath(path)) throw invalid();
|
||||
const escaped = path
|
||||
.split("*")
|
||||
.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
|
||||
.join("[^/]*");
|
||||
const prefix = path.includes("*") && !path.includes("/") ? "(?:^|/)" : "^";
|
||||
const pattern = new RegExp(`${prefix}${escaped}(?:/|$)`);
|
||||
if (pattern.test("index.html")) throw invalid();
|
||||
return pattern;
|
||||
}
|
||||
|
||||
/** @param {string} path */
|
||||
function validPatternPath(path) {
|
||||
return (
|
||||
!/[\\?![\]:]/.test(path) &&
|
||||
!path.includes("\0") &&
|
||||
!path.split("/").some((part) => !part || part === "." || part === "..") &&
|
||||
path.split("*").length <= 2
|
||||
);
|
||||
}
|
||||
|
||||
@@ -272,9 +272,9 @@ test("explicit exclusions remove scratch files from capture and render fingerpri
|
||||
test("ignore rules fail closed for unsupported patterns, entrypoint exclusions, and symlinks", async (t) => {
|
||||
const root = await project({ "index.html": "<html></html>" });
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
for (const rule of ["index.html", "../secret", "*.json", "!out.json"]) {
|
||||
for (const rule of ["index.html", "../secret", "*.html", "**/*.json", "!out.json"]) {
|
||||
await writeFile(join(root, ".hyperframesignore"), rule);
|
||||
await assert.rejects(captureProject(root), /literal project-relative/);
|
||||
await assert.rejects(captureProject(root), /project-relative/);
|
||||
}
|
||||
await rm(join(root, ".hyperframesignore"));
|
||||
await symlink(join(root, "index.html"), join(root, ".hyperframesignore"));
|
||||
@@ -294,3 +294,20 @@ test("ignore configuration rejects oversized files, directories and dangling sym
|
||||
await symlink(join(root, "missing"), file);
|
||||
await assert.rejects(captureProject(root), /regular file/);
|
||||
});
|
||||
|
||||
test("scratch files and wildcard exclusions do not change the snapshot", async (t) => {
|
||||
const { projectFingerprint } = await import("../src/projectSnapshot.mjs");
|
||||
const root = await project({
|
||||
"index.html": "<html></html>",
|
||||
".hyperframesignore": "*.scratch\n",
|
||||
});
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const before = await projectFingerprint(root);
|
||||
const first = captured(await captureProject(root));
|
||||
await writeFile(join(root, "other.log"), "diagnostic");
|
||||
await writeFile(join(root, "notes.scratch"), "temporary");
|
||||
assert.equal(await projectFingerprint(root), before);
|
||||
assert.deepEqual(captured(await captureProject(root)).manifest, first.manifest);
|
||||
await writeFile(join(root, "data.json"), "{}");
|
||||
assert.notEqual(await projectFingerprint(root), before);
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface LocalShareSpace {
|
||||
}
|
||||
export interface LocalShareState {
|
||||
upToDate?: boolean;
|
||||
updated?: boolean;
|
||||
state: "not_shared" | "link_off" | "ready" | "processing" | "failed" | "unavailable";
|
||||
url: string | null;
|
||||
manageUrl: string;
|
||||
|
||||
@@ -583,3 +583,23 @@ it("resets the copied acknowledgement after two seconds", async () => {
|
||||
expect(button("Copy link")).toBeDefined();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("offers Only you for an existing public share", async () => {
|
||||
snapshot.share = { ...snapshot.share, state: "ready", audience: "public", spaceId: "team1" };
|
||||
await mount();
|
||||
const option = host.querySelector<HTMLOptionElement>('option[value="private"]');
|
||||
expect(option?.disabled).toBe(false);
|
||||
});
|
||||
it("confirms a newly published version", async () => {
|
||||
snapshot.share = {
|
||||
...snapshot.share,
|
||||
state: "ready",
|
||||
url: "https://hyperframes.dev/r/test",
|
||||
audience: "public",
|
||||
spaceId: "team1",
|
||||
};
|
||||
job = { ...job, state: "done", result: { ...snapshot.share, updated: true } };
|
||||
await mount();
|
||||
await act(async () => button("Update shared version")?.click());
|
||||
expect(host.textContent).toContain("Shared version updated.");
|
||||
});
|
||||
|
||||
@@ -16,7 +16,7 @@ const AUDIENCES = {
|
||||
detail: "People you add in Manage sharing",
|
||||
icon: UserPlus,
|
||||
},
|
||||
private: { label: "Only you", detail: "This existing share is private", icon: Lock },
|
||||
private: { label: "Only you", detail: "Only you can access this share", icon: Lock },
|
||||
};
|
||||
|
||||
export function ShareAudience({
|
||||
@@ -30,7 +30,7 @@ export function ShareAudience({
|
||||
const Icon = selected?.icon ?? Lock;
|
||||
const space = snapshot.spaces.find((item) => item.id === model.spaceId);
|
||||
const choices: LocalShareAudience[] = ["public", "team", "invite"];
|
||||
if (snapshot.share.audience === "private") choices.push("private");
|
||||
if (snapshot.share.state !== "not_shared") choices.push("private");
|
||||
return (
|
||||
<Menu
|
||||
aria-label="Who can access"
|
||||
|
||||
@@ -194,7 +194,9 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
|
||||
export type QuickShareModel = ReturnType<typeof useQuickShare>;
|
||||
|
||||
function completionNotice(job: LocalShareJob) {
|
||||
return job.state === "done" && job.result?.upToDate ? "Already up to date." : "";
|
||||
if (job.state !== "done") return "";
|
||||
if (job.result?.upToDate) return "Already up to date.";
|
||||
return job.result?.updated ? "Shared version updated." : "";
|
||||
}
|
||||
|
||||
function useCopyAcknowledgement() {
|
||||
|
||||
Reference in New Issue
Block a user