@slicemachine/init 1.0.2-alpha.4 → 1.0.2-alpha.44

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.
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Tracker = exports.EventType = void 0;
7
+ const analytics_node_1 = __importDefault(require("analytics-node"));
8
+ var EventType;
9
+ (function (EventType) {
10
+ EventType["DownloadLibrary"] = "SliceMachine Download Library";
11
+ })(EventType = exports.EventType || (exports.EventType = {}));
12
+ class Tracker {
13
+ constructor(analytics, repo, identifier, tracking = true) {
14
+ this.analytics = analytics;
15
+ this.repo = repo;
16
+ this.identifier = identifier;
17
+ this.tracking = tracking;
18
+ this.Track = {
19
+ downloadLibrary: (library) => {
20
+ this.trackEvent(EventType.DownloadLibrary, { library });
21
+ },
22
+ };
23
+ }
24
+ static build(writeKey, repo, identifier, tracking = true) {
25
+ try {
26
+ if (!repo)
27
+ return;
28
+ const analytics = new analytics_node_1.default(writeKey);
29
+ return new Tracker(analytics, repo, identifier, tracking);
30
+ }
31
+ catch (error) {
32
+ console.warn(error);
33
+ return;
34
+ }
35
+ }
36
+ trackEvent(eventType, attributes = {}) {
37
+ this.tracking &&
38
+ this.analytics.track({
39
+ event: eventType,
40
+ ...this.identifier,
41
+ properties: attributes,
42
+ });
43
+ }
44
+ }
45
+ exports.Tracker = Tracker;
46
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHJhY2tlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlscy90cmFja2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7OztBQVFBLG9FQUE2QztBQUU3QyxJQUFZLFNBRVg7QUFGRCxXQUFZLFNBQVM7SUFDbkIsOERBQWlELENBQUE7QUFDbkQsQ0FBQyxFQUZXLFNBQVMsR0FBVCxpQkFBUyxLQUFULGlCQUFTLFFBRXBCO0FBRUQsTUFBYSxPQUFPO0lBQ2xCLFlBQ1csU0FBMEIsRUFDMUIsSUFBWSxFQUNaLFVBQXdELEVBQ3hELFdBQVcsSUFBSTtRQUhmLGNBQVMsR0FBVCxTQUFTLENBQWlCO1FBQzFCLFNBQUksR0FBSixJQUFJLENBQVE7UUFDWixlQUFVLEdBQVYsVUFBVSxDQUE4QztRQUN4RCxhQUFRLEdBQVIsUUFBUSxDQUFPO1FBK0IxQixVQUFLLEdBQUc7WUFFTixlQUFlLEVBQUUsQ0FBQyxPQUFlLEVBQVEsRUFBRTtnQkFDekMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLEVBQUUsT0FBTyxFQUFFLENBQUMsQ0FBQztZQUMxRCxDQUFDO1NBQ0YsQ0FBQztJQW5DQyxDQUFDO0lBRUosTUFBTSxDQUFDLEtBQUssQ0FDVixRQUFnQixFQUNoQixJQUF3QixFQUN4QixVQUF3RCxFQUN4RCxRQUFRLEdBQUcsSUFBSTtRQUVmLElBQUk7WUFDRixJQUFJLENBQUMsSUFBSTtnQkFBRSxPQUFPO1lBQ2xCLE1BQU0sU0FBUyxHQUFHLElBQUksd0JBQWUsQ0FBQyxRQUFRLENBQUMsQ0FBQztZQUNoRCxPQUFPLElBQUksT0FBTyxDQUFDLFNBQVMsRUFBRSxJQUFJLEVBQUUsVUFBVSxFQUFFLFFBQVEsQ0FBQyxDQUFDO1NBQzNEO1FBQUMsT0FBTyxLQUFLLEVBQUU7WUFDZCxPQUFPLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDO1lBQ3BCLE9BQU87U0FDUjtJQUNILENBQUM7SUFFTyxVQUFVLENBQ2hCLFNBQW9CLEVBQ3BCLGFBQXNDLEVBQUU7UUFFeEMsSUFBSSxDQUFDLFFBQVE7WUFDWCxJQUFJLENBQUMsU0FBUyxDQUFDLEtBQUssQ0FBQztnQkFDbkIsS0FBSyxFQUFFLFNBQVM7Z0JBQ2hCLEdBQUcsSUFBSSxDQUFDLFVBQVU7Z0JBQ2xCLFVBQVUsRUFBRSxVQUFVO2FBQ3ZCLENBQUMsQ0FBQztJQUNQLENBQUM7Q0FRRjtBQTFDRCwwQkEwQ0MifQ==
package/jest.config.js CHANGED
@@ -13,4 +13,5 @@ module.exports = {
13
13
  "^.+\\.(ts|tsx)$": "ts-jest",
14
14
  "^.+\\.js$": "babel-jest",
15
15
  },
16
+ testTimeout: 15000,
16
17
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slicemachine/init",
3
- "version": "1.0.2-alpha.4",
3
+ "version": "1.0.2-alpha.44",
4
4
  "license": "MIT",
5
5
  "description": "The easiest way to add Slice Machine to your project",
6
6
  "bin": {
@@ -23,10 +23,14 @@
23
23
  "@babel/core": "^7.15.8",
24
24
  "@babel/preset-env": "^7.15.8",
25
25
  "@babel/preset-typescript": "^7.15.0",
26
+ "@types/adm-zip": "^0.4.34",
27
+ "@types/analytics-node": "^3.1.7",
28
+ "@types/fs-extra": "^9.0.13",
26
29
  "@types/inquirer": "^8.1.3",
27
30
  "@types/jest": "^27.0.2",
28
- "@typescript-eslint/eslint-plugin": "^4.29.1",
29
- "@typescript-eslint/parser": "^4.29.1",
31
+ "@types/tmp": "^0.2.2",
32
+ "@typescript-eslint/eslint-plugin": "^5.10.0",
33
+ "@typescript-eslint/parser": "^5.10.0",
30
34
  "babel-jest": "^27.0.2",
31
35
  "better-npm-audit": "^3.4.0",
32
36
  "eslint": "^7.32.0",
@@ -42,10 +46,15 @@
42
46
  "typescript": "^4.4.3"
43
47
  },
44
48
  "dependencies": {
45
- "@slicemachine/core": "1.0.2-alpha.4",
49
+ "@slicemachine/core": "1.0.2-alpha.44",
50
+ "adm-zip": "^0.5.9",
51
+ "analytics-node": "^6.0.0",
52
+ "axios": "^0.24.0",
46
53
  "fp-ts": "^2.11.5",
54
+ "fs-extra": "^10.0.0",
47
55
  "inquirer": "^8.2.0",
48
- "io-ts": "^2.2.16"
56
+ "io-ts": "^2.2.16",
57
+ "tmp": "^0.2.1"
49
58
  },
50
- "gitHead": "d095d34843c9246acaae1070798806afa28527d3"
59
+ "gitHead": "17a73ae5e18d51ebdbd7980bed67dad93dcec95b"
51
60
  }
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { Utils, FileSystem } from "@slicemachine/core";
4
+ import { Tracker } from "./utils/tracker";
4
5
  import {
5
6
  installRequiredDependencies,
6
7
  validatePkg,
@@ -10,13 +11,17 @@ import {
10
11
  configureProject,
11
12
  displayFinalMessage,
12
13
  detectFramework,
14
+ installLib,
13
15
  } from "./steps";
14
16
  import { findArgument } from "./utils";
15
17
 
16
18
  async function init() {
17
19
  const cwd = findArgument(process.argv, "cwd") || process.cwd();
18
- const base = (findArgument(process.argv, "base") ||
19
- Utils.CONSTS.DEFAULT_BASE) as Utils.Endpoints.Base;
20
+ const base = findArgument(process.argv, "base") || Utils.CONSTS.DEFAULT_BASE;
21
+ const lib: string | undefined = findArgument(process.argv, "library");
22
+ const branch: string | undefined = findArgument(process.argv, "branch");
23
+ const isTrackingAvailable =
24
+ findArgument(process.argv, "tracking") === "false" ? false : true;
20
25
 
21
26
  console.log(
22
27
  Utils.purple(
@@ -28,10 +33,11 @@ async function init() {
28
33
  validatePkg(cwd);
29
34
 
30
35
  // login
31
- await loginOrBypass(base);
36
+ const user = await loginOrBypass(base);
37
+ if (!user) throw new Error("The user should be logged in!");
32
38
 
33
39
  // retrieve tokens for api calls
34
- const config = FileSystem.getOrCreateAuthConfig();
40
+ const config = FileSystem.PrismicSharedConfigManager.get();
35
41
 
36
42
  // detect the framework used by the project
37
43
  const frameworkResult = await detectFramework(cwd);
@@ -47,11 +53,33 @@ async function init() {
47
53
  await createRepository(name, frameworkResult.value, config);
48
54
  }
49
55
 
56
+ const tracker = user.profile?.shortId
57
+ ? Tracker.build(
58
+ "JfTfmHaATChc4xueS7RcCBsixI71dJIJ",
59
+ name,
60
+ {
61
+ userId: user.profile.shortId,
62
+ },
63
+ isTrackingAvailable
64
+ )
65
+ : undefined;
66
+
50
67
  // install the required dependencies in the project.
51
68
  await installRequiredDependencies(cwd, frameworkResult.value);
52
69
 
70
+ const sliceLibPath = lib
71
+ ? await installLib(tracker, cwd, lib, branch)
72
+ : undefined;
73
+
53
74
  // configure the SM.json file and the json package file of the project..
54
- configureProject(cwd, base, name, frameworkResult);
75
+ configureProject(
76
+ cwd,
77
+ base,
78
+ name,
79
+ frameworkResult,
80
+ sliceLibPath,
81
+ isTrackingAvailable
82
+ );
55
83
 
56
84
  // ask the user to run slice-machine.
57
85
  displayFinalMessage(cwd);
@@ -1,4 +1,5 @@
1
1
  import { FileSystem, Utils } from "@slicemachine/core";
2
+ import type { Models } from "@slicemachine/core";
2
3
  import { FrameworkResult } from "./detect-framework";
3
4
 
4
5
  type Base = Utils.Endpoints.Base;
@@ -7,7 +8,9 @@ export function configureProject(
7
8
  cwd: string,
8
9
  base: Base,
9
10
  repository: string,
10
- framework: FrameworkResult
11
+ framework: FrameworkResult,
12
+ sliceLibPath: string[] = [],
13
+ tracking = true
11
14
  ): void {
12
15
  const spinner = Utils.spinner(
13
16
  `Configuring your ${framework.value} & Prismic project...`
@@ -17,16 +20,25 @@ export function configureProject(
17
20
  try {
18
21
  const manifest = FileSystem.retrieveManifest(cwd);
19
22
 
20
- const manifestUpdated: FileSystem.Manifest = {
23
+ const manifestUpdated: Models.Manifest = {
21
24
  ...(manifest.exists && manifest.content ? manifest.content : {}),
22
25
  apiEndpoint: Utils.Endpoints.buildRepositoryEndpoint(base, repository),
23
- libraries: ["@/slices"],
26
+ libraries: ["@/slices", ...sliceLibPath],
24
27
  ...(framework.manuallyAdded ? { framework: framework.value } : {}),
28
+ ...(!tracking ? { tracking } : {}),
25
29
  };
26
30
 
27
31
  if (!manifest.exists) FileSystem.createManifest(cwd, manifestUpdated);
28
32
  else FileSystem.patchManifest(cwd, manifestUpdated);
29
33
 
34
+ // create the default slices folder if it doesn't exist.
35
+ const pathToSlicesFolder = FileSystem.CustomPaths(cwd)
36
+ .library("slices")
37
+ .value();
38
+ if (!Utils.Files.exists(pathToSlicesFolder))
39
+ Utils.Files.mkdir(pathToSlicesFolder, { recursive: true });
40
+
41
+ // add slicemachine script to package.json.
30
42
  FileSystem.addJsonPackageSmScript(cwd);
31
43
 
32
44
  spinner.succeed("Project configured! Ready to start");
@@ -1,9 +1,10 @@
1
- import { Communication, Utils, FileSystem } from "@slicemachine/core";
1
+ import { Communication, Utils } from "@slicemachine/core";
2
+ import type { Models } from "@slicemachine/core";
2
3
 
3
4
  export function createRepository(
4
5
  domain: string,
5
- framework: Utils.Framework.FrameworkEnum,
6
- config: FileSystem.AuthConfig
6
+ framework: Models.Frameworks,
7
+ config: Models.PrismicSharedConfig
7
8
  ): Promise<void> {
8
9
  const spinner = Utils.spinner("Creating Prismic Repository");
9
10
  spinner.start();
@@ -1,13 +1,14 @@
1
1
  import { Utils } from "@slicemachine/core";
2
+ import { Models } from "@slicemachine/core";
2
3
  import * as inquirer from "inquirer";
3
4
 
4
5
  export type FrameworkResult = {
5
- value: Utils.Framework.FrameworkEnum;
6
+ value: Models.Frameworks;
6
7
  manuallyAdded: boolean;
7
8
  };
8
9
 
9
10
  export async function promptForFramework(): Promise<FrameworkResult> {
10
- const choices = Utils.Framework.SupportedFrameworks.map((framework) => {
11
+ const choices = Models.SupportedFrameworks.map((framework) => {
11
12
  return {
12
13
  name: Utils.Framework.fancyName(framework),
13
14
  value: framework,
@@ -15,7 +16,7 @@ export async function promptForFramework(): Promise<FrameworkResult> {
15
16
  });
16
17
 
17
18
  return inquirer
18
- .prompt<{ framework: Utils.Framework.FrameworkEnum }>([
19
+ .prompt<{ framework: Models.Frameworks }>([
19
20
  {
20
21
  name: "framework",
21
22
  type: "list",
@@ -44,13 +45,13 @@ export async function detectFramework(cwd: string): Promise<FrameworkResult> {
44
45
  spinner.start();
45
46
 
46
47
  try {
47
- const maybeFramework = Utils.Framework.detectFramework(cwd);
48
+ const maybeFramework = Utils.Framework.detectFramework(
49
+ cwd,
50
+ Object.values(Models.Frameworks)
51
+ );
48
52
  spinner.stop();
49
53
 
50
- if (
51
- !maybeFramework ||
52
- maybeFramework === Utils.Framework.FrameworkEnum.vanillajs
53
- ) {
54
+ if (!maybeFramework || maybeFramework === Models.Frameworks.vanillajs) {
54
55
  Utils.writeError("Framework not detected");
55
56
  return await promptForFramework();
56
57
  }
@@ -6,3 +6,4 @@ export { detectFramework } from "./detect-framework";
6
6
  export { loginOrBypass } from "./loginOrBypass";
7
7
  export { configureProject } from "./configure-project";
8
8
  export { displayFinalMessage } from "./display-final-message";
9
+ export { installLib } from "./install-lib";
@@ -0,0 +1,115 @@
1
+ import { Utils } from "@slicemachine/core";
2
+ import tmp from "tmp";
3
+ import AdmZip from "adm-zip";
4
+ import fsExtra from "fs-extra";
5
+ import axios from "axios";
6
+
7
+ import fs from "fs";
8
+ import path from "path";
9
+ import { getOrElseW } from "fp-ts/Either";
10
+ import { PackageManager, Dependencies } from "../utils/PackageManager";
11
+ import { PackageJsonHelper } from "@slicemachine/core/build/src/utils/PackageJson";
12
+ import {
13
+ Manifest,
14
+ ManifestHelper,
15
+ } from "@slicemachine/core/build/src/models/Manifest";
16
+ import Files from "@slicemachine/core/build/src/utils/files";
17
+ import { Tracker } from "../utils/tracker";
18
+
19
+ const downloadFile = async (reqUrl: string): Promise<string> => {
20
+ const res = await axios.get<Buffer>(reqUrl, { responseType: "arraybuffer" });
21
+
22
+ return new Promise((resolve, reject) => {
23
+ if (res.status == 200) {
24
+ const tmpZipFile = tmp.tmpNameSync();
25
+ const zip = new AdmZip(res.data);
26
+ zip.extractAllTo(tmpZipFile);
27
+ resolve(tmpZipFile);
28
+ } else {
29
+ reject();
30
+ }
31
+ });
32
+ };
33
+
34
+ function toGithubSource(githubPath: string, branch: string): string {
35
+ return `https://codeload.github.com/${githubPath}/zip/${branch}`;
36
+ }
37
+
38
+ export async function installLib(
39
+ tracker: Tracker | undefined,
40
+ cwd: string,
41
+ libGithubPath: string,
42
+ branch = "HEAD"
43
+ ): Promise<string[] | undefined> {
44
+ const spinner = Utils.spinner(
45
+ `Installing the ${libGithubPath} lib in your project...`
46
+ );
47
+
48
+ try {
49
+ spinner.start();
50
+
51
+ const [githubUserName, githubProjectName] = libGithubPath.split("/");
52
+ const source = toGithubSource(libGithubPath, branch);
53
+
54
+ const zipFilePath = await downloadFile(source);
55
+ const outputFolder = `${githubProjectName}-${branch}`;
56
+ const projectPath = path.join(zipFilePath, outputFolder);
57
+
58
+ const name = `${githubUserName}-${githubProjectName}`;
59
+ const libDestinationFolder = path.join(cwd, name);
60
+
61
+ // We should be able to offer the ability to override or not an existing library
62
+ if (fs.existsSync(libDestinationFolder)) {
63
+ spinner.succeed(`Lib "${libGithubPath}" was already installed (skipped)`);
64
+ return;
65
+ }
66
+
67
+ // We copy all the slices into the the user project minus the src folder
68
+ fsExtra.moveSync(path.join(projectPath, "src"), libDestinationFolder);
69
+
70
+ // handle dependencies
71
+ const pkgManager = PackageManager.get(cwd);
72
+ const pkgJson = PackageJsonHelper.fromPath(
73
+ path.join(projectPath, "package.json")
74
+ );
75
+ if (pkgJson instanceof Error) throw pkgJson;
76
+
77
+ const dependencies = Dependencies.fromPkgFormat(pkgJson.dependencies);
78
+ if (dependencies) await pkgManager.install(dependencies);
79
+
80
+ // generate meta file
81
+ Files.write(path.join(libDestinationFolder, "meta.json"), {
82
+ name: pkgJson.name,
83
+ });
84
+
85
+ // retrieve all slices lib paths
86
+ const manifest = Files.readEntity<Error | Manifest>(
87
+ path.join(projectPath, "sm.json"),
88
+ (payload: unknown) => {
89
+ return getOrElseW(
90
+ () => new Error(`Unable to parse sm.json from lib ${libGithubPath}`)
91
+ )(Manifest.decode(payload));
92
+ }
93
+ );
94
+ if (manifest instanceof Error) throw manifest;
95
+
96
+ const localLibs = ManifestHelper.localLibraries(manifest).map(
97
+ ({ path }) => {
98
+ return `~/${name}/${path.replace("src/", "")}`;
99
+ }
100
+ );
101
+
102
+ spinner.succeed(
103
+ `Slice library "${libGithubPath}" was installed successfully`
104
+ );
105
+
106
+ tracker?.Track.downloadLibrary(libGithubPath);
107
+ return localLibs;
108
+ } catch (error) {
109
+ spinner.fail(`Error installing ${libGithubPath} lib!`);
110
+ if (error instanceof Error) {
111
+ console.error(error.message);
112
+ }
113
+ process.exit(-1);
114
+ }
115
+ }
@@ -1,6 +1,6 @@
1
1
  import path from "path";
2
2
  import { execCommand } from "../utils";
3
- import { Utils, FileSystem } from "@slicemachine/core";
3
+ import { Utils, FileSystem, Models } from "@slicemachine/core";
4
4
 
5
5
  const {
6
6
  PRISMIC_CLIENT,
@@ -12,20 +12,22 @@ const {
12
12
  NUXT_SM,
13
13
  VUE_SLICEZONE,
14
14
  PRISMIC_VUE,
15
+ SLICE_SIMULATOR_REACT,
16
+ SLICE_SIMULATOR_VUE,
15
17
  } = Utils.CONSTS;
16
18
 
17
- function depsForFramework(framework: Utils.Framework.FrameworkEnum): string {
19
+ function depsForFramework(framework: Models.Frameworks): string {
18
20
  switch (framework) {
19
- case Utils.Framework.FrameworkEnum.react:
21
+ case Models.Frameworks.react:
20
22
  return `${PRISMIC_REACT_PACKAGE_NAME} ${PRISMIC_CLIENT}`;
21
- case Utils.Framework.FrameworkEnum.next:
22
- return `${PRISMIC_REACT_PACKAGE_NAME} ${PRISMIC_CLIENT} ${NEXT_SLICEZONE}`;
23
- case Utils.Framework.FrameworkEnum.svelte:
23
+ case Models.Frameworks.next:
24
+ return `${PRISMIC_REACT_PACKAGE_NAME} ${PRISMIC_CLIENT}@v5.1.1 ${NEXT_SLICEZONE} ${SLICE_SIMULATOR_REACT}`;
25
+ case Models.Frameworks.svelte:
24
26
  return `${PRISMIC_DOM_PACKAGE_NAME} ${PRISMIC_CLIENT}`;
25
- case Utils.Framework.FrameworkEnum.nuxt:
26
- return `${NUXT_PRISMIC} ${NUXT_SM} ${VUE_SLICEZONE}`;
27
- case Utils.Framework.FrameworkEnum.vue:
28
- return `${PRISMIC_VUE} ${PRISMIC_CLIENT} ${PRISMIC_DOM_PACKAGE_NAME} ${VUE_SLICEZONE}`;
27
+ case Models.Frameworks.nuxt:
28
+ return `${NUXT_PRISMIC} ${NUXT_SM} ${VUE_SLICEZONE} ${SLICE_SIMULATOR_VUE}`;
29
+ case Models.Frameworks.vue:
30
+ return `${PRISMIC_VUE} ${PRISMIC_CLIENT}@v5.1.1 ${PRISMIC_DOM_PACKAGE_NAME} ${VUE_SLICEZONE}`;
29
31
  default:
30
32
  return "";
31
33
  }
@@ -33,7 +35,7 @@ function depsForFramework(framework: Utils.Framework.FrameworkEnum): string {
33
35
 
34
36
  export async function installRequiredDependencies(
35
37
  cwd: string,
36
- framework: Utils.Framework.FrameworkEnum
38
+ framework: Models.Frameworks
37
39
  ): Promise<void> {
38
40
  const yarnLock = Utils.Files.exists(FileSystem.YarnLockPath(cwd));
39
41
  const installDevDependencyCommand = yarnLock
@@ -1,7 +1,23 @@
1
- import { Utils, Auth } from "@slicemachine/core";
1
+ import { Utils, Communication, Auth } from "@slicemachine/core";
2
+ import {
3
+ validateSessionAndGetProfile,
4
+ UserProfile,
5
+ } from "../utils/communication";
2
6
 
3
- export async function loginOrBypass(base: string): Promise<void> {
4
- const user = await Auth.validateSession(base);
5
- if (user) return Utils.writeCheck(`Logged in as ${Utils.bold(user.email)}`);
6
- else await Auth.login(base);
7
+ export async function loginOrBypass(base: string): Promise<{
8
+ info: Communication.UserInfo;
9
+ profile: UserProfile | null;
10
+ } | null> {
11
+ const user = await validateSessionAndGetProfile(base).catch((err) =>
12
+ console.log(err)
13
+ );
14
+ if (user) {
15
+ const email = user.info.email;
16
+ Utils.writeCheck(`Logged in as ${Utils.bold(email)}`);
17
+ return user;
18
+ } else {
19
+ await Auth.login(base);
20
+ const user = await validateSessionAndGetProfile(base);
21
+ return user;
22
+ }
7
23
  }
@@ -1,7 +1,9 @@
1
1
  import * as inquirer from "inquirer";
2
2
  import Separator from "inquirer/lib/objects/separator";
3
3
  import { Communication, Utils, FileSystem } from "@slicemachine/core";
4
- import { RepoData } from "@slicemachine/core/src/core/communication";
4
+ import { Repositories } from "@slicemachine/core/src/models/Repositories";
5
+ import { Repository } from "@slicemachine/core/src/models/Repository";
6
+ import { parsePrismicAuthToken } from "@slicemachine/core/build/src/utils/cookie";
5
7
 
6
8
  export const CREATE_REPO = "$_CREATE_REPO"; // not a valid domain name
7
9
  const DEFAULT_BASE = Utils.CONSTS.DEFAULT_BASE;
@@ -28,7 +30,7 @@ export async function promptForRepoName(base: string): Promise<string> {
28
30
  type: "input",
29
31
  required: true,
30
32
  transformer: (value) => prettyRepoName(address, String(value)),
31
- async validate(name) {
33
+ async validate(name: string) {
32
34
  const result = await Communication.validateRepositoryName(
33
35
  name,
34
36
  base,
@@ -48,30 +50,24 @@ export type PromptOrSeparator = RepoPrompt | Separator;
48
50
  export type RepoPrompts = Array<PromptOrSeparator>;
49
51
 
50
52
  export function makeReposPretty(base: string) {
51
- return function (
52
- arg: [
53
- string,
54
- { role: Utils.roles.Roles | Record<string, Utils.roles.Roles> }
55
- ]
56
- ): RepoPrompt {
57
- const [repoName, { role }] = arg;
53
+ return function ({ name, domain, role }: Repository): RepoPrompt {
58
54
  const address = new URL(base);
59
- address.hostname = `${repoName}.${address.hostname}`;
55
+ address.hostname = `${domain}.${address.hostname}`;
60
56
  if (Utils.roles.canUpdateCustomTypes(role) === false) {
61
57
  return {
62
58
  name: `${Utils.purple.dim("Use")} ${Utils.bold.dim(
63
- repoName
59
+ name
64
60
  )} ${Utils.purple.dim(`"${address.hostname}"`)}`,
65
- value: repoName,
61
+ value: domain,
66
62
  disabled: "Unauthorized",
67
63
  };
68
64
  }
69
65
 
70
66
  return {
71
- name: `${Utils.purple("Use")} ${Utils.bold(repoName)} ${Utils.purple(
67
+ name: `${Utils.purple("Use")} ${Utils.bold(name)} ${Utils.purple(
72
68
  `"${address.hostname}"`
73
69
  )}`,
74
- value: repoName,
70
+ value: name,
75
71
  };
76
72
  };
77
73
  }
@@ -97,7 +93,7 @@ export function maybeStickTheRepoToTheTopOfTheList(repoName?: string | null) {
97
93
  }
98
94
 
99
95
  export function sortReposForPrompt(
100
- repos: RepoData,
96
+ repos: Repositories,
101
97
  base: string,
102
98
  cwd: string
103
99
  ): RepoPrompts {
@@ -110,7 +106,7 @@ export function sortReposForPrompt(
110
106
 
111
107
  const maybeConfiguredRepoName = FileSystem.maybeRepoNameFromSMFile(cwd, base);
112
108
 
113
- return Object.entries(repos)
109
+ return repos
114
110
  .reverse()
115
111
  .map(makeReposPretty(base))
116
112
  .reduce(maybeStickTheRepoToTheTopOfTheList(maybeConfiguredRepoName), [
@@ -120,13 +116,14 @@ export function sortReposForPrompt(
120
116
  }
121
117
 
122
118
  export async function maybeExistingRepo(
123
- cookie: string,
119
+ cookies: string,
124
120
  cwd: string,
125
121
  base = DEFAULT_BASE
126
122
  ): Promise<{ name: string; existing: boolean }> {
127
- const repos = await Communication.listRepositories(cookie, base);
123
+ const token = parsePrismicAuthToken(cookies);
124
+ const repos = await Communication.listRepositories(token);
128
125
 
129
- if (Object.keys(repos).length === 0) {
126
+ if (repos.length === 0) {
130
127
  const name = await promptForRepoName(base);
131
128
  return { existing: false, name };
132
129
  }
@@ -0,0 +1,66 @@
1
+ import { Utils, FileSystem } from "@slicemachine/core";
2
+ import { execCommand } from "../utils";
3
+
4
+ export type Dependency = string | { name: string; version: string };
5
+ export const Dependencies = {
6
+ fromPkgFormat(
7
+ pkgDeps: Record<string, string> | undefined
8
+ ): ReadonlyArray<Dependency> | undefined {
9
+ if (!pkgDeps) return;
10
+
11
+ return Object.entries(pkgDeps).map(([name, version]) => ({
12
+ name,
13
+ version,
14
+ }));
15
+ },
16
+ };
17
+ function formatDeps(dependencies: ReadonlyArray<Dependency>): string {
18
+ return dependencies
19
+ .map((dep) => {
20
+ if (typeof dep === "string") return dep;
21
+ return `${dep.name}@${dep.version}`;
22
+ })
23
+ .join(" ");
24
+ }
25
+
26
+ export interface PackageManager {
27
+ install(dependencies: ReadonlyArray<Dependency>): Promise<{ stderr: string }>;
28
+ installDev(
29
+ dependencies: ReadonlyArray<Dependency>
30
+ ): Promise<{ stderr: string }>;
31
+ }
32
+
33
+ export const PackageManager = {
34
+ get(cwd: string): PackageManager {
35
+ if (Utils.Files.exists(FileSystem.YarnLockPath(cwd))) {
36
+ return Yarn;
37
+ }
38
+ return Npm;
39
+ },
40
+ };
41
+
42
+ export const Yarn: PackageManager = {
43
+ install(
44
+ dependencies: ReadonlyArray<Dependency>
45
+ ): Promise<{ stderr: string }> {
46
+ return execCommand(`yarn add ${formatDeps(dependencies)}`);
47
+ },
48
+ installDev(
49
+ dependencies: ReadonlyArray<Dependency>
50
+ ): Promise<{ stderr: string }> {
51
+ return execCommand(`yarn add --dev ${formatDeps(dependencies)}`);
52
+ },
53
+ };
54
+
55
+ export const Npm: PackageManager = {
56
+ install(
57
+ dependencies: ReadonlyArray<Dependency>
58
+ ): Promise<{ stderr: string }> {
59
+ return execCommand(`npm i --save ${formatDeps(dependencies)}`);
60
+ },
61
+ installDev(
62
+ dependencies: ReadonlyArray<Dependency>
63
+ ): Promise<{ stderr: string }> {
64
+ return execCommand(`npm i --save-dev ${formatDeps(dependencies)}`);
65
+ },
66
+ };