@storm-software/cloudflare-tools
Version:
A Nx plugin package that contains various executors, generators, and utilities that assist in managing Cloudflare services.
69 lines (66 loc) • 2.21 kB
JavaScript
import {
joinPaths,
writeDebug,
writeError,
writeWarning
} from "./chunk-OBUVLRI3.mjs";
// src/utils/r2-bucket-helpers.ts
import { Upload } from "@aws-sdk/lib-storage";
import { createHash } from "node:crypto";
import prettyBytes from "pretty-bytes";
async function uploadFile(client, bucketName, bucketPath, fileName, version, fileContent, contentType = "application/octet-stream", isDryRun = false) {
const key = (!bucketPath?.trim() || bucketPath?.trim() === "/" ? fileName : joinPaths(bucketPath.trim(), fileName))?.replace(/^\/+/g, "") || "";
writeDebug(
`Uploading ${key} (content-type: ${contentType}, size: ${prettyBytes(
Buffer.byteLength(fileContent, getEncoding(contentType))
)}) to the ${bucketName} R2 bucket`
);
try {
if (!isDryRun) {
const upload = new Upload({
client,
params: {
Bucket: bucketName,
Key: key,
Body: Buffer.from(fileContent, getEncoding(contentType)),
ContentType: contentType,
Metadata: {
version,
checksum: createHash("sha256").update(fileContent).digest("base64")
}
}
});
await upload.done();
} else {
writeWarning("[Dry run]: Skipping upload to the R2 bucket.");
}
} catch (error) {
writeError(`Failed to upload ${key} to the ${bucketName} R2 bucket.`);
throw error;
}
}
function getInternalDependencies(projectName, graph) {
const allDeps = graph.dependencies[projectName] ?? [];
return Array.from(
allDeps.reduce(
(acc, node) => {
const found = graph.nodes[node.target];
if (found) acc.push(found);
return acc;
},
[]
)
);
}
function isTextFile(mimeType) {
return mimeType.startsWith("text/") || mimeType === "application/json" || mimeType === "application/javascript" || mimeType === "application/xml" || mimeType === "application/x-yaml" || mimeType === "application/xhtml+xml" || mimeType === "application/x-httpd-php" || mimeType === "image/svg+xml";
}
function getEncoding(mimeType) {
return isTextFile(mimeType) ? "utf8" : "binary";
}
export {
uploadFile,
getInternalDependencies,
isTextFile,
getEncoding
};