eitri-cli 1.0.5 → 1.1.0-beta

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.
@@ -1,9 +1,10 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
- const WookCoffee = require('./WoodCoffeeFactory')
3
+ const WoodCoffee = require('./WoodCoffeeFactory')
4
4
  const {getVersion} = require('../../cmd/version')
5
5
 
6
- class MiniWebAppFactory extends WookCoffee {
6
+ // o MiniWebAppFactory nao eh um WoodCoffee :-(
7
+ class MiniWebAppFactory extends WoodCoffee {
7
8
 
8
9
  async create(projectName, templateUrl) {
9
10
 
@@ -20,7 +21,7 @@ class MiniWebAppFactory extends WookCoffee {
20
21
  return { projectPath }
21
22
  }
22
23
 
23
- writeAmeConf(project, conf, libsName) {
24
+ writeEitriAppConf(project, conf, libsName) {
24
25
  return new Promise((resolve, reject) => {
25
26
 
26
27
  libsName.forEach(libName => {
@@ -1,156 +1,185 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
- const AdmZip = require('adm-zip')
4
- const tmp = require('tmp')
5
- const util = require('util')
6
- const exec = util.promisify(require('child_process').exec)
7
- const rm = util.promisify(fs.rm)
8
- const { execSync } = require('child_process')
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const AdmZip = require("adm-zip");
4
+ const tmp = require("tmp");
5
+ const util = require("util");
6
+ const exec = util.promisify(require("child_process").exec);
7
+ const rm = util.promisify(fs.rm);
8
+ const { execSync } = require("child_process");
9
9
 
10
10
  class WoodCoffee {
11
- static COMPONENTS_LIBRARY_VERSION_HIGHLIGHTER = '###COMPONENTS_LIBRARY_VERSION_HIGHLIGHTER###'
12
- static SUPER_APP_CLIENT_VERSION_HIGHLIGHTER = '###SUPER_APP_CLIENT_VERSION_HIGHLIGHTER###'
13
- static SUPER_APP_CLIENT = 'eitri-app-client'
14
- static MINIAPP_COMPONENTS = 'eitri-app-components'
11
+ static COMPONENTS_LIBRARY_VERSION_HIGHLIGHTER =
12
+ "###COMPONENTS_LIBRARY_VERSION_HIGHLIGHTER###";
13
+ static SUPER_APP_CLIENT_VERSION_HIGHLIGHTER =
14
+ "###SUPER_APP_CLIENT_VERSION_HIGHLIGHTER###";
15
+ static SUPER_APP_CLIENT = "eitri-app-client";
16
+ static MINIAPP_COMPONENTS = "eitri-app-components";
15
17
 
16
18
  async create(projectName, templateUrl, target) {
17
- const projectPath = await this.verifyFolder(projectName)
18
- let localPath
19
+ const projectPath = await this.verifyFolder(projectName);
20
+ let localPath;
19
21
 
20
- if (process.env.LOG_LEVEL === 'full') {
21
- console.log('Boilerplate localPath', localPath)
22
+ if (process.env.LOG_LEVEL === "full") {
23
+ console.log("Boilerplate localPath", localPath);
22
24
  }
23
-
24
-
25
25
  try {
26
-
27
26
  if (templateUrl) {
28
- const projectStructure = await this.template(projectName, templateUrl, projectPath, target)
29
- return { projectPath, structure: projectStructure }
27
+ const projectStructure = await this.template(
28
+ projectName,
29
+ templateUrl,
30
+ projectPath,
31
+ target
32
+ );
33
+ return { projectPath, structure: projectStructure };
30
34
  }
31
35
  } catch (error) {
32
- if (error.message.includes('Command failed')) return await this.extractZip(localPath, projectPath)
33
- console.error('Erro ao obter template', error)
36
+ if (error.message.includes("Command failed"))
37
+ return await this.extractZip(localPath, projectPath);
38
+ console.error("Erro ao obter template", error);
34
39
  }
35
- return { projectPath }
40
+ return { projectPath };
36
41
  }
37
42
 
38
43
  /**
39
- *
44
+ *
40
45
  * @returns Objeto que representa a estrutura de diretorios do projeto criado
41
46
  */
42
47
  async template(projectName, templateUrl, projectPath, target) {
43
- await this.downloadFromGithub(templateUrl, projectName, projectPath)
44
- const aboutJsxPath = path.join(projectPath, 'src', 'views', 'About.jsx')
48
+ await this.downloadFromGithub(templateUrl, projectName, projectPath);
49
+ const aboutJsxPath = path.join(
50
+ projectPath,
51
+ "src",
52
+ "views",
53
+ "About.jsx"
54
+ );
45
55
 
46
- const miniAppConf = require(path.join(projectPath, 'miniapp.conf.js'))
56
+ const miniAppConf = require(path.join(projectPath, "miniapp.conf.js"));
47
57
 
48
- if(fs.existsSync(aboutJsxPath)) {
58
+ if (fs.existsSync(aboutJsxPath)) {
49
59
  try {
50
-
51
-
52
- await this.checkAboutJsx(aboutJsxPath)
60
+ await this.checkAboutJsx(aboutJsxPath);
53
61
  // TODO EITRI descomentar qd as libs forem pro npm
54
- await this.updateAboutJSXFile(aboutJsxPath, miniAppConf)
62
+ await this.updateAboutJSXFile(aboutJsxPath, miniAppConf);
55
63
  } catch (e) {
56
64
  // 'Usando template consistente para o About.jsx.'
57
- const templateAboutJsxPath = path.join(path.dirname(__dirname), '..', 'util', 'AboutTemplate.jsx')
58
- await this.copyFile(templateAboutJsxPath, aboutJsxPath)
65
+ const templateAboutJsxPath = path.join(
66
+ path.dirname(__dirname),
67
+ "..",
68
+ "util",
69
+ "AboutTemplate.jsx"
70
+ );
71
+ await this.copyFile(templateAboutJsxPath, aboutJsxPath);
59
72
  // TODO EITRI descomentar qd as libs forem pro npm
60
- await this.updateAboutJSXFile(aboutJsxPath, miniAppConf)
73
+ await this.updateAboutJSXFile(aboutJsxPath, miniAppConf);
61
74
  }
62
75
  }
63
-
76
+
64
77
  return {
65
78
  src: { views: {} },
66
- miniAppConf
67
- }
79
+ miniAppConf,
80
+ };
68
81
  }
69
82
 
70
83
  async checkAboutJsx(aboutJsxPath) {
71
- const contents = await this.getFile(aboutJsxPath)
72
- if (!contents.includes(WoodCoffee.COMPONENTS_LIBRARY_VERSION_HIGHLIGHTER) || !contents.includes(WoodCoffee.SUPER_APP_CLIENT_VERSION_HIGHLIGHTER)) {
84
+ const contents = await this.getFile(aboutJsxPath);
85
+ if (
86
+ !contents.includes(
87
+ WoodCoffee.COMPONENTS_LIBRARY_VERSION_HIGHLIGHTER
88
+ ) ||
89
+ !contents.includes(WoodCoffee.SUPER_APP_CLIENT_VERSION_HIGHLIGHTER)
90
+ ) {
73
91
  // 'O arquivo About.jsx baixado, não é um arquivo consistente.'
74
- throw new Error('Faltam placeholders para exibicao da versao do components e client')
92
+ throw new Error(
93
+ "Faltam placeholders para exibicao da versao do components e client"
94
+ );
75
95
  }
76
- return true
96
+ return true;
77
97
  }
78
98
 
79
99
  async updateAboutJSXFile(aboutJsxPath, newMiniAppConf) {
80
- const superAppClientLibVersion = newMiniAppConf[WoodCoffee.SUPER_APP_CLIENT]
81
- const componentsLibVersion = newMiniAppConf[WoodCoffee.MINIAPP_COMPONENTS]
82
- const contents = await this.getFile(aboutJsxPath)
100
+ const superAppClientLibVersion =
101
+ newMiniAppConf[WoodCoffee.SUPER_APP_CLIENT];
102
+ const componentsLibVersion =
103
+ newMiniAppConf[WoodCoffee.MINIAPP_COMPONENTS];
104
+ const contents = await this.getFile(aboutJsxPath);
83
105
  return new Promise((resolve, reject) => {
84
106
  const replaced = contents
85
- .replace(WoodCoffee.COMPONENTS_LIBRARY_VERSION_HIGHLIGHTER, componentsLibVersion)
86
- .replace(WoodCoffee.SUPER_APP_CLIENT_VERSION_HIGHLIGHTER, superAppClientLibVersion)
107
+ .replace(
108
+ WoodCoffee.COMPONENTS_LIBRARY_VERSION_HIGHLIGHTER,
109
+ componentsLibVersion
110
+ )
111
+ .replace(
112
+ WoodCoffee.SUPER_APP_CLIENT_VERSION_HIGHLIGHTER,
113
+ superAppClientLibVersion
114
+ );
87
115
 
88
- fs.writeFile(aboutJsxPath, replaced, 'utf-8', function (err) {
116
+ fs.writeFile(aboutJsxPath, replaced, "utf-8", function (err) {
89
117
  if (err) {
90
- console.error(err)
91
- reject(err)
118
+ console.error(err);
119
+ reject(err);
92
120
  }
93
- resolve()
94
- })
95
- })
121
+ resolve();
122
+ });
123
+ });
96
124
  }
97
125
 
98
126
  getFile(aboutJsxPath) {
99
127
  return new Promise((resolve, reject) => {
100
- fs.readFile(aboutJsxPath, 'utf-8', function (err, contents) {
128
+ fs.readFile(aboutJsxPath, "utf-8", function (err, contents) {
101
129
  if (err) {
102
- console.error(err)
103
- reject(err)
130
+ console.error(err);
131
+ reject(err);
104
132
  }
105
- resolve(contents)
106
- })
107
- })
133
+ resolve(contents);
134
+ });
135
+ });
108
136
  }
109
137
 
110
138
  async copyFile(currentPath, destinyPath) {
111
139
  return new Promise((resolve, reject) => {
112
140
  fs.copyFile(currentPath, destinyPath, (error) => {
113
141
  if (error) {
114
- console.error(error)
115
- reject(error)
142
+ console.error(error);
143
+ reject(error);
116
144
  }
117
- resolve()
118
- })
119
- })
145
+ resolve();
146
+ });
147
+ });
120
148
  }
121
149
 
122
150
  validateFileName(folderName) {
123
- const re = /[<>:"/\\|?*\x00-\x1F]|^(?:aux|con|clock\$|nul|prn|com[1-9]|lpt[1-9])$/i
151
+ const re =
152
+ /[<>:"/\\|?*\x00-\x1F]|^(?:aux|con|clock\$|nul|prn|com[1-9]|lpt[1-9])$/i;
124
153
  if (re.test(folderName)) {
125
- return false
154
+ return false;
126
155
  }
127
- return true
156
+ return true;
128
157
  }
129
158
 
130
159
  verifyFolder(projectName, options) {
131
- options = options || {}
160
+ options = options || {};
132
161
  return new Promise((resolve, reject) => {
133
- let projPath = process.cwd()
162
+ let projPath = process.cwd();
134
163
  if (!this.validateFileName(projectName)) {
135
164
  return reject(
136
- `O nome do projeto ${projectName} possui caracteres proibidos.`,
137
- )
165
+ `O nome do projeto ${projectName} possui caracteres proibidos.`
166
+ );
138
167
  }
139
168
  if (projectName) {
140
- projPath = path.join(process.cwd(), projectName)
169
+ projPath = path.join(process.cwd(), projectName);
141
170
  }
142
- const folder2check = path.join(projPath, 'src')
171
+ const folder2check = path.join(projPath, "src");
143
172
  if (!options.supressLog) {
144
- console.log('Verificando', folder2check)
173
+ console.log("Verificando", folder2check);
145
174
  }
146
175
  if (fs.existsSync(folder2check)) {
147
176
  return reject(
148
- `A pasta ${folder2check} existe, abortando e deixando tudo inalterado.`,
149
- )
177
+ `A pasta ${folder2check} existe, abortando e deixando tudo inalterado.`
178
+ );
150
179
  }
151
180
 
152
- resolve(projPath)
153
- })
181
+ resolve(projPath);
182
+ });
154
183
  }
155
184
 
156
185
  extractZip(localPath, projectPath) {
@@ -160,71 +189,83 @@ class WoodCoffee {
160
189
  /* overwrite*/ true,
161
190
  (err) => {
162
191
  if (err) {
163
- reject('Erro ao descompactar o boilerplate')
164
- console.log(err)
165
- return
192
+ reject("Erro ao descompactar o boilerplate");
193
+ console.log(err);
194
+ return;
166
195
  }
167
- console.log('Exemplo gerado.')
168
- resolve()
169
- },
170
- )
171
- })
196
+ console.log("Exemplo gerado.");
197
+ resolve();
198
+ }
199
+ );
200
+ });
172
201
  }
173
202
 
174
203
  createTempFile() {
175
204
  return new Promise((resolve, reject) => {
176
- tmp.file({ prefix: 'eitri-', postfix: '.zip', keep: true }, function (
177
- err,
178
- localPath,
179
- ) {
180
- if (err) {
181
- return reject(err)
205
+ tmp.file(
206
+ { prefix: "eitri-", postfix: ".zip", keep: true },
207
+ function (err, localPath) {
208
+ if (err) {
209
+ return reject(err);
210
+ }
211
+ resolve(localPath);
182
212
  }
183
- resolve(localPath)
184
- })
185
- })
213
+ );
214
+ });
186
215
  }
187
216
 
188
217
  downloadFromGithub(boilerplateUrl, projectName, projectPath) {
189
218
  return new Promise((resolve, reject) => {
190
- const CMD = `git clone ${boilerplateUrl} ${projectName}`
219
+ const CMD = `git clone ${boilerplateUrl} ${projectName}`;
191
220
  exec(CMD, async (error, stdout, stderr) => {
192
221
  if (error) {
193
- console.error('Não foi possível obter o template remoto. Resolvendo localmente.')
194
- return reject(error)
222
+ console.error(
223
+ "Não foi possível obter o template remoto. Resolvendo localmente."
224
+ );
225
+ return reject(error);
195
226
  }
196
- console.log('Download de template completo.')
197
- Promise.resolve(rm(`${projectPath}/.git`, { recursive: true, force: true }))
198
- resolve({ stdout: stdout, stderr: stderr })
199
- })
200
- })
201
-
227
+ console.log("Download de template completo.");
228
+ Promise.resolve(
229
+ rm(`${projectPath}/.git`, { recursive: true, force: true })
230
+ );
231
+ resolve({ stdout: stdout, stderr: stderr });
232
+ });
233
+ });
202
234
  }
203
235
 
204
- writeAmeConf(project, conf) {
236
+ writeEitriAppConf(project, conf) {
205
237
  return new Promise((resolve, reject) => {
206
-
207
- conf['version'] = '0.1.0'
208
- let confString = `module.exports = ${JSON.stringify(conf, null, 4)}`
209
- fs.writeFile(path.join(project.projectPath, 'miniapp.conf.js'), confString, (err) => {
210
- if (err) {
211
- return reject(err)
238
+ conf["version"] = "0.1.0";
239
+ let confString = `module.exports = ${JSON.stringify(
240
+ conf,
241
+ null,
242
+ 4
243
+ )}`;
244
+ fs.writeFile(
245
+ path.join(project.projectPath, "miniapp.conf.js"),
246
+ confString,
247
+ (err) => {
248
+ if (err) {
249
+ return reject(err);
250
+ }
251
+ resolve();
212
252
  }
213
- resolve()
214
- })
215
- })
253
+ );
254
+ });
216
255
  }
217
256
 
218
257
  _getLatestLibVersion(libName) {
219
258
  try {
220
- const cmd = `npm view ${libName} version`
221
- const version = execSync(cmd).toString()
222
- return version
259
+ const cmd = `npm view ${libName} version`;
260
+ const version = execSync(cmd).toString();
261
+ return version;
223
262
  } catch (error) {
224
- console.error(`Não foi possível recuperar a última versão da biblioteca ${libName}.`)
225
- throw error
263
+ console.error(
264
+ `Não foi possível recuperar a última versão da biblioteca ${libName}.`
265
+ );
266
+ throw error;
226
267
  }
227
268
  }
228
269
  }
229
270
 
230
- module.exports = WoodCoffee
271
+ module.exports = WoodCoffee;
@@ -1,9 +1,9 @@
1
1
  const MiniWebAppFactory = require('../service/factories/MiniWebAppFactory')
2
- const WookCoffee = require('../service/factories/WoodCoffeeFactory')
2
+ const WoodCoffee = require('../service/factories/WoodCoffeeFactory')
3
3
 
4
4
  module.exports = function getCreateFactory(platform) {
5
5
  if(platform === 'mobile') {
6
- return new WookCoffee()
6
+ return new WoodCoffee()
7
7
  }
8
8
  return new MiniWebAppFactory()
9
9
  }
@@ -0,0 +1,36 @@
1
+ const { existsSync } = require("fs");
2
+ const { readFile } = require("fs/promises");
3
+ const path = require("path");
4
+ const os = require("os");
5
+ module.exports = async function getWorkspace() {
6
+ try {
7
+ const workspaceEitriAppProjectPath = path.resolve(
8
+ process.cwd(),
9
+ ".workspaces",
10
+ "workspace"
11
+ );
12
+
13
+ if (existsSync(workspaceEitriAppProjectPath)) {
14
+ const fileContent = await readFile(
15
+ workspaceEitriAppProjectPath,
16
+ "utf8"
17
+ );
18
+ const workspace = JSON.parse(fileContent);
19
+ return workspace;
20
+ }
21
+ const workspaceGlobalPath = path.resolve(
22
+ os.homedir(),
23
+ ".eitri",
24
+ "workspaces",
25
+ "workspace"
26
+ );
27
+ const fileContent = await readFile(workspaceGlobalPath, "utf8");
28
+ const workspace = JSON.parse(fileContent);
29
+ return workspace;
30
+ } catch (error) {
31
+ if(error.code === "ENOENT") {
32
+ throw new Error("Você não tem nenhum workspace definido para desenvolvimento, execute o comando 'eitri workspace use' para definir um workspace.")
33
+ }
34
+ throw new Error("Houve um erro inesperado ao tentar ler o workspace atual.")
35
+ }
36
+ };
@@ -0,0 +1,13 @@
1
+ module.exports = class Factory {
2
+ static generateWorkspace() {
3
+ return [
4
+ {
5
+ name: "MY_WORKSPACE",
6
+ userId: "2",
7
+ status: "ACTIVE",
8
+ id: "2a563ae3-722a-4640-8e7a-4f46aa93ec67",
9
+ createdAt: "2023-08-08T18:17:16.921Z",
10
+ },
11
+ ];
12
+ }
13
+ };
@@ -0,0 +1,37 @@
1
+ const VegvisirService = require("../../../src/modules/vegvisir/VegvisirService");
2
+ const Factory = require("../../Factory");
3
+ describe("Vegvisir Service Test", () => {
4
+ let vegvisirService = new VegvisirService();
5
+
6
+ beforeEach(() => {
7
+ vegvisirService = new VegvisirService();
8
+ });
9
+
10
+ it("should return error when user doesn't have workspace", async () => {
11
+ vegvisirService.http = {
12
+ get: () =>
13
+ Promise.reject({
14
+ isAxiosError: true,
15
+ response: {
16
+ status: 404,
17
+ },
18
+ }),
19
+ };
20
+ const consoleErrorSpy = jest.spyOn(console, "error");
21
+ await vegvisirService.listMyWorkspaces();
22
+
23
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
24
+ "Você não possui workspaces cadastrados, utilize o comando 'eitri workspace create' para cadastrar"
25
+ );
26
+ });
27
+
28
+ it("should list all user workspaces", async () => {
29
+ vegvisirService.http = {
30
+ get: () => Promise.resolve(Factory.generateWorkspace()),
31
+ };
32
+ const result = await vegvisirService.listMyWorkspaces();
33
+
34
+ expect(result).toBeTruthy();
35
+ expect(result.length).toBeGreaterThan(0);
36
+ });
37
+ });
@@ -0,0 +1,16 @@
1
+ const getWorkspace = require("../../src/util/getWorkspace");
2
+ const fs = require('fs/promises')
3
+
4
+
5
+ jest.mock('fs', () => ({
6
+ existsSync: (path) => true
7
+ }))
8
+
9
+ describe('Get WorkspaceID Tests', () => {
10
+
11
+ it('should return error if workspace file not found', async () => {
12
+ const promise = getWorkspace()
13
+ await expect(promise).rejects.toThrow("Você não tem nenhum workspace definido para desenvolvimento, execute o comando 'eitri workspace use' para definir um workspace.")
14
+ });
15
+
16
+ });