| 1 | import type { ProviderInstanceId } from "@t3tools/contracts"; |
| 2 | |
| 3 | const MODEL_KEY_PREFIX = "model:"; |
| 4 | const LEGACY_SECTION_KEY_PREFIX = "legacy-models:"; |
| 5 | |
| 6 | export function modelPickerModelKey(instanceId: ProviderInstanceId, slug: string): string { |
| 7 | return `${MODEL_KEY_PREFIX}${instanceId.length}:${instanceId}${slug}`; |
| 8 | } |
| 9 | |
| 10 | export function parseModelPickerModelKey( |
| 11 | key: string, |
| 12 | ): { instanceId: ProviderInstanceId; slug: string } | null { |
| 13 | if (!key.startsWith(MODEL_KEY_PREFIX)) { |
| 14 | return null; |
| 15 | } |
| 16 | const encoded = key.slice(MODEL_KEY_PREFIX.length); |
| 17 | const separatorIndex = encoded.indexOf(":"); |
| 18 | if (separatorIndex === -1) { |
| 19 | return null; |
| 20 | } |
| 21 | |
| 22 | const instanceIdLengthText = encoded.slice(0, separatorIndex); |
| 23 | if (!/^\d+$/.test(instanceIdLengthText)) { |
| 24 | return null; |
| 25 | } |
| 26 | |
| 27 | const instanceIdLength = Number(instanceIdLengthText); |
| 28 | const value = encoded.slice(separatorIndex + 1); |
| 29 | if (!Number.isSafeInteger(instanceIdLength) || instanceIdLength > value.length) { |
| 30 | return null; |
| 31 | } |
| 32 | |
| 33 | return { |
| 34 | instanceId: value.slice(0, instanceIdLength) as ProviderInstanceId, |
| 35 | slug: value.slice(instanceIdLength), |
| 36 | }; |
| 37 | } |
| 38 | |
| 39 | export function modelPickerLegacySectionKey(instanceId: ProviderInstanceId): string { |
| 40 | return `${LEGACY_SECTION_KEY_PREFIX}${instanceId}`; |
| 41 | } |
| 42 | |
| 43 | export function parseModelPickerLegacySectionKey(key: string): ProviderInstanceId | null { |
| 44 | return key.startsWith(LEGACY_SECTION_KEY_PREFIX) |
| 45 | ? (key.slice(LEGACY_SECTION_KEY_PREFIX.length) as ProviderInstanceId) |
| 46 | : null; |
| 47 | } |