-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublish.mjs
77 lines (62 loc) · 2.54 KB
/
publish.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// TODO: Write documentation
import { execSync } from 'child_process';
import { readFileSync, writeFileSync } from 'fs';
import { exit } from 'process';
import { readCachedProjectGraph } from '@nrwl/devkit';
import chalk from 'chalk';
const VERSION_PATTERN = /^\d+\.\d+\.\d+(-\w+\.\d+)?/;
const DEFAULT_ENVIRONMENT = 'local';
const ENVIRONMENTS = {
production: {
registry: 'https://registry.npmjs.org',
defaultVersion: null,
defaultTag: (version) => (version.includes('-') ? 'next' : 'latest'),
overwrite: false,
},
local: {
registry: 'http://localhost:4873',
defaultVersion: '0.0.0-local.1',
defaultTag: (_version) => 'local',
overwrite: true,
},
};
function invariant(condition, message) {
if (!condition) {
console.error(chalk.bold.red(message));
throw new Error(message);
}
}
function getArgOrDefault(value, defaultValue) {
return !value || value === 'undefined' ? defaultValue : value;
}
const [, , name, versionArg, envArg, tagArg] = process.argv;
const environment = ENVIRONMENTS[getArgOrDefault(envArg, DEFAULT_ENVIRONMENT)];
invariant(environment, `Environment is not supported, got ${envArg}.`);
const version = getArgOrDefault(versionArg, environment.defaultVersion);
invariant(version && VERSION_PATTERN.test(version), `No version provided or version did not match Semantic Versioning, expected: #.#.#-tag.# or #.#.#, got ${version}.`);
const tag = getArgOrDefault(tagArg, environment.defaultTag(version));
const graph = readCachedProjectGraph();
const project = graph.nodes[name];
invariant(project, `Could not find project "${name}" in the workspace. Is the project.json configured correctly?`);
const outputPath = project.data.root + '/dist';
invariant(outputPath, `Could not find package folder of "${name}". Is project.json configured correctly?`);
process.chdir(outputPath);
let packageName;
// Updating the version in "package.json" before publishing
try {
const json = JSON.parse(readFileSync('package.json').toString());
packageName = json.name;
json.version = version;
writeFileSync('package.json', JSON.stringify(json, null, 4));
} catch (e) {
console.error(chalk.bold.red('Error reading package.json file from library build output.'));
exit(1);
}
if (environment.overwrite) {
try {
execSync(`npm unpublish --force ${packageName}@${version} --registry ${environment.registry}`);
} catch (e) {
console.warn('Could not unpublish');
}
}
execSync(`npm publish --tag ${tag} --registry ${environment.registry}`);