|
| 1 | +import { EDGE } from '@/executor/constants' |
| 2 | + |
| 3 | +/** |
| 4 | + * Remaps condition/router block IDs in a parsed conditions array. |
| 5 | + * Condition IDs use the format `{blockId}-{suffix}` and must be updated |
| 6 | + * when a block is duplicated to reference the new block ID. |
| 7 | + * |
| 8 | + * @param conditions - Parsed array of condition block objects with `id` fields |
| 9 | + * @param oldBlockId - The original block ID prefix to replace |
| 10 | + * @param newBlockId - The new block ID prefix |
| 11 | + * @returns Whether any IDs were changed (mutates in place) |
| 12 | + */ |
| 13 | +export function remapConditionBlockIds( |
| 14 | + conditions: Array<{ id: string; [key: string]: unknown }>, |
| 15 | + oldBlockId: string, |
| 16 | + newBlockId: string |
| 17 | +): boolean { |
| 18 | + let changed = false |
| 19 | + const prefix = `${oldBlockId}-` |
| 20 | + for (const condition of conditions) { |
| 21 | + if (typeof condition.id === 'string' && condition.id.startsWith(prefix)) { |
| 22 | + const suffix = condition.id.slice(prefix.length) |
| 23 | + condition.id = `${newBlockId}-${suffix}` |
| 24 | + changed = true |
| 25 | + } |
| 26 | + } |
| 27 | + return changed |
| 28 | +} |
| 29 | + |
| 30 | +/** Handle prefixes that embed block-scoped condition/route IDs */ |
| 31 | +const HANDLE_PREFIXES = [EDGE.CONDITION_PREFIX, EDGE.ROUTER_PREFIX] as const |
| 32 | + |
| 33 | +/** |
| 34 | + * Remaps a condition or router edge sourceHandle from the old block ID to the new one. |
| 35 | + * Handle formats: |
| 36 | + * - Condition: `condition-{blockId}-{suffix}` |
| 37 | + * - Router V2: `router-{blockId}-{suffix}` |
| 38 | + * |
| 39 | + * @returns The remapped handle string, or the original if no remapping needed |
| 40 | + */ |
| 41 | +export function remapConditionEdgeHandle( |
| 42 | + sourceHandle: string, |
| 43 | + oldBlockId: string, |
| 44 | + newBlockId: string |
| 45 | +): string { |
| 46 | + for (const handlePrefix of HANDLE_PREFIXES) { |
| 47 | + if (!sourceHandle.startsWith(handlePrefix)) continue |
| 48 | + |
| 49 | + const innerId = sourceHandle.slice(handlePrefix.length) |
| 50 | + if (!innerId.startsWith(`${oldBlockId}-`)) continue |
| 51 | + |
| 52 | + const suffix = innerId.slice(oldBlockId.length + 1) |
| 53 | + return `${handlePrefix}${newBlockId}-${suffix}` |
| 54 | + } |
| 55 | + |
| 56 | + return sourceHandle |
| 57 | +} |
0 commit comments