Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots 📖

feat(guides): import a bundle under freshly minted ids

davbioc3fde3147dbc
diff --git a/src/core/guides/__tests__/import-guide.test.ts b/src/core/guides/__tests__/import-guide.test.ts
new file mode 100644
index 0000000..bff0a40
--- /dev/null
+++ b/src/core/guides/__tests__/import-guide.test.ts
@@ -0,0 +1,149 @@
+import 'fake-indexeddb/auto';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ globalThis.BroadcastChannel = class {
+ postMessage() {}
+ addEventListener() {}
+ removeEventListener() {}
+ close() {}
+ } as unknown as typeof BroadcastChannel;
+});
+
+import type { ParsedBundle } from '@/core/transfer/parse';
+import { BUNDLE_VERSION } from '@/core/transfer/schema';
+import { db } from '../db';
+import { createGuide, getGuide, importGuide } from '../service';
+import type { Step } from '../types';
+
+function makeBundle(overrides: Partial<ParsedBundle['manifest']> = {}): ParsedBundle {
+ return {
+ manifest: {
+ version: BUNDLE_VERSION,
+ exportedAt: 1_700_000_000_000,
+ guide: { title: 'Reset a password', description: 'How to do it', createdAt: 1_600_000_000_000 },
+ sourceDomain: 'app.example.com',
+ redacted: { screenshots: true, inputValues: true, urls: 'path' },
+ steps: [
+ { id: 'step-1', index: 0, description: 'Open settings', action: 'click', url: 'https://a.test', timestamp: 1 },
+ { id: 'step-2', index: 1, description: 'Click save', action: 'click', url: 'https://a.test', timestamp: 2 },
+ ],
+ screenshots: [
+ {
+ id: 'ss-1',
+ stepId: 'step-1',
+ file: 'screenshots/ss-1.webp',
+ mimeType: 'image/webp',
+ width: 800,
+ height: 600,
+ },
+ ],
+ ...overrides,
+ },
+ images: new Map([['screenshots/ss-1.webp', new Blob(['pixels'], { type: 'image/webp' })]]),
+ };
+}
+
+beforeEach(async () => {
+ await db.delete();
+ await db.open();
+});
+
+describe('importGuide', () => {
+ it('adds the guide with its steps and screenshots', async () => {
+ const guideId = await importGuide(makeBundle());
+ const loaded = await getGuide(guideId);
+
+ expect(loaded?.guide.title).toBe('Reset a password');
+ expect(loaded?.guide.description).toBe('How to do it');
+ expect(loaded?.steps.map((s) => s.description)).toEqual(['Open settings', 'Click save']);
+ expect(loaded?.screenshots.size).toBe(1);
+ });
+
+ it('mints new identifiers rather than reusing the ones in the file', async () => {
+ const guideId = await importGuide(makeBundle());
+ const loaded = await getGuide(guideId);
+
+ expect(guideId).not.toBe('guide-1');
+ expect(loaded?.steps.map((s) => s.id)).not.toContain('step-1');
+ expect(loaded?.steps.every((s) => s.guideId === guideId)).toBe(true);
+ expect(loaded?.guide.stepIds).toEqual(loaded?.steps.map((s) => s.id));
+ });
+
+ it('cannot overwrite a step the recipient already has', async () => {
+ // Step ids come from the file, so this is the collision that can actually
+ // happen: a guide the recipient recorded already owns 'step-1'.
+ await createGuide('mine');
+ const mine: Step = {
+ id: 'step-1',
+ guideId: 'mine',
+ index: 0,
+ description: 'My own step',
+ action: 'click',
+ url: 'https://mine.test',
+ timestamp: 1,
+ };
+ await db.steps.add(mine);
+
+ await importGuide(makeBundle());
+
+ expect(await db.steps.get('step-1')).toEqual(mine);
+ expect(await db.guides.count()).toBe(2);
+ const imported = await getGuide((await db.guides.toArray()).find((g) => g.id !== 'mine')!.id);
+ expect(imported?.steps.map((s) => s.id)).not.toContain('step-1');
+ });
+
+ it('importing the same file twice makes two independent guides', async () => {
+ const first = await importGuide(makeBundle());
+ const second = await importGuide(makeBundle());
+
+ expect(first).not.toBe(second);
+ const [a, b] = await Promise.all([getGuide(first), getGuide(second)]);
+ expect(a?.steps[0].id).not.toBe(b?.steps[0].id);
+ expect(await db.steps.count()).toBe(4);
+ });
+
+ it('points each step at its own newly minted screenshot', async () => {
+ const guideId = await importGuide(makeBundle());
+ const loaded = await getGuide(guideId);
+ const [first, second] = loaded?.steps as Step[];
+ const screenshot = loaded?.screenshots.get(first.id);
+
+ expect(screenshot?.id).toBe(first.screenshotId);
+ expect(screenshot?.id).not.toBe('ss-1');
+ expect(screenshot?.stepId).toBe(first.id);
+ expect(second.screenshotId).toBeUndefined();
+ });
+
+ it('clears aiPending so the editor does not wait on a job that will never run', async () => {
+ const bundle = makeBundle();
+ (bundle.manifest.steps[0] as Record<string, unknown>).aiPending = true;
+
+ const loaded = await getGuide(await importGuide(bundle));
+ expect(loaded?.steps.every((s) => !s.aiPending)).toBe(true);
+ });
+
+ it('resets ownership: the imported guide is new here, not starred or trashed', async () => {
+ const loaded = await getGuide(await importGuide(makeBundle()));
+
+ expect(loaded?.guide.starred).toBe(false);
+ expect(loaded?.guide.deletedAt).toBeNull();
+ expect(loaded?.guide.createdAt).toBeGreaterThan(1_600_000_000_000);
+ });
+
+ it('skips a screenshot whose image is missing from the archive', async () => {
+ const bundle = makeBundle();
+ bundle.images.clear();
+
+ const loaded = await getGuide(await importGuide(bundle));
+ expect(loaded?.screenshots.size).toBe(0);
+ expect(loaded?.steps[0].screenshotId).toBeUndefined();
+ expect(await db.screenshots.count()).toBe(0);
+ });
+
+ it('does not leave the zip entry path on the stored screenshot', async () => {
+ const loaded = await getGuide(await importGuide(makeBundle()));
+ const screenshot = loaded?.screenshots.get(loaded.steps[0].id) as unknown as Record<string, unknown>;
+ expect(screenshot.file).toBeUndefined();
+ });
+});
diff --git a/src/core/guides/service.ts b/src/core/guides/service.ts
index 26c8b42..0498d5e 100644
--- a/src/core/guides/service.ts
+++ b/src/core/guides/service.ts
@@ -1,6 +1,7 @@
import { i18n } from '#imports';
import type { NarrationUpdate } from '@/core/capture/voice/narration-updates';
import type { ScreenshotEdits } from '@/core/screenshot/types';
+import type { ParsedBundle } from '@/core/transfer/parse';
import { db } from './db';
import { hashPayload } from './snapshot-hash';
import type { BlockType, CalloutVariant, DescriptionSource, Guide, Screenshot, Snapshot, Step } from './types';
@@ -128,6 +129,71 @@ export async function permanentlyDeleteGuide(id: string): Promise<void> {
notifyGuidesChanged({ type: 'mutated' });
}
+/**
+ * Writes an imported bundle into this browser's library.
+ *
+ * Every identifier is minted fresh. Reusing the ones in the file would let a
+ * shared guide silently overwrite a guide the recipient recorded themselves, and
+ * the file comes from someone else's machine. Ownership flags reset for the same
+ * reason: the guide is new here, whatever it was to its author.
+ */
+export async function importGuide(bundle: ParsedBundle): Promise<string> {
+ const { manifest, images } = bundle;
+ const guideId = crypto.randomUUID();
+ const now = Date.now();
+
+ const stepIds = new Map<string, string>();
+ for (const step of manifest.steps) stepIds.set(step.id, crypto.randomUUID());
+
+ const screenshotsByStep = new Map(manifest.screenshots.map((shot) => [shot.stepId, shot]));
+
+ const steps: Step[] = [];
+ const screenshots: Screenshot[] = [];
+
+ manifest.steps.forEach((incoming, index) => {
+ const id = stepIds.get(incoming.id)!;
+ const shot = screenshotsByStep.get(incoming.id);
+ const blob = shot ? images.get(shot.file) : undefined;
+ const screenshotId = shot && blob ? crypto.randomUUID() : undefined;
+
+ if (shot && blob && screenshotId) {
+ const { file: _file, ...rest } = shot;
+ screenshots.push({ ...rest, id: screenshotId, stepId: id, blob });
+ }
+
+ steps.push({
+ ...incoming,
+ id,
+ guideId,
+ index,
+ // No background job exists to resolve a pending description here, and a
+ // step that waits for one spins in the editor forever.
+ aiPending: undefined,
+ ...(screenshotId ? { screenshotId } : {}),
+ });
+ });
+
+ const guide: Guide = {
+ id: guideId,
+ title: manifest.guide.title,
+ ...(manifest.guide.description ? { description: manifest.guide.description } : {}),
+ createdAt: now,
+ updatedAt: now,
+ stepIds: steps.map((s) => s.id),
+ starred: false,
+ deletedAt: null,
+ };
+
+ await db.transaction('rw', db.guides, db.steps, db.screenshots, async () => {
+ await db.guides.add(guide);
+ await db.steps.bulkAdd(steps);
+ if (screenshots.length > 0) await db.screenshots.bulkAdd(screenshots);
+ });
+
+ notifyGuidesChanged({ type: 'mutated' });
+ return guideId;
+}
+
export async function reorderSteps(guideId: string, orderedStepIds: string[]): Promise<void> {
await db.transaction('rw', db.steps, db.guides, async () => {
for (let i = 0; i < orderedStepIds.length; i++) {
diff --git a/src/core/transfer/__tests__/round-trip.test.ts b/src/core/transfer/__tests__/round-trip.test.ts
new file mode 100644
index 0000000..9c1a5f0
--- /dev/null
+++ b/src/core/transfer/__tests__/round-trip.test.ts
@@ -0,0 +1,207 @@
+import 'fake-indexeddb/auto';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ globalThis.BroadcastChannel = class {
+ postMessage() {}
+ addEventListener() {}
+ removeEventListener() {}
+ close() {}
+ } as unknown as typeof BroadcastChannel;
+});
+
+vi.mock('@/core/screenshot/render', () => ({
+ renderScreenshot: async () => new Blob(['flattened'], { type: 'image/webp' }),
+}));
+vi.mock('@/core/export/markdown-export', () => ({
+ exportGuideAsMarkdown: async () => '# guide',
+}));
+
+import { db } from '@/core/guides/db';
+import { getGuide, importGuide } from '@/core/guides/service';
+import type { Guide, Screenshot, Step } from '@/core/guides/types';
+import { exportGuideAsBundle } from '../bundle';
+import { readBundle } from '../parse';
+
+const guide: Guide = {
+ id: 'guide-1',
+ title: 'Reset a password',
+ description: 'For support agents',
+ createdAt: 1_600_000_000_000,
+ updatedAt: 1_600_000_000_000,
+ stepIds: ['step-1', 'step-2', 'step-3'],
+ starred: true,
+ deletedAt: null,
+};
+
+const steps: Step[] = [
+ {
+ id: 'step-1',
+ guideId: 'guide-1',
+ index: 0,
+ description: 'Open the security page',
+ action: 'click',
+ url: 'https://app.example.com/settings?session=abc',
+ timestamp: 1,
+ screenshotId: 'ss-1',
+ descriptionSource: 'narration',
+ elementMeta: {
+ tag: 'a',
+ cssSelector: 'nav a.security',
+ textContent: 'Security',
+ ariaLabel: null,
+ placeholder: null,
+ altText: null,
+ name: null,
+ role: 'link',
+ href: 'https://app.example.com/settings',
+ inputType: null,
+ dataTestId: 'nav-security',
+ rect: { x: 10, y: 20, width: 80, height: 24 },
+ devicePixelRatio: 2,
+ },
+ },
+ {
+ id: 'step-2',
+ guideId: 'guide-1',
+ index: 1,
+ description: 'A word of warning',
+ action: 'block',
+ url: '',
+ timestamp: 2,
+ blockType: 'callout',
+ calloutVariant: 'warning',
+ },
+ {
+ id: 'step-3',
+ guideId: 'guide-1',
+ index: 2,
+ description: 'Type the new password',
+ action: 'input',
+ url: 'https://app.example.com/settings/security',
+ timestamp: 3,
+ screenshotId: 'ss-3',
+ inputValue: 'hunter2',
+ },
+];
+
+const screenshots = new Map<string, Screenshot>([
+ [
+ 'step-1',
+ {
+ id: 'ss-1',
+ stepId: 'step-1',
+ blob: new Blob(['raw-1'], { type: 'image/png' }),
+ mimeType: 'image/png',
+ width: 1000,
+ height: 800,
+ bounds: { x: 10, y: 20, width: 80, height: 24 },
+ pixelRatio: 2,
+ edits: {
+ annotations: [
+ { id: 'r1', type: 'redact', x: 400, y: 300, w: 120, h: 30, style: 'blur' },
+ { id: 'a1', type: 'arrow', x1: 10, y1: 10, x2: 90, y2: 90, color: '#EF4444' },
+ ],
+ alt: 'the security link',
+ },
+ },
+ ],
+ [
+ 'step-3',
+ {
+ id: 'ss-3',
+ stepId: 'step-3',
+ blob: new Blob(['raw-3'], { type: 'image/png' }),
+ mimeType: 'image/png',
+ width: 1000,
+ height: 800,
+ },
+ ],
+]);
+
+beforeEach(async () => {
+ await db.delete();
+ await db.open();
+});
+
+async function roundTrip() {
+ const file = await exportGuideAsBundle(guide, steps, screenshots);
+ const guideId = await importGuide(await readBundle(file));
+ const loaded = await getGuide(guideId);
+ if (!loaded) throw new Error('imported guide not found');
+ return loaded;
+}
+
+describe('bundle round trip', () => {
+ it('rebuilds the guide on the other side', async () => {
+ const { guide: imported, steps: importedSteps } = await roundTrip();
+
+ expect(imported.title).toBe('Reset a password');
+ expect(imported.description).toBe('For support agents');
+ expect(importedSteps.map((s) => s.description)).toEqual([
+ 'Open the security page',
+ 'A word of warning',
+ 'Type the new password',
+ ]);
+ expect(importedSteps.map((s) => s.index)).toEqual([0, 1, 2]);
+ });
+
+ it('carries the editorial structure a guide depends on', async () => {
+ const { steps: importedSteps } = await roundTrip();
+
+ expect(importedSteps[1].blockType).toBe('callout');
+ expect(importedSteps[1].calloutVariant).toBe('warning');
+ expect(importedSteps[0].descriptionSource).toBe('narration');
+ });
+
+ it('keeps the element metadata Guide Me matches on', async () => {
+ const { steps: importedSteps } = await roundTrip();
+ const meta = importedSteps[0].elementMeta;
+
+ expect(meta?.cssSelector).toBe('nav a.security');
+ expect(meta?.textContent).toBe('Security');
+ expect(meta?.dataTestId).toBe('nav-security');
+ expect(meta?.role).toBe('link');
+ });
+
+ it('leaves the redaction behind and keeps the ordinary annotation', async () => {
+ const { steps: importedSteps, screenshots: importedShots } = await roundTrip();
+ const shot = importedShots.get(importedSteps[0].id);
+
+ expect(shot?.edits?.annotations?.map((a) => a.type)).toEqual(['arrow']);
+ expect(shot?.edits?.alt).toBe('the security link');
+ expect(await shot?.blob.text()).toBe('flattened');
+ });
+
+ it('strips the secrets the defaults promise to strip', async () => {
+ const { steps: importedSteps } = await roundTrip();
+
+ expect(importedSteps[2].inputValue).toBeUndefined();
+ expect(importedSteps[0].url).toBe('https://app.example.com/settings');
+ });
+
+ it('attaches each screenshot to the right step and leaves the blockless step bare', async () => {
+ const { steps: importedSteps, screenshots: importedShots } = await roundTrip();
+
+ expect(importedShots.size).toBe(2);
+ expect(importedShots.get(importedSteps[0].id)?.stepId).toBe(importedSteps[0].id);
+ expect(importedSteps[1].screenshotId).toBeUndefined();
+ });
+
+ it('carries non-ascii text through the zip intact', async () => {
+ const accented: Guide = { ...guide, title: 'Redefinir a senha · 中文 · café', description: 'Für Support — naïve' };
+ const file = await exportGuideAsBundle(accented, steps, screenshots);
+ const { guide: imported } = (await getGuide(await importGuide(await readBundle(file))))!;
+
+ expect(imported.title).toBe('Redefinir a senha · 中文 · café');
+ expect(imported.description).toBe('Für Support — naïve');
+ });
+
+ it("lands as a fresh guide rather than the author's", async () => {
+ const { guide: imported } = await roundTrip();
+
+ expect(imported.id).not.toBe('guide-1');
+ expect(imported.starred).toBe(false);
+ expect(imported.createdAt).toBeGreaterThan(1_600_000_000_000);
+ });
+});