@slicemachine/init 1.1.5-alpha.5 → 1.1.5-alpha.8

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