This repository has been archived on 2025-12-24. You can view files and clone it, but cannot push or open issues or pull requests.
site-template/packages/imagetoolsOSR/integration/utils/saveAndCopyAsset.js
2025-03-07 14:59:06 +01:00

42 lines
1.2 KiB
JavaScript

import fs from "node:fs/promises"
import { posix as path, join, resolve } from "node:path"
import { fsCachePath } from "../../utils/runtimeChecks.js";
//import { sync as copy } from "@polymech/fs/copy"
import { sync as exists } from "@polymech/fs/exists"
import { sync as mkdir } from "@polymech/fs/dir"
import { createLogger } from "@polymech/log"
const logger = createLogger("imagetools:integration")
const copied = [];
let assetsDirExists;
export async function saveAndCopyAsset(
hash,
image,
buffer,
outDir,
assetsDir,
assetPath,
isSsrBuild
) {
const src = resolve(join(fsCachePath,hash))
const dest = join(outDir, isSsrBuild ? "/client" : "", assetPath)
assetsDir = join(outDir, isSsrBuild ? "/client" : "/", assetsDir)
if (copied.includes(assetPath)) return
if(!exists(src)){
logger.error(`imagetools : saveAndCopyAsset : ${src} does not exist`)
return false
}
mkdir(assetsDir)
await fs.copyFile(src, dest).catch(async (error) => {
if (error.code === "ENOENT") {
const imageBuffer = buffer || (await image.toBuffer())
await Promise.all(
[src, dest].map(async (dir) => {
await fs.writeFile(dir, imageBuffer);
})
);
} else throw error;
})
copied.push(assetPath)
}