100 lines
2.4 KiB
TypeScript
100 lines
2.4 KiB
TypeScript
import "server-only";
|
|
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { promises as fs } from "node:fs";
|
|
|
|
const PSD_LOCAL_CACHE_ROOT = path.join(
|
|
process.env.AGENT_PSD_LOCAL_CACHE_DIR || os.tmpdir(),
|
|
"agent-psd-cache"
|
|
);
|
|
|
|
function sanitizePathSegment(value: string, fallback: string) {
|
|
const normalized = String(value || "")
|
|
.trim()
|
|
.replace(/[^a-zA-Z0-9_-]/g, "-")
|
|
.replace(/-+/g, "-")
|
|
.replace(/^-+|-+$/g, "");
|
|
|
|
return normalized || fallback;
|
|
}
|
|
|
|
function normalizeTemplateExtension(fileName: string) {
|
|
const normalized = String(fileName || "").trim().toLowerCase();
|
|
if (normalized.endsWith(".psb")) {
|
|
return "psb";
|
|
}
|
|
return "psd";
|
|
}
|
|
|
|
function toBuffer(value: ArrayBuffer | Buffer) {
|
|
if (Buffer.isBuffer(value)) {
|
|
return value;
|
|
}
|
|
|
|
return Buffer.from(value);
|
|
}
|
|
|
|
export function resolveAgentPsdLocalCachePath(params: {
|
|
templateId: string;
|
|
fileName?: string | null;
|
|
}) {
|
|
const templateId = sanitizePathSegment(params.templateId, "template");
|
|
const extension = normalizeTemplateExtension(String(params.fileName || ""));
|
|
return path.join(PSD_LOCAL_CACHE_ROOT, `${templateId}.${extension}`);
|
|
}
|
|
|
|
export async function cacheAgentPsdSourceLocally(params: {
|
|
templateId: string;
|
|
fileName?: string | null;
|
|
buffer: ArrayBuffer | Buffer;
|
|
}) {
|
|
const localFilePath = resolveAgentPsdLocalCachePath({
|
|
templateId: params.templateId,
|
|
fileName: params.fileName,
|
|
});
|
|
await fs.mkdir(path.dirname(localFilePath), { recursive: true });
|
|
await fs.writeFile(localFilePath, toBuffer(params.buffer));
|
|
return localFilePath;
|
|
}
|
|
|
|
export async function readAgentPsdSourceFromLocalCache(params: {
|
|
templateId: string;
|
|
fileName?: string | null;
|
|
}) {
|
|
return fs.readFile(
|
|
resolveAgentPsdLocalCachePath({
|
|
templateId: params.templateId,
|
|
fileName: params.fileName,
|
|
})
|
|
);
|
|
}
|
|
|
|
export async function hasAgentPsdLocalCache(params: {
|
|
templateId: string;
|
|
fileName?: string | null;
|
|
}) {
|
|
try {
|
|
await fs.access(
|
|
resolveAgentPsdLocalCachePath({
|
|
templateId: params.templateId,
|
|
fileName: params.fileName,
|
|
})
|
|
);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function deleteAgentPsdLocalCache(params: {
|
|
templateId: string;
|
|
fileName?: string | null;
|
|
}) {
|
|
const localFilePath = resolveAgentPsdLocalCachePath({
|
|
templateId: params.templateId,
|
|
fileName: params.fileName,
|
|
});
|
|
await fs.rm(localFilePath, { force: true });
|
|
}
|