@nanggo/social-preview
Version:
Generate beautiful social media preview images from any URL
65 lines (64 loc) • 2.23 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCachedPreview = getCachedPreview;
exports.setCachedPreview = setCachedPreview;
const crypto_1 = __importDefault(require("crypto"));
const cache_1 = require("./cache");
function isPlainObject(value) {
if (!value || typeof value !== 'object')
return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function normalizeForCache(value) {
if (value === undefined) {
return undefined;
}
if (value === null || typeof value !== 'object') {
return value;
}
if (Array.isArray(value)) {
// Keep array length stable; `JSON.stringify` will convert `undefined` entries to `null`.
return value.map(normalizeForCache);
}
// Preserve non-plain objects so `JSON.stringify` can apply `toJSON` (e.g. Date -> ISO string).
if (!isPlainObject(value)) {
return value;
}
const record = value;
const output = {};
for (const key of Object.keys(record).sort()) {
const normalized = normalizeForCache(record[key]);
if (normalized === undefined)
continue;
output[key] = normalized;
}
return output;
}
function createPreviewCacheKey(url, options) {
try {
const optionsWithoutCache = { ...options };
delete optionsWithoutCache.cache;
const normalized = normalizeForCache({ url, options: optionsWithoutCache });
const serialized = JSON.stringify(normalized) ?? 'null';
return crypto_1.default.createHash('sha256').update(serialized).digest('hex');
}
catch {
return undefined;
}
}
function getCachedPreview(url, options) {
const key = createPreviewCacheKey(url, options);
if (!key)
return undefined;
return cache_1.previewCache.get(key);
}
function setCachedPreview(url, options, preview, ttlMs) {
const key = createPreviewCacheKey(url, options);
if (!key)
return;
cache_1.previewCache.set(key, preview, ttlMs);
}