@slicemachine/init 1.1.4 → 1.1.5-alpha.11

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
@@ -3,14 +3,19 @@
3
3
  'use strict';
4
4
 
5
5
  const core = require('@slicemachine/core');
6
+ const Prismic = require('@slicemachine/core/build/prismic');
6
7
  const ServerAnalytics = require('analytics-node');
7
8
  const uuid = require('uuid');
8
9
  const path = require('path');
9
10
  const util = require('util');
10
11
  const child_process = require('child_process');
12
+ const chalk = require('chalk');
13
+ const ora = require('ora');
14
+ const hapi = require('@hapi/hapi');
15
+ const open = require('open');
16
+ const NodeUtils = require('@slicemachine/core/build/node-utils');
11
17
  const inquirer = require('inquirer');
12
18
  const Separator = require('inquirer/lib/objects/separator');
13
- const cookie = require('@slicemachine/core/build/src/utils/cookie');
14
19
  const axios = require('axios');
15
20
  const _function = require('fp-ts/function');
16
21
  const Either = require('fp-ts/Either');
@@ -18,9 +23,6 @@ const tmp = require('tmp');
18
23
  const AdmZip = require('adm-zip');
19
24
  const fsExtra = require('fs-extra');
20
25
  const fs = require('fs');
21
- const PackageJson = require('@slicemachine/core/build/src/utils/PackageJson');
22
- const Manifest = require('@slicemachine/core/build/src/models/Manifest');
23
- const Files = require('@slicemachine/core/build/src/utils/files');
24
26
 
25
27
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
26
28
 
@@ -42,9 +44,16 @@ function _interopNamespace(e) {
42
44
  return Object.freeze(n);
43
45
  }
44
46
 
47
+ const Prismic__namespace = /*#__PURE__*/_interopNamespace(Prismic);
48
+ const Prismic__default = /*#__PURE__*/_interopDefaultLegacy(Prismic);
45
49
  const ServerAnalytics__default = /*#__PURE__*/_interopDefaultLegacy(ServerAnalytics);
46
50
  const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
47
51
  const util__default = /*#__PURE__*/_interopDefaultLegacy(util);
52
+ const chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
53
+ const ora__default = /*#__PURE__*/_interopDefaultLegacy(ora);
54
+ const hapi__namespace = /*#__PURE__*/_interopNamespace(hapi);
55
+ const open__default = /*#__PURE__*/_interopDefaultLegacy(open);
56
+ const NodeUtils__namespace = /*#__PURE__*/_interopNamespace(NodeUtils);
48
57
  const inquirer__namespace = /*#__PURE__*/_interopNamespace(inquirer);
49
58
  const Separator__default = /*#__PURE__*/_interopDefaultLegacy(Separator);
50
59
  const axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
@@ -52,7 +61,6 @@ const tmp__default = /*#__PURE__*/_interopDefaultLegacy(tmp);
52
61
  const AdmZip__default = /*#__PURE__*/_interopDefaultLegacy(AdmZip);
53
62
  const fsExtra__default = /*#__PURE__*/_interopDefaultLegacy(fsExtra);
54
63
  const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
55
- const Files__default = /*#__PURE__*/_interopDefaultLegacy(Files);
56
64
 
57
65
  var __accessCheck = (obj, member, msg) => {
58
66
  if (!member.has(obj))
@@ -129,8 +137,11 @@ class InitTracker {
129
137
  trackDownloadLibrary(library) {
130
138
  this._trackEvent("SliceMachine Download Library" /* DownloadLibrary */, { library });
131
139
  }
132
- trackInitStart() {
133
- this._trackEvent("SliceMachine Init Start" /* InitStart */);
140
+ trackInitIdentify(repoDomain) {
141
+ this._trackEvent("SliceMachine Init Identify" /* InitIdentify */, { repo: repoDomain });
142
+ }
143
+ trackInitStart(repoDomain) {
144
+ this._trackEvent("SliceMachine Init Start" /* InitStart */, { repo: repoDomain });
134
145
  }
135
146
  trackInitDone(framework, repoDomain) {
136
147
  this._trackEvent("SliceMachine Init Done" /* InitDone */, { framework, repo: repoDomain });
@@ -152,6 +163,193 @@ const Tracker = (() => {
152
163
  };
153
164
  })();
154
165
 
166
+ const purple = chalk__default["default"].hex("8c76fc");
167
+ const error = chalk__default["default"].hex("FF6868");
168
+ const warning = chalk__default["default"].hex("F3AD38");
169
+ const underline$1 = chalk__default["default"].underline;
170
+ const bold$1 = chalk__default["default"].bold;
171
+ const dim = chalk__default["default"].dim;
172
+ const cyan = chalk__default["default"].cyan;
173
+ const yellow = chalk__default["default"].yellow;
174
+ const white = chalk__default["default"].white;
175
+ const spinner$1 = ora__default["default"];
176
+ const writeError$1 = (msg, prefix = "Error!") => console.error(`${error(prefix)} ${msg}`);
177
+ const writeWarning = (msg, prefix = "Warning!") => console.warn(`${warning(prefix)} ${msg}`);
178
+ const writeCheck = (msg) => {
179
+ ora__default["default"]().succeed(msg);
180
+ };
181
+ const writeInfo = (msg) => {
182
+ console.log(`${yellow("\u2139")} ${dim(msg)}`);
183
+ };
184
+
185
+ const logs = /*#__PURE__*/Object.freeze({
186
+ __proto__: null,
187
+ purple: purple,
188
+ error: error,
189
+ warning: warning,
190
+ underline: underline$1,
191
+ bold: bold$1,
192
+ dim: dim,
193
+ cyan: cyan,
194
+ yellow: yellow,
195
+ white: white,
196
+ spinner: spinner$1,
197
+ writeError: writeError$1,
198
+ writeWarning: writeWarning,
199
+ writeCheck: writeCheck,
200
+ writeInfo: writeInfo
201
+ });
202
+
203
+ const { Cookie } = core.Utils;
204
+ const { DEFAULT_BASE: DEFAULT_BASE$1, DEFAULT_SERVER_PORT } = core.CONSTS;
205
+ const { bold, underline, spinner, writeError } = logs;
206
+ const isHandlerData = (data) => {
207
+ if (typeof data != "object")
208
+ return false;
209
+ const { email, cookies } = data;
210
+ return Boolean(email && cookies) && Array.isArray(cookies) && !cookies.some((c) => typeof c !== "string");
211
+ };
212
+ const Routes = {
213
+ authentication: (server) => (onSuccess, onFail) => ({
214
+ method: "POST",
215
+ path: "/",
216
+ handler: authenticationHandler(server)(onSuccess, onFail)
217
+ }),
218
+ notFound: {
219
+ method: ["GET", "POST"],
220
+ path: "/{any*}",
221
+ handler: (request, h) => {
222
+ return h.response(`not found: [${request.method}]: ${request.url.toString()}`).code(404);
223
+ }
224
+ }
225
+ };
226
+ function validatePayload(payload) {
227
+ if (Buffer.isBuffer(payload))
228
+ return null;
229
+ return isHandlerData(payload) ? payload : null;
230
+ }
231
+ const authenticationHandler = (server) => (onSuccess, onFail) => {
232
+ return (request, h) => {
233
+ try {
234
+ const data = validatePayload(request.payload);
235
+ if (!data) {
236
+ onFail();
237
+ h.response("Error with cookies").code(400);
238
+ throw new Error("It seems the server didn't respond properly, please contact us.");
239
+ }
240
+ onSuccess(data);
241
+ return h.response(data).code(200);
242
+ } finally {
243
+ void server.stop({ timeout: 1e4 });
244
+ }
245
+ };
246
+ };
247
+ function buildServer(base, port, host) {
248
+ const server = hapi__namespace.server({
249
+ port,
250
+ host,
251
+ routes: {
252
+ cors: {
253
+ origin: [base],
254
+ headers: ["Origin", "X-Requested-With", "Content-Type", "Accept"]
255
+ }
256
+ }
257
+ });
258
+ return server;
259
+ }
260
+ function askSingleChar(title) {
261
+ return new Promise((resolve) => {
262
+ process.stdout.write(title);
263
+ const rawMode = process.stdin.isRaw;
264
+ if (process.stdin.setRawMode)
265
+ process.stdin.setRawMode(true);
266
+ function handler(key) {
267
+ const response = key.toString("utf-8");
268
+ if (process.stdin.setRawMode)
269
+ process.stdin.setRawMode(Boolean(rawMode));
270
+ process.stdin.removeListener("data", handler);
271
+ resolve(response);
272
+ }
273
+ process.stdin.on("data", handler);
274
+ });
275
+ }
276
+ async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE$1, port = DEFAULT_SERVER_PORT) {
277
+ const confirmation = await askSingleChar(`>> Press any key to open the browser to ${action} or q to exit:`);
278
+ if (confirmation === "q" || confirmation === "")
279
+ return process.exit(-1);
280
+ const s = spinner("Waiting for the browser response");
281
+ const onLoginFail = () => {
282
+ s.stop();
283
+ writeError(`We failed to log you into your Prismic account`);
284
+ console.log(`Run ${bold("npx slicemachine init")} again!`);
285
+ process.exit(-1);
286
+ };
287
+ function onSuccess(data) {
288
+ s.succeed(`Logged in as ${bold(data.email)}`).stop();
289
+ Prismic.PrismicSharedConfigManager.setProperties({
290
+ cookies: Cookie.serializeCookies(data.cookies),
291
+ base
292
+ });
293
+ }
294
+ function onFail() {
295
+ onLoginFail();
296
+ }
297
+ const server = buildServer(base, port, "localhost");
298
+ server.route([
299
+ Routes.authentication(server)(onSuccess, onFail),
300
+ Routes.notFound
301
+ ]);
302
+ return server.start().then(() => {
303
+ console.log("\nOpening browser to " + underline(url));
304
+ s.start();
305
+ void open__default["default"](url);
306
+ return {
307
+ onLoginFail
308
+ };
309
+ });
310
+ }
311
+
312
+ async function startAuth({
313
+ base,
314
+ url,
315
+ action
316
+ }) {
317
+ const { onLoginFail } = await startServerAndOpenBrowser(url, action, base);
318
+ try {
319
+ await core.Utils.Poll.startPolling(() => Auth.validateSession(base), (user) => !!user, 3e3, 60);
320
+ return;
321
+ } catch (e) {
322
+ onLoginFail();
323
+ }
324
+ }
325
+ const Auth = {
326
+ login: async (base) => {
327
+ const endpoints = Prismic.Endpoints.buildEndpoints(base);
328
+ return startAuth({
329
+ base,
330
+ url: endpoints.Dashboard.cliLogin,
331
+ action: "login"
332
+ });
333
+ },
334
+ signup: async (base) => {
335
+ const endpoints = Prismic.Endpoints.buildEndpoints(base);
336
+ return startAuth({
337
+ base,
338
+ url: endpoints.Dashboard.cliSignup,
339
+ action: "signup"
340
+ });
341
+ },
342
+ logout: () => Prismic.PrismicSharedConfigManager.remove(),
343
+ validateSession: async (requiredBase) => {
344
+ const config = Prismic.PrismicSharedConfigManager.get();
345
+ if (!config.cookies.length)
346
+ return Promise.resolve(null);
347
+ if (requiredBase != config.base)
348
+ return Promise.resolve(null);
349
+ return Prismic.Communication.validateSession(config.cookies, requiredBase).catch(() => null);
350
+ }
351
+ };
352
+
155
353
  function findArgument(args, name) {
156
354
  const flagIndex = args.indexOf(`--${name}`);
157
355
  if (flagIndex === -1)
@@ -175,7 +373,7 @@ const {
175
373
  SLICE_SIMULATOR_REACT,
176
374
  SLICE_SIMULATOR_VUE,
177
375
  PRISMIC_HELPERS
178
- } = core.Utils.CONSTS;
376
+ } = core.CONSTS;
179
377
  function depsForFramework(framework) {
180
378
  switch (framework) {
181
379
  case core.Models.Frameworks.react:
@@ -193,41 +391,41 @@ function depsForFramework(framework) {
193
391
  }
194
392
  }
195
393
  async function installRequiredDependencies(cwd, framework) {
196
- const yarnLock = core.Utils.Files.exists(core.FileSystem.YarnLockPath(cwd));
394
+ const yarnLock = NodeUtils__namespace.Files.exists(NodeUtils__namespace.YarnLockPath(cwd));
197
395
  const installDevDependencyCommand = yarnLock ? "yarn add -D" : "npm install --save-dev";
198
396
  const installDependencyCommand = yarnLock ? "yarn add" : "npm install --save";
199
- const spinner = core.Utils.spinner("Downloading Slice Machine");
397
+ const spinner = spinner$1("Downloading Slice Machine");
200
398
  spinner.start();
201
399
  const { stderr } = await execCommand(`${installDevDependencyCommand} ${SM_PACKAGE_NAME}`);
202
400
  const deps = depsForFramework(framework);
203
401
  if (deps)
204
402
  await execCommand(`${installDependencyCommand} ${deps}`);
205
- const pathToPkg = path__default["default"].join(core.FileSystem.PackagePaths(cwd).value(), SM_PACKAGE_NAME);
206
- const isPackageInstalled = core.Utils.Files.exists(pathToPkg);
403
+ const pathToPkg = path__default["default"].join(NodeUtils__namespace.PackagePaths(cwd).value(), SM_PACKAGE_NAME);
404
+ const isPackageInstalled = NodeUtils__namespace.Files.exists(pathToPkg);
207
405
  if (isPackageInstalled || !stderr.length) {
208
406
  spinner.succeed("Slice Machine was installed successfully");
209
407
  return;
210
408
  }
211
409
  spinner.fail();
212
- core.Utils.writeWarning(`could not install ${SM_PACKAGE_NAME}. Please do it manually!`);
410
+ writeWarning(`could not install ${SM_PACKAGE_NAME}. Please do it manually!`);
213
411
  }
214
412
 
215
413
  function validatePkg(cwd) {
216
- const jsonPackage = core.FileSystem.retrieveJsonPackage(cwd);
414
+ const jsonPackage = NodeUtils__namespace.retrieveJsonPackage(cwd);
217
415
  if (!jsonPackage.exists) {
218
- core.Utils.writeError(`package.json not found. Are you in the right folder?`);
416
+ writeError$1(`package.json not found. Are you in the right folder?`);
219
417
  return process.exit(-1);
220
418
  }
221
419
  if (!jsonPackage.content) {
222
- core.Utils.writeError(`could not parse package.json.`);
420
+ writeError$1(`could not parse package.json.`);
223
421
  return process.exit(-1);
224
422
  }
225
423
  }
226
424
 
227
425
  function createRepository(domain, framework, cookies, base) {
228
- const spinner = core.Utils.spinner("Creating Prismic Repository");
426
+ const spinner = spinner$1("Creating Prismic Repository");
229
427
  spinner.start();
230
- return core.Communication.createRepository(domain, cookies, framework, base).then((res) => {
428
+ return Prismic__namespace.Communication.createRepository(domain, cookies, framework, base).then((res) => {
231
429
  const addressUrl = new URL(base);
232
430
  const repoDomainName = res.data.domain || domain;
233
431
  addressUrl.hostname = `${repoDomainName}.${addressUrl.hostname}`;
@@ -237,23 +435,23 @@ function createRepository(domain, framework, cookies, base) {
237
435
  }).catch((error) => {
238
436
  spinner.fail(`Error creating repository ${domain}`);
239
437
  if (error.message) {
240
- core.Utils.writeError(error.message);
438
+ writeError$1(error.message);
241
439
  }
242
- core.Utils.writeError(`We failed to create you new prismic repository`);
243
- console.log(`Run ${core.Utils.bold("npx @slicemachine/init")} again!`);
440
+ writeError$1(`We failed to create you new prismic repository`);
441
+ console.log(`Run ${bold$1("npx @slicemachine/init")} again!`);
244
442
  process.exit(-1);
245
443
  });
246
444
  }
247
445
 
248
446
  const CREATE_REPO = "$_CREATE_REPO";
249
- const DEFAULT_BASE = core.Utils.CONSTS.DEFAULT_BASE;
447
+ const DEFAULT_BASE = core.CONSTS.DEFAULT_BASE;
250
448
  function prettyRepoName(address, value) {
251
- const repoName = value ? core.Utils.cyan(value) : core.Utils.dim.cyan("repo-name");
252
- return `${core.Utils.cyan.dim(`${address.protocol}//`)}${repoName}${core.Utils.cyan.dim(`.${address.hostname}`)}`;
449
+ const repoName = value ? cyan(value) : dim.cyan("repo-name");
450
+ return `${cyan.dim(`${address.protocol}//`)}${repoName}${cyan.dim(`.${address.hostname}`)}`;
253
451
  }
254
452
  async function promptForRepoDomain(base, defaultValue) {
255
453
  const address = new URL(base);
256
- core.Utils.writeInfo("The name acts as a domain/endpoint for your content repo and should be completely unique.");
454
+ writeInfo("The name acts as a domain/endpoint for your content repo and should be completely unique.");
257
455
  return inquirer__namespace.prompt([
258
456
  {
259
457
  name: "repoDomain",
@@ -261,9 +459,9 @@ async function promptForRepoDomain(base, defaultValue) {
261
459
  type: "input",
262
460
  required: true,
263
461
  default: defaultValue,
264
- transformer: (value) => prettyRepoName(address, String(value || defaultValue)),
462
+ transformer: (value) => prettyRepoName(address, value || defaultValue),
265
463
  async validate(name) {
266
- const result = await core.Communication.validateRepositoryName(name, base, false);
464
+ const result = await Prismic__namespace.Communication.validateRepositoryName(name, base, false);
267
465
  return result === name || result;
268
466
  }
269
467
  }
@@ -275,13 +473,13 @@ function makeReposPretty(base) {
275
473
  address.hostname = `${domain}.${address.hostname}`;
276
474
  if (core.Models.canUpdateCustomTypes(role) === false) {
277
475
  return {
278
- name: `${core.Utils.purple.dim("Use")} ${core.Utils.bold.dim(name)} ${core.Utils.purple.dim(`"${address.hostname}"`)}`,
476
+ name: `${purple.dim("Use")} ${bold$1.dim(name)} ${purple.dim(`"${address.hostname}"`)}`,
279
477
  value: domain,
280
478
  disabled: "Unauthorized"
281
479
  };
282
480
  }
283
481
  return {
284
- name: `${core.Utils.purple("Use")} ${core.Utils.bold(name)} ${core.Utils.purple(`"${address.hostname}"`)}`,
482
+ name: `${purple("Use")} ${bold$1(name)} ${purple(`"${address.hostname}"`)}`,
285
483
  value: domain
286
484
  };
287
485
  };
@@ -311,17 +509,17 @@ function maybeStickTheRepoToTheTopOfTheList(repoName) {
311
509
  }
312
510
  function sortReposForPrompt(repos, base, cwd) {
313
511
  const createNew = {
314
- name: `${core.Utils.purple("Create a")} ${core.Utils.bold("new")} ${core.Utils.purple("Repository")}`,
512
+ name: `${purple("Create a")} ${bold$1("new")} ${purple("Repository")}`,
315
513
  value: CREATE_REPO
316
514
  };
317
- const maybeConfiguredRepoName = core.FileSystem.maybeRepoNameFromSMFile(cwd, base);
515
+ const maybeConfiguredRepoName = NodeUtils__namespace.maybeRepoNameFromSMFile(cwd, base);
318
516
  return repos.reverse().map(makeReposPretty(base)).reduce(maybeStickTheRepoToTheTopOfTheList(maybeConfiguredRepoName), [
319
517
  createNew
320
518
  ]).sort(orderPrompts(maybeConfiguredRepoName));
321
519
  }
322
520
  async function chooseOrCreateARepository(cwd, framework, cookies, base = DEFAULT_BASE, domain) {
323
- const token = cookie.parsePrismicAuthToken(cookies);
324
- const repos = await core.Communication.listRepositories(token, base);
521
+ const token = core.Utils.Cookie.parsePrismicAuthToken(cookies);
522
+ const repos = await Prismic__namespace.Communication.listRepositories(token, base);
325
523
  const hasRepo = domain && repos.find((d) => d.domain === domain);
326
524
  if (hasRepo)
327
525
  return domain;
@@ -356,7 +554,7 @@ async function chooseOrCreateARepository(cwd, framework, cookies, base = DEFAULT
356
554
  async function promptForFramework() {
357
555
  const choices = core.Models.SupportedFrameworks.map((framework) => {
358
556
  return {
359
- name: core.Utils.Framework.fancyName(framework),
557
+ name: NodeUtils__namespace.Framework.fancyName(framework),
360
558
  value: framework
361
559
  };
362
560
  });
@@ -376,26 +574,26 @@ async function promptForFramework() {
376
574
  });
377
575
  }
378
576
  async function detectFramework(cwd) {
379
- const failMessage = `Please run ${core.Utils.bold("npx @slicemachine/init")} in a Nuxt or Next.js project`;
380
- const spinner = core.Utils.spinner("Detecting framework to install correct dependencies");
577
+ const failMessage = `Please run ${bold$1("npx @slicemachine/init")} in a Nuxt or Next.js project`;
578
+ const spinner = spinner$1("Detecting framework to install correct dependencies");
381
579
  spinner.start();
382
580
  try {
383
- const maybeFramework = core.Utils.Framework.defineFramework({
581
+ const maybeFramework = NodeUtils__namespace.Framework.defineFramework({
384
582
  cwd,
385
583
  supportedFrameworks: Object.values(core.Models.Frameworks)
386
584
  });
387
585
  spinner.stop();
388
586
  if (!maybeFramework || maybeFramework === core.Models.Frameworks.vanillajs) {
389
- core.Utils.writeError("Framework not detected");
587
+ writeError$1("Framework not detected");
390
588
  return await promptForFramework();
391
589
  }
392
- const nameToPrint = core.Utils.Framework.fancyName(maybeFramework);
393
- if (!core.Utils.Framework.isFrameworkSupported(maybeFramework)) {
394
- core.Utils.writeError(`${nameToPrint} is currently not supported`);
590
+ const nameToPrint = NodeUtils__namespace.Framework.fancyName(maybeFramework);
591
+ if (!NodeUtils__namespace.Framework.isFrameworkSupported(maybeFramework)) {
592
+ writeError$1(`${nameToPrint} is currently not supported`);
395
593
  console.log(failMessage);
396
594
  process.exit(1);
397
595
  }
398
- core.Utils.writeCheck(`${nameToPrint} detected`);
596
+ writeCheck(`${nameToPrint} detected`);
399
597
  return {
400
598
  value: maybeFramework,
401
599
  manuallyAdded: false
@@ -403,7 +601,7 @@ async function detectFramework(cwd) {
403
601
  } catch (error) {
404
602
  spinner.fail("package.json not found");
405
603
  if (error instanceof Error && error.message) {
406
- core.Utils.writeError(error.message);
604
+ writeError$1(error.message);
407
605
  } else {
408
606
  console.log(failMessage);
409
607
  }
@@ -411,8 +609,8 @@ async function detectFramework(cwd) {
411
609
  }
412
610
  }
413
611
 
414
- async function getUserProfile(cookies, base = core.Utils.CONSTS.DEFAULT_BASE) {
415
- const userServiceBase = core.Utils.CONSTS.DEFAULT_BASE === base ? core.Utils.CONSTS.USER_SERVICE_BASE : core.Utils.CONSTS.USER_SERVICE_STAGING_BASE;
612
+ async function getUserProfile(cookies, base = core.CONSTS.DEFAULT_BASE) {
613
+ const userServiceBase = core.CONSTS.DEFAULT_BASE === base ? core.CONSTS.USER_SERVICE_BASE : core.CONSTS.USER_SERVICE_STAGING_BASE;
416
614
  const url = new URL(userServiceBase);
417
615
  url.pathname = "profile";
418
616
  const endpoint = url.toString();
@@ -425,17 +623,17 @@ async function getUserProfile(cookies, base = core.Utils.CONSTS.DEFAULT_BASE) {
425
623
  throw new Error("Can't parse user profile");
426
624
  }, (data) => data)));
427
625
  }
428
- async function validateSessionAndGetProfile(base = core.Utils.CONSTS.DEFAULT_BASE) {
429
- const config = core.FileSystem.PrismicSharedConfigManager.get();
626
+ async function validateSessionAndGetProfile(base = core.CONSTS.DEFAULT_BASE) {
627
+ const config = Prismic__namespace.PrismicSharedConfigManager.get();
430
628
  if (!config.cookies.length)
431
629
  return Promise.resolve(null);
432
630
  if (base != config.base)
433
631
  return Promise.resolve(null);
434
632
  try {
435
- const info = await core.Communication.validateSession(config.cookies, base);
633
+ const info = await Prismic__namespace.Communication.validateSession(config.cookies, base);
436
634
  const profile = await getUserProfile(config.cookies, base).catch(() => null);
437
635
  if (profile == null ? void 0 : profile.shortId) {
438
- core.FileSystem.PrismicSharedConfigManager.setProperties({
636
+ Prismic__namespace.PrismicSharedConfigManager.setProperties({
439
637
  shortId: profile.shortId
440
638
  });
441
639
  }
@@ -449,10 +647,10 @@ async function loginOrBypass(base) {
449
647
  const user = await validateSessionAndGetProfile(base).catch((err) => console.log(err));
450
648
  if (user) {
451
649
  const email = user.info.email;
452
- core.Utils.writeCheck(`Logged in as ${core.Utils.bold(email)}`);
650
+ writeCheck(`Logged in as ${bold$1(email)}`);
453
651
  return user;
454
652
  } else {
455
- await core.Auth.login(base);
653
+ await Auth.login(base);
456
654
  const user2 = await validateSessionAndGetProfile(base);
457
655
  return user2;
458
656
  }
@@ -460,28 +658,29 @@ async function loginOrBypass(base) {
460
658
 
461
659
  const defaultSliceMachineVersion = "0.0.41";
462
660
  function configureProject(cwd, base, repositoryDomainName, framework, sliceLibPath = [], tracking = true) {
463
- const spinner = core.Utils.spinner(`Configuring your ${framework.value} & Prismic project...`);
661
+ const spinner = spinner$1(`Configuring your ${framework.value} & Prismic project...`);
464
662
  spinner.start();
465
663
  try {
466
- const manifest = core.FileSystem.retrieveManifest(cwd);
467
- const packageJson = core.FileSystem.retrieveJsonPackage(cwd);
664
+ const manifest = NodeUtils__namespace.retrieveManifest(cwd);
665
+ const packageJson = NodeUtils__namespace.retrieveJsonPackage(cwd);
468
666
  const sliceMachineVersionInstalled = getTheSliceMachineVersionInstalled(packageJson);
469
667
  const manifestAlreadyExistWithContent = manifest.exists && manifest.content;
470
668
  const manifestUpdated = {
471
669
  ...manifestAlreadyExistWithContent ? manifest.content : { _latest: sliceMachineVersionInstalled },
472
- apiEndpoint: core.Utils.Endpoints.buildRepositoryEndpoint(base, repositoryDomainName),
670
+ apiEndpoint: Prismic__namespace.Endpoints.buildRepositoryEndpoint(base, repositoryDomainName),
473
671
  libraries: ["@/slices", ...sliceLibPath],
474
672
  ...framework.manuallyAdded ? { framework: framework.value } : {},
475
673
  ...!tracking ? { tracking } : {}
476
674
  };
477
675
  if (!manifest.exists)
478
- core.FileSystem.createManifest(cwd, manifestUpdated);
676
+ NodeUtils__namespace.createManifest(cwd, manifestUpdated);
479
677
  else
480
- core.FileSystem.patchManifest(cwd, manifestUpdated);
481
- const pathToSlicesFolder = core.FileSystem.CustomPaths(cwd).library("slices").value();
482
- if (!core.Utils.Files.exists(pathToSlicesFolder))
483
- core.Utils.Files.mkdir(pathToSlicesFolder, { recursive: true });
484
- core.FileSystem.addJsonPackageSmScript(cwd);
678
+ NodeUtils__namespace.patchManifest(cwd, manifestUpdated);
679
+ const pathToSlicesFolder = NodeUtils__namespace.CustomPaths(cwd).library("slices").value();
680
+ if (!NodeUtils__namespace.Files.exists(pathToSlicesFolder)) {
681
+ NodeUtils__namespace.Files.mkdir(pathToSlicesFolder, { recursive: true });
682
+ }
683
+ NodeUtils__namespace.addJsonPackageSmScript(cwd);
485
684
  spinner.succeed("Project configured! Ready to start");
486
685
  } catch (e) {
487
686
  spinner.fail("Failed to configure Slice Machine");
@@ -491,7 +690,7 @@ function configureProject(cwd, base, repositoryDomainName, framework, sliceLibPa
491
690
  const getTheSliceMachineVersionInstalled = (packageJson) => {
492
691
  var _a;
493
692
  const sliceMachinePackageInstalled = Object.entries(((_a = packageJson.content) == null ? void 0 : _a.devDependencies) || {}).find((devDependency) => {
494
- if (devDependency[0] === core.Utils.CONSTS.SM_PACKAGE_NAME) {
693
+ if (devDependency[0] === core.CONSTS.SM_PACKAGE_NAME) {
495
694
  return devDependency;
496
695
  }
497
696
  });
@@ -513,9 +712,9 @@ const extractVersionNumberFromSemver = (semver) => {
513
712
  };
514
713
 
515
714
  function displayFinalMessage(cwd) {
516
- const yarnLock = core.Utils.Files.exists(core.FileSystem.YarnLockPath(cwd));
517
- const command = `${yarnLock ? "yarn" : "npm"} run ${core.Utils.CONSTS.SCRIPT_NAME}`;
518
- console.log(`${core.Utils.white("\u25A0")} Run ${core.Utils.purple(command)} to now launch Slice Machine`);
715
+ const yarnLock = NodeUtils__namespace.Files.exists(NodeUtils__namespace.YarnLockPath(cwd));
716
+ const command = `${yarnLock ? "yarn" : "npm"} run ${core.CONSTS.SCRIPT_NAME}`;
717
+ console.log(`${white("\u25A0")} Run ${purple(command)} to now launch Slice Machine`);
519
718
  }
520
719
 
521
720
  const Dependencies = {
@@ -537,7 +736,7 @@ function formatDeps(dependencies) {
537
736
  }
538
737
  const PackageManager = {
539
738
  get(cwd) {
540
- if (core.Utils.Files.exists(core.FileSystem.YarnLockPath(cwd))) {
739
+ if (NodeUtils__namespace.Files.exists(NodeUtils__namespace.YarnLockPath(cwd))) {
541
740
  return Yarn;
542
741
  }
543
742
  return Npm;
@@ -560,6 +759,7 @@ const Npm = {
560
759
  }
561
760
  };
562
761
 
762
+ const { PackageJsonHelper } = NodeUtils__namespace;
563
763
  const downloadFile = async (reqUrl) => {
564
764
  const res = await axios__default["default"].get(reqUrl, { responseType: "arraybuffer" });
565
765
  return new Promise((resolve, reject) => {
@@ -577,7 +777,7 @@ function toGithubSource(githubPath, branch) {
577
777
  return `https://codeload.github.com/${githubPath}/zip/${branch}`;
578
778
  }
579
779
  async function installLib(cwd, libGithubPath, branch = "HEAD") {
580
- const spinner = core.Utils.spinner(`Installing the ${libGithubPath} lib in your project...`);
780
+ const spinner = spinner$1(`Installing the ${libGithubPath} lib in your project...`);
581
781
  try {
582
782
  spinner.start();
583
783
  const [githubUserName, githubProjectName] = libGithubPath.split("/");
@@ -593,21 +793,21 @@ async function installLib(cwd, libGithubPath, branch = "HEAD") {
593
793
  }
594
794
  fsExtra__default["default"].moveSync(path__default["default"].join(projectPath, "src"), libDestinationFolder);
595
795
  const pkgManager = PackageManager.get(cwd);
596
- const pkgJson = PackageJson.PackageJsonHelper.fromPath(path__default["default"].join(projectPath, "package.json"));
796
+ const pkgJson = PackageJsonHelper.fromPath(path__default["default"].join(projectPath, "package.json"));
597
797
  if (pkgJson instanceof Error)
598
798
  throw pkgJson;
599
799
  const dependencies = Dependencies.fromPkgFormat(pkgJson.dependencies);
600
800
  if (dependencies)
601
801
  await pkgManager.install(dependencies);
602
- Files__default["default"].write(path__default["default"].join(libDestinationFolder, "meta.json"), {
802
+ NodeUtils__namespace.Files.write(path__default["default"].join(libDestinationFolder, "meta.json"), {
603
803
  name: pkgJson.name
604
804
  });
605
- const manifest = Files__default["default"].readEntity(path__default["default"].join(projectPath, "sm.json"), (payload) => {
606
- return Either.getOrElseW(() => new Error(`Unable to parse sm.json from lib ${libGithubPath}`))(Manifest.Manifest.decode(payload));
805
+ const manifest = NodeUtils__namespace.Files.readEntity(path__default["default"].join(projectPath, "sm.json"), (payload) => {
806
+ return Either.getOrElseW(() => new Error(`Unable to parse sm.json from lib ${libGithubPath}`))(core.Models.Manifest.decode(payload));
607
807
  });
608
808
  if (manifest instanceof Error)
609
809
  throw manifest;
610
- const localLibs = Manifest.ManifestHelper.localLibraries(manifest).map(({ path: path2 }) => {
810
+ const localLibs = core.Models.ManifestHelper.localLibraries(manifest).map(({ path: path2 }) => {
611
811
  return `~/${name}/${path2.replace("src/", "")}`;
612
812
  });
613
813
  spinner.succeed(`Slice library "${libGithubPath}" was installed successfully`);
@@ -624,14 +824,14 @@ async function installLib(cwd, libGithubPath, branch = "HEAD") {
624
824
 
625
825
  async function init() {
626
826
  const cwd = findArgument(process.argv, "cwd") || process.cwd();
627
- const base = findArgument(process.argv, "base") || core.Utils.CONSTS.DEFAULT_BASE;
827
+ const base = findArgument(process.argv, "base") || core.CONSTS.DEFAULT_BASE;
628
828
  const lib = findArgument(process.argv, "library");
629
829
  const branch = findArgument(process.argv, "branch");
630
830
  const isTrackingAvailable = findArgument(process.argv, "tracking") !== "false";
631
831
  const maybeRepositorySubdomain = findArgument(process.argv, "repository");
632
- Tracker.get().initialize("ED3O1FVsa8DteNyRmAuDyMcPoftJ6VdP" , isTrackingAvailable);
633
- Tracker.get().trackInitStart();
634
- console.log(core.Utils.purple("You're about to configure Slicemachine... Press ctrl + C to cancel"));
832
+ Tracker.get().initialize("JfTfmHaATChc4xueS7RcCBsixI71dJIJ" , isTrackingAvailable);
833
+ Tracker.get().trackInitStart(maybeRepositorySubdomain);
834
+ console.log(purple("You're about to configure Slicemachine... Press ctrl + C to cancel"));
635
835
  validatePkg(cwd);
636
836
  const user = await loginOrBypass(base);
637
837
  if (!user)
@@ -639,7 +839,8 @@ async function init() {
639
839
  if (user.profile) {
640
840
  Tracker.get().identifyUser(user.profile.shortId);
641
841
  }
642
- const config = core.FileSystem.PrismicSharedConfigManager.get();
842
+ Tracker.get().trackInitIdentify(maybeRepositorySubdomain);
843
+ const config = Prismic__default["default"].PrismicSharedConfigManager.get();
643
844
  const frameworkResult = await detectFramework(cwd);
644
845
  const repositoryDomainName = await chooseOrCreateARepository(cwd, frameworkResult.value, config.cookies, config.base, maybeRepositorySubdomain);
645
846
  await installRequiredDependencies(cwd, frameworkResult.value);
@@ -652,7 +853,7 @@ try {
652
853
  void init();
653
854
  } catch (error) {
654
855
  if (error instanceof Error)
655
- core.Utils.writeError(error.message);
856
+ writeError$1(error.message);
656
857
  else
657
858
  console.error(error);
658
859
  }