eitri-cli 1.7.0-beta.2 → 1.7.0-beta.4

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eitri-cli",
3
- "version": "1.7.0-beta.2",
3
+ "version": "1.7.0-beta.4",
4
4
  "description": "Command Line Interface to make \"Eitri-App\" with code and fire.",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -19,6 +19,7 @@ const vegvisirService = new VegvisirService()
19
19
  const standardVersion = require('standard-version')
20
20
  const releaseService = require('../service/ReleaseService')
21
21
  const {isGitRepo} = require('../util/GenericUtils')
22
+ const debug = require('debug')('eitri:pushVersion')
22
23
 
23
24
  module.exports = async function pushVersion(cmdObj) {
24
25
  try {
@@ -29,6 +30,9 @@ module.exports = async function pushVersion(cmdObj) {
29
30
  return
30
31
  }
31
32
 
33
+ const {slug: miniConfSlug} = workspace.getMiniConf()
34
+ await vegvisirService.isCurrentWorkspaceOwnedByUser(miniConfSlug)
35
+
32
36
  const separator = '======================================================================='
33
37
 
34
38
  try {
package/src/cmd/start.js CHANGED
@@ -7,7 +7,6 @@ const TrackingService = require('../service/TrackingService')
7
7
  const fs = require('fs')
8
8
  const config = require('../service/ConfigService')
9
9
  const handleStartServer = require('../service/StarterService')
10
- const inquirer = require('inquirer')
11
10
  const TrackingEitriAnalytics = require('../service/TrackingEitriAnalytics')
12
11
  const VegvisirService = require('../modules/vegvisir/VegvisirService')
13
12
  const UserLocalCredential = require('../util/UserLocalCredential')
@@ -16,11 +15,14 @@ const blindGuardian = workspace.blindGuardian
16
15
  const hashFolder = workspace.hashFolder
17
16
  const trackingService = new TrackingService(blindGuardian, { ignoreCredentialError: true })
18
17
  const watcher = new Watcher(workspace, hashFolder, trackingService)
19
- const vegvisirService = new VegvisirService()
18
+ const vegvisirService = new VegvisirService(workspace)
20
19
  const debug = require('debug')('eitri:start')
21
20
 
22
21
  module.exports = async function start(args) {
23
22
  debug("Iniciando start()")
23
+ const miniConf = workspace.getMiniConf()
24
+
25
+ await vegvisirService.isCurrentWorkspaceOwnedByUser(miniConf.slug)
24
26
 
25
27
  const separator = '======================================================================='
26
28
  let displayFriendlyErrorAtEnd = ""
@@ -48,7 +50,6 @@ module.exports = async function start(args) {
48
50
  workspace.setResourceFolder2Watch(resourceFolders2watch)
49
51
  }
50
52
 
51
- const miniConf = workspace.getMiniConf()
52
53
  await vegvisirService.check(miniConf.slug)
53
54
  debug("Fim da busca e validação do EitriAppConf", {miniConf})
54
55
 
@@ -57,20 +58,6 @@ module.exports = async function start(args) {
57
58
  debug("Informações do setupResult do workspace", {setupResult})
58
59
 
59
60
  const target = setupResult.target.name
60
-
61
- let targetConfig = {}
62
-
63
- if(args.listTargetConfigs) {
64
- await listTargetConfigs(target)
65
- process.exit(1)
66
- }
67
-
68
- debug("Verificando se há targetConfig nos argumentos", {targetConfig: args?.targetConfig})
69
- if(args.targetConfig) {
70
- targetConfig = await askTargetConfig(args, target)
71
- } else {
72
- targetConfig = await getDefaultTargetConfig(target)
73
- }
74
61
 
75
62
  blindGuardian.readConf()
76
63
  const qrCodeUrl = config.get('qrCode').url
@@ -124,8 +111,8 @@ module.exports = async function start(args) {
124
111
  ...args,
125
112
  deepLinks: loadedTarget?.deepLinks || []
126
113
  }
127
- debug("Iniciando servidor", {argsWithDeeplinks, trackingService, watcher, workspace, target, targetConfig, platform})
128
- await handleStartServer(argsWithDeeplinks, trackingService, watcher, workspace, target, targetConfig, platform)
114
+ debug("Iniciando servidor", {argsWithDeeplinks, trackingService, watcher, workspace, target, setupResult, platform})
115
+ await handleStartServer(argsWithDeeplinks, trackingService, watcher, workspace, target, setupResult, platform)
129
116
  debug("Servidor iniciado", {loadedTarget})
130
117
 
131
118
  TrackingEitriAnalytics.sendEvent({
@@ -175,34 +162,3 @@ module.exports = async function start(args) {
175
162
  }
176
163
  }
177
164
  }
178
-
179
- async function askTargetConfig(args, target) {
180
- const availableConfigs = await workspace.getTargetConfig(args.targetConfig, target)
181
-
182
- console.log(`Utilizando configuração: ${availableConfigs[0].id}`)
183
- return availableConfigs[0]
184
-
185
- }
186
-
187
- async function getDefaultTargetConfig(target) {
188
- const configs = await workspace.getTargetConfig('default', target)
189
- return configs[0]
190
- }
191
-
192
- async function listTargetConfigs(target) {
193
- const availableConfigs = await workspace.getAllTargetConfigs(target)
194
-
195
- const availableConfigsIds = availableConfigs.map(config => config.id)
196
-
197
- const res = await inquirer.prompt([
198
- {
199
- name: 'accepted',
200
- type: 'rawlist',
201
- message: 'Configurações disponíveis:',
202
- choices: availableConfigsIds
203
- }
204
- ]).then(input => input)
205
-
206
- const config = availableConfigs.find(cfg => cfg.id === res.accepted)
207
- console.log(`Utilize o comando --target-config ${config.id} para iniciar o Eitri-App com a configuração desejada`)
208
- }
@@ -1,15 +1,4 @@
1
1
  /* eslint-disable no-unused-vars */
2
- class TargetConfig {
3
- constructor() {
4
- this.id = ''
5
- this.libUrl = ''
6
- this.runnerUrl = ''
7
- this.bootstrapBaseUrl = ''
8
- this.askUserDataApiUrl = ''
9
- this.default = ''
10
- }
11
- }
12
-
13
2
  class MiniAppBoilerplateList {
14
3
  constructor() {
15
4
  this.name = ''
@@ -57,10 +46,6 @@ module.exports = class Target {
57
46
  */
58
47
  this.platform= ''
59
48
  /**
60
- * @type {TargetConfig[]}
61
- */
62
- this.targetConfig= ''
63
- /**
64
49
  * @type {string}
65
50
  */
66
51
  this.sdkSupport= ''
@@ -9,6 +9,8 @@ const {validateUUID} = require("../../util/GenericUtils");
9
9
  const path = require("path");
10
10
  const fs = require('fs')
11
11
  const debug = require('debug')('eitri:VegvisirService')
12
+ const inquirer = require("inquirer");
13
+ const chalk = require("chalk");
12
14
 
13
15
  module.exports = class VegvisirService {
14
16
  constructor() {
@@ -134,4 +136,57 @@ module.exports = class VegvisirService {
134
136
  return process.exit(1)
135
137
  }
136
138
  };
139
+
140
+ async isCurrentWorkspaceOwnedByUser(slug = "") {
141
+ const localWorkspace = await this.getWorkspace()
142
+ if (!localWorkspace?.id) {
143
+ return
144
+ }
145
+
146
+ const workspacesRemote = await this.listMyWorkspaces()
147
+
148
+ const isOwner = workspacesRemote.find(w => w?.id === localWorkspace?.id)
149
+ if (isOwner) return
150
+
151
+ debug("Workspace local é diferente do remoto para esse usuário", {localWorkspace, workspacesRemote})
152
+
153
+ const reseted = await this.redefineWorkspace(slug)
154
+ if (reseted) return debug("Workspace validado com sucesso. Continuando...")
155
+
156
+ console.log("Parece que você está usando um workspace de outro usuário. Como não foi redefinido, não podemos prosseguir.")
157
+ process.exit(1)
158
+ };
159
+
160
+ async redefineWorkspace(slug = "") {
161
+ const question1 = "\n Deseja redefinir o seu workspace?"
162
+ const question2 = chalk.italic(" O workspace atual pertence a outro usuário, portanto, é necessária a redefinição.")
163
+ const question3 = chalk.italic(" Atenção! A redefinição do workspace poderá acarretar na alteração do tema.")
164
+
165
+ const res = await inquirer.prompt([
166
+ {
167
+ name: "confirm",
168
+ type: "confirm",
169
+ message:
170
+ question1 + "\n" + question2 + "\n" + question3 + "\n",
171
+ default: true,
172
+ },
173
+ ]);
174
+
175
+ if (res.confirm) {
176
+ const workspaceGlobalPath = path.resolve(
177
+ os.homedir(),
178
+ ".eitri",
179
+ "workspaces",
180
+ "workspace"
181
+ );
182
+
183
+ if (fs.existsSync(workspaceGlobalPath)) {
184
+ fs.unlinkSync(workspaceGlobalPath);
185
+ }
186
+
187
+ await this.check(slug)
188
+ }
189
+
190
+ return res.confirm
191
+ }
137
192
  };
@@ -1,5 +1,6 @@
1
1
  const util = require('util');
2
2
  const exec = util.promisify(require("child_process").exec)
3
+ const inquirer = require("inquirer");
3
4
 
4
5
  module.exports = class IOSEmulatorService {
5
6
 
@@ -4,7 +4,7 @@ const WebStarterFactory = require('./factories/WebStarterFactory')
4
4
 
5
5
 
6
6
  const strategy = require('./GATrackingStrategy')
7
- async function handleStartServer(args, trackingService, watcher, workspace, factoryName, targetConfig, platform) {
7
+ async function handleStartServer(args, trackingService, watcher, workspace, factoryName, setupConfig, platform) {
8
8
  const factories = {
9
9
  mobile: new QRCodeStarterFactory(),
10
10
  web: new WebStarterFactory(),
@@ -24,7 +24,7 @@ async function handleStartServer(args, trackingService, watcher, workspace, fact
24
24
  }
25
25
 
26
26
 
27
- const starter = await factory.create(args, trackingService, watcher, workspace, targetConfig)
27
+ const starter = await factory.create(args, trackingService, watcher, workspace, setupConfig)
28
28
  await starter.startServer()
29
29
  }
30
30
 
@@ -93,49 +93,6 @@ class Workspace {
93
93
  return this.resourceFolders2watch;
94
94
  }
95
95
 
96
-
97
- async getTargetConfig(id, target) {
98
- try {
99
- const configs = await this.getAllTargetConfigs(target);
100
- const config = configs.find((cfg) => cfg.id === id);
101
-
102
- if (!config) {
103
- console.log(
104
- `TargetConfig [${target}] não encontrado, utilize o comando --list-target-configs para ver as configurações disponíveis`
105
- );
106
- process.exit(1);
107
- }
108
-
109
- return [config];
110
- } catch (e) {
111
- console.log(`Erro ao buscar configuração: ${e}`);
112
- if (process.env.NODE_ENV !== 'test') {
113
- process.exit(1);
114
- }
115
- }
116
- }
117
-
118
- async getAllTargetConfigs(applicationName) {
119
- // const targetUrl = `${this.config.url}${this.config.targetPath}?name=${target}`
120
- try {
121
- // const response = await axios.get(targetUrl)
122
- // const fullTarget = response.data
123
-
124
- const targets = await this.availableTargets();
125
- const fullTarget = targets.filter(
126
- (a) => a.name === applicationName
127
- );
128
- const configs = fullTarget[0].targetConfig;
129
-
130
- return configs;
131
- } catch (e) {
132
- console.log(`Erro ao buscar configuração: ${e}`);
133
- if (process.env.NODE_ENV !== 'test') {
134
- process.exit(1);
135
- }
136
- }
137
- }
138
-
139
96
  getTarget() {
140
97
  if (!this.target) {
141
98
  console.warn("Target não foi detectado no setup()");
@@ -357,51 +314,6 @@ class Workspace {
357
314
  return Base64.encode(JSON.stringify(miniAppData));
358
315
  }
359
316
 
360
- async getWorkspaceURL(args, targetConfig) {
361
- args = args || {};
362
- const cookie = await this.http.getCookieSession(this.serverUrl);
363
- let paramOrderId = "";
364
- let paramShareId = "";
365
- let cid;
366
- const viewHtml = (args.view || "index") + ".html";
367
- const miniAppConf = this.getMiniConf();
368
- const data = {
369
- publicKey: miniAppConf["public-key"],
370
- metadata: miniAppConf["metadata"],
371
- slug: miniAppConf["slug"],
372
- title: miniAppConf["title"],
373
- };
374
- if (args.orderId) {
375
- paramOrderId = "&orderId=" + encodeURIComponent(args.orderId);
376
- }
377
- if (args.shareId) {
378
- paramShareId = "&shareId=" + encodeURIComponent(args.shareId);
379
- }
380
- if (args.initializationParams) {
381
- data.initializationParams = args.initializationParams;
382
- }
383
- const encodedData = Base64.encode(JSON.stringify(data));
384
- if (cookie) {
385
- cid = Base64.encode(cookie.cookieString());
386
- }
387
-
388
- if (!targetConfig.bootstrapBaseUrl) {
389
- throw new Error(
390
- "Workspace.getWorkspaceURL.internalError#missingBootstrapBaseUrl"
391
- );
392
- }
393
-
394
- let miniAppUrl = `${this.getBootstrapURL(
395
- targetConfig.bootstrapBaseUrl
396
- )}/${this.config.basePath || "workspace"
397
- }/user/${(await vegvisirService.getWorkspace()).id}/${viewHtml}?data=${encodedData}${paramOrderId}${paramShareId}&devmode=true`;
398
-
399
- if (cid) {
400
- miniAppUrl = miniAppUrl + "&cid=" + cid;
401
- }
402
- return miniAppUrl;
403
- }
404
-
405
317
  /**
406
318
  *
407
319
  * @param {string} bootstrapBaseUrl
@@ -419,13 +331,11 @@ class Workspace {
419
331
  return bootstrapBaseUrl;
420
332
  }
421
333
 
422
- async getNewWorkspaceURL(args, targetConfig) {
423
- const qrCodeConfig = await this.getQrCodeConfig(args, targetConfig);
334
+ async getNewWorkspaceURL(args, setupConfig) {
335
+ const qrCodeConfig = await this.getQrCodeConfig(args, setupConfig);
424
336
  const stateData = await this.saveShareState(qrCodeConfig);
425
337
  const stateId = stateData.id;
426
- const miniAppUrl = `${this.qrCodeUrl}/${stateId}?environment=${(process.env.NODE_ENV === "hmlv2" ? "hml" : process.env.NODE_ENV) ||
427
- "hml"
428
- }`;
338
+ const miniAppUrl = `${this.qrCodeUrl}/${stateId}`;
429
339
  return {
430
340
  miniAppConf: {
431
341
  ...qrCodeConfig,
@@ -448,7 +358,7 @@ class Workspace {
448
358
  return response.data;
449
359
  }
450
360
 
451
- async getQrCodeConfig(args, targetConfig) {
361
+ async getQrCodeConfig(args, setupConfig) {
452
362
  args = args || {};
453
363
  const cookie = await this.http.getCookieSession(this.serverUrl);
454
364
  let cid;
@@ -468,10 +378,7 @@ class Workspace {
468
378
  slug: miniAppConf["slug"],
469
379
  title: miniAppConf["title"],
470
380
  permissions: miniAppConf["permissions"],
471
-
472
- // Se nao enviarmos essa url pronta, o superapp tera que monta-la
473
- // Essa url chama a funcao users.js do workspace-api
474
- miniAppBootstrapUrl: await this.getWorkspaceURL(args, targetConfig),
381
+ miniAppBootstrapUrl: this.getBootstrapURL(setupConfig.eitriAppBootstrapURL),
475
382
  initializationParams,
476
383
  orderId,
477
384
  view,
@@ -9,29 +9,20 @@ function QRCodeStarter(
9
9
  trackingService,
10
10
  watcher,
11
11
  workspace,
12
- targetConfig
12
+ setupConfig
13
13
  ) {
14
14
  this.args = args;
15
15
  this.trackingService = trackingService;
16
16
  this.watcher = watcher;
17
17
  this.workspace = workspace;
18
- this.targetConfig = targetConfig;
18
+ this.setupConfig = setupConfig;
19
19
 
20
20
  this.startServer = async function () {
21
- let fullUrl;
22
- if (this.args.oldQrcode) {
23
- fullUrl = await this.workspace.getWorkspaceURL(
21
+ const workspaceURLConfig = await this.workspace.getNewWorkspaceURL(
24
22
  this.args,
25
- this.targetConfig
23
+ this.setupConfig
26
24
  );
27
- } else {
28
- const { miniAppUrl } = await this.workspace.getNewWorkspaceURL(
29
- this.args,
30
- this.targetConfig
31
- );
32
- fullUrl = miniAppUrl;
33
- }
34
-
25
+ const fullUrl = workspaceURLConfig.miniAppUrl
35
26
  if (this.args.verbose) {
36
27
  console.log(`QrCodeUrl: ${fullUrl}`);
37
28
  }
@@ -130,14 +121,14 @@ function QRCodeContentFactory() {
130
121
  trackingService,
131
122
  watcher,
132
123
  workspace,
133
- targetConfig
124
+ setupConfig
134
125
  ) {
135
126
  return new QRCodeStarter(
136
127
  args,
137
128
  trackingService,
138
129
  watcher,
139
130
  workspace,
140
- targetConfig
131
+ setupConfig
141
132
  );
142
133
  };
143
134
  }
@@ -131,126 +131,6 @@ describe('Workspace', () => {
131
131
  ])
132
132
  })
133
133
  })
134
-
135
- describe('.getWorkspaceURL()', () => {
136
- beforeEach(() => {
137
- workspace.userEmail = 'dev@calindra.com.br'
138
- workspace.target = {
139
- bootstrapBaseUrl: 'http://minhaconta.base.url'
140
- }
141
- workspace.folder2watch = path.resolve(
142
- __dirname,
143
- '..',
144
- '_fixtures',
145
- 'src'
146
- )
147
- })
148
-
149
- it('retorna a url do workspace do usuario apontando para index.html', async () => {
150
- let url = await workspace.getWorkspaceURL('', {bootstrapBaseUrl: 'http://minhaconta.base.url'})
151
- expect(url).toContain('/index.html?')
152
- })
153
-
154
- it('Deve retornar queries string ', async () => {
155
- let args = {
156
- initializationParams: {
157
- foo: 'bar'
158
- }
159
- }
160
- let urlValue = await workspace.getWorkspaceURL(args, {bootstrapBaseUrl: 'http://minhaconta.base.url'})
161
- console.log(urlValue)
162
- let query = url.parse(urlValue, true).query
163
- let dataString = Buffer.from(query.data, 'base64').toString()
164
- let data = JSON.parse(dataString)
165
- expect(data.initializationParams).toMatchObject(args.initializationParams)
166
- })
167
-
168
- it('retorna a url do workspace do usuario apontando para OrderDetails.html', async () => {
169
- let url = await workspace.getWorkspaceURL({ view: 'OrderDetails' }, {bootstrapBaseUrl: 'http://minhaconta.base.url'})
170
- expect(url).toContain('/OrderDetails.html?')
171
- })
172
-
173
- it('retorna a url do workspace do usuario com o parametro order id', async () => {
174
- let url = await workspace.getWorkspaceURL({
175
- view: 'OrderDetails',
176
- orderId: 'e08a2547-b8d6-4437-91a7-0bc67987689d',
177
- }, {bootstrapBaseUrl: 'http://minhaconta.base.url'})
178
- expect(url).toContain(
179
- 'orderId=e08a2547-b8d6-4437-91a7-0bc67987689d'
180
- )
181
- })
182
- })
183
- describe('.getTargetConfig() & .getAllTargetConfigs()', () => {
184
- const target = 'CALINDRA_MOBILE'
185
- const res = [
186
- {
187
- id: 7,
188
- name: 'CALINDRA_MOBILE',
189
- minimumCliVersion: '1.16.5',
190
- boilerplateUrl: 'https://github.com/Calindra/servless-backend-template.git',
191
- superAppClientLibName: 'eitri-app-client',
192
- componentsLibName: 'eitri-app-components',
193
- description: 'CALINDRA_MOBILE',
194
- status: 'ACTIVE',
195
- platform: 'mobile',
196
- targetConfig: [
197
- {
198
- id: 'default',
199
- libUrl: 'https://www.npmjs.com/package/eitri-app-client',
200
- runnerUrl: 'https://dev.eitri.calindra.com.br/app/',
201
- bootstrapBaseUrl: 'https://dev.eitri.calindra.com.br',
202
- askUserDataApiUrl: 'https://dev.eitri.calindra.com.br/miniapp-manager-api/o/mini-apps/:slug/token'
203
- },
204
- {
205
- id: 'ws',
206
- libUrl: 'https://www.npmjs.com/package/eitri-app-client',
207
- runnerUrl: 'https://dev.eitri.calindra.com.br/app/',
208
- bootstrapBaseUrl: 'http://localhost:3333',
209
- askUserDataApiUrl: 'https://dev.eitri.calindra.com.br/miniapp-manager-api/p/mini-apps/:slug/token/foundry'
210
- }
211
- ],
212
- default: true
213
- }
214
- ]
215
-
216
- beforeEach(() => {
217
- nock.cleanAll()
218
- nock('https://dev.eitri.calindra.com.br')
219
- .get(/\/eitri-manager-api\/p\/users\/self\/targets/).reply(200, res)
220
- })
221
-
222
- it('deve receber a configuração correta', async () => {
223
- const config = await workspace.getTargetConfig('default', target)
224
- expect(config[0]).toStrictEqual({
225
- id: 'default',
226
- libUrl: 'https://www.npmjs.com/package/eitri-app-client',
227
- runnerUrl: 'https://dev.eitri.calindra.com.br/app/',
228
- bootstrapBaseUrl: 'https://dev.eitri.calindra.com.br',
229
- askUserDataApiUrl: 'https://dev.eitri.calindra.com.br/miniapp-manager-api/o/mini-apps/:slug/token'
230
- })
231
-
232
- }
233
- )
234
- it('deve retornar todos os configs', async () => {
235
- const config = await workspace.getAllTargetConfigs(target)
236
- expect(config).toMatchObject([
237
- {
238
- id: 'default',
239
- libUrl: 'https://www.npmjs.com/package/eitri-app-client',
240
- runnerUrl: 'https://dev.eitri.calindra.com.br/app/',
241
- bootstrapBaseUrl: 'https://dev.eitri.calindra.com.br',
242
- askUserDataApiUrl: 'https://dev.eitri.calindra.com.br/miniapp-manager-api/o/mini-apps/:slug/token'
243
- },
244
- {
245
- id: 'ws',
246
- libUrl: 'https://www.npmjs.com/package/eitri-app-client',
247
- runnerUrl: 'https://dev.eitri.calindra.com.br/app/',
248
- bootstrapBaseUrl: 'http://localhost:3333',
249
- askUserDataApiUrl: 'https://dev.eitri.calindra.com.br/miniapp-manager-api/p/mini-apps/:slug/token/foundry'
250
- }
251
- ])
252
- })
253
- })
254
134
 
255
135
  describe('.availableTargets()', () => {
256
136