mirror of
https://github.com/LukeHagar/skeleton.git
synced 2025-12-09 12:47:44 +00:00
V2 csa only updates (#1859)
This commit is contained in:
@@ -1,26 +1,25 @@
|
||||
// Types
|
||||
import { create } from 'create-svelte';
|
||||
import fs from 'fs-extra';
|
||||
import { readFileSync, writeFileSync, cpSync, appendFileSync, existsSync } from 'fs';
|
||||
import got from 'got';
|
||||
import { bold, cyan, red } from 'kleur/colors';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'path';
|
||||
import process from 'process';
|
||||
import { dist, mkdirp, removeFilesExceptSync, whichPMRuns } from './utils.js';
|
||||
import * as url from 'url';
|
||||
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
|
||||
import { join, resolve } from 'path';
|
||||
import { cwd, chdir } from 'process';
|
||||
import { mkdirp, setNestedValue, checkIfDirSafeToInstall, iit } from './utils.js';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||
|
||||
export const presetThemes = ['skeleton', 'modern', 'hamlindigo', 'rocket', 'sahara', 'gold-nouveau', 'vintage', 'seafoam', 'crimson'];
|
||||
// NOTE: Any changes here must also be reflected in the --help output in utils.js and shortcut expansions in index.js.
|
||||
// Probably a good idea to do a search on the values you are changing to catch any other areas they are used in
|
||||
|
||||
export class SkeletonOptions {
|
||||
// svelte-create expects these options, do not change the names or values.
|
||||
constructor() {
|
||||
this.name = 'new-skel-app';
|
||||
this.template = 'skeleton';
|
||||
this.types = 'typescript';
|
||||
this.prettier = true;
|
||||
this.eslint = true;
|
||||
// svelte-create expects these options, do not change the names or values.
|
||||
this.name = 'skeleton-app'; // only used for the name field in the package.json
|
||||
this.template = 'skeleton'; // 'default' | 'skeleton' | 'skeletonlib' has nothing to do with Skeleton
|
||||
this.types = 'typescript'; //'typescript' | 'checkjs' | null;
|
||||
this.prettier = false;
|
||||
this.eslint = false;
|
||||
this.playwright = false;
|
||||
this.vitest = false;
|
||||
|
||||
@@ -32,112 +31,141 @@ export class SkeletonOptions {
|
||||
this.forms = false;
|
||||
this.typography = false;
|
||||
this.codeblocks = false;
|
||||
this.popups = true;
|
||||
this.popups = false;
|
||||
this.mdsvex = false;
|
||||
this.inspector = false;
|
||||
this.skeletontheme = 'skeleton';
|
||||
this.skeletontemplate = 'bare';
|
||||
this.packagemanager = 'pnpm';
|
||||
this.packages = [];
|
||||
this.skeletontheme = ['skeleton'];
|
||||
this.skeletontemplate = 'skeleton-template-bare';
|
||||
this.skeletontemplatedir = '../templates';
|
||||
this.packagemanager = 'npm';
|
||||
this.devDependencies = new Map([
|
||||
['postcss', 'latest'],
|
||||
['autoprefixer', 'latest'],
|
||||
['tailwindcss', 'latest'],
|
||||
['@skeletonlabs/skeleton', 'latest'],
|
||||
]);
|
||||
|
||||
// props below are private to the Skeleton team
|
||||
this.verbose = false;
|
||||
this.monorepo = false;
|
||||
this.packages = [];
|
||||
this.skeletontemplatedir = '../templates';
|
||||
this.workspace = '';
|
||||
this.monorepo = false; // Adds additional config for installing into a pnpm monorepo
|
||||
this.library = false; // allows forcing of a library install (could be forced by directly setting template to skeletonlib)
|
||||
this.test = false; // adjusts tests to a common parent directory for monorepo testing, API only, set by testing scripts
|
||||
this.meta = undefined; // holds the csa-meta.json data
|
||||
}
|
||||
set metaObject(value) {
|
||||
this.meta = value;
|
||||
if (this.meta.requiredFeatures) {
|
||||
this.meta.requiredFeatures.forEach((val) => {
|
||||
Object.assign(this, val);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function createSkeleton(opts) {
|
||||
const startPath = process.cwd();
|
||||
|
||||
// When being run multiple times in a row, we need to make sure we return to this current directory
|
||||
// and not the newly created projects subdir
|
||||
const startPath = cwd();
|
||||
// Hidden option to change the install type to be a Svelte-Kit library project
|
||||
if (opts?.library) {
|
||||
if (opts.library) {
|
||||
opts.template = 'skeletonlib';
|
||||
}
|
||||
// We could have been called directly as an API, so we still need to check if the directory is safe to install into
|
||||
checkIfDirSafeToInstall(opts.path);
|
||||
|
||||
//create-svelte will build the base install for us
|
||||
// create-svelte will build the base install for us
|
||||
await create(opts.path, opts);
|
||||
process.chdir(opts.path);
|
||||
|
||||
// install packages
|
||||
opts.packagemanager = whichPMRuns()?.name || 'npm';
|
||||
|
||||
// the order matters due to dependency resolution, because yarn
|
||||
let packages = ['postcss', 'autoprefixer', 'tailwindcss', '@skeletonlabs/skeleton'];
|
||||
// Extra packages for a monorepo install
|
||||
if (opts?.monorepo) {
|
||||
packages.push('@sveltejs/adapter-vercel');
|
||||
packages.push('is-ci');
|
||||
chdir(opts.path);
|
||||
if (opts.meta == undefined) {
|
||||
if (existsSync(opts.skeletontemplate)) {
|
||||
opts.metaObject = JSON.parse(readFileSync(opts.skeletontemplate, 'utf8'));
|
||||
} else {
|
||||
const err = new Error(`Could not find skeleton template meta file at ${opts.skeletontemplate}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Tailwind Packages
|
||||
if (opts?.typography) packages.push('@tailwindcss/typography');
|
||||
if (opts?.forms) packages.push('@tailwindcss/forms');
|
||||
|
||||
// Component dependencies
|
||||
if (opts?.codeblocks) packages.push('highlight.js');
|
||||
if (opts?.popups) packages.push('@floating-ui/dom');
|
||||
|
||||
let result = spawnSync(opts.packagemanager, ['add', '-D', ...packages], {
|
||||
shell: true,
|
||||
});
|
||||
|
||||
// Capture any errors from stderr and display for the user to report it to us
|
||||
if (result?.stderr.toString().length) {
|
||||
console.log(
|
||||
red(
|
||||
bold(
|
||||
'The following was reported to stderr - please read carefully to determine whether it actually affects your install:\n',
|
||||
),
|
||||
),
|
||||
result?.stderr.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
// Just to help with any user error reports
|
||||
if (opts.verbose) {
|
||||
const stdout = result?.stdout.toString();
|
||||
if (stdout.length) console.log(bold(cyan('stdout:')), stdout);
|
||||
const stderr = result?.stderr.toString();
|
||||
if (stderr.length) console.log(bold(red('stderr:')), stderr);
|
||||
// mri may only receive a single template and pass it to us as a string
|
||||
if (typeof opts.skeletontheme === 'string') {
|
||||
opts.skeletontheme = [opts.skeletontheme];
|
||||
}
|
||||
|
||||
await modifyPackageJson(opts);
|
||||
// write out config files
|
||||
out('svelte.config.js', createSvelteConfig(opts));
|
||||
out('.vscode/settings.json', await createVSCodeSettings());
|
||||
out('tailwind.config.cjs', createTailwindConfig(opts));
|
||||
out('postcss.config.cjs', createPostCssConfig());
|
||||
createSvelteConfig(opts);
|
||||
createViteConfig(opts);
|
||||
await createVSCodeSettings();
|
||||
createTailwindConfig(opts);
|
||||
createPostCssConfig();
|
||||
copyTemplate(opts);
|
||||
|
||||
// Monorepo additions
|
||||
if (opts?.monorepo) {
|
||||
fs.copySync(__dirname + '../README-MONO.md', process.cwd() + '/README.md', { overwrite: true });
|
||||
mkdirp('scripts');
|
||||
fs.copySync(__dirname + './swapdeps.mjs', process.cwd() + '/scripts/swapdeps.mjs', { overwrite: true });
|
||||
let pkg = JSON.parse(fs.readFileSync('package.json'));
|
||||
pkg.scripts['install'] = 'node ./scripts/swapdeps.mjs';
|
||||
pkg.scripts['dep'] = 'vercel build && vercel deploy --prebuilt';
|
||||
pkg.scripts['prod'] = 'vercel build --prod && vercel deploy --prebuilt --prod';
|
||||
fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
|
||||
}
|
||||
// copy over selected template
|
||||
copyTemplate(opts);
|
||||
// creating the missing lib folder...
|
||||
mkdirp(path.join('src', 'lib'));
|
||||
if (opts.monorepo) cpSync(resolve(__dirname, '../README-MONO.md'), resolve(cwd(), 'README.md'), { force: true });
|
||||
|
||||
if (opts.test) createTestConfig(opts);
|
||||
// go back to starting location in case we get called again to create another template
|
||||
process.chdir(startPath);
|
||||
chdir(startPath);
|
||||
opts.meta = undefined;
|
||||
return opts;
|
||||
}
|
||||
|
||||
async function createVSCodeSettings() {
|
||||
try {
|
||||
mkdirp('.vscode');
|
||||
const data = await got('https://raw.githubusercontent.com/skeletonlabs/skeleton/master/scripts/tw-settings.json').text();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Unable to download settings file for VSCode, please read manual instructions at https://skeleton.dev/guides/install',
|
||||
);
|
||||
async function modifyPackageJson(opts) {
|
||||
const pkgPath = join(cwd(), 'package.json');
|
||||
let pkgJson = JSON.parse(readFileSync(pkgPath));
|
||||
|
||||
// add required packages
|
||||
for (const pkg of [
|
||||
'postcss',
|
||||
'autoprefixer',
|
||||
'tailwindcss',
|
||||
'@skeletonlabs/skeleton',
|
||||
'@skeletonlabs/tw-plugin',
|
||||
'vite-plugin-tailwind-purgecss',
|
||||
]) {
|
||||
setNestedValue(pkgJson, ['devDependencies', pkg], 'latest');
|
||||
}
|
||||
|
||||
// Extra packages and scripts for a monorepo install
|
||||
if (opts.monorepo) {
|
||||
['@sveltejs/adapter-vercel'].forEach((pkg) => (pkg.devDependencies[pkg] = opts.devDependencies.get(pkg)));
|
||||
// TODO copy over github workflows for deploying to CF
|
||||
// TODO auto-detect if we are in a mono from '@pnpm/find-workspace-dir';
|
||||
pkgJson['deployConfig'] = { '@skeletonlabs/skeleton': '^1.0.0' };
|
||||
}
|
||||
|
||||
// Optional packages
|
||||
if (opts.mdsvex) pkgJson.devDependencies['mdsvex'] = 'latest';
|
||||
if (opts.typography) pkgJson.devDependencies['@tailwindcss/typography'] = 'latest';
|
||||
if (opts.forms) pkgJson.devDependencies['@tailwindcss/forms'] = 'latest';
|
||||
if (opts.types == 'typescript') pkgJson.devDependencies['@types/node'] = 'latest';
|
||||
if (opts.codeblocks) setNestedValue(pkgJson, ['dependencies', 'highlight.js'], 'latest');
|
||||
if (opts.popups) setNestedValue(pkgJson, ['dependencies', '@floating-ui/dom'], 'latest');
|
||||
|
||||
// Template specific packages
|
||||
if (opts.meta?.dependencies) {
|
||||
pkgJson.dependencies = { ...pkgJson.dependencies, ...opts.meta.dependencies };
|
||||
}
|
||||
if (opts.meta?.devDependencies) {
|
||||
pkgJson.devDependencies = { ...pkgJson.devDependencies, ...opts.meta.devDependencies };
|
||||
}
|
||||
|
||||
await getLatestPackageVersions(pkgJson);
|
||||
writeFileSync(pkgPath, JSON.stringify(pkgJson, null, 2));
|
||||
}
|
||||
|
||||
async function getLatestPackageVersions(pkgJson) {
|
||||
const devDeps = Object.keys(pkgJson.devDependencies);
|
||||
for await (const pkg of devDeps) {
|
||||
if (pkgJson.devDependencies[pkg] == 'latest') {
|
||||
const data = await got(`https://registry.npmjs.org/${pkg}/latest`).json();
|
||||
pkgJson.devDependencies[pkg] = data.version;
|
||||
}
|
||||
}
|
||||
const deps = pkgJson.dependencies == undefined ? [] : Object.keys(pkgJson.dependencies);
|
||||
for await (const pkg of deps) {
|
||||
if (pkgJson.dependencies[pkg] == 'latest') {
|
||||
const data = await got(`https://registry.npmjs.org/${pkg}/latest`).json();
|
||||
pkgJson.dependencies[pkg] = data.version;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,30 +173,28 @@ function createSvelteConfig(opts) {
|
||||
// For some reason create-svelte will turn off preprocessing for jsdoc and no type checking
|
||||
// this will break the using of all CSS preprocessing as well, which is undesirable.
|
||||
// Here we will just return the typescript default setup
|
||||
let str = '';
|
||||
if (opts?.monorepo) {
|
||||
str += `import adapter from '@sveltejs/adapter-vercel';\n`;
|
||||
} else {
|
||||
str += `import adapter from '@sveltejs/adapter-auto';\n`;
|
||||
}
|
||||
str += `import { vitePreprocess } from '@sveltejs/kit/vite';`;
|
||||
if (opts?.monorepo) {
|
||||
str += `\nimport path from 'path';`;
|
||||
}
|
||||
str += `
|
||||
const mdsvexConfig = `import { mdsvex } from 'mdsvex'
|
||||
|
||||
/** @type {import('mdsvex').MdsvexOptions} */
|
||||
const mdsvexOptions = {
|
||||
extensions: ['.md'],
|
||||
}`;
|
||||
const inspectorConfig = `
|
||||
vitePlugin: {
|
||||
inspector: true,
|
||||
},`;
|
||||
|
||||
let str = `import adapter from '@sveltejs/adapter-auto';
|
||||
import { vitePreprocess } from '@sveltejs/kit/vite';
|
||||
${iit(opts.mdsvex, mdsvexConfig)}
|
||||
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
extensions: ['.svelte'${iit(opts.mdsvex, `, '.md'`)}],
|
||||
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
|
||||
// for more information about preprocessors
|
||||
preprocess: vitePreprocess(),
|
||||
${
|
||||
opts?.inspector
|
||||
? `
|
||||
vitePlugin: {
|
||||
inspector: true,
|
||||
},`
|
||||
: ''
|
||||
}
|
||||
preprocess: [${iit(opts.mdsvex, 'mdsvex(mdsvexOptions),')} vitePreprocess()],
|
||||
${iit(opts.inspector, inspectorConfig)}
|
||||
kit: {
|
||||
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
|
||||
// If your environment is not supported or you settled on a specific environment, switch out the adapter.
|
||||
@@ -177,7 +203,34 @@ const config = {
|
||||
}
|
||||
};
|
||||
export default config;`;
|
||||
return str;
|
||||
writeFileSync(join(cwd(), 'svelte.config.js'), str);
|
||||
}
|
||||
|
||||
function createViteConfig(opts) {
|
||||
const filename = join(cwd(), opts.types == 'typescript' ? 'vite.config.ts' : 'vite.config.js');
|
||||
let contents = `import { purgeCss } from 'vite-plugin-tailwind-purgecss';
|
||||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [sveltekit(), purgeCss()]
|
||||
});
|
||||
`;
|
||||
writeFileSync(filename, contents);
|
||||
}
|
||||
|
||||
async function createVSCodeSettings() {
|
||||
try {
|
||||
mkdirp(join(cwd(), '.vscode'));
|
||||
const data = await got(
|
||||
'https://raw.githubusercontent.com/skeletonlabs/skeleton/master/packages/skeleton/scripts/tw-settings.json',
|
||||
).text();
|
||||
writeFileSync(join(cwd(), '.vscode', 'settings.json'), data);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Unable to download settings file for VSCode, please read manual instructions at https://skeleton.dev/guides/install',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function createTailwindConfig(opts) {
|
||||
@@ -192,10 +245,25 @@ function createTailwindConfig(opts) {
|
||||
pluginImports.push(`import typography from '@tailwindcss/typography'`);
|
||||
plugins.push(`typography`);
|
||||
}
|
||||
pluginImports.push(`import skeleton from '@skeletonlabs/skeleton/tailwind/skeleton.cjs'`);
|
||||
plugins.push(`...skeleton()`);
|
||||
pluginImports.push(`import { skeleton } from '@skeletonlabs/tw-plugin'`);
|
||||
// Can't use JSON.stringify because we node code literals in there without everything being coerced to quoted strings
|
||||
// space on the end is important
|
||||
let presetConfig = '{ themes: { preset: [ ';
|
||||
let customConfig = '';
|
||||
for (const theme of opts.skeletontheme) {
|
||||
if (typeof theme === 'string') {
|
||||
presetConfig += `{ name: "${theme}", enhancements: true },`;
|
||||
} else {
|
||||
pluginImports.push(`import { ${theme.custom} } from './src/${theme.custom}.js'`);
|
||||
customConfig = `, custom:[${theme.custom}]`;
|
||||
createCustomTheme(opts, theme.custom);
|
||||
}
|
||||
}
|
||||
const finalConfig = presetConfig.slice(0, -1) + ']' + customConfig + '}}';
|
||||
plugins.push(`skeleton(${finalConfig})`);
|
||||
|
||||
const str = `import { join } from 'path'
|
||||
${iit(opts.types == 'typescript', `import type { Config } from 'tailwindcss'`)}
|
||||
${pluginImports.join('\n')}
|
||||
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
@@ -206,11 +274,116 @@ module.exports = {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [${plugins.join(',')}],
|
||||
}
|
||||
}${iit(opts.types == 'typescript', ' satisfies Config')};
|
||||
`;
|
||||
return str;
|
||||
writeFileSync(join(cwd(), `tailwind.config.${iit(opts.types == 'typescript', 'ts', 'js')}`), str);
|
||||
}
|
||||
|
||||
function createCustomTheme(opts, name) {
|
||||
const str = `// You can also use the generator at https://skeleton.dev/docs/generator to create these values for you
|
||||
${iit(opts.types == 'typescript', `import type { CustomThemeConfig } from '@skeletonlabs/tw-plugin';`)}
|
||||
export const ${name}${iit(opts.types == 'typescript', ': CustomThemeConfig')} = {
|
||||
name: '${name}',
|
||||
properties: {
|
||||
// =~= Theme Properties =~=
|
||||
"--theme-font-family-base": "system-ui",
|
||||
"--theme-font-family-heading": "system-ui",
|
||||
"--theme-font-color-base": "0 0 0",
|
||||
"--theme-font-color-dark": "255 255 255",
|
||||
"--theme-rounded-base": "9999px",
|
||||
"--theme-rounded-container": "8px",
|
||||
"--theme-border-base": "1px",
|
||||
// =~= Theme On-X Colors =~=
|
||||
"--on-primary": "0 0 0",
|
||||
"--on-secondary": "255 255 255",
|
||||
"--on-tertiary": "0 0 0",
|
||||
"--on-success": "0 0 0",
|
||||
"--on-warning": "0 0 0",
|
||||
"--on-error": "255 255 255",
|
||||
"--on-surface": "255 255 255",
|
||||
// =~= Theme Colors =~=
|
||||
// primary | #0FBA81
|
||||
"--color-primary-50": "219 245 236", // #dbf5ec
|
||||
"--color-primary-100": "207 241 230", // #cff1e6
|
||||
"--color-primary-200": "195 238 224", // #c3eee0
|
||||
"--color-primary-300": "159 227 205", // #9fe3cd
|
||||
"--color-primary-400": "87 207 167", // #57cfa7
|
||||
"--color-primary-500": "15 186 129", // #0FBA81
|
||||
"--color-primary-600": "14 167 116", // #0ea774
|
||||
"--color-primary-700": "11 140 97", // #0b8c61
|
||||
"--color-primary-800": "9 112 77", // #09704d
|
||||
"--color-primary-900": "7 91 63", // #075b3f
|
||||
// secondary | #4F46E5
|
||||
"--color-secondary-50": "229 227 251", // #e5e3fb
|
||||
"--color-secondary-100": "220 218 250", // #dcdafa
|
||||
"--color-secondary-200": "211 209 249", // #d3d1f9
|
||||
"--color-secondary-300": "185 181 245", // #b9b5f5
|
||||
"--color-secondary-400": "132 126 237", // #847eed
|
||||
"--color-secondary-500": "79 70 229", // #4F46E5
|
||||
"--color-secondary-600": "71 63 206", // #473fce
|
||||
"--color-secondary-700": "59 53 172", // #3b35ac
|
||||
"--color-secondary-800": "47 42 137", // #2f2a89
|
||||
"--color-secondary-900": "39 34 112", // #272270
|
||||
// tertiary | #0EA5E9
|
||||
"--color-tertiary-50": "219 242 252", // #dbf2fc
|
||||
"--color-tertiary-100": "207 237 251", // #cfedfb
|
||||
"--color-tertiary-200": "195 233 250", // #c3e9fa
|
||||
"--color-tertiary-300": "159 219 246", // #9fdbf6
|
||||
"--color-tertiary-400": "86 192 240", // #56c0f0
|
||||
"--color-tertiary-500": "14 165 233", // #0EA5E9
|
||||
"--color-tertiary-600": "13 149 210", // #0d95d2
|
||||
"--color-tertiary-700": "11 124 175", // #0b7caf
|
||||
"--color-tertiary-800": "8 99 140", // #08638c
|
||||
"--color-tertiary-900": "7 81 114", // #075172
|
||||
// success | #84cc16
|
||||
"--color-success-50": "237 247 220", // #edf7dc
|
||||
"--color-success-100": "230 245 208", // #e6f5d0
|
||||
"--color-success-200": "224 242 197", // #e0f2c5
|
||||
"--color-success-300": "206 235 162", // #ceeba2
|
||||
"--color-success-400": "169 219 92", // #a9db5c
|
||||
"--color-success-500": "132 204 22", // #84cc16
|
||||
"--color-success-600": "119 184 20", // #77b814
|
||||
"--color-success-700": "99 153 17", // #639911
|
||||
"--color-success-800": "79 122 13", // #4f7a0d
|
||||
"--color-success-900": "65 100 11", // #41640b
|
||||
// warning | #EAB308
|
||||
"--color-warning-50": "252 244 218", // #fcf4da
|
||||
"--color-warning-100": "251 240 206", // #fbf0ce
|
||||
"--color-warning-200": "250 236 193", // #faecc1
|
||||
"--color-warning-300": "247 225 156", // #f7e19c
|
||||
"--color-warning-400": "240 202 82", // #f0ca52
|
||||
"--color-warning-500": "234 179 8", // #EAB308
|
||||
"--color-warning-600": "211 161 7", // #d3a107
|
||||
"--color-warning-700": "176 134 6", // #b08606
|
||||
"--color-warning-800": "140 107 5", // #8c6b05
|
||||
"--color-warning-900": "115 88 4", // #735804
|
||||
// error | #D41976
|
||||
"--color-error-50": "249 221 234", // #f9ddea
|
||||
"--color-error-100": "246 209 228", // #f6d1e4
|
||||
"--color-error-200": "244 198 221", // #f4c6dd
|
||||
"--color-error-300": "238 163 200", // #eea3c8
|
||||
"--color-error-400": "225 94 159", // #e15e9f
|
||||
"--color-error-500": "212 25 118", // #D41976
|
||||
"--color-error-600": "191 23 106", // #bf176a
|
||||
"--color-error-700": "159 19 89", // #9f1359
|
||||
"--color-error-800": "127 15 71", // #7f0f47
|
||||
"--color-error-900": "104 12 58", // #680c3a
|
||||
// surface | #495a8f
|
||||
"--color-surface-50": "228 230 238", // #e4e6ee
|
||||
"--color-surface-100": "219 222 233", // #dbdee9
|
||||
"--color-surface-200": "210 214 227", // #d2d6e3
|
||||
"--color-surface-300": "182 189 210", // #b6bdd2
|
||||
"--color-surface-400": "128 140 177", // #808cb1
|
||||
"--color-surface-500": "73 90 143", // #495a8f
|
||||
"--color-surface-600": "66 81 129", // #425181
|
||||
"--color-surface-700": "55 68 107", // #37446b
|
||||
"--color-surface-800": "44 54 86", // #2c3656
|
||||
"--color-surface-900": "36 44 70", // #242c46
|
||||
}
|
||||
}`;
|
||||
let filename = name + iit(opts.types == 'typescript', '.ts', '.js');
|
||||
writeFileSync(join('src', filename), str);
|
||||
}
|
||||
function createPostCssConfig() {
|
||||
const str = `module.exports = {
|
||||
plugins: {
|
||||
@@ -218,68 +391,71 @@ function createPostCssConfig() {
|
||||
autoprefixer: {},
|
||||
},
|
||||
}`;
|
||||
return str;
|
||||
writeFileSync(join(cwd(), 'postcss.config.cjs'), str);
|
||||
}
|
||||
|
||||
function copyTemplate(opts) {
|
||||
const src = path.resolve(dist(opts.skeletontemplatedir), opts.skeletontemplate);
|
||||
if (opts.meta == null) {
|
||||
opts.meta = JSON.parse(readFileSync(opts.skeletontemplate, 'utf8'));
|
||||
}
|
||||
|
||||
fs.copySync(src + '/src', './src', { overwrite: true });
|
||||
fs.copySync(src + '/static', './static', { overwrite: true });
|
||||
opts.meta.foldersToCopy.forEach((folder) => {
|
||||
cpSync(resolve(opts.skeletontemplatedir, folder), resolve(opts.path, folder), { force: true, recursive: true });
|
||||
});
|
||||
|
||||
// All fonts are in the template static folder, so we need to remove the ones that are not relevant to the theme
|
||||
// Determine which font is used by the theme, copy it over to the static folder
|
||||
// and then update the app.postcss file to include the correct font
|
||||
// Themes can by applied to any template, so we can't have the fonts as part of the templates themselves.
|
||||
let fontFamily = '';
|
||||
let fontFile = '';
|
||||
switch (opts.skeletontheme) {
|
||||
case 'gold-nouveau':
|
||||
case 'modern':
|
||||
case 'seasonal':
|
||||
fontFamily = 'Quicksand';
|
||||
fontFile = ['Quicksand.ttf'];
|
||||
break;
|
||||
case 'rocket':
|
||||
fontFamily = 'Space Grotesk';
|
||||
fontFile = ['SpaceGrotesk.ttf'];
|
||||
break;
|
||||
case 'seafoam':
|
||||
fontFamily = 'Playfair Display';
|
||||
fontFile = ['PlayfairDisplay-Italic.ttf'];
|
||||
break;
|
||||
case 'vintage':
|
||||
fontFamily = 'Abril Fatface';
|
||||
fontFile = ['AbrilFatface.ttf'];
|
||||
break;
|
||||
default:
|
||||
fontFamily = '';
|
||||
fontFile = '';
|
||||
}
|
||||
if (fontFamily !== '') {
|
||||
fs.appendFileSync(
|
||||
'./src/app.postcss',
|
||||
`
|
||||
let addedFontConfig = '';
|
||||
for (const theme of opts.skeletontheme) {
|
||||
switch (theme) {
|
||||
case 'gold-nouveau':
|
||||
case 'modern':
|
||||
case 'seasonal':
|
||||
fontFamily = 'Quicksand';
|
||||
fontFile = 'Quicksand.ttf';
|
||||
break;
|
||||
case 'rocket':
|
||||
fontFamily = 'Space Grotesk';
|
||||
fontFile = 'SpaceGrotesk.ttf';
|
||||
break;
|
||||
case 'seafoam':
|
||||
fontFamily = 'Playfair Display';
|
||||
fontFile = 'PlayfairDisplay-Italic.ttf';
|
||||
break;
|
||||
case 'vintage':
|
||||
fontFamily = 'Abril Fatface';
|
||||
fontFile = 'AbrilFatface.ttf';
|
||||
break;
|
||||
default:
|
||||
fontFamily = '';
|
||||
fontFile = '';
|
||||
}
|
||||
if (fontFamily !== '') {
|
||||
addedFontConfig += `
|
||||
/* ${theme} theme */
|
||||
@font-face {
|
||||
font-family: '${fontFamily}';
|
||||
src: url('/fonts/${fontFile}');
|
||||
font-display: swap;
|
||||
}`,
|
||||
);
|
||||
removeFilesExceptSync('./static/fonts/', fontFile);
|
||||
} else {
|
||||
fs.removeSync('./static/fonts');
|
||||
}`;
|
||||
cpSync(resolve(__dirname, '../fonts/', fontFile), join(cwd(), 'static', 'fonts', fontFile));
|
||||
}
|
||||
}
|
||||
appendFileSync(join(cwd(), 'src', 'app.postcss'), addedFontConfig);
|
||||
|
||||
const layoutFile = resolve(cwd(), 'src/routes/+layout.svelte');
|
||||
// patch back in their theme choice - it may have been replaced by the theme template, it may still be the correct auto-genned one, depends on the template - we don't care, this fixes it.
|
||||
let content = fs.readFileSync('./src/routes/+layout.svelte', {
|
||||
encoding: 'utf8',
|
||||
flag: 'r',
|
||||
});
|
||||
const themeReg = /theme-.*\.css';$/gim;
|
||||
content = content.replace(themeReg, `theme-${opts.skeletontheme}.css';`);
|
||||
content = (opts.types === 'typescript' ? "<script lang='ts'>" : '<script>') + content.substring(content.indexOf('\n'));
|
||||
let content = readFileSync(layoutFile, { encoding: 'utf8' });
|
||||
// Set the script ype depending on their choice of typescript or checkjs
|
||||
content = (opts.types === 'typescript' ? `<script lang="ts">` : '<script>') + content.substring(content.indexOf('\n'));
|
||||
|
||||
// Add in the basic boilerplate for codeblocks and popups if they were selected and do a basic check for the import name to avoid duplicates
|
||||
const scriptEndReg = /<\/script>/g;
|
||||
if (opts?.highlightjs) {
|
||||
|
||||
if (opts.codeblocks && content.indexOf('highlight.js') === -1) {
|
||||
content = content.replace(
|
||||
scriptEndReg,
|
||||
`
|
||||
@@ -292,7 +468,7 @@ function copyTemplate(opts) {
|
||||
);
|
||||
}
|
||||
|
||||
if (opts?.highlightjs) {
|
||||
if (opts?.popups && content.indexOf('@floating-ui/dom') === -1) {
|
||||
content = content.replace(
|
||||
scriptEndReg,
|
||||
`
|
||||
@@ -304,20 +480,33 @@ function copyTemplate(opts) {
|
||||
);
|
||||
}
|
||||
|
||||
fs.writeFileSync('./src/routes/+layout.svelte', content);
|
||||
writeFileSync(layoutFile, content);
|
||||
|
||||
// update the <body> to have the data-theme
|
||||
content = fs.readFileSync('./src/app.html', {
|
||||
encoding: 'utf8',
|
||||
flag: 'r',
|
||||
});
|
||||
fs.writeFileSync(
|
||||
'./src/app.html',
|
||||
content.replace('<body>', `<body data-sveltekit-preload-data="hover" data-theme="${opts.skeletontheme}">`),
|
||||
);
|
||||
// Update the data-theme attribute in the app.html file
|
||||
content = readFileSync(resolve(opts.path, 'src/app.html'), { encoding: 'utf8' });
|
||||
const dataThemeRegex = /data-theme=".*"/gim;
|
||||
let activeTheme = 'skeleton';
|
||||
if (typeof opts.skeletontheme[0] === 'string') {
|
||||
activeTheme = opts.skeletontheme[0];
|
||||
} else {
|
||||
activeTheme = opts.skeletontheme[0].custom;
|
||||
}
|
||||
writeFileSync(resolve(opts.path, 'src/app.html'), content.replace(dataThemeRegex, `data-theme="${activeTheme}"`));
|
||||
}
|
||||
|
||||
function out(filename, data) {
|
||||
if (data == undefined) return;
|
||||
fs.writeFileSync(filename, data);
|
||||
function createTestConfig() {
|
||||
const str = `import type { PlaywrightTestConfig } from '@playwright/test';
|
||||
|
||||
const config: PlaywrightTestConfig = {
|
||||
webServer: {
|
||||
command: 'pnpm build && pnpm preview',
|
||||
port: 4173
|
||||
},
|
||||
testDir: '../../../tests/',
|
||||
testMatch: /(.+\.)?(test|spec)\.[jt]s/
|
||||
};
|
||||
|
||||
export default config;
|
||||
`;
|
||||
writeFileSync('playwright.config.ts', str);
|
||||
}
|
||||
|
||||
@@ -4,10 +4,11 @@ import fs from 'fs-extra';
|
||||
import mri from 'mri';
|
||||
import { bold, cyan, gray, grey, red } from 'kleur/colors';
|
||||
import { intro, text, select, multiselect, spinner } from '@clack/prompts';
|
||||
import events from 'events';
|
||||
import { dist, getHelpText, goodbye } from './utils.js';
|
||||
import path from 'path';
|
||||
import { dist, getHelpText, goodbye, whichPMRuns, checkIfDirSafeToInstall } from './utils.js';
|
||||
import path, { resolve, join } from 'path';
|
||||
import semver from 'semver';
|
||||
import fg from 'fast-glob';
|
||||
|
||||
// Minimum version required for Svelte Kit
|
||||
const requiredVersion = '16.14.0';
|
||||
|
||||
@@ -17,35 +18,56 @@ async function main() {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// This is required to handle spawning processes
|
||||
events.EventEmitter.defaultMaxListeners = 15;
|
||||
|
||||
const startPath = process.cwd();
|
||||
let defaults = new SkeletonOptions();
|
||||
|
||||
// grab any passed arguments from the command line
|
||||
let opts = await parseArgs();
|
||||
|
||||
if ('quiet' in opts) {
|
||||
// in quiet mode we prefill the defaults, then overlay the passed options and bypass all of askForMissingParams so that it
|
||||
// doesn't have to constantly check for quietmode all the time.
|
||||
let defaults = new SkeletonOptions();
|
||||
opts = Object.assign(defaults, opts);
|
||||
// need to set some defaults if they are not passed in
|
||||
if (!('quiet' in opts)) opts.quiet = false;
|
||||
// if no templatedir is provided we have to account for the dist location
|
||||
if (!('skeletontemplatedir' in opts)) {
|
||||
opts.skeletontemplatedir = resolve(dist('.'), '../templates');
|
||||
} else {
|
||||
// in interactive mode we ask the user to fill anything not passed in
|
||||
// Resolve can handle multiple absolute paths so passing in a relative or absolute path is fine
|
||||
opts.skeletontemplatedir = resolve(process.cwd(), opts.skeletontemplatedir);
|
||||
}
|
||||
|
||||
try {
|
||||
checkIfDirSafeToInstall(opts.path);
|
||||
} catch (e) {
|
||||
console.error(red(`\n${e.message}`));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!opts.quiet) {
|
||||
opts = await askForMissingParams(opts);
|
||||
}
|
||||
opts = Object.assign(defaults, opts);
|
||||
opts.packagemanager = whichPMRuns()?.name;
|
||||
|
||||
// Now that we have all of the options, lets create it.
|
||||
const s = spinner();
|
||||
s.start('Installing');
|
||||
await createSkeleton(opts);
|
||||
s.stop('Done installing');
|
||||
// And give the user some final information on what to do Next
|
||||
if (!opts?.quiet) {
|
||||
if (!opts.quiet) {
|
||||
s.start('Installing');
|
||||
}
|
||||
|
||||
try {
|
||||
await createSkeleton(opts);
|
||||
} catch (e) {
|
||||
console.error(red(`\n${e.message}`));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!opts.quiet) {
|
||||
s.stop('Done installing');
|
||||
// And give the user some final information on what to do Next
|
||||
|
||||
const pm = opts.packagemanager;
|
||||
let runString = `${pm} dev\n`;
|
||||
let runString = `${pm} install\n${pm} dev\n`;
|
||||
|
||||
if (pm == 'npm') {
|
||||
runString = 'npm run dev\n';
|
||||
runString = 'npm install\nnpm run dev\n';
|
||||
}
|
||||
let finalInstructions = bold(cyan(`\nDone! You can now:\n\n`));
|
||||
if (startPath != opts.path) {
|
||||
@@ -66,7 +88,6 @@ async function parseArgs() {
|
||||
const opts = mri(argv, {
|
||||
alias: {
|
||||
h: 'help',
|
||||
n: 'name',
|
||||
p: 'path',
|
||||
t: 'skeletontheme',
|
||||
m: 'monorepo',
|
||||
@@ -77,7 +98,6 @@ async function parseArgs() {
|
||||
'help',
|
||||
'quiet',
|
||||
'monorepo',
|
||||
'skeletonui',
|
||||
'library',
|
||||
'prettier',
|
||||
'eslint',
|
||||
@@ -88,15 +108,15 @@ async function parseArgs() {
|
||||
'popups',
|
||||
'forms',
|
||||
'typography',
|
||||
'verbose',
|
||||
'mdsvex',
|
||||
],
|
||||
});
|
||||
|
||||
// If a user invokes 'create-app blah foo', it falls into the _ catch all list, the best we can do is take the first one and use that as the name
|
||||
// If a user invokes 'create-app blah foo', it falls into the _ catch all list, the best we can do is take the first one and use that as the path
|
||||
// if args are passed in incorrectly such as --prettier=0 instead of --prettier=false then a 0 will be added to the _ collection, we check that the
|
||||
// first one isn't a bungled arg set to 0
|
||||
if (opts._.length && opts._[0] != 0) {
|
||||
opts.name = opts._[0];
|
||||
opts.path = opts._[0];
|
||||
}
|
||||
// Show help if specified regardless of how many other options are specified, have fun updating the text string in utils.ts :(
|
||||
if ('help' in opts) {
|
||||
@@ -106,37 +126,6 @@ async function parseArgs() {
|
||||
return opts;
|
||||
}
|
||||
|
||||
function checkIfDirSafeToInstall(path) {
|
||||
// Check if the directory already exists.
|
||||
if (!fs.existsSync(path)) return;
|
||||
|
||||
//lets see whats in there
|
||||
const conflicts = fs
|
||||
.readdirSync(path)
|
||||
.filter((file) =>
|
||||
/^(package.json|svelte.config.js|tailwind.config.cjs|pnpm-lock.yaml|postcss.config.cjs|vite.config.ts)$/.test(file),
|
||||
);
|
||||
|
||||
if (conflicts.length > 0) {
|
||||
console.log("create-skeleton-app doesn't support updating an existing project, it needs a new empty directory to install into");
|
||||
console.log(`The directory ${path} contains files that could conflict:`);
|
||||
console.log();
|
||||
for (const file of conflicts) {
|
||||
try {
|
||||
const stats = fs.lstatSync(path + '/' + file);
|
||||
if (stats.isDirectory()) {
|
||||
console.log(` ${red(file)}/`);
|
||||
} else {
|
||||
console.log(` ${red(file)}`);
|
||||
}
|
||||
} catch {
|
||||
console.log(` ${red(file)}`);
|
||||
}
|
||||
}
|
||||
console.log('Either try using a new directory name, or remove the files listed above.');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param {SkeletonOptions} opts
|
||||
*/
|
||||
@@ -150,21 +139,154 @@ ${bold(cyan('Welcome to Skeleton 💀! A UI toolkit for Svelte + Tailwind'))}
|
||||
Problems? Open an issue on ${cyan('https://github.com/skeletonlabs/skeleton/issues')} if none exists already.`);
|
||||
|
||||
//NOTE: When doing checks here, make sure to test for the presence of the prop, not the prop value as it may be set to false deliberately.
|
||||
if (!('name' in opts)) {
|
||||
opts.name = await text({
|
||||
message: 'Name for your new project:?',
|
||||
placeholder: 'my-app',
|
||||
if (!('path' in opts)) {
|
||||
opts.path = await text({
|
||||
message: 'Where should we install your project (Enter for current directory) ?',
|
||||
placeholder: '',
|
||||
validate(value) {
|
||||
if (value.length === 0) return `App name is required!`;
|
||||
if (value.length === 0) value = '.';
|
||||
try {
|
||||
checkIfDirSafeToInstall(resolve(process.cwd(), value));
|
||||
} catch (e) {
|
||||
return e.message;
|
||||
}
|
||||
},
|
||||
});
|
||||
goodbye(opts.name);
|
||||
goodbye(opts.path);
|
||||
}
|
||||
// name to set in package.json
|
||||
opts.name = opts.path;
|
||||
|
||||
// Skeleton Template Selection
|
||||
// We have to ask for the template first as it may dictate things like required packages and typechecking
|
||||
// skeletontemplatedir is the path to the templates directory, it's either passed in as an arg or set to cwd
|
||||
// it may be a single directory with a csa-meta in the root,
|
||||
// or it holds multiple directories with csa-meta files in them and skeletontemplate selects that sub folder.
|
||||
|
||||
let templateFound = false;
|
||||
if (opts?.skeletontemplate) {
|
||||
// they have asked for a specific template within the folder
|
||||
opts.skeletontemplate = resolve(opts.skeletontemplatedir, opts.skeletontemplate, 'csa-meta.json');
|
||||
//check that it exists
|
||||
if (!fs.existsSync(opts.skeletontemplate)) {
|
||||
console.error(`The template ${opts.skeletontemplate} does not exist`);
|
||||
process.exit(1);
|
||||
}
|
||||
templateFound = true;
|
||||
}
|
||||
// no template specified, so scan the templatedir for csa-meta files
|
||||
if (!templateFound) {
|
||||
const metaFiles = fg.sync(['**/csa-meta.json'], { cwd: opts.skeletontemplatedir, deep: 2 });
|
||||
if (metaFiles.length === 0) {
|
||||
console.error(`No templates found in ${opts.skeletontemplatedir}`);
|
||||
process.exit(1);
|
||||
}
|
||||
let parsedChoices = [];
|
||||
metaFiles.forEach((meta_file) => {
|
||||
const path = join(opts.skeletontemplatedir, meta_file);
|
||||
const { position, label, description, enabled } = JSON.parse(fs.readFileSync(path, 'utf8'));
|
||||
if (enabled) {
|
||||
parsedChoices.push({ position, label, hint: description, value: path });
|
||||
}
|
||||
});
|
||||
parsedChoices.sort((a, b) => a.position - b.position);
|
||||
opts.skeletontemplate = await select({
|
||||
message: 'Which Skeleton app template?',
|
||||
options: parsedChoices,
|
||||
});
|
||||
goodbye(opts.skeletontemplate);
|
||||
}
|
||||
// Now that we have the template, lets get the meta data from it and the base path
|
||||
opts.meta = JSON.parse(fs.readFileSync(opts.skeletontemplate, 'utf8'));
|
||||
if (opts.meta.requiredFeatures) {
|
||||
opts.meta.requiredFeatures.forEach((val) => {
|
||||
Object.assign(opts, val);
|
||||
});
|
||||
}
|
||||
opts.skeletontemplatedir = path.dirname(opts.skeletontemplate);
|
||||
|
||||
// If it's a premium template, wording needs to be change to indicate that there is a theme already built in
|
||||
// Skeleton Theme Selection
|
||||
if (!('skeletontheme' in opts)) {
|
||||
let themeChoices = [
|
||||
{ label: 'Skeleton', value: 'skeleton' },
|
||||
{ label: 'Modern', value: 'modern' },
|
||||
{ label: 'Hamlindigo', value: 'hamlindigo' },
|
||||
{ label: 'Rocket', value: 'rocket' },
|
||||
{ label: 'Sahara', value: 'sahara' },
|
||||
{ label: 'Gold Nouveau', value: 'gold-nouveau' },
|
||||
{ label: 'Vintage', value: 'vintage' },
|
||||
{ label: 'Seafoam', value: 'seafoam' },
|
||||
{ label: 'Crimson', value: 'crimson' },
|
||||
{ label: cyan('Custom'), value: 'custom', hint: 'Will ask for a name next' },
|
||||
];
|
||||
if (opts.meta.type === 'premium') {
|
||||
themeChoices.unshift({ label: 'Use templates built in theme', value: 'builtin' });
|
||||
}
|
||||
opts.skeletontheme = await multiselect({
|
||||
message: 'Select a theme (top most selection will be default):',
|
||||
options: themeChoices,
|
||||
required: true,
|
||||
});
|
||||
goodbye(opts.skeletontheme);
|
||||
}
|
||||
|
||||
if (opts.skeletontheme.includes('custom')) {
|
||||
let customName = await text({
|
||||
message: 'Enter a name for your custom theme:',
|
||||
placeholder: 'theme_name',
|
||||
validate(value) {
|
||||
if (value.length === 0) {
|
||||
return 'Please enter a name for your custom theme';
|
||||
}
|
||||
// regex to check if value can be used as a variable name, it cannot allow hyphens
|
||||
if (!/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(value)) {
|
||||
return 'Name for theme must be a valid syntax for a Javascript variable name';
|
||||
}
|
||||
},
|
||||
});
|
||||
opts.skeletontheme.pop('custom');
|
||||
opts.skeletontheme.push({ custom: customName });
|
||||
goodbye();
|
||||
}
|
||||
|
||||
// Additional packages to install - these can be influenced by the template selected
|
||||
let packages = [
|
||||
{ value: 'forms', label: 'Add Tailwind forms ?', package: '@tailwindcss/forms', force: false },
|
||||
{ value: 'typography', label: 'Add Tailwind typography ?', package: '@tailwindcss/typography', force: false },
|
||||
{ value: 'codeblocks', label: 'Add CodeBlock (installs highlight.js) ?', package: 'highlight.js', force: false },
|
||||
{ value: 'popups', label: 'Add Popups (installs floating-ui) ?', package: '@floating-ui/dom', force: false },
|
||||
// { value: 'mdsvex', label: 'Add Markdown support (installs mdsvex) ?', package: 'mdsvex', force: false },
|
||||
];
|
||||
// Force the packages that are required by the template
|
||||
packages.forEach((pkg) => {
|
||||
if (opts[pkg.value] != undefined) pkg.force = true;
|
||||
});
|
||||
// Now we can ask the user about any options that are not forced to be installed
|
||||
let optionalPackages = packages.filter((pkg) => !pkg.force);
|
||||
// Get list of forced packages to display to the user
|
||||
let msg = '';
|
||||
packages.forEach((p) => {
|
||||
if (p.force) msg += p.package + '\n';
|
||||
});
|
||||
if (msg.length > 0) {
|
||||
msg = `\nThe following packages will be installed because they are required by the template:\n\n${msg}\nWhat other packages would you like to install:`;
|
||||
} else {
|
||||
msg = `\nWhat other packages would you like to install:`;
|
||||
}
|
||||
|
||||
if (optionalPackages.length > 0) {
|
||||
// check which options are set and fill the initialValues array
|
||||
const packageChoices = await multiselect({
|
||||
message: msg,
|
||||
options: optionalPackages,
|
||||
required: false,
|
||||
});
|
||||
goodbye(packages);
|
||||
if (Array.isArray(packageChoices)) {
|
||||
packageChoices.forEach((value) => (opts[value] = true));
|
||||
}
|
||||
}
|
||||
// test the path to make sure it is safe to install
|
||||
if (opts.path === undefined) opts.path = process.cwd();
|
||||
opts.name = opts.name.replace(/\s+/g, '-').toLowerCase();
|
||||
opts.path = path.resolve(opts.path, opts.name);
|
||||
checkIfDirSafeToInstall(opts.path);
|
||||
|
||||
if (!('types' in opts)) {
|
||||
opts.types = await select({
|
||||
@@ -200,79 +322,9 @@ Problems? Open an issue on ${cyan('https://github.com/skeletonlabs/skeleton/issu
|
||||
required: false,
|
||||
});
|
||||
goodbye(optionalInstalls);
|
||||
optionalInstalls.every((value) => (opts[value] = true));
|
||||
optionalInstalls.forEach((value) => (opts[value] = true));
|
||||
}
|
||||
|
||||
// Additional packages to install
|
||||
if (
|
||||
!['forms', 'typography', 'codeblocks', 'popups'].every((value) => {
|
||||
return Object.keys(opts).includes(value);
|
||||
})
|
||||
) {
|
||||
const packages = await multiselect({
|
||||
message: 'What other packages would you like to install:',
|
||||
initialValues: ['forms', 'typography', 'codeblocks', 'popups'].filter((value) => {
|
||||
return Object.keys(opts).includes(value);
|
||||
}),
|
||||
options: [
|
||||
{ value: 'forms', label: 'Add Tailwind forms ?' },
|
||||
{ value: 'typography', label: 'Add Tailwind typography ?' },
|
||||
{ value: 'codeblocks', label: 'Add CodeBlock (installs highlight.js) ?' },
|
||||
{ value: 'popups', label: 'Add Popups (installs floating-ui) ?' },
|
||||
],
|
||||
required: false,
|
||||
});
|
||||
goodbye(packages);
|
||||
packages.every((value) => (opts[value] = true));
|
||||
}
|
||||
|
||||
// Skeleton Theme Selection
|
||||
if (!('skeletontheme' in opts)) {
|
||||
opts.skeletontheme = await select({
|
||||
message: 'Select a theme:',
|
||||
options: [
|
||||
{ label: 'Skeleton', value: 'skeleton' },
|
||||
{ label: 'Modern', value: 'modern' },
|
||||
{ label: 'Hamlindigo', value: 'hamlindigo' },
|
||||
{ label: 'Rocket', value: 'rocket' },
|
||||
{ label: 'Sahara', value: 'sahara' },
|
||||
{ label: 'Gold Nouveau', value: 'gold-nouveau' },
|
||||
{ label: 'Vintage', value: 'vintage' },
|
||||
{ label: 'Seafoam', value: 'seafoam' },
|
||||
{ label: 'Crimson', value: 'crimson' },
|
||||
],
|
||||
});
|
||||
goodbye(opts.skeletontheme);
|
||||
}
|
||||
|
||||
//Skeleton Template Selection
|
||||
if (!('skeletontemplate' in opts)) {
|
||||
// need to check whether a templatedir has been passed in (might be from a script in package.json pointing to real template projects)
|
||||
const templateDir = opts.skeletontemplatedir || '../templates';
|
||||
let parsedChoices = [];
|
||||
fs.readdirSync(dist(templateDir)).forEach((dir) => {
|
||||
const meta_file = dist(`${templateDir}/${dir}/csa-meta.json`);
|
||||
const { position, label, description, enabled } = JSON.parse(fs.readFileSync(meta_file, 'utf8'));
|
||||
if (enabled) {
|
||||
parsedChoices.push({
|
||||
position,
|
||||
label,
|
||||
description,
|
||||
value: dir,
|
||||
});
|
||||
}
|
||||
});
|
||||
parsedChoices.sort((a, b) => a.position - b.position);
|
||||
opts.skeletontemplate = await select({
|
||||
message: 'Which Skeleton app template?',
|
||||
options: parsedChoices,
|
||||
});
|
||||
goodbye(opts.skeletontemplate);
|
||||
}
|
||||
|
||||
const skelOpts = new SkeletonOptions();
|
||||
Object.assign(skelOpts, opts);
|
||||
return skelOpts;
|
||||
return opts;
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import isCI from 'is-ci';
|
||||
import { readFileSync, writeFileSync } from 'fs';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
// no it can't be run on preinstall
|
||||
// no it can't be a nice little npm package
|
||||
// yes it's running install twice
|
||||
// yes it's a hack
|
||||
// but it works (on Vercel at least)
|
||||
|
||||
export function makeWorkspacePackageLinks(pkg) {
|
||||
if (pkg?.deployConfig?.dependencies != undefined) {
|
||||
for (const [dep, version] of Object.entries(pkg.deployConfig.dependencies)) {
|
||||
pkg.dependencies[dep] = 'workspace:^';
|
||||
}
|
||||
}
|
||||
if (pkg?.deployConfig?.devDependencies != undefined) {
|
||||
for (const [devDep, version] of Object.entries(pkg.deployConfig.devDependencies)) {
|
||||
pkg.devDependencies[devDep] = 'workspace:^';
|
||||
}
|
||||
}
|
||||
if (pkg?.deployConfig?.peerDependencies != undefined) {
|
||||
for (const [peerDep, version] of Object.entries(pkg.deployConfig.dependencies)) {
|
||||
pkg.peerDependencies[peerDep] = 'workspace:^';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function makeVersionedPackageLinks(pkg) {
|
||||
let clean = true;
|
||||
if (pkg?.deployConfig?.dependencies != undefined) {
|
||||
for (const [dep, version] of Object.entries(pkg.deployConfig.dependencies)) {
|
||||
if (pkg.dependencies[dep] !== version) {
|
||||
pkg.dependencies[dep] = version;
|
||||
clean = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pkg?.deployConfig?.devDependencies != undefined) {
|
||||
for (const [devDep, version] of Object.entries(pkg?.deployConfig?.devDependencies)) {
|
||||
if (pkg?.devDependencies[devDep] !== version) {
|
||||
pkg.devDependencies[devDep] = version;
|
||||
clean = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pkg?.deployConfig?.peerDependencies != undefined) {
|
||||
for (const [peerDep, version] of Object.entries(pkg?.deployConfig?.devDependencies)) {
|
||||
if (pkg?.peerDependencies[peerDep] !== version) {
|
||||
pkg.peerDependencies[peerDep] = version;
|
||||
clean = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { pkg: pkg, clean: clean };
|
||||
}
|
||||
|
||||
export function swapdeps() {
|
||||
let pkg = JSON.parse(readFileSync('./package.json', 'utf8'));
|
||||
let clean = true;
|
||||
|
||||
switch (process.argv.slice(2)[0]) {
|
||||
case 'workspace':
|
||||
console.log('Setting dependencies to workspace:^');
|
||||
makeWorkspacePackageLinks(pkg);
|
||||
break;
|
||||
case 'versioned':
|
||||
console.log('Setting dependencies to versioned');
|
||||
makeVersionedPackageLinks(pkg);
|
||||
break;
|
||||
case '-h':
|
||||
case 'h':
|
||||
case '--help':
|
||||
case 'help':
|
||||
console.log(
|
||||
'swapdeps [workspace|versioned] or no args for auto-change to versioned if in a CI environment or workspace links if not',
|
||||
);
|
||||
break;
|
||||
default:
|
||||
if (isCI) {
|
||||
({ pkg, clean } = makeVersionedPackageLinks(pkg));
|
||||
} else {
|
||||
console.log('No CI detected, setting dependencies to workspace:^');
|
||||
makeWorkspacePackageLinks(pkg);
|
||||
}
|
||||
}
|
||||
writeFileSync('./package.json', JSON.stringify(pkg, null, 2), 'utf8');
|
||||
if (clean === false) {
|
||||
execSync('pnpm install --no-frozen-lockfile');
|
||||
}
|
||||
}
|
||||
|
||||
swapdeps();
|
||||
@@ -1,21 +1,33 @@
|
||||
import { fileURLToPath } from 'url';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { cancel, isCancel } from '@clack/prompts';
|
||||
import path from 'path';
|
||||
import path from 'node:path';
|
||||
import fs from 'fs-extra';
|
||||
import columnify from 'columnify';
|
||||
|
||||
export function whichPMRuns() {
|
||||
const userAgent = process.env.npm_config_user_agent;
|
||||
if (!userAgent) {
|
||||
return undefined;
|
||||
return 'npm';
|
||||
}
|
||||
const pmSpec = userAgent.split(' ')[0] || '';
|
||||
const separatorPos = pmSpec.lastIndexOf('/');
|
||||
const name = pmSpec?.substring(0, separatorPos);
|
||||
return {
|
||||
name: name === 'npminstall' ? 'cnpm' : name,
|
||||
name: name === 'npminstall' ? 'npm' : name,
|
||||
version: pmSpec?.substring(separatorPos + 1),
|
||||
};
|
||||
}
|
||||
// Set a JSON value when the parent keys may not exist
|
||||
export function setNestedValue(obj, path, value) {
|
||||
let current = obj;
|
||||
for (let i = 0; i < path.length - 1; i++) {
|
||||
if (current[path[i]] === undefined) {
|
||||
current[path[i]] = {};
|
||||
}
|
||||
current = current[path[i]];
|
||||
}
|
||||
current[path[path.length - 1]] = value;
|
||||
}
|
||||
|
||||
/** @param {string} dir */
|
||||
export function mkdirp(dir) {
|
||||
@@ -26,6 +38,18 @@ export function mkdirp(dir) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
// Insert If True
|
||||
export function iit(valToBeTruthy, valToReturnIfTruthy, valToReturnIfFalsy) {
|
||||
if (valToBeTruthy) {
|
||||
return valToReturnIfTruthy;
|
||||
} else {
|
||||
if (valToReturnIfFalsy === undefined) {
|
||||
return '';
|
||||
} else {
|
||||
return valToReturnIfFalsy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function dist(pathToFind) {
|
||||
let pathAdjust = '';
|
||||
@@ -54,41 +78,124 @@ export function goodbye(option) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getHelpText() {
|
||||
// Must use spaces for adjustments as output can get very wonky with tab output
|
||||
// Why not array of arrays, TBH it's more readable in source like this and easy to edit with column selection etc.
|
||||
// But the advantage would be that padEnd could be adjusted to the console.width... will wait for feedback.
|
||||
return `
|
||||
Option Short Quiet Default Values Description
|
||||
--help -h This help screen
|
||||
--quiet -q Quiet mode - see below
|
||||
--verbose -v Show shell output for troubleshooting
|
||||
--name -n new-skel-app string, no spaces Name of the directory for the project
|
||||
--types typescript typescript|checkjs TypeScript or JavaScript with JSDoc
|
||||
--prettier true true|false Whether Prettier is added
|
||||
--eslint true true|false Whether ESLint is added
|
||||
--playwright false true|false Whether Playwright is added
|
||||
--vitest false true|false Whether Vitest is added
|
||||
--codeblocks false true|false Install codeblock optional dependencies
|
||||
--popups true true|false Install popups dependencies
|
||||
--path -p '' relative or absolute path Location to install, name is appended
|
||||
--forms false true|false Add Tailwinds Forms plugin
|
||||
--typography false true|false Add Tailwinds Typography plugin
|
||||
--skeletontheme -t skeleton skeleton Choose one for the Skeleton theme
|
||||
modern
|
||||
hamlindigo
|
||||
rocket
|
||||
sahara
|
||||
gold-nouveau
|
||||
vintage
|
||||
seafoam
|
||||
crimson
|
||||
--skeletontemplate bare bare The Skeleton template to use
|
||||
welcome
|
||||
export function checkIfDirSafeToInstall(path) {
|
||||
// no dir, no conflicts
|
||||
if (!fs.existsSync(path)) {
|
||||
return true;
|
||||
}
|
||||
let conflicts = fs.readdirSync(path);
|
||||
conflicts = conflicts.filter((file) =>
|
||||
/^(package.json|svelte.config.js|tailwind.config.cjs|postcss.config.cjs|vite.config.ts)$/.test(file),
|
||||
);
|
||||
|
||||
if (conflicts.length > 0) {
|
||||
const err = new Error(
|
||||
`The directory ${path} contains files that could conflict:\n${conflicts.join(
|
||||
'\n',
|
||||
)}\n\nPlease provide a clean directory to install into.`,
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
|
||||
// 10 was picked because if it's in something like a ~/projects directory and it would be annoying to strip out the added files and folders
|
||||
if (conflicts.length > 10) {
|
||||
const err = new Error(`The directory ${path} contains too many files/folders to safely install.`);
|
||||
throw err;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getHelpText() {
|
||||
// TODO: Ensure options are up to date
|
||||
const data = [
|
||||
{ Option: '--help', Short: '-h', 'Quiet Default': '', Value: '', Description: 'This help screen' },
|
||||
{ Option: '--quiet', Short: '-q', 'Quiet Default': '', Value: '', Description: 'Quiet mode - see below' },
|
||||
{
|
||||
Option: '--name',
|
||||
Short: '-n',
|
||||
'Quiet Default': 'skeleton-app',
|
||||
Value: 'skeleton-app',
|
||||
Description: 'Name of the directory for the project',
|
||||
},
|
||||
{
|
||||
Option: '--path',
|
||||
Short: '-p',
|
||||
'Quiet Default': "''",
|
||||
Value: 'relative or absolute path',
|
||||
Description: 'Location to install, name is appended',
|
||||
},
|
||||
{
|
||||
Option: '--types',
|
||||
Short: '',
|
||||
'Quiet Default': 'typescript',
|
||||
Value: 'typescript|checkjs',
|
||||
Description: 'TypeScript or JavaScript with JSDoc',
|
||||
},
|
||||
{ Option: '--prettier', Short: '', 'Quiet Default': 'true', Value: 'true|false', Description: 'Whether Prettier is added' },
|
||||
{ Option: '--eslint', Short: '', 'Quiet Default': 'true', Value: 'true|false', Description: 'Whether ESLint is added' },
|
||||
{ Option: '--playwright', Short: '', 'Quiet Default': 'false', Value: 'true|false', Description: 'Whether Playwright is added' },
|
||||
{ Option: '--vitest', Short: '', 'Quiet Default': 'false', Value: 'true|false', Description: 'Whether Vitest is added' },
|
||||
{
|
||||
Option: '--codeblocks',
|
||||
Short: '',
|
||||
'Quiet Default': 'false',
|
||||
Value: 'true|false',
|
||||
Description: 'Install codeblock optional dependencies',
|
||||
},
|
||||
{ Option: '--popups', Short: '', 'Quiet Default': 'false', Value: 'true|false', Description: 'Install popups dependencies' },
|
||||
{
|
||||
Option: '--mdsvex',
|
||||
Short: '',
|
||||
'Quiet Default': 'false',
|
||||
Value: 'true|false',
|
||||
Description: 'Install mdsvex for markdown processing',
|
||||
},
|
||||
{ Option: '--forms', Short: '', 'Quiet Default': 'false', Value: 'true|false', Description: 'Install Tailwinds Forms plugin' },
|
||||
{
|
||||
Option: '--typography',
|
||||
Short: '',
|
||||
'Quiet Default': 'false',
|
||||
Value: 'true|false',
|
||||
Description: 'Install Tailwinds Typography plugin',
|
||||
},
|
||||
{
|
||||
Option: '--skeletontemplatedir',
|
||||
Short: '',
|
||||
'Quiet Default': '',
|
||||
Value: '',
|
||||
Description: 'Path to directory containing templates',
|
||||
},
|
||||
{
|
||||
Option: '--skeletontheme',
|
||||
Short: '-t',
|
||||
'Quiet Default': 'skeleton',
|
||||
Value: 'skeleton',
|
||||
Description: 'Choose one for the Skeleton theme',
|
||||
},
|
||||
{ Option: '', Short: '', 'Quiet Default': 'modern', Value: 'modern', Description: '' },
|
||||
{ Option: '', Short: '', 'Quiet Default': 'hamlindigo', Value: 'hamlindigo', Description: '' },
|
||||
{ Option: '', Short: '', 'Quiet Default': 'rocket', Value: 'rocket', Description: '' },
|
||||
{ Option: '', Short: '', 'Quiet Default': 'sahara', Value: 'sahara', Description: '' },
|
||||
{ Option: '', Short: '', 'Quiet Default': 'gold-nouveau', Value: 'gold-nouveau', Description: '' },
|
||||
{ Option: '', Short: '', 'Quiet Default': 'vintage', Value: 'vintage', Description: '' },
|
||||
{ Option: '', Short: '', 'Quiet Default': 'seafoam', Value: 'seafoam', Description: '' },
|
||||
{ Option: '', Short: '', 'Quiet Default': 'crimson', Value: 'crimson', Description: '' },
|
||||
{
|
||||
Option: '--skeletontemplate',
|
||||
Short: '',
|
||||
'Quiet Default': 'bare',
|
||||
Value: 'bare',
|
||||
Description: 'Name of built in template to use',
|
||||
},
|
||||
{ Option: '', Short: '', 'Quiet Default': 'welcome', Value: 'welcome', Description: '' },
|
||||
];
|
||||
return (
|
||||
columnify(data, { columns: ['Option', 'Short', 'Default', 'Value', 'Description'] }) +
|
||||
`
|
||||
|
||||
Quiet mode is for automated installs for testing, CI/CD. It will take all of the default values in the
|
||||
Quiet Default column, but you can provide any other flags to override as you see fit. If you just want
|
||||
to generate a new project but still ask for a name, you need to provide all the other args except the
|
||||
ones to be filled in by the user.
|
||||
`;
|
||||
ones to be filled in by the user.\n`
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user