Skip to content

Commit

Permalink
Experimental @curi/cli package
Browse files Browse the repository at this point in the history
  • Loading branch information
pshrmn committed Mar 19, 2019
1 parent 3d92da7 commit c8436b6
Show file tree
Hide file tree
Showing 49 changed files with 1,922 additions and 633 deletions.
1,521 changes: 888 additions & 633 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
"@curi-example/transitions-react": "file:examples/react/transitions",
"@curi-example/transitions-vue": "file:examples/vue/transitions",
"@curi-example/updating-routes": "file:examples/misc/updating-routes",
"@curi/cli": "file:packages/cli",
"@curi/helpers": "file:packages/helpers",
"@curi/react-dom": "file:packages/react-dom",
"@curi/react-native": "file:packages/react-native",
Expand Down
13 changes: 13 additions & 0 deletions packages/cli/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
node_modules/
*.log
.rpt2_cache/

dist/
bin/
!src/bin/
tests/fixtures/
fake-src/
testing-grounds/
curi.config.js

coverage/
7 changes: 7 additions & 0 deletions packages/cli/.size-snapshot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"bin/curi-cli.js": {
"bundled": 31893,
"minified": 15435,
"gzipped": 4413
}
}
21 changes: 21 additions & 0 deletions packages/cli/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2018 Paul Sherman

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.
16 changes: 16 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# @curi/cli

[![npm][badge]][npm-link]

[badge]: https://img.shields.io/npm/v/@curi/cli.svg
[npm-link]: https://npmjs.com/package/@curi/cli

`@curi/cli` provides command line actions for Curi applications.

## Installation

```
npm install --save-dev @curi/cli
```

For more information, please check out the [`@curi/cli`](https://curi.js.org/packages/@curi/cli) page on the documentation website.
12 changes: 12 additions & 0 deletions packages/cli/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = {
preset: "ts-jest",
moduleFileExtensions: ["ts", "js"],
testMatch: ["**/tests/**/*.spec.ts"],
globals: {
"ts-jest": {
module: "es6",
diagnostics: false
}
},
testURL: "http://localhost"
};
50 changes: 50 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "@curi/cli",
"version": "1.0.0-alpha.0",
"description": "CLI for Curi projects",
"bin": {
"curi": "bin/curi-cli.js"
},
"types": "types/index.d.ts",
"files": [
"dist",
"types",
"LICENSE",
"*.md"
],
"scripts": {
"prebuild": "rimraf bin && rimraf types",
"build": "rollup -c",
"prepare": "npm run build",
"prepublishOnly": "npm test"
},
"repository": {
"type": "git",
"url": "https://github.com/pshrmn/curi/tree/master/packages/cli"
},
"keywords": [
"curi",
"router",
"cli"
],
"author": "Paul Sherman",
"license": "MIT",
"dependencies": {
"@babel/core": "^7.2.2",
"@babel/generator": "^7.2.2",
"@babel/parser": "^7.2.3",
"@babel/types": "^7.2.2",
"@posh/ast": "^0.3.0",
"@types/babel__core": "^7.0.4",
"@types/babel__generator": "^7.0.1",
"@types/cross-spawn": "^6.0.0",
"@types/dedent": "^0.7.0",
"@types/fs-extra": "^5.0.4",
"@types/inquirer": "0.0.43",
"commander": "^2.19.0",
"cross-spawn": "^6.0.5",
"dedent": "^0.7.0",
"fs-extra": "^7.0.0",
"inquirer": "^6.2.0"
}
}
29 changes: 29 additions & 0 deletions packages/cli/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const plugins = require("../../scripts/rollup/plugins");

// don't bundle dependencies for esm/cjs builds
const pkg = require("./package.json");
const deps = Object.keys(pkg.dependencies).map(key => key);

const input = "src/index.ts";
const sourcemap = false;

module.exports = [
{
input,
external: [...deps, "path"],
plugins: [
plugins.typescript,
plugins.replacePure,
plugins.replaceWithProduction,
plugins.resolveNode,
plugins.commonjs,
plugins.sizeSnapshot
],
output: {
format: "cjs",
file: "bin/curi-cli.js",
banner: "#!/usr/bin/env node",
sourcemap
}
}
];
119 changes: 119 additions & 0 deletions packages/cli/src/actions/createRouterFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import path from "path";
import * as fs from "fs-extra";
import generate from "@babel/generator";
import * as t from "@babel/types";
import { stringify, types } from "@posh/ast";

import {
mapHistoryName,
mapInteractionName,
mapSideEffectName
} from "./utils/nameMaps";

import { CuriConfig, CuriDependencies } from "../types";

function generateRouterModule(routes: string, deps: CuriDependencies) {
const curiImport = types.importNamed(["curi"], "@curi/router");

const historyImportName = mapHistoryName(deps.history);
const historyImport = types.importDefault(historyImportName, deps.history);

const routesImport = types.importDefault("routes", routes);

let hasOptions = false;
const routerOptions = types.object([]);

// import & create interactions
let interactionImports: Array<t.ImportDeclaration> = [];
if (deps.interactions.length) {
hasOptions = true;
const interactionArray = types.array();

deps.interactions.forEach(i => {
const name = mapInteractionName(i);

interactionImports.push(types.importDefault(name, i));

interactionArray.elements.push(types.call(name, []));
});

routerOptions.properties.push(
types.objProp(types.id("route"), interactionArray)
);
}

// import & create side effects
let sideEffectImports: Array<t.ImportDeclaration> = [];
let sideEffectCreates: Array<t.VariableDeclaration> = [];
if (deps.sideEffects.length) {
hasOptions = true;
const sideEffectArray = types.array();

deps.sideEffects.forEach(s => {
const name = mapSideEffectName(s);
const sideEffectName = `${name}Effect`;

sideEffectImports.push(types.importDefault(name, s));

sideEffectCreates.push(
types.constVar(sideEffectName, types.call(name, []))
);

sideEffectArray.elements.push(types.id(sideEffectName));
});

routerOptions.properties.push(
types.objProp(types.id("sideEffects"), sideEffectArray)
);
}

const history = types.constVar("history", types.call(historyImportName, []));
const callCuri = types.call("curi", [
types.id("history"),
types.id("routes")
]);
const router = types.constVar("router", callCuri);

if (hasOptions) {
callCuri.arguments.push(routerOptions);
}

const exportRouter = types.exportDefault(types.id("router"));

let code = "";
code += stringify(
[curiImport, historyImport, ...interactionImports, ...sideEffectImports],
2
);
code += stringify([routesImport], 2);
code += stringify([history], 2);
if (sideEffectCreates.length) {
code += stringify(sideEffectCreates, 2);
}
code += stringify([router, exportRouter], 1);

return code;
}

export default async function createRouterFile(
config: CuriConfig,
deps: CuriDependencies,
root: string
) {
const { src, router, routes } = config.files;
const srcDir = path.join(root, src);
const routerSrc = path.join(srcDir, router);
const routerDir = path.dirname(routerSrc);
const routesSrc = path.join(srcDir, routes);
let relativeRoutes = path.relative(routerDir, routesSrc);

if (relativeRoutes.charAt(0) !== ".") {
relativeRoutes = `./${relativeRoutes}`;
}

// use ensure file in case the file is in a dir that needs to be created
await fs.ensureFile(routerSrc);
const routerCode = generateRouterModule(relativeRoutes, deps);

return fs.writeFile(routerSrc, routerCode);
}
33 changes: 33 additions & 0 deletions packages/cli/src/actions/createRoutesFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import path from "path";
import * as fs from "fs-extra";
import { types, stringify } from "@posh/ast";

import { createRoute } from "../ast/route";

import { CuriConfig } from "../types";

export default async function createRoutesFile(
config: CuriConfig,
root: string
) {
const { src, routes } = config.files;
const srcDir = path.join(root, src);
const routesSrc = path.join(srcDir, routes);

const importPrepare = types.importNamed(["prepareRoutes"], "@curi/router");
const routesArray = types.array();
const preparedRoutes = types.call("prepareRoutes", [routesArray]);

const notFoundRoute = createRoute("Not Found", "(.*)");
routesArray.elements.push(notFoundRoute);

const exportRoutes = types.exportDefault(preparedRoutes);

let code = "";
code += stringify([importPrepare], 2);
code += stringify([exportRoutes], 1);

// use ensure file in case the file is in a dir that needs to be created
await fs.ensureFile(routesSrc);
fs.writeFile(routesSrc, code);
}
23 changes: 23 additions & 0 deletions packages/cli/src/actions/ensureFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import path from "path";
import * as fs from "fs-extra";

import createRouterFile from "./createRouterFile";
import createRoutesFile from "./createRoutesFile";

import { CuriConfig, CuriDependencies } from "../types";

export default async function setupProjectFiles(
config: CuriConfig,
deps: CuriDependencies,
root: string
) {
const { src, components } = config.files;

await fs.ensureDir(src);
await createRouterFile(config, deps, root);
await createRoutesFile(config, root);

const srcDir = path.join(root, src);
const componentDir = path.join(srcDir, components);
await fs.ensureDir(componentDir);
}
52 changes: 52 additions & 0 deletions packages/cli/src/actions/installDependencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import spawn from "cross-spawn";
import dedent from "dedent";

async function installRegularDependencies(deps: Array<string>) {
try {
await runInstallCommand("npm", ["install", "--save", ...deps]);
} catch (e) {
console.error(e);
}
}

async function installDevDependencies(deps: Array<string>) {
if (!deps.length) {
return;
}
try {
await runInstallCommand("npm", ["install", "--save-dev", ...deps]);
} catch (e) {
console.error(e);
}
}

function runInstallCommand(command: string, args: Array<string>) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { stdio: "inherit" });
child.on("close", exit => {
if (exit !== 0) {
reject(dedent`
Install failed:
${command} ${args.join(" ")}
`);
} else {
resolve();
}
});
});
}

export default async function installDependencies(
deps: Array<string>,
devDeps: Array<string>
) {
try {
// can these safely be run concurrently?
await installRegularDependencies(deps);
await installDevDependencies(devDeps);
} catch (e) {
console.error(e);
return;
}
console.log("Finished installing dependencies");
}
Loading

0 comments on commit c8436b6

Please sign in to comment.