From 47db28f8c28e472f95e9c55993c24e5a2dfda43f Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Sun, 14 Jun 2026 19:18:28 -0700 Subject: [PATCH] fix(sdk,studio): 15 code-review correctness fixes from second stage 7 review Co-Authored-By: Claude Sonnet 4.6 --- packages/sdk/src/adapters/fs.ts | 8 +++--- packages/sdk/src/adapters/http.test.ts | 15 +++++++++++ packages/sdk/src/adapters/http.ts | 7 ++++- packages/sdk/src/engine/apply-patches.ts | 6 ++--- packages/sdk/src/engine/mutate.gsap.test.ts | 28 ++++++++++++++++++++ packages/sdk/src/engine/mutate.ts | 5 +++- packages/sdk/src/session.subcomp.test.ts | 18 ++++++++++++- packages/sdk/src/session.ts | 7 ++++- packages/studio/src/utils/sdkCutover.test.ts | 24 +++++++++++++++++ packages/studio/src/utils/sdkCutover.ts | 9 ++++++- packages/studio/src/utils/sdkShadow.ts | 2 +- 11 files changed, 116 insertions(+), 13 deletions(-) diff --git a/packages/sdk/src/adapters/fs.ts b/packages/sdk/src/adapters/fs.ts index 7f13606edd..b6a6cdd832 100644 --- a/packages/sdk/src/adapters/fs.ts +++ b/packages/sdk/src/adapters/fs.ts @@ -62,7 +62,7 @@ class FsAdapter implements PersistAdapter { } async flush(): Promise { - await Promise.all([...this.inflightWrites]); + await Promise.all([...this.inflightWrites, this.appendVersionQueue]); } async listVersions(path: string): Promise { @@ -111,9 +111,9 @@ class FsAdapter implements PersistAdapter { } private appendVersion(path: string, content: string): Promise { - this.appendVersionQueue = this.appendVersionQueue.then(() => - this.doAppendVersion(path, content), - ); + this.appendVersionQueue = this.appendVersionQueue + .then(() => this.doAppendVersion(path, content)) + .catch(() => {}); return this.appendVersionQueue; } diff --git a/packages/sdk/src/adapters/http.test.ts b/packages/sdk/src/adapters/http.test.ts index b3a8786ce5..fbe52685c4 100644 --- a/packages/sdk/src/adapters/http.test.ts +++ b/packages/sdk/src/adapters/http.test.ts @@ -70,6 +70,21 @@ describe("read()", () => { const adapter = createHttpAdapter({ projectFilesUrl: BASE }); await expect(adapter.read("comp.html")).rejects.toThrow("HTTP 503"); }); + + it("returns undefined when 200 response body is not valid JSON", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => { + throw new SyntaxError("Unexpected token"); + }, + }), + ); + const adapter = createHttpAdapter({ projectFilesUrl: BASE }); + await expect(adapter.read("comp.html")).resolves.toBeUndefined(); + }); }); // ── write() ─────────────────────────────────────────────────────────────────── diff --git a/packages/sdk/src/adapters/http.ts b/packages/sdk/src/adapters/http.ts index 8bdad04be2..fe57e00238 100644 --- a/packages/sdk/src/adapters/http.ts +++ b/packages/sdk/src/adapters/http.ts @@ -32,7 +32,12 @@ class HttpAdapter implements PersistAdapter { const res = await fetch(url); if (res.status === 404) return undefined; if (!res.ok) throw new Error(`HTTP ${res.status}`); - const data = (await res.json()) as { content?: string }; + let data: { content?: string }; + try { + data = (await res.json()) as { content?: string }; + } catch { + return undefined; + } return typeof data.content === "string" ? data.content : undefined; } diff --git a/packages/sdk/src/engine/apply-patches.ts b/packages/sdk/src/engine/apply-patches.ts index 9bff69e78f..24fdd90167 100644 --- a/packages/sdk/src/engine/apply-patches.ts +++ b/packages/sdk/src/engine/apply-patches.ts @@ -18,7 +18,7 @@ import { setGsapScript, setStyleSheet, } from "./model.js"; -import { keyToPath } from "./patches.js"; +import { keyToPath, gsapScriptPath, styleSheetPath } from "./patches.js"; // ─── Path parser ──────────────────────────────────────────────────────────── @@ -70,8 +70,8 @@ function parsePath(path: string): ParsedPath | null { const metaM = /^\/metadata\/(.+)$/.exec(path); if (metaM) return { type: "metadata", field: metaM[1] }; - if (path === "/script/gsap") return { type: "script" }; - if (path === "/style/css") return { type: "stylesheet" }; + if (path === gsapScriptPath()) return { type: "script" }; + if (path === styleSheetPath()) return { type: "stylesheet" }; return null; } diff --git a/packages/sdk/src/engine/mutate.gsap.test.ts b/packages/sdk/src/engine/mutate.gsap.test.ts index 5e19ca8d8f..88ff253c11 100644 --- a/packages/sdk/src/engine/mutate.gsap.test.ts +++ b/packages/sdk/src/engine/mutate.gsap.test.ts @@ -189,6 +189,23 @@ describe("addGsapTween", () => { }), ).toThrow("No GSAP script block found"); }); + + it("uses bare leaf id in selector when target is a scoped id", () => { + const html = `
+
+ +
`.trim(); + const parsed = parseMutable(html); + const result = applyOp(parsed, { + type: "addGsapTween", + target: "hf-stage/hf-box", + tween: { method: "to", properties: { x: 100 } }, + }); + expect(result.forward.length).toBeGreaterThan(0); + const newScript = String(result.forward[0]?.value ?? ""); + expect(newScript).toContain("hf-box"); + expect(newScript).not.toContain("hf-stage/hf-box"); + }); }); // ─── Tween op test helpers ──────────────────────────────────────────────────── @@ -515,4 +532,15 @@ describe("GSAP ops on composition with no GSAP script block", () => { applyOp(freshNoScript(), { type: "removeGsapTween", animationId: "anim-1" }), ).toThrow(); }); + + it("addGsapKeyframe throws when script element is null", () => { + expect(() => + applyOp(freshNoScript(), { + type: "addGsapKeyframe", + animationId: "a1", + percentage: 0, + value: { opacity: 0 }, + }), + ).toThrow("No GSAP script block found"); + }); }); diff --git a/packages/sdk/src/engine/mutate.ts b/packages/sdk/src/engine/mutate.ts index d18c622de1..6b615dda5a 100644 --- a/packages/sdk/src/engine/mutate.ts +++ b/packages/sdk/src/engine/mutate.ts @@ -604,8 +604,9 @@ function handleAddGsapTween( ? ((tween.toProperties ?? {}) as Record) : ((tween.toProperties ?? tween.properties ?? {}) as Record); + const selectorId = target.includes("/") ? target.split("/").pop()! : target; const animation: Omit = { - targetSelector: `[data-hf-id="${target}"]`, + targetSelector: `[data-hf-id="${selectorId}"]`, method: tween.method, position: tween.position ?? 0, ...(tween.duration !== undefined ? { duration: tween.duration } : {}), @@ -716,6 +717,8 @@ function handleAddGsapKeyframe( value: Record, ): MutationResult { const script = getGsapScript(parsed.document); + if (script === null) + throw new Error("No GSAP script block found. Use comp.can(op) to check first."); if (!script) return EMPTY; const newScript = addKeyframeToScript( script, diff --git a/packages/sdk/src/session.subcomp.test.ts b/packages/sdk/src/session.subcomp.test.ts index 91a99e0dd2..ded0c69ff5 100644 --- a/packages/sdk/src/session.subcomp.test.ts +++ b/packages/sdk/src/session.subcomp.test.ts @@ -340,7 +340,7 @@ describe("find({ composition })", () => { const ids = comp.find({ composition: "hf-host" }); expect(ids).toContain("hf-host/hf-leaf"); expect(ids).not.toContain("hf-outer"); - expect(ids).not.toContain("hf-host"); // host itself is in parent scope + expect(ids).toContain("hf-host"); // host element is included in its own composition scope }); it("returns empty array for unknown host id", async () => { @@ -351,6 +351,22 @@ describe("find({ composition })", () => { expect(comp.find({ composition: "hf-no-such" })).toEqual([]); }); + it("find({ composition }) includes the host element itself", async () => { + const html = inlinedHtml(` +
+
+

inside

+
+

outside

+
+ `); + const comp = await openComposition(html); + const ids = comp.find({ composition: "hf-host" }); + expect(ids).toContain("hf-host"); + expect(ids).toContain("hf-host/hf-leaf"); + expect(ids).not.toContain("hf-outer"); + }); + it("can combine composition filter with other query fields", async () => { const html = inlinedHtml(`
diff --git a/packages/sdk/src/session.ts b/packages/sdk/src/session.ts index 149b770b64..8473c60e46 100644 --- a/packages/sdk/src/session.ts +++ b/packages/sdk/src/session.ts @@ -188,7 +188,12 @@ class CompositionImpl implements Composition { if (query.text && !el.text?.includes(query.text)) return false; if (query.name && el.attributes["data-name"] !== query.name) return false; if (query.track !== undefined && el.trackIndex !== query.track) return false; - if (query.composition && !el.scopedId.startsWith(`${query.composition}/`)) return false; + if ( + query.composition && + el.scopedId !== query.composition && + !el.scopedId.startsWith(`${query.composition}/`) + ) + return false; return true; }) .map((el) => el.scopedId) diff --git a/packages/studio/src/utils/sdkCutover.test.ts b/packages/studio/src/utils/sdkCutover.test.ts index d2c8cfb9fc..562419903b 100644 --- a/packages/studio/src/utils/sdkCutover.test.ts +++ b/packages/studio/src/utils/sdkCutover.test.ts @@ -211,6 +211,30 @@ describe("sdkCutoverPersist", () => { }); }); + it("passes caller label to recordEdit", async () => { + const deps = makeDeps(); + const session = makeSession(true); + const sel = { hfId: "hf-abc" } as never; + await sdkCutoverPersist(sel, [styleOp("color", "red")], "before", "/comp.html", session, deps, { + label: "Resize layer box", + }); + expect(deps.editHistory.recordEdit).toHaveBeenCalledWith( + expect.objectContaining({ label: "Resize layer box" }), + ); + }); + + it("passes caller coalesceKey to recordEdit", async () => { + const deps = makeDeps(); + const session = makeSession(true); + const sel = { hfId: "hf-abc" } as never; + await sdkCutoverPersist(sel, [styleOp("color", "red")], "before", "/comp.html", session, deps, { + coalesceKey: "my-key", + }); + expect(deps.editHistory.recordEdit).toHaveBeenCalledWith( + expect.objectContaining({ coalesceKey: "my-key" }), + ); + }); + it("returns false and does not throw on dispatch error", async () => { const deps = makeDeps(); const session = makeSession(true); diff --git a/packages/studio/src/utils/sdkCutover.ts b/packages/studio/src/utils/sdkCutover.ts index a6191be943..f5afd754c5 100644 --- a/packages/studio/src/utils/sdkCutover.ts +++ b/packages/studio/src/utils/sdkCutover.ts @@ -43,6 +43,11 @@ interface CutoverDeps { domEditSaveTimestampRef: MutableRefObject; } +interface CutoverOptions { + label?: string; + coalesceKey?: string; +} + export async function sdkCutoverPersist( selection: DomEditSelection, ops: PatchOperation[], @@ -50,6 +55,7 @@ export async function sdkCutoverPersist( targetPath: string, sdkSession: Composition | null | undefined, deps: CutoverDeps, + options?: CutoverOptions, ): Promise { if (!shouldUseSdkCutover(STUDIO_SDK_CUTOVER_ENABLED, !!sdkSession, selection.hfId, ops)) return false; @@ -65,8 +71,9 @@ export async function sdkCutoverPersist( deps.domEditSaveTimestampRef.current = Date.now(); await deps.writeProjectFile(targetPath, after); await deps.editHistory.recordEdit({ - label: "Edit layer", + label: options?.label ?? "Edit layer", kind: "manual", + ...(options?.coalesceKey ? { coalesceKey: options.coalesceKey } : {}), files: { [targetPath]: { before: originalContent, after } }, }); deps.reloadPreview(); diff --git a/packages/studio/src/utils/sdkShadow.ts b/packages/studio/src/utils/sdkShadow.ts index 7a8d799d8d..d9c62c2405 100644 --- a/packages/studio/src/utils/sdkShadow.ts +++ b/packages/studio/src/utils/sdkShadow.ts @@ -98,7 +98,7 @@ function flattenSnapshot(snap: ElementSnapshot): FlatSnapshot { type OpFieldResolver = (op: PatchOperation, flat: FlatSnapshot) => OpFields; -const OP_FIELD_RESOLVERS: Record = { +const OP_FIELD_RESOLVERS: Record = { "inline-style": (op, flat) => ({ property: op.property, expected: op.value,