A named path no longer moves another Rules file. Duplicate and Make a copy write their own copies of files they keep.
46 lines
1.4 KiB
TypeScript
46 lines
1.4 KiB
TypeScript
import { isValidUploadFileId } from "./uploadConstants";
|
|
|
|
const UPLOAD_PATH_RE =
|
|
/\/api\/uploads\/([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/gi;
|
|
|
|
function stringifyUnknown(value: unknown): string | null {
|
|
try {
|
|
return JSON.stringify(value ?? null);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** UUID stems referenced as `/api/uploads/{id}` inside JSON. */
|
|
export function extractUploadIdsFromUnknown(value: unknown): string[] {
|
|
const text = stringifyUnknown(value);
|
|
if (text == null) return [];
|
|
UPLOAD_PATH_RE.lastIndex = 0;
|
|
const ids = new Set<string>();
|
|
for (const match of text.matchAll(UPLOAD_PATH_RE)) {
|
|
const id = match[1]?.toLowerCase();
|
|
if (id && isValidUploadFileId(id)) ids.add(id);
|
|
}
|
|
return [...ids];
|
|
}
|
|
|
|
/** Rewrite `/api/uploads/{id}` paths using `replacements` (old id → new id). */
|
|
export function rewriteUploadIdsInUnknown(
|
|
value: unknown,
|
|
replacements: ReadonlyMap<string, string>,
|
|
): unknown {
|
|
if (replacements.size === 0) return value;
|
|
const text = stringifyUnknown(value);
|
|
if (text == null) return value;
|
|
UPLOAD_PATH_RE.lastIndex = 0;
|
|
const rewritten = text.replace(UPLOAD_PATH_RE, (full, id: string) => {
|
|
const next = replacements.get(id.toLowerCase());
|
|
return next ? `/api/uploads/${next}` : full;
|
|
});
|
|
try {
|
|
return JSON.parse(rewritten) as unknown;
|
|
} catch {
|
|
return value;
|
|
}
|
|
}
|