create-marp-presentation 1.2.0 → 1.2.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.
- package/cli/commands/add-themes-cli.js +85 -0
- package/cli/commands/create-project.js +199 -0
- package/cli/utils/file-utils.js +106 -0
- package/cli/utils/prompt-utils.js +89 -0
- package/docs/plans/2025-02-19-marp-template-design.md +207 -0
- package/docs/plans/2025-02-19-marp-template-implementation.md +848 -0
- package/docs/plans/2026-02-20-example-slides-design.md +179 -0
- package/docs/plans/2026-02-20-example-slides-implementation.md +811 -0
- package/docs/plans/2026-02-23-theme-management-design.md +836 -0
- package/docs/plans/2026-02-23-theme-management-implementation.md +3585 -0
- package/docs/plans/2026-02-26-theme-addition-refactoring-design.md +172 -0
- package/docs/plans/2026-02-26-theme-addition-refactoring.md +456 -0
- package/docs/plans/2026-02-27-theme-add-fix-design.md +136 -0
- package/docs/plans/2026-02-27-theme-add-fix.md +353 -0
- package/docs/plans/TODO.md +5 -0
- package/docs/reqs/themes-requirements.md +49 -0
- package/docs/theme-management.md +261 -0
- package/package.json +3 -1
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// cli/commands/add-themes-cli.js
|
|
2
|
+
/**
|
|
3
|
+
* Add themes to existing project command for meta-package CLI
|
|
4
|
+
* This file is NOT copied to generated projects
|
|
5
|
+
*/
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
|
|
9
|
+
const { AddThemesCommand } = require('../../lib/add-themes-command');
|
|
10
|
+
const { ThemeError } = require('../../lib/errors');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Add themes to an existing project
|
|
14
|
+
* @param {string} targetPath - Path to the target project
|
|
15
|
+
* @param {Object} options - Configuration options
|
|
16
|
+
* @param {string} options.themesLibraryPath - Path to themes library
|
|
17
|
+
* @param {string[]} options.themeNames - Specific theme names to add (optional)
|
|
18
|
+
* @returns {Promise<void>}
|
|
19
|
+
*/
|
|
20
|
+
async function addThemesToExistingProject(targetPath, options = {}) {
|
|
21
|
+
const {
|
|
22
|
+
themesLibraryPath = path.join(__dirname, '../..', 'themes'),
|
|
23
|
+
themeNames = null
|
|
24
|
+
} = options;
|
|
25
|
+
|
|
26
|
+
// Validate target path exists
|
|
27
|
+
const resolvedPath = path.resolve(targetPath);
|
|
28
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
29
|
+
console.error(`Error: Directory does not exist: ${targetPath}`);
|
|
30
|
+
throw new ThemeError(`Target path does not exist: ${targetPath}`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Check if it's a valid Marp project (has presentation.md or package.json)
|
|
34
|
+
const hasPresentation = fs.existsSync(path.join(resolvedPath, 'presentation.md'));
|
|
35
|
+
const hasPackageJson = fs.existsSync(path.join(resolvedPath, 'package.json'));
|
|
36
|
+
|
|
37
|
+
if (!hasPresentation && !hasPackageJson) {
|
|
38
|
+
console.warn('Warning: This does not appear to be a Marp presentation project.');
|
|
39
|
+
console.warn(' (no presentation.md or package.json found)');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Create AddThemesCommand with themes library path
|
|
43
|
+
const command = new AddThemesCommand({
|
|
44
|
+
templatePath: themesLibraryPath,
|
|
45
|
+
interactive: true
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
console.log(`Adding themes to: ${resolvedPath}`);
|
|
50
|
+
console.log();
|
|
51
|
+
|
|
52
|
+
// Execute command - pass theme names if provided, otherwise prompt
|
|
53
|
+
const { copied, skipped, conflicts } = await command.execute(resolvedPath, {
|
|
54
|
+
themes: themeNames || undefined
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// Show summary
|
|
58
|
+
const copiedNames = copied.map(t => t.name);
|
|
59
|
+
console.log(`\nCopied themes: ${copiedNames.join(', ') || 'none'}`);
|
|
60
|
+
if (skipped.length > 0) {
|
|
61
|
+
console.log(`Skipped: ${skipped.join(', ')}`);
|
|
62
|
+
}
|
|
63
|
+
if (conflicts.length > 0) {
|
|
64
|
+
console.log(`Conflicts: ${conflicts.join(', ')}`);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
console.log();
|
|
68
|
+
console.log('Themes added successfully!');
|
|
69
|
+
console.log(`\nNext steps in ${targetPath}:`);
|
|
70
|
+
console.log(' npm run theme:list # List available themes');
|
|
71
|
+
console.log(' npm run theme:set <theme> # Set active theme');
|
|
72
|
+
console.log();
|
|
73
|
+
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (error instanceof ThemeError) {
|
|
76
|
+
console.error(`Error: ${error.message}`);
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
module.exports = {
|
|
84
|
+
addThemesToExistingProject
|
|
85
|
+
};
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// cli/commands/create-project.js
|
|
2
|
+
/**
|
|
3
|
+
* Project creation command for meta-package CLI
|
|
4
|
+
* This file is NOT copied to generated projects
|
|
5
|
+
*/
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const { spawnSync } = require('child_process');
|
|
9
|
+
|
|
10
|
+
const { AddThemesCommand } = require('../../lib/add-themes-command');
|
|
11
|
+
const { Prompts } = require('../../lib/prompts');
|
|
12
|
+
const { ThemeManager } = require('../../lib/theme-manager');
|
|
13
|
+
|
|
14
|
+
const { copyDir, copyOptionalFiles } = require('../utils/file-utils');
|
|
15
|
+
const { askCreateExamples } = require('../utils/prompt-utils');
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Validate project name
|
|
19
|
+
* @param {string} name - Project name to validate
|
|
20
|
+
* @returns {boolean} True if valid
|
|
21
|
+
*/
|
|
22
|
+
function validateProjectName(name) {
|
|
23
|
+
const validName = /^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/;
|
|
24
|
+
return validName.test(name);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Parse --path argument from argv
|
|
29
|
+
* @param {string[]} argv - Process argv (should start from index 2)
|
|
30
|
+
* @returns {{outputPath: string, pathIndex: number|null}} Parsed arguments
|
|
31
|
+
*/
|
|
32
|
+
function parsePathArg(argv) {
|
|
33
|
+
let outputPath = process.cwd();
|
|
34
|
+
const pathIndex = argv.indexOf('--path');
|
|
35
|
+
if (pathIndex !== -1 && pathIndex + 1 < argv.length) {
|
|
36
|
+
return { outputPath: null, pathIndex }; // Signal that validation is needed
|
|
37
|
+
}
|
|
38
|
+
return { outputPath, pathIndex: null };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Create a new Marp presentation project
|
|
43
|
+
* @param {string} projectName - Name of the project
|
|
44
|
+
* @param {Object} options - Configuration options
|
|
45
|
+
* @param {string} options.outputPath - Output directory path (default: current directory)
|
|
46
|
+
* @param {string} options.templatePath - Path to template directory
|
|
47
|
+
* @param {string} options.themesLibraryPath - Path to themes library
|
|
48
|
+
* @param {Function} options.validatePath - Path validation function
|
|
49
|
+
* @returns {Promise<void>}
|
|
50
|
+
*/
|
|
51
|
+
async function createProject(projectName, options = {}) {
|
|
52
|
+
const {
|
|
53
|
+
outputPath: providedOutputPath,
|
|
54
|
+
templatePath = path.join(__dirname, '../..', 'template'),
|
|
55
|
+
themesLibraryPath = path.join(__dirname, '../..', 'themes'),
|
|
56
|
+
validatePath
|
|
57
|
+
} = options;
|
|
58
|
+
|
|
59
|
+
// Validate project name
|
|
60
|
+
if (!validateProjectName(projectName)) {
|
|
61
|
+
console.error(`Invalid project name: "${projectName}"`);
|
|
62
|
+
console.error('Project name must be lowercase, contain only letters, numbers, and hyphens.');
|
|
63
|
+
throw new Error('Invalid project name');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Determine output path
|
|
67
|
+
let outputPath = providedOutputPath || process.cwd();
|
|
68
|
+
|
|
69
|
+
// Build final project path
|
|
70
|
+
const projectPath = path.join(outputPath, projectName);
|
|
71
|
+
|
|
72
|
+
// Check if project already exists
|
|
73
|
+
if (fs.existsSync(projectPath)) {
|
|
74
|
+
console.error(`Directory "${projectName}" already exists.`);
|
|
75
|
+
throw new Error('Project directory already exists');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
console.log(`Creating Marp presentation: ${projectName}`);
|
|
79
|
+
if (outputPath !== process.cwd()) {
|
|
80
|
+
console.log(` Location: ${projectPath}`);
|
|
81
|
+
}
|
|
82
|
+
console.log();
|
|
83
|
+
|
|
84
|
+
// Ask about example slides
|
|
85
|
+
const createExamples = await askCreateExamples();
|
|
86
|
+
|
|
87
|
+
// Create project directory
|
|
88
|
+
fs.mkdirSync(projectPath, { recursive: true });
|
|
89
|
+
|
|
90
|
+
// Copy template completely
|
|
91
|
+
copyDir(templatePath, projectPath);
|
|
92
|
+
|
|
93
|
+
// Copy lib scripts to project
|
|
94
|
+
const rootLibPath = path.join(__dirname, '../..', 'lib');
|
|
95
|
+
const projectScriptsLibPath = path.join(projectPath, 'scripts', 'lib');
|
|
96
|
+
fs.mkdirSync(projectScriptsLibPath, { recursive: true });
|
|
97
|
+
copyDir(rootLibPath, projectScriptsLibPath);
|
|
98
|
+
|
|
99
|
+
// Verify marp.themeSet configuration exists in package.json
|
|
100
|
+
ThemeManager.ensureThemeSetConfig(projectPath);
|
|
101
|
+
|
|
102
|
+
console.log('✓ Project created');
|
|
103
|
+
|
|
104
|
+
// Copy optional files
|
|
105
|
+
if (createExamples) {
|
|
106
|
+
copyOptionalFiles(projectPath);
|
|
107
|
+
console.log('✓ Example slides added');
|
|
108
|
+
console.log('✓ Demo image added to static/');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Copy theme management documentation
|
|
112
|
+
const themeDocsSource = path.join(__dirname, '../..', 'docs', 'theme-management.md');
|
|
113
|
+
const themeDocsDest = path.join(projectPath, 'docs', 'theme-management.md');
|
|
114
|
+
if (fs.existsSync(themeDocsSource)) {
|
|
115
|
+
fs.mkdirSync(path.dirname(themeDocsDest), { recursive: true });
|
|
116
|
+
fs.copyFileSync(themeDocsSource, themeDocsDest);
|
|
117
|
+
console.log('✓ Theme management guide added');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Add themes to project (prompts user interactively if TTY)
|
|
121
|
+
let copied = [];
|
|
122
|
+
if (process.stdin.isTTY) {
|
|
123
|
+
// Interactive mode - prompt for themes
|
|
124
|
+
console.log();
|
|
125
|
+
const command = new AddThemesCommand({
|
|
126
|
+
templatePath: themesLibraryPath,
|
|
127
|
+
interactive: true
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
const result = await command.execute(projectPath, {
|
|
131
|
+
themes: null // Triggers built-in prompt
|
|
132
|
+
});
|
|
133
|
+
copied = result.copied;
|
|
134
|
+
}
|
|
135
|
+
// Non-interactive mode: skip theme addition entirely
|
|
136
|
+
|
|
137
|
+
// Select and set active theme from copied themes
|
|
138
|
+
if (copied && copied.length > 0) {
|
|
139
|
+
console.log();
|
|
140
|
+
const themeNames = copied.map(t => t.name);
|
|
141
|
+
const activeTheme = await Prompts.promptActiveTheme(themeNames);
|
|
142
|
+
const themeManager = new ThemeManager(projectPath);
|
|
143
|
+
try {
|
|
144
|
+
themeManager.setActiveTheme(activeTheme);
|
|
145
|
+
console.log(`✓ Set active theme to "${activeTheme}"`);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
console.warn(` Warning: Could not set active theme: ${error.message}`);
|
|
148
|
+
}
|
|
149
|
+
} else {
|
|
150
|
+
// No themes copied, set default active theme
|
|
151
|
+
const themeManager = new ThemeManager(projectPath);
|
|
152
|
+
try {
|
|
153
|
+
themeManager.setActiveTheme('default');
|
|
154
|
+
console.log(`✓ Set active theme to "default"`);
|
|
155
|
+
} catch (error) {
|
|
156
|
+
console.warn(` Warning: Could not set active theme: ${error.message}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
console.log();
|
|
161
|
+
|
|
162
|
+
// Run npm install
|
|
163
|
+
console.log('Installing dependencies...');
|
|
164
|
+
const installResult = spawnSync('npm', ['install'], {
|
|
165
|
+
cwd: projectPath,
|
|
166
|
+
stdio: 'inherit',
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
if (installResult.status !== 0) {
|
|
170
|
+
console.error();
|
|
171
|
+
console.error('Failed to install dependencies.');
|
|
172
|
+
console.error('Please run "cd ' + projectName + ' && npm install" manually.');
|
|
173
|
+
throw new Error('npm install failed');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
console.log();
|
|
177
|
+
console.log('✓ Dependencies installed');
|
|
178
|
+
console.log();
|
|
179
|
+
console.log('Next steps:');
|
|
180
|
+
const cwdRelativePath = path.relative(process.cwd(), projectPath);
|
|
181
|
+
const cdPath = cwdRelativePath.startsWith('..') ? projectPath : cwdRelativePath;
|
|
182
|
+
const readmePath = path.join(cdPath, 'README.md');
|
|
183
|
+
console.log(` cd ${cdPath}`);
|
|
184
|
+
console.log(' npm run dev # Start live preview');
|
|
185
|
+
console.log(' npm run theme:list # List available themes');
|
|
186
|
+
console.log(' npm run theme:set <theme-name> # Set active theme');
|
|
187
|
+
console.log(' npm run theme:add # Add more themes to the project');
|
|
188
|
+
console.log(' npm run build:all # Build all formats');
|
|
189
|
+
console.log(' Open project folder in vscode with Marp extension for editing your presentation');
|
|
190
|
+
console.log(` Read ${readmePath} for more information`);
|
|
191
|
+
console.log(' Enjoy!');
|
|
192
|
+
console.log();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
module.exports = {
|
|
196
|
+
createProject,
|
|
197
|
+
validateProjectName,
|
|
198
|
+
parsePathArg
|
|
199
|
+
};
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// cli/utils/file-utils.js
|
|
2
|
+
/**
|
|
3
|
+
* File and directory utilities for meta-package CLI commands
|
|
4
|
+
* These functions are NOT copied to generated projects
|
|
5
|
+
*/
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Expand ~ to home directory
|
|
12
|
+
* @param {string} input - Path that may start with ~
|
|
13
|
+
* @returns {string} Expanded path
|
|
14
|
+
*/
|
|
15
|
+
function expandHomePath(input) {
|
|
16
|
+
if (input.startsWith('~')) {
|
|
17
|
+
return path.join(os.homedir(), input.slice(1));
|
|
18
|
+
}
|
|
19
|
+
return input;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Validate and normalize an output directory path
|
|
24
|
+
* @param {string} inputPath - Path to validate
|
|
25
|
+
* @returns {{valid: boolean, error?: string, resolvedPath?: string}} Validation result
|
|
26
|
+
*/
|
|
27
|
+
function validateOutputPath(inputPath) {
|
|
28
|
+
if (!inputPath || inputPath.trim() === '') {
|
|
29
|
+
return { valid: false, error: 'Path cannot be empty' };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Check for null bytes (security)
|
|
33
|
+
if (inputPath.includes('\0')) {
|
|
34
|
+
return { valid: false, error: 'Path contains null bytes' };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const expanded = expandHomePath(inputPath);
|
|
38
|
+
const resolved = path.resolve(expanded);
|
|
39
|
+
const normalizedResolved = resolved.toLowerCase();
|
|
40
|
+
|
|
41
|
+
// Block system-sensitive directories
|
|
42
|
+
const sensitiveDirs = ['/etc', '/sys', '/proc', '/root', '/boot'];
|
|
43
|
+
for (const sensitive of sensitiveDirs) {
|
|
44
|
+
if (normalizedResolved.startsWith(sensitive.toLowerCase() + path.sep) ||
|
|
45
|
+
normalizedResolved === sensitive.toLowerCase()) {
|
|
46
|
+
return { valid: false, error: `Cannot create project in system directory: ${sensitive}` };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Don't allow creation inside node_modules
|
|
51
|
+
if (normalizedResolved.includes('node_modules')) {
|
|
52
|
+
return { valid: false, error: 'Cannot create project inside node_modules directory' };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return { valid: true, resolvedPath: resolved };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Recursively copy a directory
|
|
60
|
+
* @param {string} src - Source directory path
|
|
61
|
+
* @param {string} dest - Destination directory path
|
|
62
|
+
*/
|
|
63
|
+
function copyDir(src, dest) {
|
|
64
|
+
const entries = fs.readdirSync(src, { withFileTypes: true });
|
|
65
|
+
|
|
66
|
+
for (const entry of entries) {
|
|
67
|
+
const srcPath = path.join(src, entry.name);
|
|
68
|
+
const destPath = path.join(dest, entry.name);
|
|
69
|
+
|
|
70
|
+
if (entry.isDirectory()) {
|
|
71
|
+
fs.mkdirSync(destPath, { recursive: true });
|
|
72
|
+
copyDir(srcPath, destPath);
|
|
73
|
+
} else {
|
|
74
|
+
fs.copyFileSync(srcPath, destPath);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Copy optional template files to destination
|
|
81
|
+
* @param {string} destPath - Destination project path
|
|
82
|
+
*/
|
|
83
|
+
function copyOptionalFiles(destPath) {
|
|
84
|
+
const optionalPath = path.join(__dirname, '..', '..', 'template-optional');
|
|
85
|
+
|
|
86
|
+
// Copy examples.md
|
|
87
|
+
const examplesSrc = path.join(optionalPath, 'examples.md');
|
|
88
|
+
const examplesDest = path.join(destPath, 'examples.md');
|
|
89
|
+
if (fs.existsSync(examplesSrc)) {
|
|
90
|
+
fs.copyFileSync(examplesSrc, examplesDest);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Copy demo image
|
|
94
|
+
const demoImageSrc = path.join(optionalPath, 'static', 'demo-image.png');
|
|
95
|
+
const demoImageDest = path.join(destPath, 'static', 'demo-image.png');
|
|
96
|
+
if (fs.existsSync(demoImageSrc)) {
|
|
97
|
+
fs.copyFileSync(demoImageSrc, demoImageDest);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = {
|
|
102
|
+
expandHomePath,
|
|
103
|
+
validateOutputPath,
|
|
104
|
+
copyDir,
|
|
105
|
+
copyOptionalFiles
|
|
106
|
+
};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// cli/utils/prompt-utils.js
|
|
2
|
+
/**
|
|
3
|
+
* Prompt utilities for meta-package CLI commands
|
|
4
|
+
* These functions are NOT copied to generated projects
|
|
5
|
+
*/
|
|
6
|
+
const readline = require('readline');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Ask user if they want to create example slides
|
|
10
|
+
* @returns {Promise<boolean>} True if user wants examples
|
|
11
|
+
*/
|
|
12
|
+
async function askCreateExamples() {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
// Interactive mode - ask user
|
|
15
|
+
if (process.stdin.isTTY) {
|
|
16
|
+
const rl = readline.createInterface({
|
|
17
|
+
input: process.stdin,
|
|
18
|
+
output: process.stdout
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
rl.question('Create example slides file? (Y/n) ', (answer) => {
|
|
22
|
+
rl.close();
|
|
23
|
+
const normalized = answer.toLowerCase().trim();
|
|
24
|
+
resolve(normalized !== 'n' && normalized !== 'no');
|
|
25
|
+
});
|
|
26
|
+
} else {
|
|
27
|
+
// Non-interactive mode - read from stdin if there's data
|
|
28
|
+
let input = '';
|
|
29
|
+
process.stdin.setEncoding('utf8');
|
|
30
|
+
|
|
31
|
+
process.stdin.on('readable', () => {
|
|
32
|
+
let chunk;
|
|
33
|
+
while ((chunk = process.stdin.read()) !== null) {
|
|
34
|
+
input += chunk;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
process.stdin.on('end', () => {
|
|
39
|
+
const normalized = input.toLowerCase().trim();
|
|
40
|
+
// If input is empty, create examples by default
|
|
41
|
+
if (normalized === '') {
|
|
42
|
+
resolve(true);
|
|
43
|
+
} else {
|
|
44
|
+
resolve(normalized !== 'n' && normalized !== 'no');
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// If stdin has no data immediately, finish
|
|
49
|
+
if (process.stdin.readableLength === 0) {
|
|
50
|
+
// Give a short time for data to appear
|
|
51
|
+
setTimeout(() => {
|
|
52
|
+
if (input === '') {
|
|
53
|
+
process.stdin.destroy();
|
|
54
|
+
resolve(true);
|
|
55
|
+
}
|
|
56
|
+
}, 10);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Ask user if they want to add themes to the project
|
|
64
|
+
* @returns {Promise<boolean>} True if user wants themes
|
|
65
|
+
*/
|
|
66
|
+
async function askAddThemes() {
|
|
67
|
+
return new Promise((resolve) => {
|
|
68
|
+
if (process.stdin.isTTY) {
|
|
69
|
+
const rl = readline.createInterface({
|
|
70
|
+
input: process.stdin,
|
|
71
|
+
output: process.stdout
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
rl.question('Add custom themes to the project? (Y/n) ', (answer) => {
|
|
75
|
+
rl.close();
|
|
76
|
+
const normalized = answer.toLowerCase().trim();
|
|
77
|
+
resolve(normalized !== 'n' && normalized !== 'no');
|
|
78
|
+
});
|
|
79
|
+
} else {
|
|
80
|
+
// Non-interactive mode: default to false (don't add themes without consent)
|
|
81
|
+
resolve(false);
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
module.exports = {
|
|
87
|
+
askCreateExamples,
|
|
88
|
+
askAddThemes
|
|
89
|
+
};
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# Marp Presentation Template - Design Document
|
|
2
|
+
|
|
3
|
+
**Дата:** 2025-02-19
|
|
4
|
+
**Статус:** Draft
|
|
5
|
+
|
|
6
|
+
## Обзор
|
|
7
|
+
|
|
8
|
+
npm-пакет `create-marp-presentation` для создания готовых шаблонов Marp-презентаций. Установка через npx одной командой, поддержка статических файлов, генерация в HTML/PDF/PPTX.
|
|
9
|
+
|
|
10
|
+
## Архитектура и структура
|
|
11
|
+
|
|
12
|
+
### Структура инициализируемого проекта
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
my-presentation/
|
|
16
|
+
├── presentation.md # Главный файл презентации
|
|
17
|
+
├── marp.config.js # Конфигурация (статические папки, output директория)
|
|
18
|
+
├── package.json # Зависимости и npm-скрипты
|
|
19
|
+
├── .gitignore # Исключает output/ и node_modules/
|
|
20
|
+
├── README.md # Инструкции по использованию
|
|
21
|
+
├── output/ # Сгенерированные файлы (создаётся при сборке)
|
|
22
|
+
├── static/ # Статические файлы по умолчанию
|
|
23
|
+
└── scripts/
|
|
24
|
+
└── copy-static.js # Скрипт копирования статики
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Структура npm-пакета
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
create-marp-presentation/
|
|
31
|
+
├── package.json # Meta-package с bin полем
|
|
32
|
+
├── index.js # Точка входа для CLI
|
|
33
|
+
├── template/ # Шаблон проекта
|
|
34
|
+
│ ├── package.json # Шаблон package.json
|
|
35
|
+
│ ├── marp.config.js # Шаблон конфига
|
|
36
|
+
│ ├── presentation.md # Пример презентации
|
|
37
|
+
│ ├── .gitignore # Шаблон gitignore
|
|
38
|
+
│ ├── README.md # Шаблон README
|
|
39
|
+
│ ├── static/ # Пустая папка с .gitkeep
|
|
40
|
+
│ └── scripts/
|
|
41
|
+
│ └── copy-static.js # Скрипт копирования статики
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Конфигурация
|
|
45
|
+
|
|
46
|
+
### marp.config.js
|
|
47
|
+
|
|
48
|
+
```javascript
|
|
49
|
+
module.exports = {
|
|
50
|
+
staticFolders: ['static/**', 'assets/**'], // glob-паттерны для копирования
|
|
51
|
+
outputDir: 'output', // папка для генерации
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
- `staticFolders` - массив glob-паттернов для поиска статических файлов
|
|
56
|
+
- `outputDir` - папка для генерации (по умолчанию `output`)
|
|
57
|
+
|
|
58
|
+
## Команды и скрипты
|
|
59
|
+
|
|
60
|
+
### package.json скрипты
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"scripts": {
|
|
65
|
+
"dev": "marp -s . --html",
|
|
66
|
+
"build:html": "marp presentation.md -o output/index.html --html && npm run copy:static",
|
|
67
|
+
"build:pdf": "marp presentation.md -o output/presentation.pdf --allow-local-files && npm run copy:static",
|
|
68
|
+
"build:pptx": "marp presentation.md -o output/presentation.pptx --allow-local-files && npm run copy:static",
|
|
69
|
+
"build:all": "npm run build:html && npm run build:pdf && npm run build:pptx",
|
|
70
|
+
"copy:static": "node scripts/copy-static.js",
|
|
71
|
+
"clean": "rimraf output"
|
|
72
|
+
},
|
|
73
|
+
"devDependencies": {
|
|
74
|
+
"@marp-team/marp-cli": "^4.1.2",
|
|
75
|
+
"fast-glob": "^3.3.3",
|
|
76
|
+
"rimraf": "^6.0.0"
|
|
77
|
+
},
|
|
78
|
+
"engines": {
|
|
79
|
+
"node": ">=20.0.0"
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
| Команда | Описание |
|
|
85
|
+
|---------|----------|
|
|
86
|
+
| `npm run dev` | Live-предпросмотр с hot-reload |
|
|
87
|
+
| `npm run build:html` | Генерация HTML с встроенным viewer |
|
|
88
|
+
| `npm run build:pdf` | Генерация PDF |
|
|
89
|
+
| `npm run build:pptx` | Генерация PowerPoint |
|
|
90
|
+
| `npm run build:all` | Все форматы подряд |
|
|
91
|
+
| `npm run clean` | Очистка output/ |
|
|
92
|
+
|
|
93
|
+
## Скрипт копирования статики
|
|
94
|
+
|
|
95
|
+
### scripts/copy-static.js
|
|
96
|
+
|
|
97
|
+
```javascript
|
|
98
|
+
const fs = require('fs');
|
|
99
|
+
const path = require('path');
|
|
100
|
+
const { globSync } = require('fast-glob');
|
|
101
|
+
|
|
102
|
+
// Читаем конфиг с дефолтными значениями
|
|
103
|
+
let config;
|
|
104
|
+
try {
|
|
105
|
+
config = require('../marp.config.js');
|
|
106
|
+
} catch {
|
|
107
|
+
config = {};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const outputDir = config.outputDir || 'output';
|
|
111
|
+
const staticFolders = config.staticFolders || ['static/**'];
|
|
112
|
+
|
|
113
|
+
// Создаём output если нет
|
|
114
|
+
if (!fs.existsSync(outputDir)) {
|
|
115
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Находим файлы по паттернам
|
|
119
|
+
const files = globSync(staticFolders);
|
|
120
|
+
|
|
121
|
+
// Копируем с сохранением структуры
|
|
122
|
+
for (const file of files) {
|
|
123
|
+
const relativePath = path.relative(process.cwd(), file);
|
|
124
|
+
const destPath = path.join(outputDir, relativePath);
|
|
125
|
+
|
|
126
|
+
const destDir = path.dirname(destPath);
|
|
127
|
+
if (!fs.existsSync(destDir)) {
|
|
128
|
+
fs.mkdirSync(destDir, { recursive: true });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
fs.copyFileSync(file, destPath);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
console.log(`✓ Copied ${files.length} files to ${outputDir}/`);
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Обработка ошибок
|
|
138
|
+
|
|
139
|
+
### Что обрабатываем
|
|
140
|
+
|
|
141
|
+
1. **Отсутствие `marp.config.js`** - использовать дефолтные значения
|
|
142
|
+
2. **Несуществующие папки в staticFolders** - пропускать молча
|
|
143
|
+
3. **Пустая staticFolders** - не копировать ничего, не падать
|
|
144
|
+
4. **Конфликт имён файлов** - перезаписывать с предупреждением
|
|
145
|
+
5. **Ошибки копирования** - логировать и продолжать
|
|
146
|
+
|
|
147
|
+
### Валидация в CLI
|
|
148
|
+
|
|
149
|
+
- Проверять, что папка для проекта не существует
|
|
150
|
+
- Валидировать имя проекта (нет спецсимволов)
|
|
151
|
+
- Проверять успешность `npm install`
|
|
152
|
+
|
|
153
|
+
## Использование
|
|
154
|
+
|
|
155
|
+
### Инициализация
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
npx create-marp-presentation my-presentation
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### Редактирование
|
|
162
|
+
|
|
163
|
+
Откройте `presentation.md` и пишите слайды в Markdown.
|
|
164
|
+
|
|
165
|
+
### Live-предпросмотр
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
npm run dev
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Сборка
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
npm run build:html # HTML
|
|
175
|
+
npm run build:pdf # PDF
|
|
176
|
+
npm run build:pptx # PowerPoint
|
|
177
|
+
npm run build:all # Все форматы
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Очистка
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
npm run clean
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
## Зависимости
|
|
187
|
+
|
|
188
|
+
| Пакет | Версия | Описание |
|
|
189
|
+
|-------|--------|----------|
|
|
190
|
+
| `@marp-team/marp-cli` | ^4.1.2 | CLI для Marp (требует Node.js 18+) |
|
|
191
|
+
| `fast-glob` | ^3.3.3 | Быстрый glob для поиска файлов |
|
|
192
|
+
| `rimraf` | ^6.0.0 | Кроссплатформенное удаление папок (требует Node.js 20+) |
|
|
193
|
+
|
|
194
|
+
### Требования к Node.js
|
|
195
|
+
|
|
196
|
+
**Node.js >= 20.0.0** - обусловлено версией rimraf v6
|
|
197
|
+
|
|
198
|
+
### Источники
|
|
199
|
+
|
|
200
|
+
- [@marp-team/marp-cli на npm](https://www.npmjs.com/package/@marp-team/marp-cli)
|
|
201
|
+
- [fast-glob на npm](https://www.npmjs.com/package/fast-glob)
|
|
202
|
+
|
|
203
|
+
## Тестирование
|
|
204
|
+
|
|
205
|
+
- Юнит-тесты для copy-static.js
|
|
206
|
+
- Интеграционные тесты для CLI инициализатора
|
|
207
|
+
- Тесты обработки ошибок
|