@reativ/wpbox 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +288 -2
  3. package/bin/wpbox.js +12 -0
  4. package/dist/backup/dump-analysis.js +44 -0
  5. package/dist/backup/import-files.js +50 -0
  6. package/dist/backup/layout.js +89 -0
  7. package/dist/backup/readers/archive-reader.js +16 -0
  8. package/dist/backup/readers/index.js +14 -0
  9. package/dist/backup/readers/tar-reader.js +42 -0
  10. package/dist/backup/readers/wpress-reader.js +76 -0
  11. package/dist/backup/readers/zip-reader.js +51 -0
  12. package/dist/backup/stage.js +128 -0
  13. package/dist/cli.js +61 -0
  14. package/dist/commands/database.js +22 -0
  15. package/dist/commands/init/analyze.js +24 -0
  16. package/dist/commands/init/index.js +73 -0
  17. package/dist/commands/init/questions.js +42 -0
  18. package/dist/commands/project.js +12 -0
  19. package/dist/commands/site.js +58 -0
  20. package/dist/docker/compose-file.js +110 -0
  21. package/dist/docker/compose.js +41 -0
  22. package/dist/docker/environment.js +35 -0
  23. package/dist/project/config.js +60 -0
  24. package/dist/project/gitignore.js +15 -0
  25. package/dist/project/paths.js +22 -0
  26. package/dist/project/secrets.js +29 -0
  27. package/dist/project/site-url.js +27 -0
  28. package/dist/remote/connect.js +17 -0
  29. package/dist/remote/download.js +70 -0
  30. package/dist/remote/ftp-fs.js +56 -0
  31. package/dist/remote/mirror.js +72 -0
  32. package/dist/remote/remote-database.js +103 -0
  33. package/dist/remote/remote-fs.js +1 -0
  34. package/dist/remote/sftp-fs.js +54 -0
  35. package/dist/remote/wordpress-locator.js +58 -0
  36. package/dist/sources/backup-source.js +1 -0
  37. package/dist/sources/index.js +36 -0
  38. package/dist/sources/local-source.js +32 -0
  39. package/dist/sources/remote-questions.js +71 -0
  40. package/dist/sources/remote-source.js +119 -0
  41. package/dist/sources/url-source.js +32 -0
  42. package/dist/ui/output.js +24 -0
  43. package/dist/ui/prompts.js +80 -0
  44. package/dist/utils/errors.js +6 -0
  45. package/dist/utils/exec.js +45 -0
  46. package/dist/utils/format.js +22 -0
  47. package/dist/utils/fs.js +88 -0
  48. package/dist/utils/result.js +2 -0
  49. package/dist/utils/work-queue.js +30 -0
  50. package/dist/wordpress/content.js +74 -0
  51. package/dist/wordpress/database.js +78 -0
  52. package/dist/wordpress/summary.js +30 -0
  53. package/dist/wordpress/url-replacements.js +23 -0
  54. package/package.json +62 -4
  55. package/templates/Dockerfile +26 -0
  56. package/templates/exporter.php +129 -0
  57. package/templates/local-entrypoint.sh +9 -0
  58. package/templates/mailpit.php +17 -0
@@ -0,0 +1,60 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ export const DEFAULT_DISABLED_PLUGINS = [
4
+ 'wps-hide-login',
5
+ 'google-site-kit',
6
+ 'cmp-coming-soon-maintenance',
7
+ 'coming-soon',
8
+ 'maintenance',
9
+ 'under-construction-page',
10
+ 'wordfence',
11
+ 'better-wp-security',
12
+ 'all-in-one-wp-security-and-firewall',
13
+ 'really-simple-ssl',
14
+ 'wp-rocket',
15
+ 'w3-total-cache',
16
+ 'wp-super-cache',
17
+ 'litespeed-cache',
18
+ 'wp-fastest-cache',
19
+ 'autoptimize',
20
+ 'jetpack',
21
+ ];
22
+ export function defaultConfig(root) {
23
+ return {
24
+ project: slugify(path.basename(root)) || 'site',
25
+ wordpressImage: 'php8.3-apache',
26
+ devCode: { themes: [], plugins: [] },
27
+ disablePlugins: DEFAULT_DISABLED_PLUGINS,
28
+ admin: { user: 'admin', password: 'admin', email: 'admin@local.test' },
29
+ database: { name: 'wordpress', user: 'wordpress', password: 'wordpress', rootPassword: 'root' },
30
+ };
31
+ }
32
+ export function isInitialized(config) {
33
+ return Boolean(config.local && config.production && config.source);
34
+ }
35
+ export function hasConfig(paths) {
36
+ return fs.existsSync(paths.config);
37
+ }
38
+ export function loadConfig(paths) {
39
+ const defaults = defaultConfig(paths.root);
40
+ if (!hasConfig(paths))
41
+ return defaults;
42
+ const saved = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
43
+ return {
44
+ ...defaults,
45
+ ...saved,
46
+ devCode: { ...defaults.devCode, ...saved.devCode },
47
+ admin: { ...defaults.admin, ...saved.admin },
48
+ database: { ...defaults.database, ...saved.database },
49
+ };
50
+ }
51
+ export function saveConfig(paths, config) {
52
+ fs.mkdirSync(paths.box, { recursive: true });
53
+ fs.writeFileSync(paths.config, `${JSON.stringify(config, null, 2)}\n`);
54
+ }
55
+ export function slugify(value) {
56
+ return value
57
+ .toLowerCase()
58
+ .replace(/[^a-z0-9]+/g, '-')
59
+ .replace(/^-+|-+$/g, '');
60
+ }
@@ -0,0 +1,15 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ const IGNORED_PATHS = ['.wpbox/', 'import/', 'dumps/', 'src/uploads/'];
4
+ const SECTION_HEADER = '# wpbox';
5
+ export function ensureGitignore(paths) {
6
+ const file = path.join(paths.root, '.gitignore');
7
+ const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
8
+ const existing = new Set(current.split(/\r?\n/).map((line) => line.trim()));
9
+ const missing = IGNORED_PATHS.filter((entry) => !existing.has(entry));
10
+ if (missing.length === 0)
11
+ return;
12
+ const separator = current && !current.endsWith('\n') ? '\n' : '';
13
+ const header = existing.has(SECTION_HEADER) ? '' : `${SECTION_HEADER}\n`;
14
+ fs.writeFileSync(file, `${current}${separator}${header}${missing.join('\n')}\n`);
15
+ }
@@ -0,0 +1,22 @@
1
+ import path from 'node:path';
2
+ export function projectPaths(root = process.cwd()) {
3
+ const box = path.join(root, '.wpbox');
4
+ const stage = path.join(box, 'stage');
5
+ return {
6
+ root,
7
+ import: path.join(root, 'import'),
8
+ srcThemes: path.join(root, 'src', 'themes'),
9
+ srcPlugins: path.join(root, 'src', 'plugins'),
10
+ srcUploads: path.join(root, 'src', 'uploads'),
11
+ dumps: path.join(root, 'dumps'),
12
+ box,
13
+ config: path.join(box, 'config.json'),
14
+ secrets: path.join(box, 'secrets.json'),
15
+ compose: path.join(box, 'compose.yaml'),
16
+ dockerContext: path.join(box, 'docker'),
17
+ stage,
18
+ stagedContent: path.join(stage, 'wp-content'),
19
+ stagedDump: path.join(stage, 'database.sql'),
20
+ mirror: path.join(box, 'mirror', 'wp-content'),
21
+ };
22
+ }
@@ -0,0 +1,29 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ export class SecretStore {
4
+ file;
5
+ secrets;
6
+ constructor(file) {
7
+ this.file = file;
8
+ this.secrets = SecretStore.read(file);
9
+ }
10
+ get(key) {
11
+ return this.secrets[key];
12
+ }
13
+ has(key) {
14
+ return key in this.secrets;
15
+ }
16
+ set(key, value) {
17
+ this.secrets[key] = value;
18
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
19
+ fs.writeFileSync(this.file, `${JSON.stringify(this.secrets, null, 2)}\n`, { mode: 0o600 });
20
+ }
21
+ static read(file) {
22
+ try {
23
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
24
+ }
25
+ catch {
26
+ return {};
27
+ }
28
+ }
29
+ }
@@ -0,0 +1,27 @@
1
+ import { fail, ok } from '../utils/result.js';
2
+ export function parseSiteUrl(input) {
3
+ let url;
4
+ try {
5
+ url = new URL(input);
6
+ }
7
+ catch {
8
+ return fail('Not a valid URL (e.g. http://localhost:8090)');
9
+ }
10
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
11
+ return fail('Must start with http:// or https://');
12
+ if (url.pathname !== '/' || url.search || url.hash)
13
+ return fail("Can't contain a path (e.g. http://localhost:8090)");
14
+ const https = url.protocol === 'https:';
15
+ return ok({
16
+ url: `${url.protocol}//${url.host}`,
17
+ host: url.hostname,
18
+ port: url.port ? Number(url.port) : https ? 443 : 80,
19
+ https,
20
+ });
21
+ }
22
+ export function hostOf(siteUrl) {
23
+ return new URL(siteUrl).hostname;
24
+ }
25
+ export function isLoopbackHost(host) {
26
+ return host === 'localhost' || host === '127.0.0.1' || host.endsWith('.localhost');
27
+ }
@@ -0,0 +1,17 @@
1
+ import { UserError } from '../utils/errors.js';
2
+ import { FtpFileSystem } from './ftp-fs.js';
3
+ import { SftpFileSystem } from './sftp-fs.js';
4
+ export async function connect(options) {
5
+ try {
6
+ return options.protocol === 'sftp' ? await SftpFileSystem.connect(options) : await FtpFileSystem.connect(options);
7
+ }
8
+ catch (error) {
9
+ const reason = error instanceof Error ? error.message : String(error);
10
+ throw new UserError(`Could not connect to ${options.protocol.toUpperCase()} ${options.host}: ${reason}`);
11
+ }
12
+ }
13
+ export async function connectPool(options, first, size) {
14
+ const extra = await Promise.allSettled(Array.from({ length: size - 1 }, () => connect(options)));
15
+ const connected = extra.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []));
16
+ return [first, ...connected];
17
+ }
@@ -0,0 +1,70 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Readable } from 'node:stream';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import { countBytes } from '../backup/readers/archive-reader.js';
6
+ import { UserError } from '../utils/errors.js';
7
+ const DOWNLOADABLE = /\.(zip|gz|tgz|tar|wpress|sql)$/i;
8
+ export function directDownloadUrl(input) {
9
+ const url = new URL(input);
10
+ if (/(^|\.)dropbox\.com$/.test(url.hostname)) {
11
+ url.searchParams.set('dl', '1');
12
+ return url.toString();
13
+ }
14
+ const driveFileId = url.hostname === 'drive.google.com' ? url.pathname.match(/\/file\/d\/([^/]+)/)?.[1] : undefined;
15
+ if (driveFileId)
16
+ return `https://drive.usercontent.google.com/download?id=${driveFileId}&export=download&confirm=t`;
17
+ return url.toString();
18
+ }
19
+ export function fileNameFromResponse(response, requestedUrl) {
20
+ const disposition = response.headers.get('content-disposition') ?? '';
21
+ const encoded = disposition.match(/filename\*\s*=\s*(?:UTF-8'')?([^;]+)/i)?.[1];
22
+ const plain = disposition.match(/filename\s*=\s*"?([^";]+)"?/i)?.[1];
23
+ const fromUrl = path.posix.basename(new URL(response.url || requestedUrl).pathname);
24
+ const name = encoded ? decodeURIComponent(encoded.trim().replace(/^"|"$/g, '')) : (plain ?? decodeURIComponent(fromUrl));
25
+ return name.replace(/[/\\?%*:|"<>]/g, '_').trim() || 'download';
26
+ }
27
+ export async function download(input, targetDir, onProgress) {
28
+ const { url, headers } = withBasicAuth(new URL(directDownloadUrl(input)));
29
+ const response = await fetchOrExplain(url, headers);
30
+ const fileName = fileNameFromResponse(response, url.toString());
31
+ assertIsFile(response, fileName);
32
+ fs.mkdirSync(targetDir, { recursive: true });
33
+ const target = path.join(targetDir, fileName);
34
+ const partial = `${target}.part`;
35
+ const total = Number(response.headers.get('content-length')) || 0;
36
+ let done = 0;
37
+ await pipeline(Readable.fromWeb(response.body), countBytes((bytes) => onProgress?.((done += bytes), total, fileName)), fs.createWriteStream(partial));
38
+ fs.renameSync(partial, target);
39
+ return target;
40
+ }
41
+ function withBasicAuth(url) {
42
+ const headers = { 'User-Agent': 'wpbox' };
43
+ if (url.username || url.password) {
44
+ const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
45
+ headers.Authorization = `Basic ${Buffer.from(credentials).toString('base64')}`;
46
+ url.username = '';
47
+ url.password = '';
48
+ }
49
+ return { url, headers };
50
+ }
51
+ async function fetchOrExplain(url, headers) {
52
+ let response;
53
+ try {
54
+ response = await fetch(url, { headers, redirect: 'follow' });
55
+ }
56
+ catch (error) {
57
+ const reason = error instanceof Error ? (error.cause?.message ?? error.message) : String(error);
58
+ throw new UserError(`Could not reach ${url.host}: ${reason}`);
59
+ }
60
+ if (!response.ok || !response.body) {
61
+ throw new UserError(`Download failed: HTTP ${response.status} ${response.statusText} (${url.host})`);
62
+ }
63
+ return response;
64
+ }
65
+ function assertIsFile(response, fileName) {
66
+ const isWebPage = response.headers.get('content-type')?.includes('text/html');
67
+ if (isWebPage && !DOWNLOADABLE.test(fileName)) {
68
+ throw new UserError('The URL returned a web page instead of a file. Use a direct download link.');
69
+ }
70
+ }
@@ -0,0 +1,56 @@
1
+ import { Readable } from 'node:stream';
2
+ import * as ftp from 'basic-ftp';
3
+ const TIMEOUT_MS = 30_000;
4
+ export class FtpFileSystem {
5
+ client;
6
+ encrypted;
7
+ constructor(client, encrypted) {
8
+ this.client = client;
9
+ this.encrypted = encrypted;
10
+ }
11
+ static async connect(options) {
12
+ const access = {
13
+ host: options.host,
14
+ port: options.port,
15
+ user: options.user,
16
+ password: options.password,
17
+ };
18
+ const secureClient = new ftp.Client(TIMEOUT_MS);
19
+ try {
20
+ await secureClient.access({ ...access, secure: true, secureOptions: { rejectUnauthorized: false } });
21
+ return new FtpFileSystem(secureClient, true);
22
+ }
23
+ catch {
24
+ secureClient.close();
25
+ }
26
+ const plainClient = new ftp.Client(TIMEOUT_MS);
27
+ await plainClient.access({ ...access, secure: false });
28
+ return new FtpFileSystem(plainClient, false);
29
+ }
30
+ async list(dir) {
31
+ const items = await this.client.list(dir);
32
+ return items
33
+ .filter((item) => item.name !== '.' && item.name !== '..' && (item.isFile || item.isDirectory))
34
+ .map((item) => ({
35
+ name: item.name,
36
+ isDirectory: item.isDirectory,
37
+ size: item.size,
38
+ modifiedAt: item.modifiedAt?.getTime() ?? null,
39
+ }));
40
+ }
41
+ async download(remotePath, localPath) {
42
+ await this.client.downloadTo(localPath, remotePath);
43
+ }
44
+ async upload(content, remotePath) {
45
+ await this.client.uploadFrom(Readable.from([Buffer.from(content)]), remotePath);
46
+ }
47
+ async remove(remotePath) {
48
+ await this.client.remove(remotePath);
49
+ }
50
+ workingDirectory() {
51
+ return this.client.pwd();
52
+ }
53
+ async close() {
54
+ this.client.close();
55
+ }
56
+ }
@@ -0,0 +1,72 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { toLocalPath, walkFiles } from '../utils/fs.js';
4
+ import { processQueue } from '../utils/work-queue.js';
5
+ import { connectPool } from './connect.js';
6
+ const MTIME_TOLERANCE_MS = 2000;
7
+ export async function mirror(options) {
8
+ const pool = await connectPool(options.connection, options.client, options.concurrency ?? 4);
9
+ try {
10
+ const remoteFiles = await scanRemote(pool, options);
11
+ const changed = remoteFiles.filter((file) => !isUpToDate(file, options.localRoot));
12
+ await downloadAll(pool, changed, options);
13
+ const removed = removeDeleted(remoteFiles, options);
14
+ return { files: remoteFiles.length, downloaded: changed.length, removed };
15
+ }
16
+ finally {
17
+ await Promise.all(pool.slice(1).map((client) => client.close()));
18
+ }
19
+ }
20
+ async function scanRemote(pool, options) {
21
+ const files = [];
22
+ const folders = [''];
23
+ let scanned = 0;
24
+ await processQueue(pool, folders, async (client, folder) => {
25
+ for (const entry of await client.list(path.posix.join(options.remoteRoot, folder))) {
26
+ const relativePath = folder ? `${folder}/${entry.name}` : entry.name;
27
+ if (options.exclude(relativePath))
28
+ continue;
29
+ if (entry.isDirectory)
30
+ folders.push(relativePath);
31
+ else
32
+ files.push({ path: relativePath, size: entry.size, modifiedAt: entry.modifiedAt });
33
+ }
34
+ options.onProgress?.({ phase: 'scan', folders: ++scanned, files: files.length });
35
+ });
36
+ return files;
37
+ }
38
+ function isUpToDate(file, localRoot) {
39
+ try {
40
+ const local = fs.statSync(toLocalPath(localRoot, file.path));
41
+ const sameTime = file.modifiedAt === null || Math.abs(local.mtimeMs - file.modifiedAt) < MTIME_TOLERANCE_MS;
42
+ return local.size === file.size && sameTime;
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ async function downloadAll(pool, files, options) {
49
+ const totalBytes = files.reduce((sum, file) => sum + file.size, 0);
50
+ let done = 0;
51
+ let bytes = 0;
52
+ await processQueue(pool, [...files], async (client, file) => {
53
+ const target = toLocalPath(options.localRoot, file.path);
54
+ fs.mkdirSync(path.dirname(target), { recursive: true });
55
+ await client.download(path.posix.join(options.remoteRoot, file.path), target);
56
+ if (file.modifiedAt !== null)
57
+ fs.utimesSync(target, new Date(), new Date(file.modifiedAt));
58
+ bytes += file.size;
59
+ options.onProgress?.({ phase: 'download', done: ++done, total: files.length, bytes, totalBytes });
60
+ });
61
+ }
62
+ function removeDeleted(remoteFiles, options) {
63
+ const remote = new Set(remoteFiles.map((file) => file.path));
64
+ let removed = 0;
65
+ for (const relativePath of walkFiles(options.localRoot)) {
66
+ if (remote.has(relativePath) || options.exclude(relativePath))
67
+ continue;
68
+ fs.rmSync(toLocalPath(options.localRoot, relativePath), { force: true });
69
+ removed++;
70
+ }
71
+ return removed;
72
+ }
@@ -0,0 +1,103 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { Readable } from 'node:stream';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { countBytes } from '../backup/readers/archive-reader.js';
8
+ import { UserError } from '../utils/errors.js';
9
+ import { CommandError, run } from '../utils/exec.js';
10
+ const MARIADB_IMAGE = 'mariadb:11.4';
11
+ const EXPORTER_TEMPLATE = fileURLToPath(new URL('../../templates/exporter.php', import.meta.url));
12
+ const EXPORT_COMPLETE_MARKER = '-- wpbox export complete';
13
+ const TLS_ATTEMPTS = [['--ssl', '--skip-ssl-verify-server-cert'], ['--skip-ssl']];
14
+ const LOCAL_HOSTS = new Set(['', 'localhost', '127.0.0.1', '::1']);
15
+ export function parseDbHost(value, fallbackHost) {
16
+ const raw = value || 'localhost';
17
+ const withPort = raw.match(/^(.*):(\d+)$/);
18
+ const host = withPort ? withPort[1] : raw.split(':/')[0];
19
+ const port = withPort ? Number(withPort[2]) : 3306;
20
+ return { host: LOCAL_HOSTS.has(host) ? fallbackHost : host, port };
21
+ }
22
+ export async function dumpRemoteMysql(credentials, targetDir) {
23
+ fs.mkdirSync(targetDir, { recursive: true });
24
+ let lastError = '';
25
+ for (const tlsFlags of TLS_ATTEMPTS) {
26
+ try {
27
+ await runInMariadbContainer(dumpScript(credentials, tlsFlags), credentials.password, targetDir);
28
+ return path.join(targetDir, 'database.sql');
29
+ }
30
+ catch (error) {
31
+ lastError = error instanceof CommandError ? error.result.stderr.trim() : String(error);
32
+ if (!/SSL|TLS/i.test(lastError))
33
+ break;
34
+ }
35
+ }
36
+ throw new UserError(`Could not dump the remote database: ${lastError.split('\n').slice(-2).join(' ')}`);
37
+ }
38
+ export async function exportWithTemporaryScript(client, wordpressRoot, siteUrl, targetDir, onBytes) {
39
+ const token = crypto.randomBytes(24).toString('hex');
40
+ const scriptName = `wpbox-export-${crypto.randomBytes(6).toString('hex')}.php`;
41
+ const remoteScript = path.posix.join(wordpressRoot, scriptName);
42
+ const target = path.join(targetDir, 'database.sql');
43
+ fs.mkdirSync(targetDir, { recursive: true });
44
+ await client.upload(fs.readFileSync(EXPORTER_TEMPLATE, 'utf8').replace('__WPBOX_TOKEN__', token), remoteScript);
45
+ try {
46
+ const exportUrl = `${siteUrl.replace(/\/+$/, '')}/${scriptName}?token=${token}`;
47
+ await downloadExport(exportUrl, siteUrl, target, onBytes);
48
+ }
49
+ finally {
50
+ await client.remove(remoteScript).catch(() => undefined);
51
+ }
52
+ if (!readTail(target, 200).includes(EXPORT_COMPLETE_MARKER)) {
53
+ throw new UserError('The database export was cut short (server timeout or PHP error). Try the direct MySQL option.');
54
+ }
55
+ return target;
56
+ }
57
+ function dumpScript(credentials, tlsFlags) {
58
+ const connection = ['-h', credentials.host, '-P', String(credentials.port), '-u', credentials.user, ...tlsFlags]
59
+ .map(shellQuote)
60
+ .join(' ');
61
+ const likePrefix = `${credentials.tablePrefix.replace(/[\\_%]/g, (character) => `\\${character}`)}%`;
62
+ const database = shellQuote(credentials.name);
63
+ return [
64
+ 'set -e',
65
+ `tables=$(mariadb ${connection} --connect-timeout=15 -N -B -e ${shellQuote(`SHOW TABLES LIKE '${likePrefix}'`)} ${database})`,
66
+ '[ -n "$tables" ] || { echo "No tables with this prefix" >&2; exit 3; }',
67
+ `mariadb-dump ${connection} --single-transaction --quick --no-tablespaces --skip-lock-tables --hex-blob --default-character-set=utf8mb4 ${database} $tables > /out/database.sql`,
68
+ ].join('\n');
69
+ }
70
+ function runInMariadbContainer(script, password, outputDir) {
71
+ return run('docker', ['run', '--rm', '-e', 'MYSQL_PWD', '-v', `${outputDir}:/out`, '--entrypoint', 'sh', MARIADB_IMAGE, '-c', script], { env: { MYSQL_PWD: password } });
72
+ }
73
+ async function downloadExport(url, siteUrl, target, onBytes) {
74
+ let response;
75
+ try {
76
+ response = await fetch(url, { headers: { 'User-Agent': 'wpbox' }, redirect: 'follow' });
77
+ }
78
+ catch (error) {
79
+ throw new UserError(`Could not reach ${siteUrl}: ${error instanceof Error ? error.message : String(error)}`);
80
+ }
81
+ if (!response.ok || !response.body) {
82
+ const body = (await response.text().catch(() => '')).slice(0, 300);
83
+ const reason = body.startsWith('wpbox:') ? body : 'Is the public site URL right?';
84
+ throw new UserError(`The export script answered HTTP ${response.status}. ${reason}`);
85
+ }
86
+ let total = 0;
87
+ await pipeline(Readable.fromWeb(response.body), countBytes((bytes) => onBytes((total += bytes))), fs.createWriteStream(target));
88
+ }
89
+ function readTail(file, length) {
90
+ const handle = fs.openSync(file, 'r');
91
+ try {
92
+ const size = fs.fstatSync(handle).size;
93
+ const buffer = Buffer.alloc(Math.min(length, size));
94
+ fs.readSync(handle, buffer, 0, buffer.length, size - buffer.length);
95
+ return buffer.toString('utf8');
96
+ }
97
+ finally {
98
+ fs.closeSync(handle);
99
+ }
100
+ }
101
+ function shellQuote(value) {
102
+ return `'${value.replace(/'/g, `'\\''`)}'`;
103
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,54 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import SftpClient from 'ssh2-sftp-client';
4
+ const TIMEOUT_MS = 30_000;
5
+ export class SftpFileSystem {
6
+ client;
7
+ encrypted = true;
8
+ constructor(client) {
9
+ this.client = client;
10
+ }
11
+ static async connect(options) {
12
+ const client = new SftpClient();
13
+ await client.connect({
14
+ host: options.host,
15
+ port: options.port,
16
+ username: options.user,
17
+ readyTimeout: TIMEOUT_MS,
18
+ ...credentials(options),
19
+ });
20
+ return new SftpFileSystem(client);
21
+ }
22
+ async list(dir) {
23
+ const items = await this.client.list(dir);
24
+ return items
25
+ .filter((item) => item.type === 'd' || item.type === '-')
26
+ .map((item) => ({
27
+ name: item.name,
28
+ isDirectory: item.type === 'd',
29
+ size: item.size,
30
+ modifiedAt: item.modifyTime || null,
31
+ }));
32
+ }
33
+ async download(remotePath, localPath) {
34
+ await this.client.fastGet(remotePath, localPath);
35
+ }
36
+ async upload(content, remotePath) {
37
+ await this.client.put(Buffer.from(content), remotePath);
38
+ }
39
+ async remove(remotePath) {
40
+ await this.client.delete(remotePath);
41
+ }
42
+ workingDirectory() {
43
+ return this.client.cwd();
44
+ }
45
+ async close() {
46
+ await this.client.end();
47
+ }
48
+ }
49
+ function credentials(options) {
50
+ if (!options.privateKey)
51
+ return { password: options.password ?? '' };
52
+ const keyPath = options.privateKey.replace(/^~(?=$|[/\\])/, os.homedir());
53
+ return { privateKey: fs.readFileSync(keyPath), passphrase: options.password || undefined };
54
+ }
@@ -0,0 +1,58 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ const WEB_ROOT_NAMES = ['', 'public_html', 'httpdocs', 'htdocs', 'www', 'html', 'web', 'public', 'wordpress', 'site'];
5
+ const SERVER_WEB_ROOTS = ['/var/www', '/var/www/html', '/var/www/public_html', '/var/www/htdocs'];
6
+ export async function findWordPressInstalls(client) {
7
+ const home = await client.workingDirectory().catch(() => '/');
8
+ const candidates = new Set([
9
+ ...WEB_ROOT_NAMES.map((name) => path.posix.join(home, name)),
10
+ ...SERVER_WEB_ROOTS,
11
+ ...(await domainWebRoots(client, home)),
12
+ ]);
13
+ const installs = [];
14
+ for (const dir of candidates) {
15
+ const install = await inspectFolder(client, dir);
16
+ if (install)
17
+ installs.push(install);
18
+ }
19
+ return installs;
20
+ }
21
+ export async function readRemoteFile(client, remotePath) {
22
+ const temporary = path.join(os.tmpdir(), `wpbox-${process.pid}-${Date.now()}`);
23
+ try {
24
+ await client.download(remotePath, temporary);
25
+ return fs.readFileSync(temporary, 'utf8');
26
+ }
27
+ finally {
28
+ fs.rmSync(temporary, { force: true });
29
+ }
30
+ }
31
+ export function parseWpConfig(php) {
32
+ const constant = (name) => php.match(new RegExp(`define\\s*\\(\\s*['"]${name}['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)`))?.[1];
33
+ return {
34
+ dbName: constant('DB_NAME'),
35
+ dbUser: constant('DB_USER'),
36
+ dbPassword: constant('DB_PASSWORD'),
37
+ dbHost: constant('DB_HOST'),
38
+ tablePrefix: php.match(/\$table_prefix\s*=\s*['"]([^'"]+)['"]/)?.[1],
39
+ };
40
+ }
41
+ async function domainWebRoots(client, home) {
42
+ const domainsDir = path.posix.join(home, 'domains');
43
+ const domains = await client.list(domainsDir).catch(() => []);
44
+ return domains.filter((entry) => entry.isDirectory).map((entry) => path.posix.join(domainsDir, entry.name, 'public_html'));
45
+ }
46
+ async function inspectFolder(client, dir) {
47
+ const entries = await client.list(dir).catch(() => null);
48
+ if (!entries?.some((entry) => entry.isDirectory && entry.name === 'wp-content'))
49
+ return null;
50
+ if (containsWpConfig(entries))
51
+ return { root: dir, wpConfigPath: path.posix.join(dir, 'wp-config.php') };
52
+ const parent = path.posix.dirname(dir);
53
+ const parentEntries = await client.list(parent).catch(() => []);
54
+ return containsWpConfig(parentEntries) ? { root: dir, wpConfigPath: path.posix.join(parent, 'wp-config.php') } : null;
55
+ }
56
+ function containsWpConfig(entries) {
57
+ return entries.some((entry) => !entry.isDirectory && entry.name === 'wp-config.php');
58
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ import { countFiles, scanImportFolder } from '../backup/import-files.js';
2
+ import { select } from '../ui/prompts.js';
3
+ import { UserError } from '../utils/errors.js';
4
+ import { LocalSource } from './local-source.js';
5
+ import { RemoteSource } from './remote-source.js';
6
+ import { UrlSource } from './url-source.js';
7
+ const SOURCE_TYPES = ['local', 'url', 'ftp', 'sftp'];
8
+ export function isSourceType(value) {
9
+ return SOURCE_TYPES.includes(value);
10
+ }
11
+ export function createSource(type) {
12
+ switch (type) {
13
+ case 'local':
14
+ return new LocalSource();
15
+ case 'url':
16
+ return new UrlSource();
17
+ case 'ftp':
18
+ case 'sftp':
19
+ return new RemoteSource(type);
20
+ }
21
+ }
22
+ export async function chooseSourceType(paths, config, requested) {
23
+ if (requested) {
24
+ if (!isSourceType(requested))
25
+ throw new UserError(`Unknown source "${requested}". Use ${SOURCE_TYPES.join(', ')}.`);
26
+ return requested;
27
+ }
28
+ const filesInImport = countFiles(scanImportFolder(paths.import));
29
+ const importHint = filesInImport ? `${filesInImport} file(s) found` : 'empty: drop your backup files there first';
30
+ return select('Where is the backup?', [
31
+ { value: 'local', label: '📁 Files in import/', hint: importHint },
32
+ { value: 'url', label: '🌍 Download from a URL', hint: 'zip, tar.gz, wpress, sql, Dropbox / Google Drive links' },
33
+ { value: 'ftp', label: '📡 Live site over FTP / FTPS' },
34
+ { value: 'sftp', label: '🔐 Live site over SFTP (SSH)' },
35
+ ], filesInImport ? 'local' : (config.source?.type ?? 'local'));
36
+ }
@@ -0,0 +1,32 @@
1
+ import path from 'node:path';
2
+ import { countFiles, scanImportFolder } from '../backup/import-files.js';
3
+ import { stageBackup } from '../backup/stage.js';
4
+ import { log, pc } from '../ui/output.js';
5
+ import { UserError } from '../utils/errors.js';
6
+ import { formatBytes } from '../utils/format.js';
7
+ export class LocalSource {
8
+ onlyFiles;
9
+ constructor(onlyFiles) {
10
+ this.onlyFiles = onlyFiles;
11
+ }
12
+ async acquire({ paths }) {
13
+ const files = this.onlyFiles ?? scanImportFolder(paths.import);
14
+ if (countFiles(files) === 0) {
15
+ const folder = path.relative(process.cwd(), paths.import) || 'import';
16
+ throw new UserError(`No backup files in ${folder}/. Drop your backup there (zip, tar.gz, .wpress, .sql) or choose another source.`);
17
+ }
18
+ log.info(`Backup files:\n${[...files.archives, ...files.dumps].map((file) => `${file.name} ${pc.dim(formatBytes(file.size))}`).join('\n')}`);
19
+ const staged = await stageBackup(files, paths);
20
+ if (!staged.dumpPath || !staged.contentDir) {
21
+ throw new UserError('No database dump found. Add the .sql (or .sql.gz) file to import/ and run init again.');
22
+ }
23
+ log.success(`Backup format: ${staged.format}`);
24
+ return {
25
+ contentDir: staged.contentDir,
26
+ dumpPath: staged.dumpPath,
27
+ disposable: true,
28
+ format: staged.format,
29
+ source: { type: 'local' },
30
+ };
31
+ }
32
+ }