@teambit/pkg 1.0.108 → 1.0.110

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/publisher.ts DELETED
@@ -1,153 +0,0 @@
1
- import { ComponentResult, TaskMetadata } from '@teambit/builder';
2
- import { Component, ComponentID } from '@teambit/component';
3
- import { Capsule, IsolatorMain } from '@teambit/isolator';
4
- import { Logger } from '@teambit/logger';
5
- import { Workspace } from '@teambit/workspace';
6
- import { ComponentIdList } from '@teambit/component-id';
7
- import { ExtensionDataList } from '@teambit/legacy/dist/consumer/config/extension-data';
8
- import { BitError } from '@teambit/bit-error';
9
- import { Scope } from '@teambit/legacy/dist/scope';
10
- import fsx from 'fs-extra';
11
- import mapSeries from 'p-map-series';
12
- import execa from 'execa';
13
- import { PkgAspect } from './pkg.aspect';
14
- import { PkgExtensionConfig } from './pkg.main.runtime';
15
-
16
- export type PublisherOptions = {
17
- dryRun?: boolean;
18
- allowStaged?: boolean;
19
- };
20
-
21
- export class Publisher {
22
- packageManager = 'npm'; // @todo: decide if this is mandatory or using the workspace settings
23
- constructor(
24
- private isolator: IsolatorMain,
25
- private logger: Logger,
26
- private scope: Scope,
27
- private workspace: Workspace,
28
- public options: PublisherOptions = {}
29
- ) {}
30
-
31
- async publish(componentPattern: string, options: PublisherOptions): Promise<ComponentResult[]> {
32
- const componentIds = await this.workspace.idsByPattern(componentPattern);
33
- this.options = options;
34
- const capsules = await this.getComponentCapsules(componentIds);
35
- // const capsules = await this.getComponentCapsulesFromScope(componentIds);
36
- return this.publishMultipleCapsules(capsules);
37
- }
38
-
39
- public async publishMultipleCapsules(capsules: Capsule[]): Promise<ComponentResult[]> {
40
- const description = `publish components${this.options.dryRun ? ' (dry-run)' : ''}`;
41
- const longProcessLogger = this.logger.createLongProcessLogger(description, capsules.length);
42
- const results = mapSeries(capsules, (capsule) => {
43
- longProcessLogger.logProgress(capsule.component.id.toString());
44
- return this.publishOneCapsule(capsule);
45
- });
46
- longProcessLogger.end();
47
- return results;
48
- }
49
-
50
- private async publishOneCapsule(capsule: Capsule): Promise<ComponentResult> {
51
- const startTime = Date.now();
52
- const publishParams = ['publish'];
53
- if (this.options.dryRun) publishParams.push('--dry-run');
54
- publishParams.push(...this.getTagFlagForPreRelease(capsule.component.id));
55
- const extraArgs = this.getExtraArgsFromConfig(capsule.component);
56
- if (extraArgs && Array.isArray(extraArgs) && extraArgs?.length) {
57
- const extraArgsSplit = extraArgs.map((arg) => arg.split(' ')).flat();
58
- publishParams.push(...extraArgsSplit);
59
- }
60
- const publishParamsStr = publishParams.join(' ');
61
- const cwd = capsule.path;
62
- const componentIdStr = capsule.id.toString();
63
- const errors: string[] = [];
64
- let metadata: TaskMetadata = {};
65
- try {
66
- this.logger.off();
67
- // @todo: once capsule.exec works properly, replace this
68
- // It is important to use stdio: 'inherit' so when npm asks for the OTP, the user can enter it
69
- await execa(this.packageManager, publishParams, { cwd, stdio: 'inherit' });
70
- this.logger.on();
71
- this.logger.debug(`${componentIdStr}, successfully ran ${this.packageManager} ${publishParamsStr} at ${cwd}`);
72
- const pkg = await fsx.readJSON(`${capsule.path}/package.json`);
73
- metadata = this.options.dryRun ? {} : { publishedPackage: `${pkg.name}@${pkg.version}` };
74
- } catch (err: any) {
75
- const errorMsg = `failed running ${this.packageManager} ${publishParamsStr} at ${cwd}`;
76
- this.logger.error(`${componentIdStr}, ${errorMsg}`);
77
- errors.push(errorMsg);
78
- }
79
- const component = capsule.component;
80
- return { component, metadata, errors, startTime, endTime: Date.now() };
81
- }
82
-
83
- private getTagFlagForPreRelease(id: ComponentID): string[] {
84
- const preReleaseData = id.getVersionPreReleaseData();
85
- if (!preReleaseData) return [];
86
- const maybeIdentifier = preReleaseData[0]; // it can be numeric as in 1.0.0-0.
87
- if (typeof maybeIdentifier !== 'string') return [];
88
- return ['--tag', maybeIdentifier];
89
- }
90
-
91
- private async getComponentCapsules(componentIds: ComponentID[]): Promise<Capsule[]> {
92
- const idsToPublish = await this.getIdsToPublish(componentIds);
93
- this.logger.debug(`total ${idsToPublish.length} to publish out of ${componentIds.length}`);
94
- const componentIdsToPublish = await this.workspace.resolveMultipleComponentIds(idsToPublish);
95
- const network = await this.isolator.isolateComponents(componentIdsToPublish, {
96
- packageManagerConfigRootDir: this.workspace.path,
97
- });
98
- return network.seedersCapsules;
99
- }
100
-
101
- /**
102
- * only components that use pkg extension and configure "publishConfig" with their own registry
103
- * or custom "name", should be published. ignore the rest.
104
- */
105
- private async getIdsToPublish(componentIds: ComponentID[]): Promise<string[]> {
106
- await this.throwForNonStagedOrTaggedComponents(componentIds);
107
- const ids = ComponentIdList.fromArray(componentIds);
108
- const components = await this.scope.getComponentsAndVersions(ids, true);
109
- return components
110
- .filter((c) => this.shouldPublish(c.version.extensions))
111
- .map((c) => c.component.toComponentId().changeVersion(c.versionStr).toString());
112
- }
113
-
114
- // TODO: consider using isPublishedToExternalRegistry from pkg.main.runtime (need to send it a component not extensions)
115
- public shouldPublish(extensions: ExtensionDataList): boolean {
116
- const pkgExt = extensions.findExtension(PkgAspect.id);
117
- if (!pkgExt) return false;
118
- const config = pkgExt.config as PkgExtensionConfig;
119
- if (config?.avoidPublishToNPM) return false;
120
- return config?.packageJson?.name || config?.packageJson?.publishConfig;
121
- }
122
-
123
- private getExtraArgsFromConfig(component: Component): string | undefined {
124
- const pkgExt = component.config.extensions.findExtension(PkgAspect.id);
125
- return pkgExt?.config?.packageManagerPublishArgs;
126
- }
127
-
128
- private async throwForNonStagedOrTaggedComponents(componentIds: ComponentID[]) {
129
- const idsWithoutScope = componentIds.filter((id) => !this.scope.isExported(id));
130
- if (!idsWithoutScope.length) return;
131
- if (!this.options.allowStaged && !this.options.dryRun) {
132
- throw new BitError(
133
- `unable to publish the following component(s), please make sure they are exported: ${idsWithoutScope.join(
134
- ', '
135
- )}`
136
- );
137
- }
138
- const missingFromScope: ComponentID[] = [];
139
- await Promise.all(
140
- idsWithoutScope.map(async (id) => {
141
- const inScope = await this.scope.isComponentInScope(id);
142
- if (!inScope) {
143
- missingFromScope.push(id);
144
- }
145
- })
146
- );
147
- if (missingFromScope.length) {
148
- throw new BitError(
149
- `unable to publish the following component(s), please make sure they are tagged: ${missingFromScope.join(', ')}`
150
- );
151
- }
152
- }
153
- }
@@ -1,20 +0,0 @@
1
- import { join } from 'path';
2
- import fs from 'fs-extra';
3
- import { EnvsMain, PackageEnv } from '@teambit/envs';
4
- import { Capsule, CAPSULE_READY_FILE } from '@teambit/isolator';
5
- import { DEFAULT_TAR_DIR_IN_CAPSULE } from './packer';
6
-
7
- const DEFAULT_NPM_IGNORE_ENTRIES = [`${DEFAULT_TAR_DIR_IN_CAPSULE}/`, CAPSULE_READY_FILE];
8
-
9
- export async function writeNpmIgnore(capsule: Capsule, envs: EnvsMain): Promise<void> {
10
- const env = envs.getEnv(capsule.component).env as PackageEnv;
11
- const envIgnoreEntries = env.getNpmIgnore?.({ component: capsule.component, capsule });
12
- const npmIgnoreEntries = DEFAULT_NPM_IGNORE_ENTRIES.concat(envIgnoreEntries || []);
13
- if (!npmIgnoreEntries || !npmIgnoreEntries.length) {
14
- return;
15
- }
16
- const NPM_IGNORE_FILE = '.npmignore';
17
- const npmIgnorePath = join(capsule.path, NPM_IGNORE_FILE);
18
- const npmIgnoreEntriesStr = `\n${npmIgnoreEntries.join('\n')}`;
19
- await fs.appendFile(npmIgnorePath, npmIgnoreEntriesStr);
20
- }