File size: 14,377 Bytes
6efa67a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
import fs from 'node:fs';
import path from 'node:path';
import _ from 'lodash';
import sanitize from 'sanitize-filename';
import { sync as writeFileAtomicSync } from 'write-file-atomic';
import { extractFileFromZipBuffer, extractFilesFromZipBuffer, normalizeZipEntryPath, ensureDirectory } from './util.js';
import { DEFAULT_AVATAR_PATH } from './constants.js';
// 'embeded://' is intentional - RisuAI exports use this misspelling
const CHARX_EMBEDDED_URI_PREFIXES = ['embeded://', 'embedded://', '__asset:'];
const CHARX_IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'webp', 'gif', 'apng', 'avif', 'bmp', 'jfif']);
const CHARX_SPRITE_TYPES = new Set(['emotion', 'expression']);
const CHARX_BACKGROUND_TYPES = new Set(['background']);
// ZIP local file header signature: PK\x03\x04
const ZIP_SIGNATURE = Buffer.from([0x50, 0x4B, 0x03, 0x04]);
/**
* Find ZIP data start in buffer (handles SFX/self-extracting archives).
* @param {Buffer} buffer
* @returns {Buffer} Buffer starting at ZIP signature, or original if not found
*/
function findZipStart(buffer) {
const buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
const index = buf.indexOf(ZIP_SIGNATURE);
if (index > 0) {
return buf.slice(index);
}
return buf;
}
/**
* @typedef {Object} CharXAsset
* @property {string} type - Asset type (emotion, expression, background, etc.)
* @property {string} name - Asset name from metadata
* @property {string} ext - File extension (lowercase, no dot)
* @property {string} zipPath - Normalized path within the ZIP archive
* @property {number} order - Original index in assets array
* @property {string} [storageCategory] - 'sprite' | 'background' | 'misc' (set by mapCharXAssetsForStorage)
* @property {string} [baseName] - Normalized filename base (set by mapCharXAssetsForStorage)
*/
/**
* @typedef {Object} CharXParseResult
* @property {Object} card - Parsed card.json (CCv2 or CCv3 spec)
* @property {string|Buffer} avatar - Avatar image buffer or DEFAULT_AVATAR_PATH
* @property {CharXAsset[]} auxiliaryAssets - Assets mapped for storage
* @property {Map<string, Buffer>} extractedBuffers - Map of zipPath to extracted buffer
*/
export class CharXParser {
#data;
/**
* @param {ArrayBuffer|Buffer} data
*/
constructor(data) {
// Handle SFX (self-extracting) ZIP archives by finding the actual ZIP start
this.#data = findZipStart(Buffer.isBuffer(data) ? data : Buffer.from(data));
}
/**
* Parse the CharX archive and extract card data and assets.
* @returns {Promise<CharXParseResult>}
*/
async parse() {
console.info('Importing from CharX');
const cardBuffer = await extractFileFromZipBuffer(this.#data, 'card.json');
if (!cardBuffer) {
throw new Error('Failed to extract card.json from CharX file');
}
const card = JSON.parse(cardBuffer.toString());
if (card.spec === undefined) {
throw new Error('Invalid CharX card file: missing spec field');
}
const embeddedAssets = this.collectCharXAssets(card);
const iconAsset = this.pickCharXIconAsset(embeddedAssets);
const auxiliaryAssets = this.mapCharXAssetsForStorage(embeddedAssets);
const archivePaths = new Set();
if (iconAsset?.zipPath) {
archivePaths.add(iconAsset.zipPath);
}
for (const asset of auxiliaryAssets) {
if (asset?.zipPath) {
archivePaths.add(asset.zipPath);
}
}
let extractedBuffers = new Map();
if (archivePaths.size > 0) {
extractedBuffers = await extractFilesFromZipBuffer(this.#data, [...archivePaths]);
}
/** @type {string|Buffer} */
let avatar = DEFAULT_AVATAR_PATH;
if (iconAsset?.zipPath) {
const iconBuffer = extractedBuffers.get(iconAsset.zipPath);
if (iconBuffer) {
avatar = iconBuffer;
}
}
return { card, avatar, auxiliaryAssets, extractedBuffers };
}
getEmbeddedZipPathFromUri(uri) {
if (typeof uri !== 'string') {
return null;
}
const trimmed = uri.trim();
if (!trimmed) {
return null;
}
const lower = trimmed.toLowerCase();
for (const prefix of CHARX_EMBEDDED_URI_PREFIXES) {
if (lower.startsWith(prefix)) {
const rawPath = trimmed.slice(prefix.length);
return normalizeZipEntryPath(rawPath);
}
}
return null;
}
/**
* Normalize extension string: lowercase, strip leading dot.
* @param {string} ext
* @returns {string}
*/
normalizeExtString(ext) {
if (typeof ext !== 'string') return '';
return ext.trim().toLowerCase().replace(/^\./, '');
}
/**
* Strip trailing image extension from asset name if present.
* Handles cases like "image.png" with ext "png" → "image" (avoids "image.png.png")
* @param {string} name - Asset name that may contain extension
* @param {string} expectedExt - The expected extension (lowercase, no dot)
* @returns {string} Name with trailing extension stripped if it matched
*/
stripTrailingImageExtension(name, expectedExt) {
if (!name || !expectedExt) return name;
const lower = name.toLowerCase();
// Check if name ends with the expected extension
if (lower.endsWith(`.${expectedExt}`)) {
return name.slice(0, -(expectedExt.length + 1));
}
// Also check for any known image extension at the end
for (const ext of CHARX_IMAGE_EXTENSIONS) {
if (lower.endsWith(`.${ext}`)) {
return name.slice(0, -(ext.length + 1));
}
}
return name;
}
deriveCharXAssetExtension(assetExt, zipPath) {
const metaExt = this.normalizeExtString(assetExt);
const pathExt = this.normalizeExtString(path.extname(zipPath || ''));
return metaExt || pathExt;
}
collectCharXAssets(card) {
const assets = _.get(card, 'data.assets');
if (!Array.isArray(assets)) {
return [];
}
return assets.map((asset, index) => {
if (!asset) {
return null;
}
const zipPath = this.getEmbeddedZipPathFromUri(asset.uri);
if (!zipPath) {
return null;
}
const ext = this.deriveCharXAssetExtension(asset.ext, zipPath);
const type = typeof asset.type === 'string' ? asset.type.toLowerCase() : '';
const name = typeof asset.name === 'string' ? asset.name : '';
return {
type,
name,
ext,
zipPath,
order: index,
};
}).filter(Boolean);
}
pickCharXIconAsset(assets) {
const iconAssets = assets.filter(asset => asset.type === 'icon' && CHARX_IMAGE_EXTENSIONS.has(asset.ext) && asset.zipPath);
if (iconAssets.length === 0) {
return null;
}
const mainIcon = iconAssets.find(asset => asset.name?.toLowerCase() === 'main');
return mainIcon || iconAssets[0];
}
/**
* Normalize asset name for filesystem storage.
* @param {string} name - Original asset name
* @param {string} fallback - Fallback name if normalization fails
* @param {boolean} useHyphens - Use hyphens instead of underscores (for sprites)
* @returns {string} Normalized filename base (without extension)
*/
getCharXAssetBaseName(name, fallback, useHyphens = false) {
const cleaned = (String(name ?? '').trim() || '');
if (!cleaned) {
return fallback.toLowerCase();
}
const separator = useHyphens ? '-' : '_';
// Convert to lowercase, collapse non-alphanumeric runs to separator, trim edges
const base = cleaned
.toLowerCase()
.replace(/[^a-z0-9]+/g, separator)
.replace(new RegExp(`^${separator}|${separator}$`, 'g'), '');
if (!base) {
return fallback.toLowerCase();
}
const sanitized = sanitize(base);
return (sanitized || fallback).toLowerCase();
}
mapCharXAssetsForStorage(assets) {
return assets.reduce((acc, asset) => {
if (!asset?.zipPath) {
return acc;
}
const ext = (asset.ext || '').toLowerCase();
if (!CHARX_IMAGE_EXTENSIONS.has(ext)) {
return acc;
}
if (asset.type === 'icon' || asset.type === 'user_icon') {
return acc;
}
let storageCategory;
if (CHARX_SPRITE_TYPES.has(asset.type)) {
storageCategory = 'sprite';
} else if (CHARX_BACKGROUND_TYPES.has(asset.type)) {
storageCategory = 'background';
} else {
storageCategory = 'misc';
}
// Use hyphens for sprites so ST's expression label extraction works correctly
// (sprites.js extracts label via regex that splits on dash or dot)
const useHyphens = storageCategory === 'sprite';
// Strip trailing extension from name if present (e.g., "image.png" with ext "png")
const nameWithoutExt = this.stripTrailingImageExtension(asset.name, ext);
acc.push({
...asset,
ext,
storageCategory,
baseName: this.getCharXAssetBaseName(nameWithoutExt, `${storageCategory}-${asset.order ?? 0}`, useHyphens),
});
return acc;
}, []);
}
}
/**
* Delete existing file with same base name (any extension) before overwriting.
* Matches ST's sprite upload behavior in sprites.js.
* @param {string} dirPath - Directory path
* @param {string} baseName - Base filename without extension
*/
function deleteExistingByBaseName(dirPath, baseName) {
try {
const files = fs.readdirSync(dirPath, { withFileTypes: true }).filter(f => f.isFile()).map(f => f.name);
for (const file of files) {
if (path.parse(file).name === baseName) {
fs.unlinkSync(path.join(dirPath, file));
}
}
} catch {
// Directory doesn't exist yet or other error, that's fine
}
}
/**
* Persist extracted CharX assets to appropriate ST directories.
* Note: Uses sync writes consistent with ST's existing file handling.
* @param {Array} assets - Mapped assets from CharXParser
* @param {Map<string, Buffer>} bufferMap - Extracted file buffers
* @param {Object} directories - User directories object
* @param {string} characterFolder - Character folder name (sanitized)
* @returns {{sprites: number, backgrounds: number, misc: number}}
*/
export function persistCharXAssets(assets, bufferMap, directories, characterFolder) {
/** @type {{sprites: number, backgrounds: number, misc: number}} */
const summary = { sprites: 0, backgrounds: 0, misc: 0 };
if (!Array.isArray(assets) || assets.length === 0) {
return summary;
}
let spritesPath = null;
let miscPath = null;
const ensureSpritesPath = () => {
if (spritesPath) {
return spritesPath;
}
const candidate = path.join(directories.characters, characterFolder);
if (!ensureDirectory(candidate)) {
return null;
}
spritesPath = candidate;
return spritesPath;
};
const ensureMiscPath = () => {
if (miscPath) {
return miscPath;
}
// Use the image gallery path: user/images/{characterName}/
const candidate = path.join(directories.userImages, characterFolder);
if (!ensureDirectory(candidate)) {
return null;
}
miscPath = candidate;
return miscPath;
};
for (const asset of assets) {
if (!asset?.zipPath) {
continue;
}
const buffer = bufferMap.get(asset.zipPath);
if (!buffer) {
console.warn(`CharX: Asset ${asset.zipPath} missing or unsupported, skipping.`);
continue;
}
try {
if (asset.storageCategory === 'sprite') {
const targetDir = ensureSpritesPath();
if (!targetDir) {
continue;
}
// Delete existing sprite with same base name (any extension) - matches sprites.js behavior
deleteExistingByBaseName(targetDir, asset.baseName);
const filePath = path.join(targetDir, `${asset.baseName}.${asset.ext || 'png'}`);
writeFileAtomicSync(filePath, buffer);
summary.sprites += 1;
continue;
}
if (asset.storageCategory === 'background') {
// Store in character-specific backgrounds folder: characters/{charName}/backgrounds/
const backgroundDir = path.join(directories.characters, characterFolder, 'backgrounds');
if (!ensureDirectory(backgroundDir)) {
continue;
}
// Delete existing background with same base name
deleteExistingByBaseName(backgroundDir, asset.baseName);
const fileName = `${asset.baseName}.${asset.ext || 'png'}`;
const filePath = path.join(backgroundDir, fileName);
writeFileAtomicSync(filePath, buffer);
summary.backgrounds += 1;
continue;
}
if (asset.storageCategory === 'misc') {
const miscDir = ensureMiscPath();
if (!miscDir) {
continue;
}
// Overwrite existing misc asset with same name
const filePath = path.join(miscDir, `${asset.baseName}.${asset.ext || 'png'}`);
writeFileAtomicSync(filePath, buffer);
summary.misc += 1;
}
} catch (error) {
console.warn(`CharX: Failed to save asset "${asset.name}": ${error.message}`);
}
}
return summary;
}
|