Редактор: превью с поворотом, проекты, безопасное сохранение zip, dev-меню
RotatedImage: размер контейнера через clientWidth/Height (не getBoundingClientRect), чтобы cover при 90°/270° работал под zoom React Flow; убраны отладочные логи. Главное меню в dev: пункт «Вид» с DevTools (Ctrl+Shift+I без пустого application menu). Список проектов: project.list без лицензии; список подгружается при неактивной лицензии; ProjectPicker с подсказками; listProjects пропускает битые zip. Сохранение проектов: atomicReplace — замена zip без rm до commit; восстановление *.dnd.zip.tmp при старте; тесты. EditorApp: блокировка UI при открытых окнах презентации и пульта; стили оверлея. Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
import { readProjectJsonFromZip } from './yauzlProjectZip';
|
||||
|
||||
/**
|
||||
* Подменяет файл `finalPath` готовым `completedSrc` (обычно `*.dnd.zip.tmp`).
|
||||
* Нельзя сначала удалять `finalPath`: при сбое rename после rm проект теряется (Windows/антивирус).
|
||||
*/
|
||||
export async function replaceFileAtomic(completedSrc: string, finalPath: string): Promise<void> {
|
||||
if (completedSrc === finalPath) return;
|
||||
|
||||
const stSrc = await fs.stat(completedSrc).catch(() => null);
|
||||
if (!stSrc?.isFile() || stSrc.size === 0) {
|
||||
throw new Error(`replaceFileAtomic: нет или пустой источник: ${completedSrc}`);
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.rename(completedSrc, finalPath);
|
||||
return;
|
||||
} catch (first: unknown) {
|
||||
const c = (first as NodeJS.ErrnoException).code;
|
||||
if (c === 'EXDEV') {
|
||||
await fs.copyFile(completedSrc, finalPath);
|
||||
await fs.unlink(completedSrc).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
// Windows: чаще всего EEXIST — целевой файл есть, rename не перезаписывает; идём через backup ниже.
|
||||
}
|
||||
|
||||
const stFinal = await fs.stat(finalPath).catch(() => null);
|
||||
if (!stFinal?.isFile()) {
|
||||
try {
|
||||
await fs.rename(completedSrc, finalPath);
|
||||
return;
|
||||
} catch (again: unknown) {
|
||||
throw again instanceof Error ? again : new Error(String(again));
|
||||
}
|
||||
}
|
||||
|
||||
const backupPath = `${finalPath}.bak.${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
|
||||
await fs.rename(finalPath, backupPath);
|
||||
try {
|
||||
await fs.rename(completedSrc, finalPath);
|
||||
} catch (place: unknown) {
|
||||
await fs.rename(backupPath, finalPath).catch(() => undefined);
|
||||
throw place instanceof Error ? place : new Error(String(place));
|
||||
}
|
||||
await fs.unlink(backupPath).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** Если сохранение оборвалось, остаётся только `*.dnd.zip.tmp` — восстанавливаем в `*.dnd.zip`. */
|
||||
export async function recoverOrphanDndZipTmpInRoot(root: string): Promise<void> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fs.readdir(root);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const name of names) {
|
||||
if (!name.endsWith('.dnd.zip.tmp')) continue;
|
||||
const tmpPath = path.join(root, name);
|
||||
const finalName = name.slice(0, -'.tmp'.length);
|
||||
if (!finalName.endsWith('.dnd.zip')) continue;
|
||||
const finalPath = path.join(root, finalName);
|
||||
try {
|
||||
await fs.access(finalPath);
|
||||
continue;
|
||||
} catch {
|
||||
/* final отсутствует — пробуем поднять из tmp */
|
||||
}
|
||||
try {
|
||||
const st = await fs.stat(tmpPath);
|
||||
if (!st.isFile() || st.size < 22) continue;
|
||||
await readProjectJsonFromZip(tmpPath);
|
||||
await fs.rename(tmpPath, finalPath);
|
||||
} catch {
|
||||
/* битый tmp не трогаем */
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
import { replaceFileAtomic } from './atomicReplace';
|
||||
|
||||
void test('replaceFileAtomic: replaces existing file without deleting before rename succeeds', async () => {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-replace-'));
|
||||
const finalPath = path.join(dir, 'out.bin');
|
||||
const tmpPath = path.join(dir, 'out.bin.tmp');
|
||||
await fs.writeFile(finalPath, 'previous', 'utf8');
|
||||
await fs.writeFile(tmpPath, 'updated-content', 'utf8');
|
||||
await replaceFileAtomic(tmpPath, finalPath);
|
||||
assert.equal(await fs.readFile(finalPath, 'utf8'), 'updated-content');
|
||||
await assert.rejects(() => fs.stat(tmpPath));
|
||||
});
|
||||
|
||||
void test('replaceFileAtomic: rejects empty source', async () => {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-replace-'));
|
||||
const finalPath = path.join(dir, 'out.bin');
|
||||
const tmpPath = path.join(dir, 'out.bin.tmp');
|
||||
await fs.writeFile(finalPath, 'x', 'utf8');
|
||||
await fs.writeFile(tmpPath, '', 'utf8');
|
||||
await assert.rejects(() => replaceFileAtomic(tmpPath, finalPath));
|
||||
assert.equal(await fs.readFile(finalPath, 'utf8'), 'x');
|
||||
});
|
||||
@@ -45,3 +45,22 @@ void test('zipStore: normalizeScene defaults previewThumbAssetId for older proje
|
||||
assert.match(src, /previewThumbAssetId/);
|
||||
assert.match(src, /function normalizeScene\(/);
|
||||
});
|
||||
|
||||
void test('zipStore: listProjects skips unreadable archives', () => {
|
||||
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
|
||||
assert.match(
|
||||
src,
|
||||
/async listProjects[\s\S]+?for \(const filePath of files\)[\s\S]+?try \{[\s\S]+?readProjectJsonFromZip/,
|
||||
);
|
||||
});
|
||||
|
||||
void test('atomicReplace: replaceFileAtomic must not rm destination before successful commit', () => {
|
||||
const src = fs.readFileSync(path.join(here, 'atomicReplace.ts'), 'utf8');
|
||||
const i = src.indexOf('export async function replaceFileAtomic');
|
||||
assert.ok(i >= 0);
|
||||
const j = src.indexOf('export async function recoverOrphanDndZipTmpInRoot', i);
|
||||
assert.ok(j > i);
|
||||
const block = src.slice(i, j);
|
||||
assert.match(block, /rename\(finalPath, backupPath\)/);
|
||||
assert.doesNotMatch(block, /\.rm\(\s*finalPath/);
|
||||
});
|
||||
|
||||
@@ -24,6 +24,7 @@ import { asAssetId, asGraphNodeId, asProjectId } from '../../shared/types/ids';
|
||||
import { getAppSemanticVersion } from '../versionInfo';
|
||||
|
||||
import { reconcileAssetFiles } from './assetPrune';
|
||||
import { recoverOrphanDndZipTmpInRoot, replaceFileAtomic } from './atomicReplace';
|
||||
import { rmWithRetries } from './fsRetry';
|
||||
import { optimizeImageBufferVisuallyLossless } from './optimizeImageImport.lib.mjs';
|
||||
import { getLegacyProjectsRootDirs, getProjectsCacheRootDir, getProjectsRootDir } from './paths';
|
||||
@@ -75,6 +76,7 @@ export class ZipProjectStore {
|
||||
await fs.mkdir(getProjectsRootDir(), { recursive: true });
|
||||
await fs.mkdir(getProjectsCacheRootDir(), { recursive: true });
|
||||
await this.migrateLegacyProjectZipsIfNeeded();
|
||||
await recoverOrphanDndZipTmpInRoot(getProjectsRootDir());
|
||||
}
|
||||
|
||||
/** Копирует .dnd.zip из каталогов с «чужим» app name, если в текущем каталоге такого файла ещё нет. */
|
||||
@@ -135,13 +137,17 @@ export class ZipProjectStore {
|
||||
|
||||
const out: ProjectIndexEntry[] = [];
|
||||
for (const filePath of files) {
|
||||
const project = await readProjectJsonFromZip(filePath);
|
||||
out.push({
|
||||
id: project.id,
|
||||
name: project.meta.name,
|
||||
updatedAt: project.meta.updatedAt,
|
||||
fileName: path.basename(filePath),
|
||||
});
|
||||
try {
|
||||
const project = await readProjectJsonFromZip(filePath);
|
||||
out.push({
|
||||
id: project.id,
|
||||
name: project.meta.name,
|
||||
updatedAt: project.meta.updatedAt,
|
||||
fileName: path.basename(filePath),
|
||||
});
|
||||
} catch {
|
||||
// Один битый архив не должен скрывать остальные проекты в списке.
|
||||
}
|
||||
}
|
||||
out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||||
return out;
|
||||
@@ -868,6 +874,11 @@ export class ZipProjectStore {
|
||||
const tmpPath = `${zipPath}.tmp`;
|
||||
await fs.mkdir(path.dirname(zipPath), { recursive: true });
|
||||
await zipDir(cacheDir, tmpPath);
|
||||
const st = await fs.stat(tmpPath).catch(() => null);
|
||||
if (!st?.isFile() || st.size < 22) {
|
||||
await fs.unlink(tmpPath).catch(() => undefined);
|
||||
throw new Error('Сборка архива проекта не удалась (пустой или повреждённый временный файл)');
|
||||
}
|
||||
await replaceFileAtomic(tmpPath, zipPath);
|
||||
}
|
||||
|
||||
@@ -1226,20 +1237,6 @@ async function uniqueDndZipFileName(root: string, preferredBaseFileName: string)
|
||||
}
|
||||
}
|
||||
|
||||
async function replaceFileAtomic(srcPath: string, destPath: string): Promise<void> {
|
||||
try {
|
||||
await fs.rename(srcPath, destPath);
|
||||
} catch {
|
||||
try {
|
||||
await fs.rm(destPath, { force: true });
|
||||
await fs.rename(srcPath, destPath);
|
||||
} catch (second: unknown) {
|
||||
await fs.unlink(srcPath).catch(() => undefined);
|
||||
throw second instanceof Error ? second : new Error(String(second));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function copyFileWithProgress(
|
||||
src: string,
|
||||
dest: string,
|
||||
@@ -1339,17 +1336,7 @@ async function atomicWriteFile(filePath: string, contents: string): Promise<void
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
const tmp = path.join(dir, `.tmp_${path.basename(filePath)}_${crypto.randomBytes(8).toString('hex')}`);
|
||||
await fs.writeFile(tmp, contents, 'utf8');
|
||||
try {
|
||||
await fs.rename(tmp, filePath);
|
||||
} catch {
|
||||
try {
|
||||
await fs.rm(filePath, { force: true });
|
||||
await fs.rename(tmp, filePath);
|
||||
} catch (second: unknown) {
|
||||
await fs.unlink(tmp).catch(() => undefined);
|
||||
throw second instanceof Error ? second : new Error(String(second));
|
||||
}
|
||||
}
|
||||
await replaceFileAtomic(tmp, filePath);
|
||||
}
|
||||
|
||||
/** Уже сжатые контейнеры/кодеки — в ZIP кладём без deflate, качество не трогаем; project.json и сырьё — deflate 9. */
|
||||
|
||||
Reference in New Issue
Block a user