Skip to content

Commit

Permalink
🔀 merge #2 from graygalaxy/canary
Browse files Browse the repository at this point in the history
  • Loading branch information
oviirup authored Nov 16, 2023
2 parents 6629f65 + 1c8ee11 commit 2caf393
Show file tree
Hide file tree
Showing 56 changed files with 1,505 additions and 650 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ node_modules

# package-lock
package-lock.json
pnpm-*.yaml
pnpm-lock.yaml
yarn.lock
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
provenance = true
auto-install-peers = true
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20.7.0
5 changes: 4 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ client
.turbo
*.d.ts

**/template/base/
**/template/framework/

package-lock.json
pnpm-*.yaml
yarn.lock
yarn.lock
3 changes: 2 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"printWidth": 80,
"endOfLine": "lf",
"singleQuote": true,
"jsxSingleQuote": true,
"quoteProps": "consistent",
Expand All @@ -9,5 +10,5 @@
"useTabs": true,
"tabWidth": 2,
"trailingComma": "all",
"semi": false
"semi": true
}
12 changes: 0 additions & 12 deletions .vscode/settings.json

This file was deleted.

22 changes: 22 additions & 0 deletions cspell.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json",
"words": [
"Avirup",
"Ghosh",
"vite",
"webext",
"graygalaxy",
"tsup",
"newtab",
"picocolors"
],
"ignorePaths": [
"node_modules",
"package-lock.json",
"pnpm-lock.yaml",
"yarn.lock",
"**/dist/**/*",
"**/template/base/**/*",
"**/template/framework/**/*"
]
}
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"format": "prettier --write .",
"watch": "turbo run watch"
},
"dependencies": {},
"devDependencies": {
"prettier": "latest",
"prettier-plugin-imports": "latest",
Expand Down
2 changes: 2 additions & 0 deletions packages/create-vite-webext/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist
*-v*.*.*.tgz
22 changes: 22 additions & 0 deletions packages/create-vite-webext/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';

type Options = {
project: { name: string; path: string };
template?: string;
packman?: string;
javascript?: boolean;
typescript?: boolean;
}

type TemplateArgs = {
appName: string;
appRoot: string;
template: string;
packman: PackageManager;
useTS: boolean;
}

declare module 'merge-packages' {
function mergePackages(srcPkg: string|Buffer, destPkg: string|Buffer): string;
export default mergePackages
}
67 changes: 67 additions & 0 deletions packages/create-vite-webext/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/env node
import { name as pkgName, version as pkgVersion } from './package.json';
import { getPackman } from './utils/get-packman';
import { getProjectInfo } from '@/prompts/get-project-info';
import { getTemplate } from '@/prompts/get-template';
import { getUseTypescript } from '@/prompts/get-use-typescript';
import { renderTemplate } from '@/template/render-template';
import { Command } from 'commander';
import { cyan, red } from 'picocolors';

// exit process on termination
['SIGINT', 'SIGTERM', 'SIGQUIT', 'SIGKILL'].forEach((signal) =>
process.on(signal, () => process.exit()),
);

// parse the cli commands and arguments
const program = new Command(pkgName)
.version(pkgVersion)
.arguments('[project-directory]')
.usage('<project-directory> [options]')
.option(
'--ts, --typescript',
'Initialize as a TypeScript project. Explicitly tell the CLI to use Typescript version of the templates',
)
.option(
'--js, --javascript',
'Initialize as a TypeScript project. Explicitly tell the CLI to use Typescript version of the templates',
)
.option(
'-t, --template [name]',
'Bootstrap your project with pre-templated frameworks',
)
.option(
'-p, --packman <package-manager>',
'Explicitly tell the CLI to bootstrap the application using npm, pnpm, or yarn',
)
.allowUnknownOption()
.parse(process.argv);

const opts: Options = program.opts();

async function initialize() {
await getProjectInfo(program, opts);
await getUseTypescript(opts);
await getTemplate(opts);

const appName = opts.project.name;
const appRoot = opts.project.path;
const template = opts.template!;
const packman = getPackman(opts.packman);
const useTS = Boolean(opts.typescript);

await renderTemplate({ appName, appRoot, template, packman, useTS });
}

initialize()
.then(() => {})
.catch(async (reason) => {
console.log(`Aborting installation.`);
if (reason.command) {
console.log(` ${cyan(reason.command)} has failed.`);
} else {
console.log(`${red('Unexpected error. Please report it as a bug:')}`);
console.log(` ${reason}`);
}
process.exit(1);
});
21 changes: 21 additions & 0 deletions packages/create-vite-webext/license
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Avirup Ghosh

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
47 changes: 47 additions & 0 deletions packages/create-vite-webext/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "create-vite-webext",
"version": "0.0.0",
"private": false,
"description": "Simple way to bootstrap your web-extension project with vite",
"repository": {
"type": "git",
"url": "https://github.com/graygalaxy/vite-webext",
"directory": "packages/create-vite-webext"
},
"license": "MIT",
"author": "Avirup Ghosh (https://github.com/graygalaxy)",
"bin": {
"create-vite-webext": "dist/index.js"
},
"files": [
"dist",
"templates"
],
"scripts": {
"start": "tsx index.ts",
"build": "tsup-node index.ts"
},
"devDependencies": {
"@types/chrome": "latest",
"@types/cross-spawn": "6",
"@types/node": "20",
"@types/prompts": "2.4",
"@types/validate-npm-package-name": "^4.0.1",
"command-exists": "1.2",
"commander": "11.1",
"cross-spawn": "7",
"fast-glob": "3",
"merge-packages": "^0.1.6",
"picocolors": "^1.0.0",
"prompts": "2.4",
"rimraf": "latest",
"tsup": "latest",
"tsx": "latest",
"typescript": "latest",
"validate-npm-package-name": "^5.0.0"
},
"tsup": {
"minify": true,
"clean": true
}
}
84 changes: 84 additions & 0 deletions packages/create-vite-webext/prompts/get-project-info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import path from 'node:path';
import { isFolderEmpty } from '@/utils/is-folder-empty';
import { cyan, green, red } from 'picocolors';
import prompts from 'prompts';
import validateName from 'validate-npm-package-name';
import type { Command } from 'commander';

/**
* Gets the project name and path from the cli args.
* If no args is passed creates cli prompt to input project name
* @param program commander program
* @param opts commander options
*/
export async function getProjectInfo(program: Command, opts: Options) {
let programName = program.name();
let projectPath = program.args[0];
let projectName = '';

if (!projectPath) {
// prompt to get the project path
const res = await prompts({
onState: onPromptState,
type: 'text',
name: 'path',
message: 'What is your project named?',
initial: 'web-extension',
validate: (name) => {
const validation = validateProjectName(name);
return validation.valid
? true
: `Invalid project name: ${validation.error![0]}`;
},
});
if (typeof res.path === 'string') {
projectPath = res.path.trim();
}
}

if (!projectPath) {
console.log(
`\nPlease specify the project directory:`,
`\n ${cyan(programName)} ${green('<project-directory>')}`,
`\nFor example:`,
`\n ${cyan(programName)} ${green('web-extension')}`,
`\nRun ${cyan(`${programName} --help`)} to see all options.`,
);
process.exit(1);
}

projectPath = path.resolve(projectPath);
projectName = path.basename(projectPath);

const validation = validateProjectName(projectName);
if (!validation.valid) {
console.log(` Project can not be named ${red(projectName)} because:`);
validation.error.forEach((p) => console.log(` ${red(`* ${p}`)}`));
process.exit(1);
}

if (!isFolderEmpty(projectPath)) {
process.exit(1);
}

const project = { name: projectName, path: projectPath };
opts.project = project;
return project;
}

/** checks if the project name complies with newer npm rules */
export function validateProjectName(name: string) {
const test = validateName(name);
return {
valid: test.validForNewPackages,
error: [...(test.errors || []), ...(test.warnings || [])],
};
}

/* Handler function to make the cursor visible after each prompt input */
export function onPromptState(state: any) {
if (state.aborted) {
process.stdout.write('\x1B[?25h\n\n');
process.exit(1);
}
}
65 changes: 65 additions & 0 deletions packages/create-vite-webext/prompts/get-template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import fs from 'node:fs';
import path from 'node:path';
import { isWriteable } from '@/utils/is-writable';
import { blue, red } from 'picocolors';
import prompts, { Choice } from 'prompts';

/**
* Generates the template from given options
* @param opts commander options
*/
export async function getTemplate(opts: Options): Promise<void> {
let template = opts.template;
const frameworks = getFrameworkList();

const isDirWritable = await isWriteable(path.dirname(opts.project.path));
if (!isDirWritable) {
console.error(
'\nThe application path is not writable, please check folder permissions and try again.',
'\nIt is likely you do not have write permissions for this folder.',
);
process.exit(1);
}

if (!template && frameworks.length === 1) {
template = frameworks[0];
opts.template = frameworks[0];
} else {
const reactIndex = frameworks.findIndex((e) => e === 'react') ?? 0;
const res = await prompts(
{
type: 'select',
name: 'template',
message: `Select a ${blue('framework')}`,
initial: reactIndex,
choices: frameworks.reduce((acc: Choice[], value) => {
acc.push({ title: value, value });
console.log(acc);
return acc;
}, []),
},
{ onCancel: onCancelState },
);
template = res.template;
opts.template = res.template;
}

if (!template || !frameworks.includes(template)) {
console.error(
`Template ${red(template)} is not valid, please select a valid one`,
);
process.exit(1);
}
}

export function getFrameworkList() {
const root = path.resolve(__dirname, '../template');
const ls = fs.readdirSync(path.join(root, 'framework'));
return ls.filter((e) => !e.endsWith('-ts'));
}

/** Handler function to exit process tree on termination */
function onCancelState() {
console.log(red('Exiting.'));
process.exit(1);
}
Loading

0 comments on commit 2caf393

Please sign in to comment.