From 64a6947c6deb7513b5d011b6ffc87e02e4d3c2c4 Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Tue, 24 Nov 2026 02:09:30 +0530 Subject: [PATCH 01/10] feat: add client-side import/export for saved recipes --- src/components/ui/RecipeLibrary.tsx | 56 ++++++++++++- src/i18n/en.ts | 2 + src/lib/recipes.test.ts | 50 ++++++++++++ src/lib/recipes.ts | 118 +++++++++++++++++++++------- src/store/useStore.ts | 13 +++ 5 files changed, 210 insertions(+), 29 deletions(-) create mode 100644 src/lib/recipes.test.ts diff --git a/src/components/ui/RecipeLibrary.tsx b/src/components/ui/RecipeLibrary.tsx index 6464741..8ab9576 100644 --- a/src/components/ui/RecipeLibrary.tsx +++ b/src/components/ui/RecipeLibrary.tsx @@ -1,5 +1,5 @@ -import { useState } from 'react'; -import { Trash2 } from 'lucide-react'; +import { useRef, useState } from 'react'; +import { Download, Trash2, Upload } from 'lucide-react'; import { useStore } from '../../store/useStore'; import { t } from '../../i18n/en'; import { Button, IconButton } from './primitives'; @@ -13,9 +13,13 @@ export function RecipeLibrary() { const saveCurrentRecipe = useStore((s) => s.saveCurrentRecipe); const loadSavedRecipe = useStore((s) => s.loadSavedRecipe); const removeSavedRecipe = useStore((s) => s.removeSavedRecipe); + const importRecipes = useStore((s) => s.importRecipes); + const exportRecipes = useStore((s) => s.exportRecipes); const setDialog = useStore((s) => s.setDialog); const [name, setName] = useState(''); + const [message, setMessage] = useState(''); + const fileInputRef = useRef(null); const describe = (opIds: string[]) => opIds @@ -32,6 +36,30 @@ export function RecipeLibrary() { setName(''); }; + const onExport = () => { + const blob = new Blob([exportRecipes()], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = 'decodebox-recipes.json'; + link.click(); + URL.revokeObjectURL(url); + }; + + const onImport = async (file: File) => { + if (file.size > 1_000_000) { + setMessage('File is too large.'); + return; + } + try { + const text = await file.text(); + const result = importRecipes(text); + setMessage(result.error ?? `Imported ${result.imported}, skipped ${result.skipped}.`); + } catch { + setMessage('Could not read file.'); + } + }; + return ( +
+ + + { + const file = e.target.files?.[0]; + if (file) void onImport(file); + e.target.value = ''; + }} + /> +
+ + {message &&

{message}

} + {usingDetected && (

{t.library.detectedNote}{' '} diff --git a/src/i18n/en.ts b/src/i18n/en.ts index f6feefa..2129141 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -345,6 +345,8 @@ export const t = { saved: 'Saved', empty: 'Nothing saved yet.', remove: (name: string) => `Delete ${name}`, + exportRecipes: 'Export all', + importRecipes: 'Import', storageNote: 'Recipes live in this browser’s storage. Clearing site data removes them.', }, diff --git a/src/lib/recipes.test.ts b/src/lib/recipes.test.ts new file mode 100644 index 0000000..8e7bba9 --- /dev/null +++ b/src/lib/recipes.test.ts @@ -0,0 +1,50 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { importRecipes, exportRecipes, loadRecipes, saveRecipe } from './recipes'; + +describe('recipe import/export', () => { + beforeEach(() => localStorage.clear()); + afterEach(() => localStorage.clear()); + + it('exports and re-imports recipes', () => { + saveRecipe('A', []); + const json = exportRecipes(); + localStorage.clear(); + const result = importRecipes(json); + expect(result).toEqual({ imported: 1, skipped: 0 }); + expect(loadRecipes()).toHaveLength(1); + expect(loadRecipes()[0]!.name).toBe('A'); + }); + + it('rejects invalid JSON', () => { + const result = importRecipes('{bad'); + expect(result.error).toBeTruthy(); + expect(loadRecipes()).toHaveLength(0); + }); + + it('skips duplicate ids without overwriting', () => { + saveRecipe('A', []); + const json = exportRecipes(); + const result = importRecipes(json); + expect(result.imported).toBe(0); + expect(result.skipped).toBe(1); + expect(loadRecipes()).toHaveLength(1); + }); + + it('rejects unsupported versions', () => { + const result = importRecipes(JSON.stringify({ version: 2, recipes: [] })); + expect(result.error).toBeTruthy(); + }); + + it('rejects too many recipes', () => { + const result = importRecipes(JSON.stringify({ version: 1, recipes: Array(1001).fill({ id: 'x', name: 'x', steps: [] }) })); + expect(result.error).toBeTruthy(); + }); + + it('reports failure when storage write fails', () => { + const spy = vi.spyOn(localStorage, 'setItem').mockImplementation(() => { throw new Error('no'); }); + const result = importRecipes(JSON.stringify({ version: 1, recipes: [{ id: 'b', name: 'B', steps: [] }] })); + expect(result.error).toBeTruthy(); + spy.mockRestore(); + }); +}); \ No newline at end of file diff --git a/src/lib/recipes.ts b/src/lib/recipes.ts index 73d52e9..4b4dbcc 100644 --- a/src/lib/recipes.ts +++ b/src/lib/recipes.ts @@ -39,6 +39,27 @@ function readStep(value: unknown): RecipeStep | null { }; } +function readRecipe(value: unknown): SavedRecipe | null { + if (typeof value !== 'object' || value === null) return null; + const candidate = value as Partial; + if (typeof candidate.id !== 'string' || typeof candidate.name !== 'string') return null; + if (!Array.isArray(candidate.steps)) return null; + + const steps: RecipeStep[] = []; + for (const rawStep of candidate.steps) { + const step = readStep(rawStep); + if (!step) return null; + steps.push(step); + } + + return { + id: candidate.id, + name: candidate.name, + steps, + savedAt: typeof candidate.savedAt === 'number' ? candidate.savedAt : 0, + }; +} + export function loadRecipes(): SavedRecipe[] { try { const raw = localStorage.getItem(KEY); @@ -48,29 +69,8 @@ export function loadRecipes(): SavedRecipe[] { const recipes: SavedRecipe[] = []; for (const entry of parsed) { - if (typeof entry !== 'object' || entry === null) continue; - const candidate = entry as Partial; - if (typeof candidate.id !== 'string' || typeof candidate.name !== 'string') continue; - if (!Array.isArray(candidate.steps)) continue; - - const steps: RecipeStep[] = []; - let intact = true; - for (const rawStep of candidate.steps) { - const step = readStep(rawStep); - if (!step) { - intact = false; - break; - } - steps.push(step); - } - if (!intact) continue; - - recipes.push({ - id: candidate.id, - name: candidate.name, - steps, - savedAt: typeof candidate.savedAt === 'number' ? candidate.savedAt : 0, - }); + const recipe = readRecipe(entry); + if (recipe) recipes.push(recipe); } return recipes; } catch { @@ -78,13 +78,77 @@ export function loadRecipes(): SavedRecipe[] { } } -function persist(recipes: SavedRecipe[]): SavedRecipe[] { +export interface ImportResult { + imported: number; + skipped: number; + error?: string; +} + +export function exportRecipes(recipes: SavedRecipe[] = loadRecipes()): string { + return JSON.stringify({ version: 1, recipes }, null, 2); +} + +export function importRecipes(raw: string): ImportResult { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return { imported: 0, skipped: 0, error: 'Invalid JSON file.' }; + } + + let list: unknown[] | null = null; + if (Array.isArray(parsed)) { + list = parsed; + } else if (parsed && typeof parsed === 'object') { + const obj = parsed as { version?: unknown; recipes?: unknown }; + if (obj.version !== undefined && obj.version !== 1) { + return { imported: 0, skipped: 0, error: 'Unsupported export version.' }; + } + if (Array.isArray(obj.recipes)) list = obj.recipes; + } + + if (!list) return { imported: 0, skipped: 0, error: 'Expected a recipe list.' }; + if (list.length > 1000) return { imported: 0, skipped: 0, error: 'Too many recipes in file.' }; + + const existing = loadRecipes(); + const existingIds = new Set(existing.map((r) => r.id)); + const merged = [...existing]; + let imported = 0; + let skipped = 0; + + for (const entry of list) { + const recipe = readRecipe(entry); + if (!recipe) { + skipped += 1; + continue; + } + if (existingIds.has(recipe.id)) { + skipped += 1; + continue; + } + if (merged.length >= MAX) { + skipped += 1; + continue; + } + existingIds.add(recipe.id); + merged.push(recipe); + imported += 1; + } + + const { ok } = persist(merged); + if (!ok) return { imported: 0, skipped, error: 'Could not save recipes to browser storage.' }; + return { imported, skipped }; +} + +function persist(recipes: SavedRecipe[]): { recipes: SavedRecipe[]; ok: boolean } { const trimmed = recipes.slice(0, MAX); + let ok = true; try { localStorage.setItem(KEY, JSON.stringify(trimmed)); } catch { + ok = false; } - return trimmed; + return { recipes: trimmed, ok }; } export function saveRecipe(name: string, steps: RecipeStep[]): SavedRecipe[] { @@ -94,11 +158,11 @@ export function saveRecipe(name: string, steps: RecipeStep[]): SavedRecipe[] { steps: steps.map((s) => ({ ...s, args: s.args.map((a) => ({ ...a })) })), savedAt: Date.now(), }; - return persist([recipe, ...loadRecipes()]); + return persist([recipe, ...loadRecipes()]).recipes; } export function deleteRecipe(id: string): SavedRecipe[] { - return persist(loadRecipes().filter((r) => r.id !== id)); + return persist(loadRecipes().filter((r) => r.id !== id)).recipes; } export function instantiate(recipe: SavedRecipe): RecipeStep[] { diff --git a/src/store/useStore.ts b/src/store/useStore.ts index 92f5a74..2c616ea 100644 --- a/src/store/useStore.ts +++ b/src/store/useStore.ts @@ -28,7 +28,10 @@ import { instantiate, loadRecipes, saveRecipe, + importRecipes as importRecipesLib, + exportRecipes as exportRecipesLib, type SavedRecipe, + type ImportResult, } from '../lib/recipes'; type Theme = 'light' | 'dark' | 'system'; @@ -127,6 +130,8 @@ interface State { saveCurrentRecipe: (name: string, steps?: RecipeStep[]) => void; loadSavedRecipe: (id: string) => void; removeSavedRecipe: (id: string) => void; + importRecipes: (raw: string) => ImportResult; + exportRecipes: () => string; setPaneWidth: (pane: 'operations' | 'recipe', width: number) => void; setPaneHeight: (pane: 'input' | 'recipe', height: number) => void; @@ -716,6 +721,14 @@ export const useStore = create((set, get) => ({ set({ savedRecipes: deleteRecipe(id) }); }, + importRecipes: (raw) => { + const result = importRecipesLib(raw); + if (!result.error) set({ savedRecipes: loadRecipes() }); + return result; + }, + + exportRecipes: () => exportRecipesLib(get().savedRecipes), + setPaneHeight: (pane, height) => { const paneHeights = { ...get().paneHeights, [pane]: height }; set({ paneHeights }); From f059f277698982bdc076c1bca593e1da0a329ef8 Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Tue, 24 Nov 2026 16:28:32 +0530 Subject: [PATCH 02/10] fix: validate imported args against operation defs and enforce export version --- src/lib/recipes.ts | 58 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/src/lib/recipes.ts b/src/lib/recipes.ts index 4b4dbcc..c269316 100644 --- a/src/lib/recipes.ts +++ b/src/lib/recipes.ts @@ -1,5 +1,7 @@ import type { OperationArg, RecipeStep } from '../engine'; +import type { ArgType } from '../engine/types'; import { randomId } from '../engine'; +import { getOperation } from '../engine/operations'; import { safeArgValue } from './share'; export interface SavedRecipe { @@ -12,11 +14,21 @@ export interface SavedRecipe { const KEY = 'decodebox-recipes'; const MAX = 100; +const ARG_TYPES = new Set(['string', 'number', 'boolean', 'option', 'toggleString', 'textarea']); + +function fallbackFor(type: ArgType): string | number | boolean { + if (type === 'number') return 0; + if (type === 'boolean') return false; + return ''; +} + function readArg(value: unknown): OperationArg | null { if (typeof value !== 'object' || value === null) return null; const arg = value as Partial; if (typeof arg.name !== 'string' || typeof arg.type !== 'string') return null; - return { ...(arg as OperationArg), value: safeArgValue(arg.value, '') }; + if (!ARG_TYPES.has(arg.type as ArgType)) return null; + const type = arg.type as ArgType; + return { name: arg.name, type, value: safeArgValue(arg.value, fallbackFor(type)) }; } function readStep(value: unknown): RecipeStep | null { @@ -24,11 +36,29 @@ function readStep(value: unknown): RecipeStep | null { const step = value as Partial; if (typeof step.opId !== 'string' || !Array.isArray(step.args)) return null; - const args: OperationArg[] = []; - for (const raw of step.args) { - const arg = readArg(raw); - if (!arg) return null; - args.push(arg); + const op = getOperation(step.opId); + const importedArgs = step.args; + + let args: OperationArg[]; + if (op) { + args = op.args.map((def) => { + const found = importedArgs.find( + (a) => typeof a === 'object' && a !== null && (a as Partial).name === def.name, + ) as Partial | undefined; + let value = found ? safeArgValue(found.value, def.value) : def.value; + if (def.type === 'option' && def.options && !def.options.includes(String(value))) value = def.value; + if (def.type === 'toggleString' && def.toggleValues && !def.toggleValues.includes(String(value))) value = def.value; + if (def.type === 'number' && typeof value !== 'number') value = def.value; + if (def.type === 'boolean' && typeof value !== 'boolean') value = def.value; + return { ...def, value }; + }); + } else { + args = []; + for (const raw of importedArgs) { + const arg = readArg(raw); + if (!arg) return null; + args.push(arg); + } } return { @@ -96,16 +126,14 @@ export function importRecipes(raw: string): ImportResult { return { imported: 0, skipped: 0, error: 'Invalid JSON file.' }; } - let list: unknown[] | null = null; - if (Array.isArray(parsed)) { - list = parsed; - } else if (parsed && typeof parsed === 'object') { - const obj = parsed as { version?: unknown; recipes?: unknown }; - if (obj.version !== undefined && obj.version !== 1) { - return { imported: 0, skipped: 0, error: 'Unsupported export version.' }; - } - if (Array.isArray(obj.recipes)) list = obj.recipes; + if (Array.isArray(parsed) || !parsed || typeof parsed !== 'object') { + return { imported: 0, skipped: 0, error: 'Expected a versioned recipe export.' }; + } + const obj = parsed as { version?: unknown; recipes?: unknown }; + if (obj.version !== 1) { + return { imported: 0, skipped: 0, error: 'Unsupported export version.' }; } + const list = Array.isArray(obj.recipes) ? obj.recipes : null; if (!list) return { imported: 0, skipped: 0, error: 'Expected a recipe list.' }; if (list.length > 1000) return { imported: 0, skipped: 0, error: 'Too many recipes in file.' }; From 3f9a48c3f1deedf8570334e26f86ae88f70c83b2 Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Tue, 24 Nov 2026 16:33:09 +0530 Subject: [PATCH 03/10] fix: keep malformed recipes dropped while validating imported args --- src/lib/recipes.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/lib/recipes.ts b/src/lib/recipes.ts index c269316..57d9619 100644 --- a/src/lib/recipes.ts +++ b/src/lib/recipes.ts @@ -39,6 +39,10 @@ function readStep(value: unknown): RecipeStep | null { const op = getOperation(step.opId); const importedArgs = step.args; + for (const raw of importedArgs) { + if (!readArg(raw)) return null; + } + let args: OperationArg[]; if (op) { args = op.args.map((def) => { From 8b62495741526ffd5eb8caaa6b265583a193834b Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Wed, 25 Nov 2026 02:04:26 +0530 Subject: [PATCH 04/10] fix: validate toggle values and preserve safe arg metadata --- src/lib/recipes.test.ts | 34 +++++++++++++++++++++++ src/lib/recipes.ts | 60 +++++++++++++++++++++++++++++++++-------- 2 files changed, 83 insertions(+), 11 deletions(-) diff --git a/src/lib/recipes.test.ts b/src/lib/recipes.test.ts index 8e7bba9..b71e161 100644 --- a/src/lib/recipes.test.ts +++ b/src/lib/recipes.test.ts @@ -1,6 +1,7 @@ // @vitest-environment happy-dom import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { importRecipes, exportRecipes, loadRecipes, saveRecipe } from './recipes'; +import { OPERATIONS } from '../engine/operations'; describe('recipe import/export', () => { beforeEach(() => localStorage.clear()); @@ -47,4 +48,37 @@ describe('recipe import/export', () => { expect(result.error).toBeTruthy(); spy.mockRestore(); }); + + it('preserves valid toggle values', () => { + const op = OPERATIONS.find((o) => o.id === 'add')!; + const json = JSON.stringify({ + version: 1, + recipes: [{ id: 'r1', name: 'x', savedAt: 1, steps: [{ uid: 'u1', opId: 'add', args: [{ name: 'Key', type: 'toggleString', value: 'secret', toggleValue: 'Base64' }], disabled: false }] }], + }); + const result = importRecipes(json, [op]); + expect(result.imported).toBe(1); + expect(loadRecipes()[0]!.steps[0]!.args[0]!.toggleValue).toBe('Base64'); + }); + + it('resets out-of-range numeric values', () => { + const op = OPERATIONS.find((o) => o.id === 'to-hex')!; + const json = JSON.stringify({ + version: 1, + recipes: [{ id: 'r1', name: 'x', savedAt: 1, steps: [{ uid: 'u1', opId: 'to-hex', args: [{ name: 'Bytes per line', type: 'number', value: 99999 }], disabled: false }] }], + }); + const result = importRecipes(json, [op]); + expect(result.imported).toBe(1); + expect(loadRecipes()[0]!.steps[0]!.args[1]!.value).toBe(0); + }); + + it('drops recipes with unknown operation ids when operations are provided', () => { + const result = importRecipes(JSON.stringify({ version: 1, recipes: [{ id: 'r1', name: 'x', savedAt: 1, steps: [{ uid: 'u1', opId: 'nope', args: [], disabled: false }] }] }), OPERATIONS); + expect(result.imported).toBe(0); + expect(result.skipped).toBe(1); + }); + + it('rejects missing versions and raw arrays', () => { + expect(importRecipes(JSON.stringify({ recipes: [] })).error).toBeTruthy(); + expect(importRecipes(JSON.stringify([])).error).toBeTruthy(); + }); }); \ No newline at end of file diff --git a/src/lib/recipes.ts b/src/lib/recipes.ts index 57d9619..8d57a37 100644 --- a/src/lib/recipes.ts +++ b/src/lib/recipes.ts @@ -1,7 +1,6 @@ -import type { OperationArg, RecipeStep } from '../engine'; +import type { OperationArg, OperationDef, RecipeStep } from '../engine'; import type { ArgType } from '../engine/types'; import { randomId } from '../engine'; -import { getOperation } from '../engine/operations'; import { safeArgValue } from './share'; export interface SavedRecipe { @@ -28,15 +27,46 @@ function readArg(value: unknown): OperationArg | null { if (typeof arg.name !== 'string' || typeof arg.type !== 'string') return null; if (!ARG_TYPES.has(arg.type as ArgType)) return null; const type = arg.type as ArgType; - return { name: arg.name, type, value: safeArgValue(arg.value, fallbackFor(type)) }; + + const out: OperationArg = { + name: arg.name, + type, + value: safeArgValue(arg.value, fallbackFor(type)), + }; + + if (Array.isArray(arg.options) && arg.options.every((o) => typeof o === 'string')) { + out.options = arg.options; + } + if (arg.optionLabels && typeof arg.optionLabels === 'object' && !Array.isArray(arg.optionLabels)) { + const labels: Record = {}; + let ok = true; + for (const [k, v] of Object.entries(arg.optionLabels)) { + if (typeof v !== 'string') { + ok = false; + break; + } + labels[k] = v; + } + if (ok) out.optionLabels = labels; + } + if (Array.isArray(arg.toggleValues) && arg.toggleValues.every((v) => typeof v === 'string')) { + out.toggleValues = arg.toggleValues; + } + if (typeof arg.toggleValue === 'string') out.toggleValue = arg.toggleValue; + if (typeof arg.hint === 'string') out.hint = arg.hint; + if (typeof arg.min === 'number' && Number.isFinite(arg.min)) out.min = arg.min; + if (typeof arg.max === 'number' && Number.isFinite(arg.max)) out.max = arg.max; + + return out; } -function readStep(value: unknown): RecipeStep | null { +function readStep(value: unknown, operations: OperationDef[] = []): RecipeStep | null { if (typeof value !== 'object' || value === null) return null; const step = value as Partial; if (typeof step.opId !== 'string' || !Array.isArray(step.args)) return null; - const op = getOperation(step.opId); + const op = operations.find((o) => o.id === step.opId); + if (operations.length > 0 && !op) return null; const importedArgs = step.args; for (const raw of importedArgs) { @@ -52,9 +82,17 @@ function readStep(value: unknown): RecipeStep | null { let value = found ? safeArgValue(found.value, def.value) : def.value; if (def.type === 'option' && def.options && !def.options.includes(String(value))) value = def.value; if (def.type === 'toggleString' && def.toggleValues && !def.toggleValues.includes(String(value))) value = def.value; - if (def.type === 'number' && typeof value !== 'number') value = def.value; + if (def.type === 'number') { + if (typeof value !== 'number' || !Number.isFinite(value)) value = def.value; + if (def.min !== undefined && (value as number) < def.min) value = def.value; + if (def.max !== undefined && (value as number) > def.max) value = def.value; + } if (def.type === 'boolean' && typeof value !== 'boolean') value = def.value; - return { ...def, value }; + let toggleValue = def.toggleValue; + if (found && typeof found.toggleValue === 'string') { + if (!def.toggleValues || def.toggleValues.includes(found.toggleValue)) toggleValue = found.toggleValue; + } + return { ...def, value, toggleValue }; }); } else { args = []; @@ -73,7 +111,7 @@ function readStep(value: unknown): RecipeStep | null { }; } -function readRecipe(value: unknown): SavedRecipe | null { +function readRecipe(value: unknown, operations: OperationDef[] = []): SavedRecipe | null { if (typeof value !== 'object' || value === null) return null; const candidate = value as Partial; if (typeof candidate.id !== 'string' || typeof candidate.name !== 'string') return null; @@ -81,7 +119,7 @@ function readRecipe(value: unknown): SavedRecipe | null { const steps: RecipeStep[] = []; for (const rawStep of candidate.steps) { - const step = readStep(rawStep); + const step = readStep(rawStep, operations); if (!step) return null; steps.push(step); } @@ -122,7 +160,7 @@ export function exportRecipes(recipes: SavedRecipe[] = loadRecipes()): string { return JSON.stringify({ version: 1, recipes }, null, 2); } -export function importRecipes(raw: string): ImportResult { +export function importRecipes(raw: string, operations: OperationDef[] = []): ImportResult { let parsed: unknown; try { parsed = JSON.parse(raw); @@ -149,7 +187,7 @@ export function importRecipes(raw: string): ImportResult { let skipped = 0; for (const entry of list) { - const recipe = readRecipe(entry); + const recipe = readRecipe(entry, operations); if (!recipe) { skipped += 1; continue; From de495b020c90fd7c9e1e2f91c54720dba50bcfa3 Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Wed, 25 Nov 2026 02:39:45 +0530 Subject: [PATCH 05/10] fix: preserve toggleString values and validate toggle format separately --- src/lib/recipes.test.ts | 13 +++++++++++++ src/lib/recipes.ts | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/lib/recipes.test.ts b/src/lib/recipes.test.ts index b71e161..cfd5dd0 100644 --- a/src/lib/recipes.test.ts +++ b/src/lib/recipes.test.ts @@ -57,9 +57,22 @@ describe('recipe import/export', () => { }); const result = importRecipes(json, [op]); expect(result.imported).toBe(1); + expect(loadRecipes()[0]!.steps[0]!.args[0]!.value).toBe('secret'); expect(loadRecipes()[0]!.steps[0]!.args[0]!.toggleValue).toBe('Base64'); }); + it('preserves arbitrary toggleString values and resets invalid formats', () => { + const op = OPERATIONS.find((o) => o.id === 'add')!; + const json = JSON.stringify({ + version: 1, + recipes: [{ id: 'r2', name: 'x', savedAt: 1, steps: [{ uid: 'u1', opId: 'add', args: [{ name: 'Key', type: 'toggleString', value: 'my-secret-key', toggleValue: 'Nope' }], disabled: false }] }], + }); + const result = importRecipes(json, [op]); + expect(result.imported).toBe(1); + expect(loadRecipes()[0]!.steps[0]!.args[0]!.value).toBe('my-secret-key'); + expect(loadRecipes()[0]!.steps[0]!.args[0]!.toggleValue).toBe('Hex'); + }); + it('resets out-of-range numeric values', () => { const op = OPERATIONS.find((o) => o.id === 'to-hex')!; const json = JSON.stringify({ diff --git a/src/lib/recipes.ts b/src/lib/recipes.ts index 8d57a37..95278d9 100644 --- a/src/lib/recipes.ts +++ b/src/lib/recipes.ts @@ -81,7 +81,7 @@ function readStep(value: unknown, operations: OperationDef[] = []): RecipeStep | ) as Partial | undefined; let value = found ? safeArgValue(found.value, def.value) : def.value; if (def.type === 'option' && def.options && !def.options.includes(String(value))) value = def.value; - if (def.type === 'toggleString' && def.toggleValues && !def.toggleValues.includes(String(value))) value = def.value; + // toggleValues are format selections, not value constraints; keep the user value. if (def.type === 'number') { if (typeof value !== 'number' || !Number.isFinite(value)) value = def.value; if (def.min !== undefined && (value as number) < def.min) value = def.value; From 1cc1f106528069dacc060d9dbd5b50fae858c02b Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Wed, 25 Nov 2026 02:41:25 +0530 Subject: [PATCH 06/10] fix: revalidate saved recipes once operations load --- src/lib/recipes.ts | 10 ++++++++++ src/store/useStore.ts | 11 +++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/lib/recipes.ts b/src/lib/recipes.ts index 95278d9..4bb654e 100644 --- a/src/lib/recipes.ts +++ b/src/lib/recipes.ts @@ -160,6 +160,16 @@ export function exportRecipes(recipes: SavedRecipe[] = loadRecipes()): string { return JSON.stringify({ version: 1, recipes }, null, 2); } +export function normalizeRecipes(recipes: SavedRecipe[], operations: OperationDef[]): SavedRecipe[] { + const valid: SavedRecipe[] = []; + for (const recipe of recipes) { + const normalized = readRecipe(recipe, operations); + if (normalized) valid.push(normalized); + } + if (valid.length !== recipes.length) persist(valid); + return valid; +} + export function importRecipes(raw: string, operations: OperationDef[] = []): ImportResult { let parsed: unknown; try { diff --git a/src/store/useStore.ts b/src/store/useStore.ts index 2c616ea..5acc358 100644 --- a/src/store/useStore.ts +++ b/src/store/useStore.ts @@ -30,6 +30,7 @@ import { saveRecipe, importRecipes as importRecipesLib, exportRecipes as exportRecipesLib, + normalizeRecipes, type SavedRecipe, type ImportResult, } from '../lib/recipes'; @@ -130,7 +131,7 @@ interface State { saveCurrentRecipe: (name: string, steps?: RecipeStep[]) => void; loadSavedRecipe: (id: string) => void; removeSavedRecipe: (id: string) => void; - importRecipes: (raw: string) => ImportResult; + importRecipes: (raw: string, operations?: OperationDef[]) => ImportResult; exportRecipes: () => string; setPaneWidth: (pane: 'operations' | 'recipe', width: number) => void; @@ -347,7 +348,9 @@ export const useStore = create((set, get) => ({ loadOperations: async () => { if (get().operations.length > 0) return; - set({ operations: await listOperations() }); + const operations = await listOperations(); + set({ operations }); + set({ savedRecipes: normalizeRecipes(get().savedRecipes, operations) }); }, restoreFromUrl: async () => { @@ -721,8 +724,8 @@ export const useStore = create((set, get) => ({ set({ savedRecipes: deleteRecipe(id) }); }, - importRecipes: (raw) => { - const result = importRecipesLib(raw); + importRecipes: (raw, operations) => { + const result = importRecipesLib(raw, operations ?? get().operations); if (!result.error) set({ savedRecipes: loadRecipes() }); return result; }, From 6be1e0fa65f00c68fae01735b8adab5e385a50a4 Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Thu, 26 Nov 2026 00:10:27 +0530 Subject: [PATCH 07/10] fix: enforce operation-aware import validation and normalization persistence --- src/lib/recipes.test.ts | 46 +++++++++++++++++++++++++++++++++++++---- src/lib/recipes.ts | 25 ++++++++++++++++------ 2 files changed, 61 insertions(+), 10 deletions(-) diff --git a/src/lib/recipes.test.ts b/src/lib/recipes.test.ts index cfd5dd0..bef6a1d 100644 --- a/src/lib/recipes.test.ts +++ b/src/lib/recipes.test.ts @@ -1,6 +1,6 @@ // @vitest-environment happy-dom import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { importRecipes, exportRecipes, loadRecipes, saveRecipe } from './recipes'; +import { importRecipes, exportRecipes, loadRecipes, saveRecipe, normalizeRecipes } from './recipes'; import { OPERATIONS } from '../engine/operations'; describe('recipe import/export', () => { @@ -11,7 +11,7 @@ describe('recipe import/export', () => { saveRecipe('A', []); const json = exportRecipes(); localStorage.clear(); - const result = importRecipes(json); + const result = importRecipes(json, OPERATIONS); expect(result).toEqual({ imported: 1, skipped: 0 }); expect(loadRecipes()).toHaveLength(1); expect(loadRecipes()[0]!.name).toBe('A'); @@ -26,7 +26,7 @@ describe('recipe import/export', () => { it('skips duplicate ids without overwriting', () => { saveRecipe('A', []); const json = exportRecipes(); - const result = importRecipes(json); + const result = importRecipes(json, OPERATIONS); expect(result.imported).toBe(0); expect(result.skipped).toBe(1); expect(loadRecipes()).toHaveLength(1); @@ -44,7 +44,7 @@ describe('recipe import/export', () => { it('reports failure when storage write fails', () => { const spy = vi.spyOn(localStorage, 'setItem').mockImplementation(() => { throw new Error('no'); }); - const result = importRecipes(JSON.stringify({ version: 1, recipes: [{ id: 'b', name: 'B', steps: [] }] })); + const result = importRecipes(JSON.stringify({ version: 1, recipes: [{ id: 'b', name: 'B', steps: [] }] }), OPERATIONS); expect(result.error).toBeTruthy(); spy.mockRestore(); }); @@ -94,4 +94,42 @@ describe('recipe import/export', () => { expect(importRecipes(JSON.stringify({ recipes: [] })).error).toBeTruthy(); expect(importRecipes(JSON.stringify([])).error).toBeTruthy(); }); + + it('rejects import when the operation catalogue is unavailable', () => { + const result = importRecipes(JSON.stringify({ version: 1, recipes: [] })); + expect(result.error).toMatch(/catalogue/i); + }); + + it('persists normalized arguments even when the recipe count is unchanged', () => { + saveRecipe('A', [{ uid: 'u1', opId: 'to-hex', args: [{ name: 'Bytes per line', type: 'number', value: 99999 }], disabled: false }]); + const hex = OPERATIONS.find((o) => o.id === 'to-hex')!; + normalizeRecipes(loadRecipes(), [hex]); + expect(loadRecipes()[0]!.steps[0]!.args[1]!.value).toBe(0); + }); + + it('coerces wrong primitive types to operation defaults', () => { + const hex = OPERATIONS.find((o) => o.id === 'to-hex')!; + const add = OPERATIONS.find((o) => o.id === 'add')!; + const bech = OPERATIONS.find((o) => o.id === 'to-bech32')!; + const avro = OPERATIONS.find((o) => o.id === 'avro-to-json')!; + const json = JSON.stringify({ + version: 1, + recipes: [{ + id: 'r1', name: 'x', savedAt: 1, + steps: [ + { uid: 'u1', opId: 'to-hex', args: [{ name: 'Bytes per line', type: 'number', value: 'nope' }], disabled: false }, + { uid: 'u2', opId: 'add', args: [{ name: 'Key', type: 'toggleString', value: 123 }], disabled: false }, + { uid: 'u3', opId: 'to-bech32', args: [{ name: 'Human-readable part', type: 'string', value: 123 }], disabled: false }, + { uid: 'u4', opId: 'avro-to-json', args: [{ name: 'Include schema', type: 'boolean', value: 'yes' }], disabled: false }, + ], + }], + }); + const result = importRecipes(json, [hex, add, bech, avro]); + expect(result.imported).toBe(1); + const steps = loadRecipes()[0]!.steps; + expect(steps[0]!.args[1]!.value).toBe(0); + expect(steps[1]!.args[0]!.value).toBe(''); + expect(steps[2]!.args[0]!.value).toBe('bc'); + expect(steps[3]!.args[1]!.value).toBe(false); + }); }); \ No newline at end of file diff --git a/src/lib/recipes.ts b/src/lib/recipes.ts index 4bb654e..837a2c1 100644 --- a/src/lib/recipes.ts +++ b/src/lib/recipes.ts @@ -1,7 +1,6 @@ import type { OperationArg, OperationDef, RecipeStep } from '../engine'; import type { ArgType } from '../engine/types'; import { randomId } from '../engine'; -import { safeArgValue } from './share'; export interface SavedRecipe { id: string; @@ -21,6 +20,19 @@ function fallbackFor(type: ArgType): string | number | boolean { return ''; } +function normalizeValue( + type: ArgType, + value: unknown, + fallback: string | number | boolean, +): string | number | boolean { + if (type === 'string' || type === 'textarea' || type === 'toggleString' || type === 'option') { + return typeof value === 'string' ? value : fallback; + } + if (type === 'number') return typeof value === 'number' && Number.isFinite(value) ? value : fallback; + if (type === 'boolean') return typeof value === 'boolean' ? value : fallback; + return fallback; +} + function readArg(value: unknown): OperationArg | null { if (typeof value !== 'object' || value === null) return null; const arg = value as Partial; @@ -31,7 +43,7 @@ function readArg(value: unknown): OperationArg | null { const out: OperationArg = { name: arg.name, type, - value: safeArgValue(arg.value, fallbackFor(type)), + value: normalizeValue(type, arg.value, fallbackFor(type)), }; if (Array.isArray(arg.options) && arg.options.every((o) => typeof o === 'string')) { @@ -79,15 +91,13 @@ function readStep(value: unknown, operations: OperationDef[] = []): RecipeStep | const found = importedArgs.find( (a) => typeof a === 'object' && a !== null && (a as Partial).name === def.name, ) as Partial | undefined; - let value = found ? safeArgValue(found.value, def.value) : def.value; + let value = found ? normalizeValue(def.type, found.value, def.value) : def.value; if (def.type === 'option' && def.options && !def.options.includes(String(value))) value = def.value; // toggleValues are format selections, not value constraints; keep the user value. if (def.type === 'number') { - if (typeof value !== 'number' || !Number.isFinite(value)) value = def.value; if (def.min !== undefined && (value as number) < def.min) value = def.value; if (def.max !== undefined && (value as number) > def.max) value = def.value; } - if (def.type === 'boolean' && typeof value !== 'boolean') value = def.value; let toggleValue = def.toggleValue; if (found && typeof found.toggleValue === 'string') { if (!def.toggleValues || def.toggleValues.includes(found.toggleValue)) toggleValue = found.toggleValue; @@ -166,7 +176,9 @@ export function normalizeRecipes(recipes: SavedRecipe[], operations: OperationDe const normalized = readRecipe(recipe, operations); if (normalized) valid.push(normalized); } - if (valid.length !== recipes.length) persist(valid); + if (valid.length !== recipes.length || JSON.stringify(valid) !== JSON.stringify(recipes)) { + persist(valid); + } return valid; } @@ -189,6 +201,7 @@ export function importRecipes(raw: string, operations: OperationDef[] = []): Imp if (!list) return { imported: 0, skipped: 0, error: 'Expected a recipe list.' }; if (list.length > 1000) return { imported: 0, skipped: 0, error: 'Too many recipes in file.' }; + if (operations.length === 0) return { imported: 0, skipped: 0, error: 'Operation catalogue not loaded.' }; const existing = loadRecipes(); const existingIds = new Set(existing.map((r) => r.id)); From c0772f79a3e115f2fdd262128db583a0b0ea0784 Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Thu, 26 Nov 2026 00:13:21 +0530 Subject: [PATCH 08/10] test: cover import validation edge cases --- src/lib/recipes.test.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/lib/recipes.test.ts b/src/lib/recipes.test.ts index bef6a1d..249cc56 100644 --- a/src/lib/recipes.test.ts +++ b/src/lib/recipes.test.ts @@ -100,6 +100,21 @@ describe('recipe import/export', () => { expect(result.error).toMatch(/catalogue/i); }); + it('round-trips real operation steps with custom arguments', () => { + saveRecipe('Real', [ + { uid: 'u1', opId: 'add', args: [{ name: 'Key', type: 'toggleString', value: 'my-secret-key', toggleValue: 'Base64', toggleValues: ['UTF-8', 'Hex', 'Base64', 'Latin1', 'Decimal'] }], disabled: false }, + { uid: 'u2', opId: 'to-hex', args: [{ name: 'Bytes per line', type: 'number', value: 8, min: 0, max: 1024 }], disabled: false }, + ]); + const json = exportRecipes(); + localStorage.clear(); + const result = importRecipes(json, OPERATIONS); + expect(result.imported).toBe(1); + const steps = loadRecipes()[0]!.steps; + expect(steps[0]!.args[0]!.value).toBe('my-secret-key'); + expect(steps[0]!.args[0]!.toggleValue).toBe('Base64'); + expect(steps[1]!.args[1]!.value).toBe(8); + }); + it('persists normalized arguments even when the recipe count is unchanged', () => { saveRecipe('A', [{ uid: 'u1', opId: 'to-hex', args: [{ name: 'Bytes per line', type: 'number', value: 99999 }], disabled: false }]); const hex = OPERATIONS.find((o) => o.id === 'to-hex')!; @@ -112,6 +127,7 @@ describe('recipe import/export', () => { const add = OPERATIONS.find((o) => o.id === 'add')!; const bech = OPERATIONS.find((o) => o.id === 'to-bech32')!; const avro = OPERATIONS.find((o) => o.id === 'avro-to-json')!; + const template = OPERATIONS.find((o) => o.id === 'template')!; const json = JSON.stringify({ version: 1, recipes: [{ @@ -121,15 +137,17 @@ describe('recipe import/export', () => { { uid: 'u2', opId: 'add', args: [{ name: 'Key', type: 'toggleString', value: 123 }], disabled: false }, { uid: 'u3', opId: 'to-bech32', args: [{ name: 'Human-readable part', type: 'string', value: 123 }], disabled: false }, { uid: 'u4', opId: 'avro-to-json', args: [{ name: 'Include schema', type: 'boolean', value: 'yes' }], disabled: false }, + { uid: 'u5', opId: 'template', args: [{ name: 'Template', type: 'textarea', value: 42 }], disabled: false }, ], }], }); - const result = importRecipes(json, [hex, add, bech, avro]); + const result = importRecipes(json, [hex, add, bech, avro, template]); expect(result.imported).toBe(1); const steps = loadRecipes()[0]!.steps; expect(steps[0]!.args[1]!.value).toBe(0); expect(steps[1]!.args[0]!.value).toBe(''); expect(steps[2]!.args[0]!.value).toBe('bc'); expect(steps[3]!.args[1]!.value).toBe(false); + expect(steps[4]!.args[0]!.value).toBe(''); }); }); \ No newline at end of file From ea2f60ebdbdc5b0211aa885e61e86c40b1b92791 Mon Sep 17 00:00:00 2001 From: mannubaveja007 <23bis70088@cuchd.in> Date: Thu, 26 Nov 2026 00:41:38 +0530 Subject: [PATCH 09/10] fix: fail closed on empty catalogue and keep normalized recipes in sync --- src/components/ui/RecipeLibrary.tsx | 6 ++- src/lib/recipes.test.ts | 69 ++++++++++++++++++++++++++++- src/lib/recipes.ts | 15 ++++--- src/store/useStore.import.test.ts | 25 +++++++++++ src/store/useStore.ts | 1 + 5 files changed, 107 insertions(+), 9 deletions(-) create mode 100644 src/store/useStore.import.test.ts diff --git a/src/components/ui/RecipeLibrary.tsx b/src/components/ui/RecipeLibrary.tsx index 8ab9576..e734e97 100644 --- a/src/components/ui/RecipeLibrary.tsx +++ b/src/components/ui/RecipeLibrary.tsx @@ -98,7 +98,11 @@ export function RecipeLibrary() {