@slicemachine/init 1.1.10-alpha.3 → 1.1.10
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/.caches/eslint +1 -0
- package/build/index.js +284 -392
- package/build/index.js.map +1 -1
- package/package.json +4 -11
- package/src/index.ts +36 -32
- package/src/steps/choose-or-create-a-repository.ts +43 -42
- package/src/steps/configure-project.ts +3 -5
- package/src/steps/display-final-message.ts +23 -5
- package/src/steps/loginOrBypass.ts +18 -14
- package/src/steps/sendStarterData.ts +18 -30
- package/src/steps/starters/custom-types.ts +29 -30
- package/src/steps/starters/documents.ts +30 -55
- package/src/steps/starters/prompts.ts +1 -1
- package/src/steps/starters/s3.ts +51 -182
- package/src/steps/starters/slices.ts +55 -42
- package/src/utils/auth/helpers.ts +5 -1
- package/src/utils/auth/index.ts +30 -30
- package/src/utils/client.ts +67 -0
- package/src/utils/create-repo.ts +9 -15
- package/src/utils/fs.ts +18 -0
- package/src/utils/index.ts +16 -0
- package/src/utils/validateRepositoryName.ts +44 -0
- package/src/steps/starters/communication.ts +0 -171
- package/src/steps/starters/endpoints.ts +0 -20
- package/src/utils/communication.ts +0 -72
package/build/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
'use strict';
|
|
4
4
|
|
|
5
|
-
const
|
|
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
|
|
26
|
-
const
|
|
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
|
|
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
|
|
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
|
|
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["InitDone"] = "SliceMachine Init Done";
|
|
99
|
+
})(EventType || (EventType = {}));
|
|
101
100
|
class InitTracker {
|
|
102
101
|
constructor() {
|
|
103
102
|
__privateAdd(this, _client, null);
|
|
@@ -164,16 +163,16 @@ class InitTracker {
|
|
|
164
163
|
return this._identifyEvent(userId, intercomHash);
|
|
165
164
|
}
|
|
166
165
|
trackDownloadLibrary(library) {
|
|
167
|
-
return this._trackEvent(
|
|
166
|
+
return this._trackEvent(EventType.DownloadLibrary, { library });
|
|
168
167
|
}
|
|
169
168
|
trackInitIdentify() {
|
|
170
|
-
return this._trackEvent(
|
|
169
|
+
return this._trackEvent(EventType.InitIdentify);
|
|
171
170
|
}
|
|
172
171
|
trackInitStart(repoDomain) {
|
|
173
|
-
return this._trackEvent(
|
|
172
|
+
return this._trackEvent(EventType.InitStart, { repo: repoDomain });
|
|
174
173
|
}
|
|
175
174
|
trackInitDone(framework) {
|
|
176
|
-
return this._trackEvent(
|
|
175
|
+
return this._trackEvent(EventType.InitDone, { framework });
|
|
177
176
|
}
|
|
178
177
|
}
|
|
179
178
|
_client = new WeakMap();
|
|
@@ -231,7 +230,7 @@ const logs = /*#__PURE__*/Object.freeze({
|
|
|
231
230
|
});
|
|
232
231
|
|
|
233
232
|
const { Cookie } = core.Utils;
|
|
234
|
-
const { DEFAULT_BASE
|
|
233
|
+
const { DEFAULT_BASE, DEFAULT_SERVER_PORT } = core.CONSTS;
|
|
235
234
|
const { bold, underline, spinner, writeError } = logs;
|
|
236
235
|
const isHandlerData = (data) => {
|
|
237
236
|
if (typeof data != "object")
|
|
@@ -274,13 +273,16 @@ const authenticationHandler = (server) => (onSuccess, onFail) => {
|
|
|
274
273
|
}
|
|
275
274
|
};
|
|
276
275
|
};
|
|
276
|
+
function stripTrailingSlash(str) {
|
|
277
|
+
return str.endsWith("/") ? str.slice(0, -1) : str;
|
|
278
|
+
}
|
|
277
279
|
function buildServer(base, port, host) {
|
|
278
280
|
const server = hapi__namespace.server({
|
|
279
281
|
port,
|
|
280
282
|
host,
|
|
281
283
|
routes: {
|
|
282
284
|
cors: {
|
|
283
|
-
origin: [base],
|
|
285
|
+
origin: [stripTrailingSlash(base)],
|
|
284
286
|
headers: ["Origin", "X-Requested-With", "Content-Type", "Accept"]
|
|
285
287
|
}
|
|
286
288
|
}
|
|
@@ -303,7 +305,7 @@ function askSingleChar(title) {
|
|
|
303
305
|
process.stdin.on("data", handler);
|
|
304
306
|
});
|
|
305
307
|
}
|
|
306
|
-
async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE
|
|
308
|
+
async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE, port = DEFAULT_SERVER_PORT) {
|
|
307
309
|
const confirmation = await askSingleChar(`>> Press any key to open the browser to ${action} or q to exit:`);
|
|
308
310
|
if (confirmation === "q" || confirmation === "")
|
|
309
311
|
return process.exit(-1);
|
|
@@ -340,46 +342,92 @@ async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE$1, por
|
|
|
340
342
|
}
|
|
341
343
|
|
|
342
344
|
async function startAuth({
|
|
343
|
-
|
|
345
|
+
client,
|
|
344
346
|
url,
|
|
345
347
|
action
|
|
346
348
|
}) {
|
|
347
|
-
const { onLoginFail } = await startServerAndOpenBrowser(url, action,
|
|
349
|
+
const { onLoginFail } = await startServerAndOpenBrowser(url, action, client.apisEndpoints.Wroom);
|
|
348
350
|
try {
|
|
349
|
-
await core.Utils.Poll.startPolling(() => Auth.validateSession(
|
|
351
|
+
await core.Utils.Poll.startPolling(() => Auth.validateSession(client), (isSessionValid) => isSessionValid == true, 3e3, 60);
|
|
350
352
|
return;
|
|
351
353
|
} catch (e) {
|
|
352
354
|
onLoginFail();
|
|
353
355
|
}
|
|
354
356
|
}
|
|
355
357
|
const Auth = {
|
|
356
|
-
login: async (
|
|
357
|
-
const endpoints = Prismic.Endpoints.buildEndpoints(
|
|
358
|
+
login: async (client) => {
|
|
359
|
+
const endpoints = Prismic.Endpoints.buildEndpoints(client.apisEndpoints.Wroom);
|
|
358
360
|
return startAuth({
|
|
359
|
-
|
|
361
|
+
client,
|
|
360
362
|
url: endpoints.Dashboard.cliLogin,
|
|
361
363
|
action: "login"
|
|
362
364
|
});
|
|
363
365
|
},
|
|
364
|
-
|
|
365
|
-
const
|
|
366
|
-
return
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
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);
|
|
366
|
+
validateSession: async (client) => {
|
|
367
|
+
const authToken = Prismic.PrismicSharedConfigManager.getAuth();
|
|
368
|
+
return client.updateAuthenticationToken(authToken).profile().then((userProfile) => {
|
|
369
|
+
Prismic.PrismicSharedConfigManager.setProperties({
|
|
370
|
+
shortId: userProfile.shortId,
|
|
371
|
+
intercomHash: userProfile.intercomHash
|
|
372
|
+
});
|
|
373
|
+
return true;
|
|
374
|
+
}).catch(() => false);
|
|
380
375
|
}
|
|
381
376
|
};
|
|
382
377
|
|
|
378
|
+
class InitClient extends client.Client {
|
|
379
|
+
async listRepositories() {
|
|
380
|
+
return client.getAndValidateResponse(this._get(`${this.apisEndpoints.Users}repositories`), "repository list", t__namespace.array(core.Models.Repository));
|
|
381
|
+
}
|
|
382
|
+
async createRepository(domain, framework) {
|
|
383
|
+
const data = {
|
|
384
|
+
domain,
|
|
385
|
+
framework,
|
|
386
|
+
plan: "personal",
|
|
387
|
+
isAnnual: "false",
|
|
388
|
+
role: "developer"
|
|
389
|
+
};
|
|
390
|
+
return this._fetch({
|
|
391
|
+
method: "post",
|
|
392
|
+
url: `${this.apisEndpoints.Wroom}authentication/newrepository?app=slicemachine`,
|
|
393
|
+
data,
|
|
394
|
+
headers: {
|
|
395
|
+
Cookie: Prismic.PrismicSharedConfigManager.get().cookies,
|
|
396
|
+
"User-Agent": "prismic-cli/sm"
|
|
397
|
+
}
|
|
398
|
+
}).then(() => domain);
|
|
399
|
+
}
|
|
400
|
+
async domainExist(domain) {
|
|
401
|
+
return client.getAndValidateResponse(this._get(`${this.apisEndpoints.Wroom}app/dashboard/repositories/${domain}/exists`), "repository exists", t__namespace.boolean);
|
|
402
|
+
}
|
|
403
|
+
async pushDocuments(signature, documents, cookies) {
|
|
404
|
+
if (!this.repository)
|
|
405
|
+
throw new Error("Repository undefined in the client");
|
|
406
|
+
const repositoryDirectUrl = new URL(this.apisEndpoints.Wroom);
|
|
407
|
+
repositoryDirectUrl.hostname = `${this.repository}.${repositoryDirectUrl.hostname}`;
|
|
408
|
+
return this._fetch({
|
|
409
|
+
method: "post",
|
|
410
|
+
url: `${repositoryDirectUrl.toString()}starter/documents`,
|
|
411
|
+
data: { signature, documents: JSON.stringify(documents) },
|
|
412
|
+
headers: {
|
|
413
|
+
Cookie: cookies,
|
|
414
|
+
"User-Agent": "prismic-cli/0"
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function lsdir(dir) {
|
|
421
|
+
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
422
|
+
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isDirectory()).map((subdirectory) => path__default["default"].join(dir, subdirectory));
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
async function lsfiles(dir) {
|
|
426
|
+
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
427
|
+
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isFile()).map((file) => path__default["default"].join(dir, file));
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
|
|
383
431
|
function findArgument(args, name) {
|
|
384
432
|
const flagIndex = args.indexOf(`--${name}`);
|
|
385
433
|
if (flagIndex === -1)
|
|
@@ -396,6 +444,16 @@ function findFlag(args, name) {
|
|
|
396
444
|
return args.includes(toFind);
|
|
397
445
|
}
|
|
398
446
|
const execCommand = util__default["default"].promisify(child_process.exec);
|
|
447
|
+
function getApplicationMode(argumentValue) {
|
|
448
|
+
switch (argumentValue) {
|
|
449
|
+
case client.ApplicationMode.PROD:
|
|
450
|
+
case client.ApplicationMode.STAGE:
|
|
451
|
+
case client.ApplicationMode.DEV:
|
|
452
|
+
return argumentValue;
|
|
453
|
+
default:
|
|
454
|
+
return null;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
399
457
|
|
|
400
458
|
const {
|
|
401
459
|
PRISMIC_CLIENT,
|
|
@@ -465,16 +523,15 @@ function validatePkg(cwd) {
|
|
|
465
523
|
}
|
|
466
524
|
}
|
|
467
525
|
|
|
468
|
-
function createRepository(domain, framework
|
|
526
|
+
function createRepository(client, domain, framework) {
|
|
469
527
|
const spinner = spinner$1("Creating Prismic Repository");
|
|
470
528
|
spinner.start();
|
|
471
|
-
return
|
|
472
|
-
const addressUrl = new URL(
|
|
473
|
-
|
|
474
|
-
addressUrl.hostname = `${repoDomainName}.${addressUrl.hostname}`;
|
|
529
|
+
return client.createRepository(domain, framework).then((domain2) => {
|
|
530
|
+
const addressUrl = new URL(client.apisEndpoints.Wroom);
|
|
531
|
+
addressUrl.hostname = `${domain2}.${addressUrl.hostname}`;
|
|
475
532
|
const address = addressUrl.toString();
|
|
476
533
|
spinner.succeed(`We created your new repository ${address}`);
|
|
477
|
-
return
|
|
534
|
+
return domain2;
|
|
478
535
|
}).catch((error) => {
|
|
479
536
|
spinner.fail(`Error creating repository ${domain}`);
|
|
480
537
|
if (error.message) {
|
|
@@ -486,14 +543,38 @@ function createRepository(domain, framework, cookies, base) {
|
|
|
486
543
|
});
|
|
487
544
|
}
|
|
488
545
|
|
|
546
|
+
async function validateRepositoryName(client, name) {
|
|
547
|
+
const domain = name.trim();
|
|
548
|
+
const errors = [];
|
|
549
|
+
const startsWithLetter = /^[a-zA-Z]/.test(domain);
|
|
550
|
+
if (!startsWithLetter)
|
|
551
|
+
errors.push("Must start with a letter.");
|
|
552
|
+
const acceptedChars = /^[a-z0-9-]+$/.test(domain);
|
|
553
|
+
if (!acceptedChars)
|
|
554
|
+
errors.push("Must contain only lowercase letters, numbers and hyphens.");
|
|
555
|
+
const fourCharactersOrMore = domain.length >= 4;
|
|
556
|
+
if (!fourCharactersOrMore)
|
|
557
|
+
errors.push("Must have four or more alphanumeric characters and/or hyphens.");
|
|
558
|
+
const endsWithALetterOrNumber = /[a-z0-9]$/.test(domain);
|
|
559
|
+
if (!endsWithALetterOrNumber)
|
|
560
|
+
errors.push("Must end in a letter or a number.");
|
|
561
|
+
const thirtyCharacterOrLess = domain.length <= 30;
|
|
562
|
+
if (!thirtyCharacterOrLess)
|
|
563
|
+
errors.push("Must be 30 characters or less");
|
|
564
|
+
if (errors.length > 0) {
|
|
565
|
+
const errorString = errors.map((d, i) => `(${i + 1}: ${d}`).join(" ");
|
|
566
|
+
const msg = `Validation errors: ${errorString}`;
|
|
567
|
+
return Promise.reject(new Error(msg));
|
|
568
|
+
}
|
|
569
|
+
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`)));
|
|
570
|
+
}
|
|
571
|
+
|
|
489
572
|
const CREATE_REPO = "$_CREATE_REPO";
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
const repoName = value ? cyan(value) : dim.cyan("repo-name");
|
|
493
|
-
return `${cyan.dim(`${address.protocol}//`)}${repoName}${cyan.dim(`.${address.hostname}`)}`;
|
|
573
|
+
function prettyRepoName(address, domain) {
|
|
574
|
+
return `${cyan.dim(`${address.protocol}//`)}${cyan(domain)}${cyan.dim(`.${address.hostname}`)}`;
|
|
494
575
|
}
|
|
495
|
-
async function promptForRepoDomain(
|
|
496
|
-
const address = new URL(
|
|
576
|
+
async function promptForRepoDomain(client, defaultValue) {
|
|
577
|
+
const address = new URL(client.apisEndpoints.Wroom);
|
|
497
578
|
writeInfo("The name acts as a domain/endpoint for your content repo and should be completely unique.");
|
|
498
579
|
return inquirer__namespace.prompt([
|
|
499
580
|
{
|
|
@@ -502,11 +583,8 @@ async function promptForRepoDomain(base, defaultValue) {
|
|
|
502
583
|
type: "input",
|
|
503
584
|
required: true,
|
|
504
585
|
default: defaultValue,
|
|
505
|
-
transformer: (value) => prettyRepoName(address, value || defaultValue),
|
|
506
|
-
|
|
507
|
-
const result = await Prismic__namespace.Communication.validateRepositoryName(name, base, false);
|
|
508
|
-
return result === name || result;
|
|
509
|
-
}
|
|
586
|
+
transformer: (value) => prettyRepoName(address, value || defaultValue || "repository"),
|
|
587
|
+
validate: (name) => validateRepositoryName(client, name)
|
|
510
588
|
}
|
|
511
589
|
]).then((res) => res.repoDomain);
|
|
512
590
|
}
|
|
@@ -560,26 +638,26 @@ function sortReposForPrompt(repos, base, cwd) {
|
|
|
560
638
|
createNew
|
|
561
639
|
]).sort(orderPrompts(maybeConfiguredRepoName));
|
|
562
640
|
}
|
|
563
|
-
async function chooseOrCreateARepository(cwd, framework,
|
|
564
|
-
const
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
return
|
|
641
|
+
async function chooseOrCreateARepository(client, cwd, framework, preSelectedRepository) {
|
|
642
|
+
const repositories = await client.listRepositories();
|
|
643
|
+
const isPreSelectedValid = preSelectedRepository && repositories.find((repository) => repository.domain === preSelectedRepository);
|
|
644
|
+
if (isPreSelectedValid)
|
|
645
|
+
return preSelectedRepository;
|
|
646
|
+
if (repositories.length === 0) {
|
|
647
|
+
const domainName = await promptForRepoDomain(client, preSelectedRepository);
|
|
648
|
+
await createRepository(client, domainName, framework);
|
|
649
|
+
return domainName;
|
|
572
650
|
}
|
|
573
|
-
const choices = sortReposForPrompt(
|
|
651
|
+
const choices = sortReposForPrompt(repositories, client.apisEndpoints.Wroom, cwd);
|
|
574
652
|
const numberOfDisabledRepos = choices.filter((repo) => {
|
|
575
653
|
if (repo instanceof Separator__default["default"])
|
|
576
654
|
return false;
|
|
577
655
|
return repo.disabled;
|
|
578
656
|
}).length;
|
|
579
|
-
const
|
|
657
|
+
const promptResult = await inquirer__namespace.prompt([
|
|
580
658
|
{
|
|
581
659
|
type: "list",
|
|
582
|
-
name: "
|
|
660
|
+
name: "chosenRepository",
|
|
583
661
|
default: 0,
|
|
584
662
|
required: true,
|
|
585
663
|
message: "Connect a Prismic Repository or create a new one",
|
|
@@ -587,11 +665,12 @@ async function chooseOrCreateARepository(cwd, framework, cookies, base = DEFAULT
|
|
|
587
665
|
pageSize: numberOfDisabledRepos + 2 <= 7 ? 7 : numberOfDisabledRepos + 2
|
|
588
666
|
}
|
|
589
667
|
]);
|
|
590
|
-
if (
|
|
591
|
-
const domainName = await promptForRepoDomain(
|
|
592
|
-
|
|
668
|
+
if (promptResult.chosenRepository === CREATE_REPO) {
|
|
669
|
+
const domainName = await promptForRepoDomain(client, preSelectedRepository);
|
|
670
|
+
await createRepository(client, domainName, framework);
|
|
671
|
+
return domainName;
|
|
593
672
|
}
|
|
594
|
-
return
|
|
673
|
+
return promptResult.chosenRepository;
|
|
595
674
|
}
|
|
596
675
|
|
|
597
676
|
async function promptForFramework() {
|
|
@@ -652,56 +731,21 @@ async function detectFramework(cwd) {
|
|
|
652
731
|
}
|
|
653
732
|
}
|
|
654
733
|
|
|
655
|
-
async function
|
|
656
|
-
const
|
|
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));
|
|
734
|
+
async function loginOrBypass(client) {
|
|
735
|
+
const user = await client.profile().catch(() => null);
|
|
692
736
|
if (user) {
|
|
693
|
-
const email = user.
|
|
737
|
+
const email = user.email;
|
|
694
738
|
writeCheck(`Logged in as ${bold$1(email)}`);
|
|
695
739
|
return user;
|
|
696
|
-
} else {
|
|
697
|
-
await Auth.login(base);
|
|
698
|
-
const user2 = await validateSessionAndGetProfile(base);
|
|
699
|
-
return user2;
|
|
700
740
|
}
|
|
741
|
+
await Auth.login(client);
|
|
742
|
+
client.updateAuthenticationToken(Prismic.PrismicSharedConfigManager.getAuth());
|
|
743
|
+
const userAfterLogin = await client.profile();
|
|
744
|
+
return userAfterLogin;
|
|
701
745
|
}
|
|
702
746
|
|
|
703
747
|
const defaultSliceMachineVersion = "0.0.41";
|
|
704
|
-
async function configureProject(
|
|
748
|
+
async function configureProject(client, cwd, repositoryDomainName, framework, sliceLibPath = [], tracking = true) {
|
|
705
749
|
const frameworkName = NodeUtils__namespace.Framework.fancyName(framework.value);
|
|
706
750
|
const spinner = spinner$1(`Configuring your ${frameworkName} and Prismic project...`);
|
|
707
751
|
spinner.start();
|
|
@@ -713,7 +757,7 @@ async function configureProject(cwd, base, repositoryDomainName, framework, slic
|
|
|
713
757
|
const libs = manifest.content && manifest.content.libraries && manifest.content.libraries.length > 0 ? manifest.content.libraries : ["@/slices"];
|
|
714
758
|
const manifestUpdated = {
|
|
715
759
|
...manifestAlreadyExistWithContent ? manifest.content : { _latest: sliceMachineVersionInstalled },
|
|
716
|
-
apiEndpoint: Prismic__namespace.Endpoints.buildRepositoryEndpoint(
|
|
760
|
+
apiEndpoint: Prismic__namespace.Endpoints.buildRepositoryEndpoint(client.apisEndpoints.Wroom, repositoryDomainName),
|
|
717
761
|
libraries: [...libs, ...sliceLibPath],
|
|
718
762
|
...framework.manuallyAdded ? { framework: framework.value } : {},
|
|
719
763
|
...!tracking ? { tracking } : {}
|
|
@@ -758,11 +802,19 @@ const extractVersionNumberFromSemver = (semver) => {
|
|
|
758
802
|
return null;
|
|
759
803
|
};
|
|
760
804
|
|
|
761
|
-
function displayFinalMessage(cwd) {
|
|
805
|
+
function displayFinalMessage(cwd, wasStarter, reponame, base) {
|
|
762
806
|
const yarnLock = NodeUtils__namespace.Files.exists(NodeUtils__namespace.YarnLockPath(cwd));
|
|
763
807
|
const command = `${yarnLock ? "yarn" : "npm"} run ${core.CONSTS.SCRIPT_NAME}`;
|
|
764
808
|
console.log();
|
|
765
|
-
|
|
809
|
+
if (wasStarter) {
|
|
810
|
+
const repoUrl = new URL(base);
|
|
811
|
+
repoUrl.hostname = `${reponame}.${repoUrl.hostname}`;
|
|
812
|
+
const urlAsString = repoUrl.toString();
|
|
813
|
+
const message = `${white("\u25A0")} Start editing your content in Prismic ${purple(urlAsString)}`;
|
|
814
|
+
console.log(message);
|
|
815
|
+
} else {
|
|
816
|
+
console.log(`${white("\u25A0")} Run ${purple(command)} to launch Slice Machine and create your first Custom Type`);
|
|
817
|
+
}
|
|
766
818
|
}
|
|
767
819
|
|
|
768
820
|
const Dependencies = {
|
|
@@ -870,100 +922,6 @@ async function installLib(cwd, libGithubPath, branch = "HEAD") {
|
|
|
870
922
|
}
|
|
871
923
|
}
|
|
872
924
|
|
|
873
|
-
function handleErrors(prefix, err) {
|
|
874
|
-
if (axios__default["default"].isAxiosError(err) && err.response) {
|
|
875
|
-
writeError$1(`${prefix} | [${err.response.status}]: ${err.response.statusText}`);
|
|
876
|
-
} else if (err instanceof Error) {
|
|
877
|
-
writeError$1(`${prefix} ${err.message}`);
|
|
878
|
-
} else {
|
|
879
|
-
writeError$1(`${prefix} ${String(err)}`);
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
async function getRemoteSliceIds(customTypeApiEndpoint, repository, authorization) {
|
|
883
|
-
const addr = `${stripLastSlash(customTypeApiEndpoint)}/slices`;
|
|
884
|
-
return axios__default["default"].get(addr, {
|
|
885
|
-
headers: {
|
|
886
|
-
Authorization: `Bearer ${authorization}`,
|
|
887
|
-
repository
|
|
888
|
-
}
|
|
889
|
-
}).then((res) => {
|
|
890
|
-
return Array.isArray(res.data) ? res.data.map((model) => model.id) : [];
|
|
891
|
-
});
|
|
892
|
-
}
|
|
893
|
-
async function sendModelToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, model) {
|
|
894
|
-
const data = models.Slices.fromSM(model);
|
|
895
|
-
const updateOrInsertUrl = `${customTypesApiEndpoint}slices/${remoteSliceIds.includes(model.id) ? "update" : "insert"}`;
|
|
896
|
-
return axios__default["default"].post(updateOrInsertUrl, data, {
|
|
897
|
-
headers: {
|
|
898
|
-
Authorization: `Bearer ${authorization}`,
|
|
899
|
-
repository
|
|
900
|
-
}
|
|
901
|
-
}).then(() => {
|
|
902
|
-
return;
|
|
903
|
-
}).catch((err) => {
|
|
904
|
-
handleErrors(`sending slice ${model.id}, please try again. If the problem persists, contact us.`, err);
|
|
905
|
-
throw err;
|
|
906
|
-
});
|
|
907
|
-
}
|
|
908
|
-
async function sendManyModelsToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, models) {
|
|
909
|
-
return Promise.all(models.map((model) => sendModelToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, model))).then(() => {
|
|
910
|
-
return;
|
|
911
|
-
}).catch(() => {
|
|
912
|
-
process.exit(1);
|
|
913
|
-
});
|
|
914
|
-
}
|
|
915
|
-
function stripLastSlash(str) {
|
|
916
|
-
return str.replace(/\/*$/g, "");
|
|
917
|
-
}
|
|
918
|
-
function getRemoteCustomTypeIds(customTypeApiEndpoint, repository, authorization) {
|
|
919
|
-
const addr = `${stripLastSlash(customTypeApiEndpoint)}/customtypes`;
|
|
920
|
-
return axios__default["default"].get(addr, {
|
|
921
|
-
headers: {
|
|
922
|
-
Authorization: `Bearer ${authorization}`,
|
|
923
|
-
repository
|
|
924
|
-
}
|
|
925
|
-
}).then((res) => {
|
|
926
|
-
return Array.isArray(res.data) ? res.data.map((ct) => ct.id) : [];
|
|
927
|
-
});
|
|
928
|
-
}
|
|
929
|
-
async function sendCustomTypeToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customType) {
|
|
930
|
-
const shouldUpdate = remoteCustomTypeIds.includes(customType.id);
|
|
931
|
-
const addr = `${stripLastSlash(customTypeApiEndpoint)}/customtypes/${shouldUpdate ? "update" : "insert"}`;
|
|
932
|
-
return axios__default["default"].post(addr, customType, {
|
|
933
|
-
headers: {
|
|
934
|
-
repository,
|
|
935
|
-
Authorization: `Bearer ${authorization}`
|
|
936
|
-
}
|
|
937
|
-
}).then(() => {
|
|
938
|
-
return;
|
|
939
|
-
}).catch((err) => {
|
|
940
|
-
handleErrors(`sending custom type ${customType.id}, please try again. If the problem persists, contact us.`, err);
|
|
941
|
-
throw err;
|
|
942
|
-
});
|
|
943
|
-
}
|
|
944
|
-
async function sendManyCustomTypesToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customTypes) {
|
|
945
|
-
return Promise.all(customTypes.map((customType) => sendCustomTypeToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customType))).then(() => {
|
|
946
|
-
return;
|
|
947
|
-
}).catch(() => {
|
|
948
|
-
process.exit(1);
|
|
949
|
-
});
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
const ProductionApisEndpoints = {
|
|
953
|
-
Models: "https://customtypes.prismic.io/",
|
|
954
|
-
AclProvider: "https://0yyeb2g040.execute-api.us-east-1.amazonaws.com/prod/"
|
|
955
|
-
};
|
|
956
|
-
const StageApisEndpoints = {
|
|
957
|
-
Models: "https://customtypes.wroom.io/",
|
|
958
|
-
AclProvider: "https://2iamcvnxf4.execute-api.us-east-1.amazonaws.com/stage/"
|
|
959
|
-
};
|
|
960
|
-
const getEndpointsFromBase = (base) => {
|
|
961
|
-
const url = new URL(base);
|
|
962
|
-
if (url.hostname === "wroom.io")
|
|
963
|
-
return StageApisEndpoints;
|
|
964
|
-
return ProductionApisEndpoints;
|
|
965
|
-
};
|
|
966
|
-
|
|
967
925
|
async function promptToPushSlices() {
|
|
968
926
|
return inquirer__default["default"].prompt([
|
|
969
927
|
{
|
|
@@ -980,127 +938,80 @@ async function promptToPushCustomTypes() {
|
|
|
980
938
|
type: "confirm",
|
|
981
939
|
name: "pushCustomTypes",
|
|
982
940
|
default: false,
|
|
983
|
-
message: "Your repository already contains Custom Types. Do you want to continue pushing your local
|
|
941
|
+
message: "Your repository already contains Custom Types. Do you want to continue pushing your local Custom Types?"
|
|
984
942
|
}
|
|
985
943
|
]).then((res) => res.pushCustomTypes);
|
|
986
944
|
}
|
|
987
945
|
|
|
988
|
-
async function
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
return fs__default["default"].promises.readFile(filePath).then((file) => {
|
|
1006
|
-
form.append("file", file, { filename });
|
|
1007
|
-
return form;
|
|
1008
|
-
}).catch(() => {
|
|
1009
|
-
writeError$1(`Error reading preview image: ${filename}`);
|
|
1010
|
-
return null;
|
|
1011
|
-
});
|
|
1012
|
-
}
|
|
1013
|
-
function createS3Key(repository, sliceName, variationId, filename) {
|
|
1014
|
-
return `${repository}/shared-slices/${snakeCase__default["default"](sliceName)}/${snakeCase__default["default"](variationId)}-${uniqid__default["default"]()}/${filename}`;
|
|
1015
|
-
}
|
|
1016
|
-
async function sendVariationPreviewToS3(acl, repository, sliceName, variationId, filePath) {
|
|
1017
|
-
const filename = path__default["default"].basename(filePath);
|
|
1018
|
-
const key = createS3Key(repository, sliceName, variationId, filename);
|
|
1019
|
-
const form = await createFormForS3(key, filename, filePath, acl);
|
|
1020
|
-
if (form === null)
|
|
1021
|
-
return null;
|
|
1022
|
-
if (form.hasKnownLength() === false) {
|
|
1023
|
-
writeError$1(`[slice/push] An error occurred while uploading preview image ${filePath} as length in unknown`);
|
|
1024
|
-
}
|
|
1025
|
-
const errorMessage = `[slice/push] An error occurred while uploading preview images for ${sliceName}-${variationId} - please contact support`;
|
|
1026
|
-
return axios__default["default"].post(acl.values.url, form, {
|
|
1027
|
-
headers: {
|
|
1028
|
-
...form.getHeaders(),
|
|
1029
|
-
"Content-Length": String(form.getLengthSync())
|
|
1030
|
-
}
|
|
1031
|
-
}).then((res) => {
|
|
1032
|
-
if (res.status !== 204) {
|
|
1033
|
-
writeError$1(errorMessage);
|
|
1034
|
-
writeError$1(`${res.status}: ${res.statusText}`);
|
|
1035
|
-
return null;
|
|
1036
|
-
} else {
|
|
1037
|
-
return `${acl.imgixEndpoint}/${key}`;
|
|
1038
|
-
}
|
|
1039
|
-
}).catch((err) => {
|
|
1040
|
-
writeError$1(errorMessage);
|
|
1041
|
-
if (axios__default["default"].isAxiosError(err) && err.response) {
|
|
1042
|
-
writeError$1(`${err.response.status}: ${err.response.statusText}`);
|
|
1043
|
-
} else if (err instanceof Error) {
|
|
1044
|
-
writeError$1(err.message);
|
|
1045
|
-
} else {
|
|
1046
|
-
writeError$1(String(err));
|
|
1047
|
-
}
|
|
1048
|
-
return null;
|
|
1049
|
-
});
|
|
1050
|
-
}
|
|
1051
|
-
async function maybeAddImageUrlToVariation(acl, repository, modelId, pathToScreenShot, variation) {
|
|
1052
|
-
const imageUrl = await sendVariationPreviewToS3(acl, repository, modelId, variation.id, pathToScreenShot);
|
|
1053
|
-
if (!imageUrl)
|
|
946
|
+
async function updateVariationWithScreenshot(client, acl, screenshotPaths, sliceName, variation) {
|
|
947
|
+
const screenshot = screenshotPaths[variation.id];
|
|
948
|
+
if (!screenshot || !screenshot.path)
|
|
949
|
+
return Promise.resolve(variation);
|
|
950
|
+
return client.uploadScreenshot({
|
|
951
|
+
acl,
|
|
952
|
+
sliceName,
|
|
953
|
+
variationId: variation.id,
|
|
954
|
+
filePath: screenshot.path
|
|
955
|
+
}).then((screenshotUrl) => {
|
|
956
|
+
return {
|
|
957
|
+
...variation,
|
|
958
|
+
imageUrl: screenshotUrl
|
|
959
|
+
};
|
|
960
|
+
}).catch((error) => {
|
|
961
|
+
writeError$1(`Couldn't upload screenshot slice: ${sliceName} - variation: ${variation.id}`);
|
|
962
|
+
writeError$1(error.message, "Full error:");
|
|
1054
963
|
return variation;
|
|
1055
|
-
|
|
1056
|
-
...variation,
|
|
1057
|
-
imageUrl
|
|
1058
|
-
};
|
|
964
|
+
});
|
|
1059
965
|
}
|
|
1060
|
-
async function
|
|
1061
|
-
return Promise.all(
|
|
1062
|
-
const
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
966
|
+
async function updateSlicesWithScreenshots(client, acl, components) {
|
|
967
|
+
return Promise.all(components.map(async (component) => {
|
|
968
|
+
const { screenshotPaths, model } = component;
|
|
969
|
+
const variationsUpdated = await Promise.all(model.variations.map(async (variation) => updateVariationWithScreenshot(client, acl, screenshotPaths, model.id, variation)));
|
|
970
|
+
return {
|
|
971
|
+
...model,
|
|
972
|
+
variations: variationsUpdated
|
|
973
|
+
};
|
|
1066
974
|
}));
|
|
1067
975
|
}
|
|
1068
|
-
async function maybeUpdateModelVariationsWithImageUrl(acl, repository, component) {
|
|
1069
|
-
const { screenshotPaths, model } = component;
|
|
1070
|
-
const variations = await addImageUrlsToVariations(acl, repository, model.id, screenshotPaths, model.variations);
|
|
1071
|
-
return {
|
|
1072
|
-
...model,
|
|
1073
|
-
variations
|
|
1074
|
-
};
|
|
1075
|
-
}
|
|
1076
|
-
async function addImageUrlsToModelVariations(acl, repository, components) {
|
|
1077
|
-
return Promise.all(components.map(async (component) => maybeUpdateModelVariationsWithImageUrl(acl, repository, component)));
|
|
1078
|
-
}
|
|
1079
976
|
|
|
1080
|
-
async function
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
977
|
+
async function sendSlices(client, cwd, manifest) {
|
|
978
|
+
if (!manifest.libraries)
|
|
979
|
+
return Promise.resolve(false);
|
|
980
|
+
const libraries = Libraries__namespace.libraries(cwd, manifest.libraries);
|
|
981
|
+
const components = libraries.reduce((acc, lib) => {
|
|
982
|
+
return [...acc, ...lib.components];
|
|
983
|
+
}, []);
|
|
984
|
+
if (components.length === 0)
|
|
1084
985
|
return Promise.resolve(false);
|
|
1085
|
-
const
|
|
1086
|
-
if (
|
|
986
|
+
const remoteSlicesIds = await client.getSlices().then((slices) => slices.map((slice) => slice.id));
|
|
987
|
+
if (remoteSlicesIds.length) {
|
|
1087
988
|
const pushAnyway = await promptToPushSlices();
|
|
1088
989
|
if (pushAnyway === false)
|
|
1089
990
|
return Promise.resolve(true);
|
|
1090
991
|
}
|
|
1091
992
|
const spinner = spinner$1("Pushing existing Slice models to your repository");
|
|
1092
993
|
spinner.start();
|
|
1093
|
-
const acl = await createAcl(
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
await
|
|
994
|
+
const acl = await client.createAcl().catch((error) => {
|
|
995
|
+
writeError$1("Uploading screenshots for your slices failed, please contact us.");
|
|
996
|
+
writeError$1(error.message, "Full error:");
|
|
997
|
+
return null;
|
|
998
|
+
});
|
|
999
|
+
const models$1 = acl ? await updateSlicesWithScreenshots(client, acl, components) : components.map((component) => component.model);
|
|
1000
|
+
await Promise.all(models$1.map(async (model) => {
|
|
1001
|
+
const slice = models.Slices.fromSM(model);
|
|
1002
|
+
const promise = remoteSlicesIds.includes(slice.id) ? client.updateSlice(slice) : client.insertSlice(slice);
|
|
1003
|
+
return promise.catch((error) => {
|
|
1004
|
+
writeError$1(`Sending slice ${model.id} - ${error.message}`);
|
|
1005
|
+
throw error;
|
|
1006
|
+
});
|
|
1007
|
+
})).catch(() => {
|
|
1008
|
+
process.exit(1);
|
|
1009
|
+
});
|
|
1099
1010
|
spinner.succeed();
|
|
1100
1011
|
return Promise.resolve(true);
|
|
1101
1012
|
}
|
|
1102
1013
|
|
|
1103
|
-
function
|
|
1014
|
+
function readLocalCustomTypes(cwd) {
|
|
1104
1015
|
const customTypePaths = NodeUtils.CustomTypesPaths(cwd);
|
|
1105
1016
|
const dir = customTypePaths.value();
|
|
1106
1017
|
if (NodeUtils.Files.isDirectory(dir) === false)
|
|
@@ -1124,12 +1035,11 @@ function readCustomTypes(cwd) {
|
|
|
1124
1035
|
}, []);
|
|
1125
1036
|
return files;
|
|
1126
1037
|
}
|
|
1127
|
-
async function
|
|
1128
|
-
const
|
|
1129
|
-
|
|
1130
|
-
if (customTypes.length === 0)
|
|
1038
|
+
async function sendCustomTypes(client, cwd) {
|
|
1039
|
+
const localCustomTypes = readLocalCustomTypes(cwd);
|
|
1040
|
+
if (localCustomTypes.length === 0)
|
|
1131
1041
|
return Promise.resolve(false);
|
|
1132
|
-
const remoteCustomTypeIds = await
|
|
1042
|
+
const remoteCustomTypeIds = await client.getCustomTypes().then((customTypes) => customTypes.map((customType) => customType.id));
|
|
1133
1043
|
if (remoteCustomTypeIds.length) {
|
|
1134
1044
|
const shouldPush = await promptToPushCustomTypes();
|
|
1135
1045
|
if (shouldPush === false)
|
|
@@ -1137,7 +1047,15 @@ async function sendCustomTypesFromStarter(repository, authorization, base, cwd)
|
|
|
1137
1047
|
}
|
|
1138
1048
|
const spinner = spinner$1("Pushing existing custom types to your repository");
|
|
1139
1049
|
spinner.start();
|
|
1140
|
-
await
|
|
1050
|
+
await Promise.all(localCustomTypes.map(async (customType) => {
|
|
1051
|
+
const promise = remoteCustomTypeIds.includes(customType.id) ? client.updateCustomType(customType) : client.insertCustomType(customType);
|
|
1052
|
+
return promise.catch((error) => {
|
|
1053
|
+
writeError$1(`Sending custom type ${customType.id} - ${error.message}`);
|
|
1054
|
+
throw error;
|
|
1055
|
+
});
|
|
1056
|
+
})).catch(() => {
|
|
1057
|
+
process.exit(1);
|
|
1058
|
+
});
|
|
1141
1059
|
spinner.succeed();
|
|
1142
1060
|
return Promise.resolve(true);
|
|
1143
1061
|
}
|
|
@@ -1154,52 +1072,30 @@ async function readSignatureFile(cwd) {
|
|
|
1154
1072
|
})(SignatureFileReader.decode(data));
|
|
1155
1073
|
});
|
|
1156
1074
|
}
|
|
1157
|
-
async function lsdir(dir) {
|
|
1158
|
-
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
1159
|
-
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isDirectory()).map((subdirectory) => path__default["default"].join(dir, subdirectory));
|
|
1160
|
-
});
|
|
1161
|
-
}
|
|
1162
|
-
async function lsfiles(dir) {
|
|
1163
|
-
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
1164
|
-
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isFile()).map((file) => path__default["default"].join(dir, file));
|
|
1165
|
-
});
|
|
1166
|
-
}
|
|
1167
1075
|
async function readDocuments(cwd) {
|
|
1168
1076
|
const documentDir = path__default["default"].join(cwd, "documents");
|
|
1169
1077
|
const dirs = await lsdir(documentDir);
|
|
1170
1078
|
const files = (await Promise.all(dirs.map((dir) => lsfiles(dir)))).flat();
|
|
1171
1079
|
const documentObj = files.reduce((acc, file) => {
|
|
1172
|
-
const fileContent = fs__default["default"].readFileSync(file, "utf-8");
|
|
1173
1080
|
const filename = path__default["default"].parse(file).name;
|
|
1174
|
-
|
|
1175
|
-
|
|
1081
|
+
const fileContent = fs__default["default"].readFileSync(file, "utf-8");
|
|
1082
|
+
const json = JSON.parse(fileContent);
|
|
1083
|
+
return { ...acc, [filename]: json };
|
|
1176
1084
|
}, {});
|
|
1177
|
-
return
|
|
1085
|
+
return documentObj;
|
|
1178
1086
|
}
|
|
1179
|
-
|
|
1087
|
+
async function sendDocuments(client, cwd) {
|
|
1180
1088
|
const pathToDocuments = path__default["default"].join(cwd, "documents");
|
|
1181
1089
|
const pathToSignatureFile = path__default["default"].join(pathToDocuments, "index.json");
|
|
1182
|
-
if (!fs__default["default"].existsSync(pathToSignatureFile))
|
|
1090
|
+
if (!fs__default["default"].existsSync(pathToSignatureFile))
|
|
1183
1091
|
return Promise.resolve(false);
|
|
1184
|
-
}
|
|
1185
1092
|
const signatureObj = await readSignatureFile(cwd);
|
|
1186
|
-
const
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
documents: documentsStr
|
|
1190
|
-
};
|
|
1191
|
-
const prismicUrl = new URL(base);
|
|
1192
|
-
prismicUrl.hostname = `${repository}.${prismicUrl.hostname}`;
|
|
1193
|
-
prismicUrl.pathname = "starter/documents";
|
|
1194
|
-
const endpointURL = prismicUrl.toString();
|
|
1093
|
+
const documents = await readDocuments(cwd);
|
|
1094
|
+
if (Object.keys(documents).length === 0)
|
|
1095
|
+
return Promise.resolve(false);
|
|
1195
1096
|
const spinner = spinner$1("Pushing existing documents to your repository");
|
|
1196
1097
|
spinner.start();
|
|
1197
|
-
return
|
|
1198
|
-
headers: {
|
|
1199
|
-
"User-Agent": "prismic-cli/0",
|
|
1200
|
-
Cookie: cookies
|
|
1201
|
-
}
|
|
1202
|
-
}).then(() => {
|
|
1098
|
+
return client.pushDocuments(signatureObj.signature, documents, SharedConfig.PrismicSharedConfigManager.get().cookies).then(() => {
|
|
1203
1099
|
spinner.succeed();
|
|
1204
1100
|
fs__default["default"].rmSync(pathToDocuments, { recursive: true, force: true });
|
|
1205
1101
|
return true;
|
|
@@ -1209,58 +1105,54 @@ const sendDocumentsFromStarter = async (repository, cookies, base, cwd) => {
|
|
|
1209
1105
|
if (((_a = e.response) == null ? void 0 : _a.data) === "Repository should not contain documents") {
|
|
1210
1106
|
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.");
|
|
1211
1107
|
} else {
|
|
1212
|
-
|
|
1108
|
+
writeError$1("Sending documents failed, please try again. If the problem persists, contact us.");
|
|
1109
|
+
writeError$1(`Full error: ${e.code || 500} - ${e.message}`);
|
|
1213
1110
|
}
|
|
1214
1111
|
process.exit(1);
|
|
1215
1112
|
});
|
|
1216
|
-
}
|
|
1113
|
+
}
|
|
1217
1114
|
|
|
1218
|
-
async function sendStarterData(
|
|
1219
|
-
const
|
|
1220
|
-
const
|
|
1221
|
-
const hasDocuments = NodeUtils.Files.exists(
|
|
1222
|
-
if (
|
|
1115
|
+
async function sendStarterData(client, cwd, pushDocuments = true) {
|
|
1116
|
+
const manifest = NodeUtils.retrieveManifest(cwd);
|
|
1117
|
+
const documentsPath = path__default["default"].join(cwd, "documents");
|
|
1118
|
+
const hasDocuments = NodeUtils.Files.exists(documentsPath);
|
|
1119
|
+
if (manifest.exists === false || hasDocuments === false)
|
|
1223
1120
|
return Promise.resolve(false);
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
if (sendDocs === false) {
|
|
1230
|
-
fs__default["default"].rmSync(pathToDocuments, { recursive: true, force: true });
|
|
1121
|
+
if (manifest.content)
|
|
1122
|
+
await sendSlices(client, cwd, manifest.content);
|
|
1123
|
+
await sendCustomTypes(client, cwd);
|
|
1124
|
+
if (!pushDocuments) {
|
|
1125
|
+
fs__default["default"].rmSync(documentsPath, { recursive: true, force: true });
|
|
1231
1126
|
return Promise.resolve(true);
|
|
1232
1127
|
}
|
|
1233
|
-
return
|
|
1128
|
+
return sendDocuments(client, cwd);
|
|
1234
1129
|
}
|
|
1235
1130
|
|
|
1236
1131
|
async function init() {
|
|
1237
1132
|
const cwd = findArgument(process.argv, "cwd") || process.cwd();
|
|
1238
|
-
const
|
|
1133
|
+
const mode = getApplicationMode(findArgument(process.argv, "mode")) || client.ApplicationMode.PROD;
|
|
1239
1134
|
const lib = findArgument(process.argv, "library");
|
|
1240
1135
|
const branch = findArgument(process.argv, "branch");
|
|
1241
1136
|
const isTrackingAvailable = findArgument(process.argv, "tracking") !== "false";
|
|
1242
|
-
const
|
|
1243
|
-
const
|
|
1244
|
-
Tracker.get().initialize("
|
|
1245
|
-
void Tracker.get().trackInitStart(
|
|
1137
|
+
const preSelectedRepository = findArgument(process.argv, "repository");
|
|
1138
|
+
const pushDocuments = !findFlag(process.argv, "no-docs");
|
|
1139
|
+
Tracker.get().initialize("ED3O1FVsa8DteNyRmAuDyMcPoftJ6VdP" , isTrackingAvailable);
|
|
1140
|
+
void Tracker.get().trackInitStart(preSelectedRepository);
|
|
1141
|
+
const client$1 = new InitClient(mode, null, Prismic__default["default"].PrismicSharedConfigManager.getAuth());
|
|
1246
1142
|
console.log(purple("You're about to configure Slicemachine... Press ctrl + C to cancel"));
|
|
1247
1143
|
validatePkg(cwd);
|
|
1248
|
-
const user = await loginOrBypass(
|
|
1249
|
-
|
|
1250
|
-
throw new Error("The user should be logged in!");
|
|
1251
|
-
if (user.profile) {
|
|
1252
|
-
Tracker.get().identifyUser(user.profile.shortId, user.profile.intercomHash);
|
|
1253
|
-
}
|
|
1144
|
+
const user = await loginOrBypass(client$1);
|
|
1145
|
+
Tracker.get().identifyUser(user.shortId, user.intercomHash);
|
|
1254
1146
|
void Tracker.get().trackInitIdentify();
|
|
1255
|
-
const config = Prismic__default["default"].PrismicSharedConfigManager.get();
|
|
1256
1147
|
const frameworkResult = await detectFramework(cwd);
|
|
1257
|
-
const
|
|
1258
|
-
Tracker.get().setRepository(
|
|
1148
|
+
const repository = await chooseOrCreateARepository(client$1, cwd, frameworkResult.value, preSelectedRepository);
|
|
1149
|
+
Tracker.get().setRepository(repository);
|
|
1150
|
+
client$1.updateRepository(repository);
|
|
1259
1151
|
const sliceLibPath = lib ? await installLib(cwd, lib, branch) : void 0;
|
|
1260
|
-
const wasStarter = await sendStarterData(
|
|
1261
|
-
await configureProject(
|
|
1152
|
+
const wasStarter = await sendStarterData(client$1, cwd, pushDocuments);
|
|
1153
|
+
await configureProject(client$1, cwd, repository, frameworkResult, sliceLibPath, isTrackingAvailable);
|
|
1262
1154
|
await installRequiredDependencies(cwd, frameworkResult.value, wasStarter);
|
|
1263
|
-
displayFinalMessage(cwd);
|
|
1155
|
+
displayFinalMessage(cwd, wasStarter, repository, client$1.apisEndpoints.Wroom);
|
|
1264
1156
|
}
|
|
1265
1157
|
init().then(() => {
|
|
1266
1158
|
process.exit(0);
|