@slicemachine/init 1.1.10-alpha.5 → 1.1.11-alpha.2

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/build/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  'use strict';
4
4
 
5
- const core = require('@slicemachine/core');
5
+ const client = require('@slicemachine/client');
6
6
  const Prismic = require('@slicemachine/core/build/prismic');
7
7
  const ServerAnalytics = require('analytics-node');
8
8
  const uuid = require('uuid');
@@ -11,28 +11,24 @@ const util = require('util');
11
11
  const child_process = require('child_process');
12
12
  const chalk = require('chalk');
13
13
  const ora = require('ora');
14
+ const core = require('@slicemachine/core');
14
15
  const hapi = require('@hapi/hapi');
15
16
  const open = require('open');
17
+ const t = require('io-ts');
18
+ const fs = require('fs');
16
19
  const NodeUtils = require('@slicemachine/core/build/node-utils');
17
20
  const inquirer = require('inquirer');
18
21
  const Separator = require('inquirer/lib/objects/separator');
19
- const axios = require('axios');
20
- const _function = require('fp-ts/function');
21
- const Either = require('fp-ts/Either');
22
22
  const tmp = require('tmp');
23
23
  const AdmZip = require('adm-zip');
24
24
  const fsExtra = require('fs-extra');
25
- const fs = require('fs');
26
- const cookie = require('@slicemachine/core/build/utils/cookie');
27
- const Libraries = require('@slicemachine/core/build/libraries');
25
+ const axios = require('axios');
26
+ const Either = require('fp-ts/Either');
28
27
  const models = require('@slicemachine/core/build/models');
29
- const mime = require('mime');
30
- const snakeCase = require('lodash.snakecase');
31
- const FormData = require('form-data');
32
- const uniqid = require('uniqid');
28
+ const Libraries = require('@slicemachine/core/build/libraries');
33
29
  const customtypes = require('@prismicio/types-internal/lib/customtypes');
34
30
  const Either$1 = require('fp-ts/lib/Either');
35
- const t = require('io-ts');
31
+ const SharedConfig = require('@slicemachine/core/build/prismic/SharedConfig');
36
32
 
37
33
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
38
34
 
@@ -63,21 +59,17 @@ const chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
63
59
  const ora__default = /*#__PURE__*/_interopDefaultLegacy(ora);
64
60
  const hapi__namespace = /*#__PURE__*/_interopNamespace(hapi);
65
61
  const open__default = /*#__PURE__*/_interopDefaultLegacy(open);
62
+ const t__namespace = /*#__PURE__*/_interopNamespace(t);
63
+ const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
66
64
  const NodeUtils__namespace = /*#__PURE__*/_interopNamespace(NodeUtils);
67
65
  const inquirer__namespace = /*#__PURE__*/_interopNamespace(inquirer);
68
66
  const inquirer__default = /*#__PURE__*/_interopDefaultLegacy(inquirer);
69
67
  const Separator__default = /*#__PURE__*/_interopDefaultLegacy(Separator);
70
- const axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
71
68
  const tmp__default = /*#__PURE__*/_interopDefaultLegacy(tmp);
72
69
  const AdmZip__default = /*#__PURE__*/_interopDefaultLegacy(AdmZip);
73
70
  const fsExtra__default = /*#__PURE__*/_interopDefaultLegacy(fsExtra);
74
- const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
71
+ const axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
75
72
  const Libraries__namespace = /*#__PURE__*/_interopNamespace(Libraries);
76
- const mime__default = /*#__PURE__*/_interopDefaultLegacy(mime);
77
- const snakeCase__default = /*#__PURE__*/_interopDefaultLegacy(snakeCase);
78
- const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData);
79
- const uniqid__default = /*#__PURE__*/_interopDefaultLegacy(uniqid);
80
- const t__namespace = /*#__PURE__*/_interopNamespace(t);
81
73
 
82
74
  var __accessCheck = (obj, member, msg) => {
83
75
  if (!member.has(obj))
@@ -98,6 +90,13 @@ var __privateSet = (obj, member, value, setter) => {
98
90
  return value;
99
91
  };
100
92
  var _client, _isTrackingActive, _anonymousId, _userId, _repository;
93
+ var EventType;
94
+ (function(EventType2) {
95
+ EventType2["DownloadLibrary"] = "SliceMachine Download Library";
96
+ EventType2["InitStart"] = "SliceMachine Init Start";
97
+ EventType2["InitIdentify"] = "SliceMachine Init Identify";
98
+ EventType2["InitEnd"] = "SliceMachine Init End";
99
+ })(EventType || (EventType = {}));
101
100
  class InitTracker {
102
101
  constructor() {
103
102
  __privateAdd(this, _client, null);
@@ -164,16 +163,28 @@ class InitTracker {
164
163
  return this._identifyEvent(userId, intercomHash);
165
164
  }
166
165
  trackDownloadLibrary(library) {
167
- return this._trackEvent("SliceMachine Download Library" /* DownloadLibrary */, { library });
166
+ return this._trackEvent(EventType.DownloadLibrary, { library });
168
167
  }
169
168
  trackInitIdentify() {
170
- return this._trackEvent("SliceMachine Init Identify" /* InitIdentify */);
169
+ return this._trackEvent(EventType.InitIdentify);
171
170
  }
172
171
  trackInitStart(repoDomain) {
173
- return this._trackEvent("SliceMachine Init Start" /* InitStart */, { repo: repoDomain });
172
+ return this._trackEvent(EventType.InitStart, { repo: repoDomain });
174
173
  }
175
- trackInitDone(framework) {
176
- return this._trackEvent("SliceMachine Init Done" /* InitDone */, { framework });
174
+ trackInitEndSuccess(framework) {
175
+ return this._trackEvent(EventType.InitEnd, {
176
+ framework,
177
+ repo: __privateGet(this, _repository),
178
+ result: "success"
179
+ });
180
+ }
181
+ trackInitEndFail(framework, error) {
182
+ return this._trackEvent(EventType.InitEnd, {
183
+ framework,
184
+ repo: __privateGet(this, _repository),
185
+ result: "error",
186
+ error
187
+ });
177
188
  }
178
189
  }
179
190
  _client = new WeakMap();
@@ -231,7 +242,7 @@ const logs = /*#__PURE__*/Object.freeze({
231
242
  });
232
243
 
233
244
  const { Cookie } = core.Utils;
234
- const { DEFAULT_BASE: DEFAULT_BASE$1, DEFAULT_SERVER_PORT } = core.CONSTS;
245
+ const { DEFAULT_BASE, DEFAULT_SERVER_PORT } = core.CONSTS;
235
246
  const { bold, underline, spinner, writeError } = logs;
236
247
  const isHandlerData = (data) => {
237
248
  if (typeof data != "object")
@@ -274,13 +285,16 @@ const authenticationHandler = (server) => (onSuccess, onFail) => {
274
285
  }
275
286
  };
276
287
  };
288
+ function stripTrailingSlash(str) {
289
+ return str.endsWith("/") ? str.slice(0, -1) : str;
290
+ }
277
291
  function buildServer(base, port, host) {
278
292
  const server = hapi__namespace.server({
279
293
  port,
280
294
  host,
281
295
  routes: {
282
296
  cors: {
283
- origin: [base],
297
+ origin: [stripTrailingSlash(base)],
284
298
  headers: ["Origin", "X-Requested-With", "Content-Type", "Accept"]
285
299
  }
286
300
  }
@@ -303,7 +317,7 @@ function askSingleChar(title) {
303
317
  process.stdin.on("data", handler);
304
318
  });
305
319
  }
306
- async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE$1, port = DEFAULT_SERVER_PORT) {
320
+ async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE, port = DEFAULT_SERVER_PORT) {
307
321
  const confirmation = await askSingleChar(`>> Press any key to open the browser to ${action} or q to exit:`);
308
322
  if (confirmation === "q" || confirmation === "")
309
323
  return process.exit(-1);
@@ -340,46 +354,92 @@ async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE$1, por
340
354
  }
341
355
 
342
356
  async function startAuth({
343
- base,
357
+ client,
344
358
  url,
345
359
  action
346
360
  }) {
347
- const { onLoginFail } = await startServerAndOpenBrowser(url, action, base);
361
+ const { onLoginFail } = await startServerAndOpenBrowser(url, action, client.apisEndpoints.Wroom);
348
362
  try {
349
- await core.Utils.Poll.startPolling(() => Auth.validateSession(base), (user) => !!user, 3e3, 60);
363
+ await core.Utils.Poll.startPolling(() => Auth.validateSession(client), (isSessionValid) => isSessionValid == true, 3e3, 60);
350
364
  return;
351
365
  } catch (e) {
352
366
  onLoginFail();
353
367
  }
354
368
  }
355
369
  const Auth = {
356
- login: async (base) => {
357
- const endpoints = Prismic.Endpoints.buildEndpoints(base);
370
+ login: async (client) => {
371
+ const endpoints = Prismic.Endpoints.buildEndpoints(client.apisEndpoints.Wroom);
358
372
  return startAuth({
359
- base,
373
+ client,
360
374
  url: endpoints.Dashboard.cliLogin,
361
375
  action: "login"
362
376
  });
363
377
  },
364
- signup: async (base) => {
365
- const endpoints = Prismic.Endpoints.buildEndpoints(base);
366
- return startAuth({
367
- base,
368
- url: endpoints.Dashboard.cliSignup,
369
- action: "signup"
370
- });
371
- },
372
- logout: () => Prismic.PrismicSharedConfigManager.remove(),
373
- validateSession: async (requiredBase) => {
374
- const config = Prismic.PrismicSharedConfigManager.get();
375
- if (!config.cookies.length)
376
- return Promise.resolve(null);
377
- if (requiredBase != config.base)
378
- return Promise.resolve(null);
379
- return Prismic.Communication.validateSession(config.cookies, requiredBase).catch(() => null);
378
+ validateSession: async (client) => {
379
+ const authToken = Prismic.PrismicSharedConfigManager.getAuth();
380
+ return client.updateAuthenticationToken(authToken).profile().then((userProfile) => {
381
+ Prismic.PrismicSharedConfigManager.setProperties({
382
+ shortId: userProfile.shortId,
383
+ intercomHash: userProfile.intercomHash
384
+ });
385
+ return true;
386
+ }).catch(() => false);
380
387
  }
381
388
  };
382
389
 
390
+ class InitClient extends client.Client {
391
+ async listRepositories() {
392
+ return client.getAndValidateResponse(this._get(`${this.apisEndpoints.Users}repositories`), "repository list", t__namespace.array(core.Models.Repository));
393
+ }
394
+ async createRepository(domain, framework) {
395
+ const data = {
396
+ domain,
397
+ framework,
398
+ plan: "personal",
399
+ isAnnual: "false",
400
+ role: "developer"
401
+ };
402
+ return this._fetch({
403
+ method: "post",
404
+ url: `${this.apisEndpoints.Wroom}authentication/newrepository?app=slicemachine`,
405
+ data,
406
+ headers: {
407
+ Cookie: Prismic.PrismicSharedConfigManager.get().cookies,
408
+ "User-Agent": "prismic-cli/sm"
409
+ }
410
+ }).then(() => domain);
411
+ }
412
+ async domainExist(domain) {
413
+ return client.getAndValidateResponse(this._get(`${this.apisEndpoints.Wroom}app/dashboard/repositories/${domain}/exists`), "repository exists", t__namespace.boolean);
414
+ }
415
+ async pushDocuments(signature, documents, cookies) {
416
+ if (!this.repository)
417
+ throw new Error("Repository undefined in the client");
418
+ const repositoryDirectUrl = new URL(this.apisEndpoints.Wroom);
419
+ repositoryDirectUrl.hostname = `${this.repository}.${repositoryDirectUrl.hostname}`;
420
+ return this._fetch({
421
+ method: "post",
422
+ url: `${repositoryDirectUrl.toString()}starter/documents`,
423
+ data: { signature, documents: JSON.stringify(documents) },
424
+ headers: {
425
+ Cookie: cookies,
426
+ "User-Agent": "prismic-cli/0"
427
+ }
428
+ });
429
+ }
430
+ }
431
+
432
+ async function lsdir(dir) {
433
+ return fs__default["default"].promises.readdir(dir).then((dirs) => {
434
+ return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isDirectory()).map((subdirectory) => path__default["default"].join(dir, subdirectory));
435
+ });
436
+ }
437
+ async function lsfiles(dir) {
438
+ return fs__default["default"].promises.readdir(dir).then((dirs) => {
439
+ return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isFile()).map((file) => path__default["default"].join(dir, file));
440
+ });
441
+ }
442
+
383
443
  function findArgument(args, name) {
384
444
  const flagIndex = args.indexOf(`--${name}`);
385
445
  if (flagIndex === -1)
@@ -396,6 +456,16 @@ function findFlag(args, name) {
396
456
  return args.includes(toFind);
397
457
  }
398
458
  const execCommand = util__default["default"].promisify(child_process.exec);
459
+ function getApplicationMode(argumentValue) {
460
+ switch (argumentValue) {
461
+ case client.ApplicationMode.PROD:
462
+ case client.ApplicationMode.STAGE:
463
+ case client.ApplicationMode.DEV:
464
+ return argumentValue;
465
+ default:
466
+ return null;
467
+ }
468
+ }
399
469
 
400
470
  const {
401
471
  PRISMIC_CLIENT,
@@ -465,18 +535,18 @@ function validatePkg(cwd) {
465
535
  }
466
536
  }
467
537
 
468
- function createRepository(domain, framework, cookies, base) {
538
+ function createRepository(client, domain, framework) {
469
539
  const spinner = spinner$1("Creating Prismic Repository");
470
540
  spinner.start();
471
- return Prismic__namespace.Communication.createRepository(domain, cookies, framework, base).then((res) => {
472
- const addressUrl = new URL(base);
473
- const repoDomainName = res.data.domain || domain;
474
- addressUrl.hostname = `${repoDomainName}.${addressUrl.hostname}`;
541
+ return client.createRepository(domain, framework).then((domain2) => {
542
+ const addressUrl = new URL(client.apisEndpoints.Wroom);
543
+ addressUrl.hostname = `${domain2}.${addressUrl.hostname}`;
475
544
  const address = addressUrl.toString();
476
545
  spinner.succeed(`We created your new repository ${address}`);
477
- return repoDomainName;
478
- }).catch((error) => {
546
+ return domain2;
547
+ }).catch(async (error) => {
479
548
  spinner.fail(`Error creating repository ${domain}`);
549
+ await Tracker.get().trackInitEndFail(framework, "Failed to create repository");
480
550
  if (error.message) {
481
551
  writeError$1(error.message);
482
552
  }
@@ -486,14 +556,38 @@ function createRepository(domain, framework, cookies, base) {
486
556
  });
487
557
  }
488
558
 
559
+ async function validateRepositoryName(client, name) {
560
+ const domain = name.trim();
561
+ const errors = [];
562
+ const startsWithLetter = /^[a-zA-Z]/.test(domain);
563
+ if (!startsWithLetter)
564
+ errors.push("Must start with a letter.");
565
+ const acceptedChars = /^[a-z0-9-]+$/.test(domain);
566
+ if (!acceptedChars)
567
+ errors.push("Must contain only lowercase letters, numbers and hyphens.");
568
+ const fourCharactersOrMore = domain.length >= 4;
569
+ if (!fourCharactersOrMore)
570
+ errors.push("Must have four or more alphanumeric characters and/or hyphens.");
571
+ const endsWithALetterOrNumber = /[a-z0-9]$/.test(domain);
572
+ if (!endsWithALetterOrNumber)
573
+ errors.push("Must end in a letter or a number.");
574
+ const thirtyCharacterOrLess = domain.length <= 30;
575
+ if (!thirtyCharacterOrLess)
576
+ errors.push("Must be 30 characters or less");
577
+ if (errors.length > 0) {
578
+ const errorString = errors.map((d, i) => `(${i + 1}: ${d}`).join(" ");
579
+ const msg = `Validation errors: ${errorString}`;
580
+ return Promise.reject(new Error(msg));
581
+ }
582
+ return client.domainExist(domain).then((isAvailable) => isAvailable ? true : Promise.reject(new Error(`${name} is already in use`))).catch(() => Promise.reject(new Error(`${name} is already in use`)));
583
+ }
584
+
489
585
  const CREATE_REPO = "$_CREATE_REPO";
490
- const DEFAULT_BASE = core.CONSTS.DEFAULT_BASE;
491
- function prettyRepoName(address, value) {
492
- const repoName = value ? cyan(value) : dim.cyan("repo-name");
493
- return `${cyan.dim(`${address.protocol}//`)}${repoName}${cyan.dim(`.${address.hostname}`)}`;
586
+ function prettyRepoName(address, domain) {
587
+ return `${cyan.dim(`${address.protocol}//`)}${cyan(domain)}${cyan.dim(`.${address.hostname}`)}`;
494
588
  }
495
- async function promptForRepoDomain(base, defaultValue) {
496
- const address = new URL(base);
589
+ async function promptForRepoDomain(client, defaultValue) {
590
+ const address = new URL(client.apisEndpoints.Wroom);
497
591
  writeInfo("The name acts as a domain/endpoint for your content repo and should be completely unique.");
498
592
  return inquirer__namespace.prompt([
499
593
  {
@@ -502,11 +596,8 @@ async function promptForRepoDomain(base, defaultValue) {
502
596
  type: "input",
503
597
  required: true,
504
598
  default: defaultValue,
505
- transformer: (value) => prettyRepoName(address, value || defaultValue),
506
- async validate(name) {
507
- const result = await Prismic__namespace.Communication.validateRepositoryName(name, base, false);
508
- return result === name || result;
509
- }
599
+ transformer: (value) => prettyRepoName(address, value || defaultValue || "repository"),
600
+ validate: (name) => validateRepositoryName(client, name)
510
601
  }
511
602
  ]).then((res) => res.repoDomain);
512
603
  }
@@ -560,26 +651,26 @@ function sortReposForPrompt(repos, base, cwd) {
560
651
  createNew
561
652
  ]).sort(orderPrompts(maybeConfiguredRepoName));
562
653
  }
563
- async function chooseOrCreateARepository(cwd, framework, cookies, base = DEFAULT_BASE, domain) {
564
- const token = core.Utils.Cookie.parsePrismicAuthToken(cookies);
565
- const repos = await Prismic__namespace.Communication.listRepositories(token, base);
566
- const hasRepo = domain && repos.find((d) => d.domain === domain);
567
- if (hasRepo)
568
- return domain;
569
- if (repos.length === 0) {
570
- const domainName = await promptForRepoDomain(base, domain);
571
- return await createRepository(domainName, framework, cookies, base);
654
+ async function chooseOrCreateARepository(client, cwd, framework, preSelectedRepository) {
655
+ const repositories = await client.listRepositories();
656
+ const isPreSelectedValid = preSelectedRepository && repositories.find((repository) => repository.domain === preSelectedRepository);
657
+ if (isPreSelectedValid)
658
+ return preSelectedRepository;
659
+ if (repositories.length === 0) {
660
+ const domainName = await promptForRepoDomain(client, preSelectedRepository);
661
+ await createRepository(client, domainName, framework);
662
+ return domainName;
572
663
  }
573
- const choices = sortReposForPrompt(repos, base, cwd);
664
+ const choices = sortReposForPrompt(repositories, client.apisEndpoints.Wroom, cwd);
574
665
  const numberOfDisabledRepos = choices.filter((repo) => {
575
666
  if (repo instanceof Separator__default["default"])
576
667
  return false;
577
668
  return repo.disabled;
578
669
  }).length;
579
- const res = await inquirer__namespace.prompt([
670
+ const promptResult = await inquirer__namespace.prompt([
580
671
  {
581
672
  type: "list",
582
- name: "chosenRepo",
673
+ name: "chosenRepository",
583
674
  default: 0,
584
675
  required: true,
585
676
  message: "Connect a Prismic Repository or create a new one",
@@ -587,11 +678,12 @@ async function chooseOrCreateARepository(cwd, framework, cookies, base = DEFAULT
587
678
  pageSize: numberOfDisabledRepos + 2 <= 7 ? 7 : numberOfDisabledRepos + 2
588
679
  }
589
680
  ]);
590
- if (res.chosenRepo === CREATE_REPO) {
591
- const domainName = await promptForRepoDomain(base, domain);
592
- return await createRepository(domainName, framework, cookies, base);
681
+ if (promptResult.chosenRepository === CREATE_REPO) {
682
+ const domainName = await promptForRepoDomain(client, preSelectedRepository);
683
+ await createRepository(client, domainName, framework);
684
+ return domainName;
593
685
  }
594
- return res.chosenRepo;
686
+ return promptResult.chosenRepository;
595
687
  }
596
688
 
597
689
  async function promptForFramework() {
@@ -648,60 +740,26 @@ async function detectFramework(cwd) {
648
740
  } else {
649
741
  console.log(failMessage);
650
742
  }
743
+ await Tracker.get().trackInitEndFail(core.Models.Frameworks.none, "Framework not detected");
651
744
  process.exit(1);
652
745
  }
653
746
  }
654
747
 
655
- async function getUserProfile(cookies, base = core.CONSTS.DEFAULT_BASE) {
656
- const userServiceBase = core.CONSTS.DEFAULT_BASE === base ? core.CONSTS.USER_SERVICE_BASE : core.CONSTS.USER_SERVICE_STAGING_BASE;
657
- const url = new URL(userServiceBase);
658
- url.pathname = "profile";
659
- const endpoint = url.toString();
660
- const token = core.Utils.Cookie.parsePrismicAuthToken(cookies);
661
- return axios__default["default"].get(endpoint, {
662
- headers: {
663
- Authorization: `Bearer ${token}`
664
- }
665
- }).then((res) => _function.pipe(core.Models.UserProfile.decode(res.data), Either.fold(() => {
666
- throw new Error("Can't parse user profile");
667
- }, (data) => data)));
668
- }
669
- async function validateSessionAndGetProfile(base = core.CONSTS.DEFAULT_BASE) {
670
- const config = Prismic__namespace.PrismicSharedConfigManager.get();
671
- if (!config.cookies.length)
672
- return Promise.resolve(null);
673
- if (base != config.base)
674
- return Promise.resolve(null);
675
- try {
676
- const info = await Prismic__namespace.Communication.validateSession(config.cookies, base);
677
- const profile = await getUserProfile(config.cookies, base).catch(() => null);
678
- if (profile == null ? void 0 : profile.shortId) {
679
- Prismic__namespace.PrismicSharedConfigManager.setProperties({
680
- shortId: profile.shortId,
681
- intercomHash: profile.intercomHash
682
- });
683
- }
684
- return { info, profile };
685
- } catch (e) {
686
- return null;
687
- }
688
- }
689
-
690
- async function loginOrBypass(base) {
691
- const user = await validateSessionAndGetProfile(base).catch((err) => console.log(err));
748
+ async function loginOrBypass(client) {
749
+ const user = await client.profile().catch(() => null);
692
750
  if (user) {
693
- const email = user.info.email;
751
+ const email = user.email;
694
752
  writeCheck(`Logged in as ${bold$1(email)}`);
695
753
  return user;
696
- } else {
697
- await Auth.login(base);
698
- const user2 = await validateSessionAndGetProfile(base);
699
- return user2;
700
754
  }
755
+ await Auth.login(client);
756
+ client.updateAuthenticationToken(Prismic.PrismicSharedConfigManager.getAuth());
757
+ const userAfterLogin = await client.profile();
758
+ return userAfterLogin;
701
759
  }
702
760
 
703
761
  const defaultSliceMachineVersion = "0.0.41";
704
- async function configureProject(cwd, base, repositoryDomainName, framework, sliceLibPath = [], tracking = true) {
762
+ async function configureProject(client, cwd, repositoryDomainName, framework, sliceLibPath = [], tracking = true) {
705
763
  const frameworkName = NodeUtils__namespace.Framework.fancyName(framework.value);
706
764
  const spinner = spinner$1(`Configuring your ${frameworkName} and Prismic project...`);
707
765
  spinner.start();
@@ -713,7 +771,7 @@ async function configureProject(cwd, base, repositoryDomainName, framework, slic
713
771
  const libs = manifest.content && manifest.content.libraries && manifest.content.libraries.length > 0 ? manifest.content.libraries : ["@/slices"];
714
772
  const manifestUpdated = {
715
773
  ...manifestAlreadyExistWithContent ? manifest.content : { _latest: sliceMachineVersionInstalled },
716
- apiEndpoint: Prismic__namespace.Endpoints.buildRepositoryEndpoint(base, repositoryDomainName),
774
+ apiEndpoint: Prismic__namespace.Endpoints.buildRepositoryEndpoint(client.apisEndpoints.Wroom, repositoryDomainName),
717
775
  libraries: [...libs, ...sliceLibPath],
718
776
  ...framework.manuallyAdded ? { framework: framework.value } : {},
719
777
  ...!tracking ? { tracking } : {}
@@ -727,9 +785,10 @@ async function configureProject(cwd, base, repositoryDomainName, framework, slic
727
785
  NodeUtils__namespace.Files.mkdir(pathToSlicesFolder, { recursive: true });
728
786
  }
729
787
  NodeUtils__namespace.addJsonPackageSmScript(cwd);
730
- await Tracker.get().trackInitDone(framework.value);
788
+ await Tracker.get().trackInitEndSuccess(framework.value);
731
789
  spinner.succeed("Project configured! Ready to start");
732
- } catch (e) {
790
+ } catch (error) {
791
+ await Tracker.get().trackInitEndFail(framework.value, "Failed to configure Slice Machine");
733
792
  spinner.fail("Failed to configure Slice Machine");
734
793
  process.exit(-1);
735
794
  }
@@ -874,104 +933,11 @@ async function installLib(cwd, libGithubPath, branch = "HEAD") {
874
933
  if (error instanceof Error) {
875
934
  console.error(error.message);
876
935
  }
936
+ await Tracker.get().trackInitEndFail(core.Models.Frameworks.none, "Failed to install ${libGithubPath} library");
877
937
  process.exit(-1);
878
938
  }
879
939
  }
880
940
 
881
- function handleErrors(prefix, err) {
882
- if (axios__default["default"].isAxiosError(err) && err.response) {
883
- writeError$1(`${prefix} | [${err.response.status}]: ${err.response.statusText}`);
884
- } else if (err instanceof Error) {
885
- writeError$1(`${prefix} ${err.message}`);
886
- } else {
887
- writeError$1(`${prefix} ${String(err)}`);
888
- }
889
- }
890
- async function getRemoteSliceIds(customTypeApiEndpoint, repository, authorization) {
891
- const addr = `${stripLastSlash(customTypeApiEndpoint)}/slices`;
892
- return axios__default["default"].get(addr, {
893
- headers: {
894
- Authorization: `Bearer ${authorization}`,
895
- repository
896
- }
897
- }).then((res) => {
898
- return Array.isArray(res.data) ? res.data.map((model) => model.id) : [];
899
- });
900
- }
901
- async function sendModelToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, model) {
902
- const data = models.Slices.fromSM(model);
903
- const updateOrInsertUrl = `${customTypesApiEndpoint}slices/${remoteSliceIds.includes(model.id) ? "update" : "insert"}`;
904
- return axios__default["default"].post(updateOrInsertUrl, data, {
905
- headers: {
906
- Authorization: `Bearer ${authorization}`,
907
- repository
908
- }
909
- }).then(() => {
910
- return;
911
- }).catch((err) => {
912
- handleErrors(`sending slice ${model.id}, please try again. If the problem persists, contact us.`, err);
913
- throw err;
914
- });
915
- }
916
- async function sendManyModelsToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, models) {
917
- return Promise.all(models.map((model) => sendModelToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, model))).then(() => {
918
- return;
919
- }).catch(() => {
920
- process.exit(1);
921
- });
922
- }
923
- function stripLastSlash(str) {
924
- return str.replace(/\/*$/g, "");
925
- }
926
- function getRemoteCustomTypeIds(customTypeApiEndpoint, repository, authorization) {
927
- const addr = `${stripLastSlash(customTypeApiEndpoint)}/customtypes`;
928
- return axios__default["default"].get(addr, {
929
- headers: {
930
- Authorization: `Bearer ${authorization}`,
931
- repository
932
- }
933
- }).then((res) => {
934
- return Array.isArray(res.data) ? res.data.map((ct) => ct.id) : [];
935
- });
936
- }
937
- async function sendCustomTypeToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customType) {
938
- const shouldUpdate = remoteCustomTypeIds.includes(customType.id);
939
- const addr = `${stripLastSlash(customTypeApiEndpoint)}/customtypes/${shouldUpdate ? "update" : "insert"}`;
940
- return axios__default["default"].post(addr, customType, {
941
- headers: {
942
- repository,
943
- Authorization: `Bearer ${authorization}`
944
- }
945
- }).then(() => {
946
- return;
947
- }).catch((err) => {
948
- handleErrors(`sending custom type ${customType.id}, please try again. If the problem persists, contact us.`, err);
949
- throw err;
950
- });
951
- }
952
- async function sendManyCustomTypesToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customTypes) {
953
- return Promise.all(customTypes.map((customType) => sendCustomTypeToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customType))).then(() => {
954
- return;
955
- }).catch(() => {
956
- process.exit(1);
957
- });
958
- }
959
-
960
- const ProductionApisEndpoints = {
961
- Models: "https://customtypes.prismic.io/",
962
- AclProvider: "https://0yyeb2g040.execute-api.us-east-1.amazonaws.com/prod/"
963
- };
964
- const StageApisEndpoints = {
965
- Models: "https://customtypes.wroom.io/",
966
- AclProvider: "https://2iamcvnxf4.execute-api.us-east-1.amazonaws.com/stage/"
967
- };
968
- const getEndpointsFromBase = (base) => {
969
- const url = new URL(base);
970
- if (url.hostname === "wroom.io")
971
- return StageApisEndpoints;
972
- return ProductionApisEndpoints;
973
- };
974
-
975
941
  async function promptToPushSlices() {
976
942
  return inquirer__default["default"].prompt([
977
943
  {
@@ -988,127 +954,80 @@ async function promptToPushCustomTypes() {
988
954
  type: "confirm",
989
955
  name: "pushCustomTypes",
990
956
  default: false,
991
- message: "Your repository already contains Custom Types. Do you want to continue pushing your local Slices?"
957
+ message: "Your repository already contains Custom Types. Do you want to continue pushing your local Custom Types?"
992
958
  }
993
959
  ]).then((res) => res.pushCustomTypes);
994
960
  }
995
961
 
996
- async function createAcl(address, repository, authorization) {
997
- return axios__default["default"].get(address + "create", {
998
- headers: {
999
- repository,
1000
- Authorization: `Bearer ${authorization}`,
1001
- "User-Agent": "slice-machine"
1002
- }
1003
- }).then((res) => res.data);
1004
- }
1005
- async function createFormForS3(key, filename, filePath, acl) {
1006
- const form = new FormData__default["default"]();
1007
- Object.entries(acl.values.fields).forEach(([k, value]) => {
1008
- form.append(k, value);
1009
- });
1010
- form.append("key", key);
1011
- const contentType = mime__default["default"].getType(filePath);
1012
- contentType && form.append("Content-Type", contentType);
1013
- return fs__default["default"].promises.readFile(filePath).then((file) => {
1014
- form.append("file", file, { filename });
1015
- return form;
1016
- }).catch(() => {
1017
- writeError$1(`Error reading preview image: ${filename}`);
1018
- return null;
1019
- });
1020
- }
1021
- function createS3Key(repository, sliceName, variationId, filename) {
1022
- return `${repository}/shared-slices/${snakeCase__default["default"](sliceName)}/${snakeCase__default["default"](variationId)}-${uniqid__default["default"]()}/${filename}`;
1023
- }
1024
- async function sendVariationPreviewToS3(acl, repository, sliceName, variationId, filePath) {
1025
- const filename = path__default["default"].basename(filePath);
1026
- const key = createS3Key(repository, sliceName, variationId, filename);
1027
- const form = await createFormForS3(key, filename, filePath, acl);
1028
- if (form === null)
1029
- return null;
1030
- if (form.hasKnownLength() === false) {
1031
- writeError$1(`[slice/push] An error occurred while uploading preview image ${filePath} as length in unknown`);
1032
- }
1033
- const errorMessage = `[slice/push] An error occurred while uploading preview images for ${sliceName}-${variationId} - please contact support`;
1034
- return axios__default["default"].post(acl.values.url, form, {
1035
- headers: {
1036
- ...form.getHeaders(),
1037
- "Content-Length": String(form.getLengthSync())
1038
- }
1039
- }).then((res) => {
1040
- if (res.status !== 204) {
1041
- writeError$1(errorMessage);
1042
- writeError$1(`${res.status}: ${res.statusText}`);
1043
- return null;
1044
- } else {
1045
- return `${acl.imgixEndpoint}/${key}`;
1046
- }
1047
- }).catch((err) => {
1048
- writeError$1(errorMessage);
1049
- if (axios__default["default"].isAxiosError(err) && err.response) {
1050
- writeError$1(`${err.response.status}: ${err.response.statusText}`);
1051
- } else if (err instanceof Error) {
1052
- writeError$1(err.message);
1053
- } else {
1054
- writeError$1(String(err));
1055
- }
1056
- return null;
1057
- });
1058
- }
1059
- async function maybeAddImageUrlToVariation(acl, repository, modelId, pathToScreenShot, variation) {
1060
- const imageUrl = await sendVariationPreviewToS3(acl, repository, modelId, variation.id, pathToScreenShot);
1061
- if (!imageUrl)
962
+ async function updateVariationWithScreenshot(client, acl, screenshotPaths, sliceName, variation) {
963
+ const screenshot = screenshotPaths[variation.id];
964
+ if (!screenshot || !screenshot.path)
965
+ return Promise.resolve(variation);
966
+ return client.uploadScreenshot({
967
+ acl,
968
+ sliceName,
969
+ variationId: variation.id,
970
+ filePath: screenshot.path
971
+ }).then((screenshotUrl) => {
972
+ return {
973
+ ...variation,
974
+ imageUrl: screenshotUrl
975
+ };
976
+ }).catch((error) => {
977
+ writeError$1(`Couldn't upload screenshot slice: ${sliceName} - variation: ${variation.id}`);
978
+ writeError$1(error.message, "Full error:");
1062
979
  return variation;
1063
- return {
1064
- ...variation,
1065
- imageUrl
1066
- };
980
+ });
1067
981
  }
1068
- async function addImageUrlsToVariations(acl, repository, modelId, screenshotPaths, variations) {
1069
- return Promise.all(variations.map(async (variation) => {
1070
- const screenshot = screenshotPaths[variation.id];
1071
- if (!screenshot || !screenshot.path)
1072
- return variation;
1073
- return maybeAddImageUrlToVariation(acl, repository, modelId, screenshot.path, variation);
982
+ async function updateSlicesWithScreenshots(client, acl, components) {
983
+ return Promise.all(components.map(async (component) => {
984
+ const { screenshotPaths, model } = component;
985
+ const variationsUpdated = await Promise.all(model.variations.map(async (variation) => updateVariationWithScreenshot(client, acl, screenshotPaths, model.id, variation)));
986
+ return {
987
+ ...model,
988
+ variations: variationsUpdated
989
+ };
1074
990
  }));
1075
991
  }
1076
- async function maybeUpdateModelVariationsWithImageUrl(acl, repository, component) {
1077
- const { screenshotPaths, model } = component;
1078
- const variations = await addImageUrlsToVariations(acl, repository, model.id, screenshotPaths, model.variations);
1079
- return {
1080
- ...model,
1081
- variations
1082
- };
1083
- }
1084
- async function addImageUrlsToModelVariations(acl, repository, components) {
1085
- return Promise.all(components.map(async (component) => maybeUpdateModelVariationsWithImageUrl(acl, repository, component)));
1086
- }
1087
992
 
1088
- async function sendSlicesFromStarter(base, repository, authorization, libraryPaths, cwd) {
1089
- const endpoints = getEndpointsFromBase(base);
1090
- const libraries = Libraries__namespace.libraries(cwd, libraryPaths);
1091
- if (libraries.length === 0)
993
+ async function sendSlices(client, cwd, manifest) {
994
+ if (!manifest.libraries)
1092
995
  return Promise.resolve(false);
1093
- const remoteSlices = await getRemoteSliceIds(endpoints.Models, repository, authorization);
1094
- if (remoteSlices.length) {
996
+ const libraries = Libraries__namespace.libraries(cwd, manifest.libraries);
997
+ const components = libraries.reduce((acc, lib) => {
998
+ return [...acc, ...lib.components];
999
+ }, []);
1000
+ if (components.length === 0)
1001
+ return Promise.resolve(false);
1002
+ const remoteSlicesIds = await client.getSlices().then((slices) => slices.map((slice) => slice.id));
1003
+ if (remoteSlicesIds.length) {
1095
1004
  const pushAnyway = await promptToPushSlices();
1096
1005
  if (pushAnyway === false)
1097
1006
  return Promise.resolve(true);
1098
1007
  }
1099
1008
  const spinner = spinner$1("Pushing existing Slice models to your repository");
1100
1009
  spinner.start();
1101
- const acl = await createAcl(endpoints.AclProvider, repository, authorization);
1102
- const components = libraries.reduce((acc, lib) => {
1103
- return [...acc, ...lib.components];
1104
- }, []);
1105
- const models = await addImageUrlsToModelVariations(acl, repository, components);
1106
- await sendManyModelsToPrismic(repository, authorization, endpoints.Models, remoteSlices, models);
1010
+ const acl = await client.createAcl().catch((error) => {
1011
+ writeError$1("Uploading screenshots for your slices failed, please contact us.");
1012
+ writeError$1(error.message, "Full error:");
1013
+ return null;
1014
+ });
1015
+ const models$1 = acl ? await updateSlicesWithScreenshots(client, acl, components) : components.map((component) => component.model);
1016
+ await Promise.all(models$1.map(async (model) => {
1017
+ const slice = models.Slices.fromSM(model);
1018
+ const promise = remoteSlicesIds.includes(slice.id) ? client.updateSlice(slice) : client.insertSlice(slice);
1019
+ return promise.catch((error) => {
1020
+ writeError$1(`Sending slice ${model.id} - ${error.message}`);
1021
+ throw error;
1022
+ });
1023
+ })).catch(() => {
1024
+ process.exit(1);
1025
+ });
1107
1026
  spinner.succeed();
1108
1027
  return Promise.resolve(true);
1109
1028
  }
1110
1029
 
1111
- function readCustomTypes(cwd) {
1030
+ function readLocalCustomTypes(cwd) {
1112
1031
  const customTypePaths = NodeUtils.CustomTypesPaths(cwd);
1113
1032
  const dir = customTypePaths.value();
1114
1033
  if (NodeUtils.Files.isDirectory(dir) === false)
@@ -1132,12 +1051,11 @@ function readCustomTypes(cwd) {
1132
1051
  }, []);
1133
1052
  return files;
1134
1053
  }
1135
- async function sendCustomTypesFromStarter(repository, authorization, base, cwd) {
1136
- const customTypeApiEndpoint = getEndpointsFromBase(base).Models;
1137
- const customTypes = readCustomTypes(cwd);
1138
- if (customTypes.length === 0)
1054
+ async function sendCustomTypes(client, cwd) {
1055
+ const localCustomTypes = readLocalCustomTypes(cwd);
1056
+ if (localCustomTypes.length === 0)
1139
1057
  return Promise.resolve(false);
1140
- const remoteCustomTypeIds = await getRemoteCustomTypeIds(customTypeApiEndpoint, repository, authorization);
1058
+ const remoteCustomTypeIds = await client.getCustomTypes().then((customTypes) => customTypes.map((customType) => customType.id));
1141
1059
  if (remoteCustomTypeIds.length) {
1142
1060
  const shouldPush = await promptToPushCustomTypes();
1143
1061
  if (shouldPush === false)
@@ -1145,7 +1063,15 @@ async function sendCustomTypesFromStarter(repository, authorization, base, cwd)
1145
1063
  }
1146
1064
  const spinner = spinner$1("Pushing existing custom types to your repository");
1147
1065
  spinner.start();
1148
- await sendManyCustomTypesToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customTypes);
1066
+ await Promise.all(localCustomTypes.map(async (customType) => {
1067
+ const promise = remoteCustomTypeIds.includes(customType.id) ? client.updateCustomType(customType) : client.insertCustomType(customType);
1068
+ return promise.catch((error) => {
1069
+ writeError$1(`Sending custom type ${customType.id} - ${error.message}`);
1070
+ throw error;
1071
+ });
1072
+ })).catch(() => {
1073
+ process.exit(1);
1074
+ });
1149
1075
  spinner.succeed();
1150
1076
  return Promise.resolve(true);
1151
1077
  }
@@ -1162,120 +1088,96 @@ async function readSignatureFile(cwd) {
1162
1088
  })(SignatureFileReader.decode(data));
1163
1089
  });
1164
1090
  }
1165
- async function lsdir(dir) {
1166
- return fs__default["default"].promises.readdir(dir).then((dirs) => {
1167
- return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isDirectory()).map((subdirectory) => path__default["default"].join(dir, subdirectory));
1168
- });
1169
- }
1170
- async function lsfiles(dir) {
1171
- return fs__default["default"].promises.readdir(dir).then((dirs) => {
1172
- return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isFile()).map((file) => path__default["default"].join(dir, file));
1173
- });
1174
- }
1175
1091
  async function readDocuments(cwd) {
1176
1092
  const documentDir = path__default["default"].join(cwd, "documents");
1177
1093
  const dirs = await lsdir(documentDir);
1178
1094
  const files = (await Promise.all(dirs.map((dir) => lsfiles(dir)))).flat();
1179
1095
  const documentObj = files.reduce((acc, file) => {
1180
- const fileContent = fs__default["default"].readFileSync(file, "utf-8");
1181
1096
  const filename = path__default["default"].parse(file).name;
1182
- acc[filename] = JSON.parse(fileContent);
1183
- return acc;
1097
+ const fileContent = fs__default["default"].readFileSync(file, "utf-8");
1098
+ const json = JSON.parse(fileContent);
1099
+ return { ...acc, [filename]: json };
1184
1100
  }, {});
1185
- return JSON.stringify(documentObj);
1101
+ return documentObj;
1186
1102
  }
1187
- const sendDocumentsFromStarter = async (repository, cookies, base, cwd) => {
1103
+ async function sendDocuments(client, cwd) {
1188
1104
  const pathToDocuments = path__default["default"].join(cwd, "documents");
1189
1105
  const pathToSignatureFile = path__default["default"].join(pathToDocuments, "index.json");
1190
- if (!fs__default["default"].existsSync(pathToSignatureFile)) {
1106
+ if (!fs__default["default"].existsSync(pathToSignatureFile))
1191
1107
  return Promise.resolve(false);
1192
- }
1193
1108
  const signatureObj = await readSignatureFile(cwd);
1194
- const documentsStr = await readDocuments(cwd);
1195
- const payload = {
1196
- signature: signatureObj.signature,
1197
- documents: documentsStr
1198
- };
1199
- const prismicUrl = new URL(base);
1200
- prismicUrl.hostname = `${repository}.${prismicUrl.hostname}`;
1201
- prismicUrl.pathname = "starter/documents";
1202
- const endpointURL = prismicUrl.toString();
1109
+ const documents = await readDocuments(cwd);
1110
+ if (Object.keys(documents).length === 0)
1111
+ return Promise.resolve(false);
1203
1112
  const spinner = spinner$1("Pushing existing documents to your repository");
1204
1113
  spinner.start();
1205
- return axios__default["default"].post(endpointURL, payload, {
1206
- headers: {
1207
- "User-Agent": "prismic-cli/0",
1208
- Cookie: cookies
1209
- }
1210
- }).then(() => {
1114
+ return client.pushDocuments(signatureObj.signature, documents, SharedConfig.PrismicSharedConfigManager.get().cookies).then(() => {
1211
1115
  spinner.succeed();
1212
1116
  fs__default["default"].rmSync(pathToDocuments, { recursive: true, force: true });
1213
1117
  return true;
1214
- }).catch((e) => {
1118
+ }).catch(async (e) => {
1215
1119
  var _a;
1216
1120
  spinner.fail();
1217
1121
  if (((_a = e.response) == null ? void 0 : _a.data) === "Repository should not contain documents") {
1218
1122
  writeError$1("The selected repository is not empty, documents cannot be uploaded. Please choose an empty repository or delete the documents contained in your repository.");
1219
1123
  } else {
1220
- handleErrors("sending documents, please try again. If the problem persists, contact us.", e);
1124
+ writeError$1("Sending documents failed, please try again. If the problem persists, contact us.");
1125
+ writeError$1(`Full error: ${e.code || 500} - ${e.message}`);
1221
1126
  }
1127
+ await Tracker.get().trackInitEndFail(core.Models.Frameworks.none, "Failed to push documents");
1222
1128
  process.exit(1);
1223
1129
  });
1224
- };
1130
+ }
1225
1131
 
1226
- async function sendStarterData(repository, base, cookies, sendDocs = true, cwd) {
1227
- const smJson = NodeUtils.retrieveManifest(cwd);
1228
- const pathToDocuments = path__default["default"].join(cwd, "documents");
1229
- const hasDocuments = NodeUtils.Files.exists(pathToDocuments);
1230
- if (smJson.exists === false || hasDocuments === false)
1132
+ async function sendStarterData(client, cwd, pushDocuments = true) {
1133
+ const manifest = NodeUtils.retrieveManifest(cwd);
1134
+ const documentsPath = path__default["default"].join(cwd, "documents");
1135
+ const hasDocuments = NodeUtils.Files.exists(documentsPath);
1136
+ if (manifest.exists === false || hasDocuments === false)
1231
1137
  return Promise.resolve(false);
1232
- const authTokenFromCookie = cookie.parsePrismicAuthToken(cookies);
1233
- if (smJson.content && smJson.content.libraries) {
1234
- await sendSlicesFromStarter(base, repository, authTokenFromCookie, smJson.content.libraries, cwd);
1235
- }
1236
- await sendCustomTypesFromStarter(repository, authTokenFromCookie, base, cwd);
1237
- if (sendDocs === false) {
1238
- fs__default["default"].rmSync(pathToDocuments, { recursive: true, force: true });
1138
+ if (manifest.content)
1139
+ await sendSlices(client, cwd, manifest.content);
1140
+ await sendCustomTypes(client, cwd);
1141
+ if (!pushDocuments) {
1142
+ fs__default["default"].rmSync(documentsPath, { recursive: true, force: true });
1239
1143
  return Promise.resolve(true);
1240
1144
  }
1241
- return sendDocumentsFromStarter(repository, cookies, base, cwd);
1145
+ return sendDocuments(client, cwd);
1242
1146
  }
1243
1147
 
1244
1148
  async function init() {
1245
1149
  const cwd = findArgument(process.argv, "cwd") || process.cwd();
1246
- const base = findArgument(process.argv, "base") || core.CONSTS.DEFAULT_BASE;
1150
+ const mode = getApplicationMode(findArgument(process.argv, "mode")) || client.ApplicationMode.PROD;
1247
1151
  const lib = findArgument(process.argv, "library");
1248
1152
  const branch = findArgument(process.argv, "branch");
1249
1153
  const isTrackingAvailable = findArgument(process.argv, "tracking") !== "false";
1250
- const maybeRepositorySubdomain = findArgument(process.argv, "repository");
1251
- const sendDocs = !findFlag(process.argv, "no-docs");
1154
+ const preSelectedRepository = findArgument(process.argv, "repository");
1155
+ const pushDocuments = !findFlag(process.argv, "no-docs");
1252
1156
  Tracker.get().initialize("JfTfmHaATChc4xueS7RcCBsixI71dJIJ" , isTrackingAvailable);
1253
- void Tracker.get().trackInitStart(maybeRepositorySubdomain);
1157
+ void Tracker.get().trackInitStart(preSelectedRepository);
1158
+ const client$1 = new InitClient(mode, null, Prismic__default["default"].PrismicSharedConfigManager.getAuth());
1254
1159
  console.log(purple("You're about to configure Slicemachine... Press ctrl + C to cancel"));
1255
1160
  validatePkg(cwd);
1256
- const user = await loginOrBypass(base);
1257
- if (!user)
1258
- throw new Error("The user should be logged in!");
1259
- if (user.profile) {
1260
- Tracker.get().identifyUser(user.profile.shortId, user.profile.intercomHash);
1261
- }
1161
+ const user = await loginOrBypass(client$1);
1162
+ Tracker.get().identifyUser(user.shortId, user.intercomHash);
1262
1163
  void Tracker.get().trackInitIdentify();
1263
- const config = Prismic__default["default"].PrismicSharedConfigManager.get();
1264
1164
  const frameworkResult = await detectFramework(cwd);
1265
- const repositoryDomainName = await chooseOrCreateARepository(cwd, frameworkResult.value, config.cookies, config.base, maybeRepositorySubdomain);
1266
- Tracker.get().setRepository(repositoryDomainName);
1165
+ const repository = await chooseOrCreateARepository(client$1, cwd, frameworkResult.value, preSelectedRepository);
1166
+ Tracker.get().setRepository(repository);
1167
+ client$1.updateRepository(repository);
1267
1168
  const sliceLibPath = lib ? await installLib(cwd, lib, branch) : void 0;
1268
- const wasStarter = await sendStarterData(repositoryDomainName, config.base, config.cookies, sendDocs, cwd);
1269
- await configureProject(cwd, base, repositoryDomainName, frameworkResult, sliceLibPath, isTrackingAvailable);
1169
+ const wasStarter = await sendStarterData(client$1, cwd, pushDocuments);
1170
+ await configureProject(client$1, cwd, repository, frameworkResult, sliceLibPath, isTrackingAvailable);
1270
1171
  await installRequiredDependencies(cwd, frameworkResult.value, wasStarter);
1271
- displayFinalMessage(cwd, wasStarter, repositoryDomainName, config.base);
1172
+ displayFinalMessage(cwd, wasStarter, repository, client$1.apisEndpoints.Wroom);
1272
1173
  }
1273
1174
  init().then(() => {
1274
1175
  process.exit(0);
1275
- }).catch((error) => {
1176
+ }).catch(async (error) => {
1276
1177
  if (error instanceof Error)
1277
1178
  writeError$1(error.message);
1278
1179
  else
1279
1180
  console.error(error);
1181
+ await Tracker.get().trackInitEndFail(core.Models.Frameworks.none, "Failed to initialise Slice Machine.");
1280
1182
  });
1281
1183
  //# sourceMappingURL=index.js.map