@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.
@@ -1,496 +0,0 @@
1
- import { compact, omit } from 'lodash';
2
- import { join } from 'path';
3
- import fs from 'fs-extra';
4
- import { CLIAspect, CLIMain, MainRuntime } from '@teambit/cli';
5
- import ComponentAspect, { Component, ComponentMain, IComponent, Snap } from '@teambit/component';
6
- import { EnvsAspect, EnvsMain } from '@teambit/envs';
7
- import { Slot, SlotRegistry } from '@teambit/harmony';
8
- import { IsolatorAspect, IsolatorMain } from '@teambit/isolator';
9
- import { LoggerAspect, LoggerMain, Logger } from '@teambit/logger';
10
- import { ScopeAspect, ScopeMain } from '@teambit/scope';
11
- import { Workspace, WorkspaceAspect } from '@teambit/workspace';
12
- import { PackageJsonTransformer } from '@teambit/workspace.modules.node-modules-linker';
13
- import { BuilderMain, BuilderAspect } from '@teambit/builder';
14
- import { BitError } from '@teambit/bit-error';
15
- import { snapToSemver } from '@teambit/component-package-version';
16
- import { IssuesClasses } from '@teambit/component-issues';
17
- import { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';
18
- import { GraphqlMain, GraphqlAspect } from '@teambit/graphql';
19
- import { DependencyResolverAspect, DependencyResolverMain } from '@teambit/dependency-resolver';
20
- import { getMaxSizeForComponents, InMemoryCache } from '@teambit/legacy/dist/cache/in-memory-cache';
21
- import { createInMemoryCache } from '@teambit/legacy/dist/cache/cache-factory';
22
- import { Packer, PackOptions, PackResult, TAR_FILE_ARTIFACT_NAME } from './packer';
23
- // import { BitCli as CLI, BitCliExt as CLIExtension } from '@teambit/cli';
24
- import { PackCmd } from './pack.cmd';
25
- import { PkgAspect } from './pkg.aspect';
26
- import { PreparePackagesTask } from './prepare-packages.task';
27
- import { PublishCmd } from './publish.cmd';
28
- import { Publisher } from './publisher';
29
- import { PublishTask } from './publish.task';
30
- import { PackageTarFiletNotFound, PkgArtifactNotFound } from './exceptions';
31
- import { PkgArtifact } from './pkg-artifact';
32
- import { PackageRoute, routePath } from './package.route';
33
- import { PackageDependencyFactory } from './package-dependency';
34
- import { pkgSchema } from './pkg.graphql';
35
- import { PackageFragment } from './package.fragment';
36
- import { PackTask } from './pack.task';
37
- import { PkgService } from './pkg.service';
38
-
39
- export interface PackageJsonProps {
40
- [key: string]: any;
41
- }
42
-
43
- export type PackageJsonPropsRegistry = SlotRegistry<PackageJsonProps>;
44
-
45
- export type PkgExtensionConfig = {
46
- packageManagerPublishArgs?: string[];
47
- packageJson?: Record<string, any>;
48
- avoidPublishToNPM?: boolean; // by default, if packageJson.name or packageJson.publishConfig are set, it publish to npm.
49
- };
50
-
51
- type GetModulePathOptions = { absPath?: boolean };
52
-
53
- /**
54
- * Config for variants
55
- */
56
- export type ComponentPkgExtensionConfig = {
57
- /**
58
- * properties to add to the package.json of the component.
59
- */
60
- packageJson: Record<string, any>;
61
- };
62
-
63
- /**
64
- * Data stored in the component
65
- */
66
- export type ComponentPkgExtensionData = {
67
- /**
68
- * properties to add to the package.json of the component.
69
- */
70
- packageJsonModification: Record<string, any>;
71
-
72
- /**
73
- * Final package.json after creating tar file
74
- */
75
- pkgJson?: Record<string, any>;
76
-
77
- /**
78
- * integrity of the tar file
79
- */
80
- integrity?: string;
81
-
82
- /**
83
- * Checksum of the tar file
84
- */
85
- checksum?: string;
86
- };
87
-
88
- export type ComponentPackageManifest = {
89
- name: string;
90
- distTags: Record<string, string>;
91
- externalRegistry: boolean;
92
- versions: VersionPackageManifest[];
93
- };
94
-
95
- export type VersionPackageManifest = {
96
- [key: string]: any;
97
- dist: {
98
- tarball: string;
99
- shasum: string;
100
- };
101
- };
102
-
103
- export class PkgMain {
104
- static runtime = MainRuntime;
105
- static dependencies = [
106
- CLIAspect,
107
- ScopeAspect,
108
- EnvsAspect,
109
- IsolatorAspect,
110
- LoggerAspect,
111
- WorkspaceAspect,
112
- BuilderAspect,
113
- DependencyResolverAspect,
114
- ComponentAspect,
115
- GraphqlAspect,
116
- ];
117
- static slots = [Slot.withType<PackageJsonProps>()];
118
- static defaultConfig = {};
119
-
120
- static async provider(
121
- [cli, scope, envs, isolator, logger, workspace, builder, dependencyResolver, componentAspect, graphql]: [
122
- CLIMain,
123
- ScopeMain,
124
- EnvsMain,
125
- IsolatorMain,
126
- LoggerMain,
127
- Workspace,
128
- BuilderMain,
129
- DependencyResolverMain,
130
- ComponentMain,
131
- GraphqlMain
132
- ],
133
- config: PkgExtensionConfig,
134
- [packageJsonPropsRegistry]: [PackageJsonPropsRegistry]
135
- ) {
136
- const logPublisher = logger.createLogger(PkgAspect.id);
137
- const host = componentAspect.getHost();
138
- const packer = new Packer(isolator, logPublisher, host, scope);
139
- const publisher = new Publisher(isolator, logPublisher, scope?.legacyScope, workspace);
140
- const publishTask = new PublishTask(PkgAspect.id, publisher, logPublisher);
141
- const packTask = new PackTask(PkgAspect.id, packer, logPublisher);
142
- const pkg = new PkgMain(
143
- logPublisher,
144
- config,
145
- packageJsonPropsRegistry,
146
- workspace,
147
- scope,
148
- builder,
149
- packer,
150
- envs,
151
- componentAspect,
152
- publishTask,
153
- dependencyResolver
154
- );
155
-
156
- componentAspect.registerShowFragments([new PackageFragment(pkg)]);
157
- dependencyResolver.registerDependencyFactories([new PackageDependencyFactory()]);
158
-
159
- graphql.register(pkgSchema(pkg));
160
- envs.registerService(new PkgService());
161
-
162
- componentAspect.registerRoute([new PackageRoute(pkg)]);
163
-
164
- // we ended up not using the publish-dry-run task. It used to run "npm publish --dry-run"
165
- // and also "npm pack --dry-run", but it's not that useful and it takes long to complete.
166
- // we might revise our decision later.
167
- // const dryRunTask = new PublishDryRunTask(PkgAspect.id, publisher, packer, logPublisher);
168
- const preparePackagesTask = new PreparePackagesTask(PkgAspect.id, logPublisher, envs);
169
- // dryRunTask.dependencies = [BuildTaskHelper.serializeId(preparePackagesTask)];
170
- builder.registerBuildTasks([preparePackagesTask]);
171
- builder.registerTagTasks([packTask, publishTask]);
172
- builder.registerSnapTasks([packTask]);
173
-
174
- const calcPkgOnLoad = async (component: Component) => {
175
- const data = await pkg.mergePackageJsonProps(component);
176
- return {
177
- packageJsonModification: data,
178
- };
179
- };
180
-
181
- if (workspace) {
182
- // workspace.onComponentLoad(pkg.mergePackageJsonProps.bind(pkg));
183
- workspace.registerOnComponentLoad(async (component) => {
184
- await pkg.addMissingLinksFromNodeModulesIssue(component);
185
- return calcPkgOnLoad(component);
186
- });
187
- }
188
- if (scope) {
189
- scope.registerOnCompAspectReCalc(calcPkgOnLoad);
190
- }
191
-
192
- PackageJsonTransformer.registerPackageJsonTransformer(pkg.transformPackageJson.bind(pkg));
193
- // TODO: consider passing the pkg instead of packer
194
- cli.register(new PackCmd(packer), new PublishCmd(publisher));
195
- return pkg;
196
- }
197
-
198
- /**
199
- * get the package name of a component.
200
- */
201
- getPackageName(component: Component) {
202
- return this.dependencyResolver.getPackageName(component);
203
- }
204
-
205
- /*
206
- * Returns the location where the component is installed with its peer dependencies
207
- * This is used in cases you want to actually run the components and make sure all the dependencies (especially peers) are resolved correctly
208
- */
209
- getRuntimeModulePath(component: Component, options: GetModulePathOptions = {}) {
210
- const relativePath = this.dependencyResolver.getRuntimeModulePath(component);
211
- if (options?.absPath) {
212
- if (this.workspace) {
213
- return join(this.workspace.path, relativePath);
214
- }
215
- throw new Error('getModulePath with abs path option is not implemented for scope');
216
- }
217
- return relativePath;
218
- }
219
-
220
- /**
221
- * returns the package path in the /node_modules/ folder
222
- * In case you call this in order to run the code from the path, please refer to the `getRuntimeModulePath` API
223
- */
224
- getModulePath(component: Component, options: GetModulePathOptions = {}) {
225
- const relativePath = this.dependencyResolver.getModulePath(component);
226
- if (options?.absPath) {
227
- if (this.workspace) {
228
- return join(this.workspace.path, relativePath);
229
- }
230
- throw new Error('getModulePath with abs path option is not implemented for scope');
231
- }
232
- return relativePath;
233
- }
234
-
235
- isModulePathExists(component: Component): boolean {
236
- const packageDir = this.getModulePath(component, { absPath: true });
237
- return fs.existsSync(packageDir);
238
- }
239
-
240
- async addMissingLinksFromNodeModulesIssue(component: Component) {
241
- const exist = this.isModulePathExists(component);
242
- if (!exist) {
243
- component.state.issues.getOrCreate(IssuesClasses.MissingLinksFromNodeModulesToSrc).data = true;
244
- }
245
- // we don't want to add any data to the compiler aspect, only to add issues on the component
246
- return undefined;
247
- }
248
-
249
- private manifestCache: InMemoryCache<{ head: string; manifest: VersionPackageManifest[] }>; // cache components manifests
250
- constructor(
251
- /**
252
- * logger extension
253
- */
254
- readonly logger: Logger,
255
- /**
256
- * pkg extension configuration.
257
- */
258
- readonly config: PkgExtensionConfig,
259
-
260
- /**
261
- * Registry for changes by other extensions.
262
- */
263
- private packageJsonPropsRegistry: PackageJsonPropsRegistry,
264
-
265
- private workspace: Workspace,
266
- private scope: ScopeMain,
267
-
268
- private builder: BuilderMain,
269
- /**
270
- * A utils class to packing components into tarball
271
- */
272
- private packer: Packer,
273
-
274
- /**
275
- * envs extension.
276
- */
277
- private envs: EnvsMain,
278
-
279
- private componentAspect: ComponentMain,
280
-
281
- /**
282
- * keep it as public. external env might want to register it to the snap pipeline
283
- */
284
- public publishTask: PublishTask,
285
-
286
- private dependencyResolver: DependencyResolverMain
287
- ) {
288
- this.manifestCache = createInMemoryCache({ maxSize: getMaxSizeForComponents() });
289
- }
290
-
291
- /**
292
- * register changes in the package.json
293
- */
294
- registerPackageJsonNewProps(props: PackageJsonProps): void {
295
- return this.packageJsonPropsRegistry.register(props);
296
- }
297
-
298
- /**
299
- * Pack a component and generate a tarball suitable for npm registry
300
- *
301
- * @param {string} componentId
302
- * @param {(string | undefined)} scopePath
303
- * @param {string} outDir
304
- * @param {boolean} [prefix=false]
305
- * @param {boolean} [override=false]
306
- * @param {boolean} [keep=false]
307
- * @returns {Promise<PackResult>}
308
- * @memberof PkgExtension
309
- */
310
- async packComponent(componentId: string, scopePath: string | undefined, options: PackOptions): Promise<PackResult> {
311
- return this.packer.packComponent(componentId, scopePath, options);
312
- }
313
-
314
- /**
315
- * Merge the configs provided by:
316
- * 1. envs configured in the component - via getPackageJsonProps method
317
- * 2. extensions that registered to the registerPackageJsonNewProps slot (and configured for the component)
318
- * 3. props defined by the user (they are the strongest one)
319
- */
320
- async mergePackageJsonProps(component: Component): Promise<PackageJsonProps> {
321
- let newProps: PackageJsonProps = {};
322
- const mergeToNewProps = (otherProps: PackageJsonProps) => {
323
- const files = [...(newProps.files || []), ...(otherProps.files || [])];
324
- const merged = { ...newProps, ...otherProps };
325
- if (files.length) merged.files = files;
326
- return merged;
327
- };
328
- const env = this.envs.calculateEnv(component, { skipWarnings: !!this.workspace?.inInstallContext })?.env;
329
- if (env?.getPackageJsonProps && typeof env.getPackageJsonProps === 'function') {
330
- const propsFromEnv = env.getPackageJsonProps();
331
- newProps = mergeToNewProps(propsFromEnv);
332
- }
333
-
334
- const configuredIds = component.state.aspects.ids;
335
- configuredIds.forEach((extId) => {
336
- // Only get props from configured extensions on this specific component
337
- const props = this.packageJsonPropsRegistry.get(extId);
338
- if (props) {
339
- newProps = mergeToNewProps(props);
340
- }
341
- });
342
-
343
- const currentExtension = component.state.aspects.get(PkgAspect.id);
344
- const currentConfig = currentExtension?.config as unknown as ComponentPkgExtensionConfig;
345
- if (currentConfig && currentConfig.packageJson) {
346
- newProps = mergeToNewProps(currentConfig.packageJson);
347
- }
348
- // Keys not allowed to override
349
- const specialKeys = ['extensions', 'dependencies', 'devDependencies', 'peerDependencies'];
350
- return omit(newProps, specialKeys);
351
- }
352
-
353
- getPackageJsonModifications(component: Component): Record<string, any> {
354
- const currentExtension = component.state.aspects.get(PkgAspect.id);
355
- const currentData = currentExtension?.data as unknown as ComponentPkgExtensionData;
356
- return currentData?.packageJsonModification ?? {};
357
- }
358
-
359
- async getPkgArtifact(component: Component): Promise<PkgArtifact> {
360
- const artifacts = await this.builder.getArtifactsVinylByAspect(component, PkgAspect.id);
361
- if (!artifacts.length) throw new PkgArtifactNotFound(component.id);
362
-
363
- return new PkgArtifact(artifacts);
364
- }
365
-
366
- async getManifest(component: Component): Promise<ComponentPackageManifest> {
367
- const name = this.getPackageName(component);
368
- const latestVersion = component.latest;
369
- if (!latestVersion) {
370
- throw new BitError('can not get manifest for component without versions');
371
- }
372
- const preReleaseLatestTags = component.tags.getPreReleaseLatestTags();
373
- const latest = snapToSemver(latestVersion);
374
- const distTags = {
375
- latest,
376
- ...preReleaseLatestTags,
377
- };
378
- const versionsFromCache = this.manifestCache.get(name);
379
- const getVersions = async (): Promise<VersionPackageManifest[]> => {
380
- const headHash = component.head?.hash;
381
- if (!headHash) throw new BitError(`unable to get manifest for "${name}", the head is empty`);
382
- if (versionsFromCache) {
383
- if (versionsFromCache.head !== headHash) this.manifestCache.delete(name);
384
- else {
385
- return versionsFromCache.manifest;
386
- }
387
- }
388
- const versions = await this.getAllSnapsManifests(component);
389
- const versionsWithoutEmpty = compact(versions);
390
- this.manifestCache.set(name, { head: headHash, manifest: versionsWithoutEmpty });
391
- return versionsWithoutEmpty;
392
- };
393
-
394
- const versions = await getVersions();
395
- const externalRegistry = this.isPublishedToExternalRegistry(component);
396
- return {
397
- name,
398
- distTags,
399
- externalRegistry,
400
- versions,
401
- };
402
- }
403
-
404
- private async getAllSnapsManifests(component: Component): Promise<VersionPackageManifest[]> {
405
- const iterable = component.snapsIterable();
406
- const result: VersionPackageManifest[] = [];
407
- for await (const snap of iterable) {
408
- const manifest = await this.getSnapManifest(component, snap);
409
- if (manifest) {
410
- result.push(manifest);
411
- }
412
- }
413
- return result;
414
- }
415
-
416
- /**
417
- * Check if the component should be fetched from bit registry or from another registry
418
- * This will usually determined by the latest version of the component
419
- * @param component
420
- */
421
- isPublishedToExternalRegistry(component: IComponent): boolean {
422
- const pkgExt = component.get(PkgAspect.id);
423
- // By default publish to bit registry
424
- if (!pkgExt) return false;
425
- return !!(pkgExt.config?.packageJson?.name || pkgExt.config?.packageJson?.publishConfig);
426
- }
427
-
428
- private getComponentBuildData(component: Component): ComponentPkgExtensionData | undefined {
429
- const data = this.builder.getDataByAspect(component, PkgAspect.id);
430
- if (data) return data as ComponentPkgExtensionData;
431
- // backward compatibility. the data used to be saved on the pkg aspect rather than on the
432
- // builder aspect
433
- const currentExtension = component.state.aspects.get(PkgAspect.id);
434
- return currentExtension?.data as ComponentPkgExtensionData | undefined;
435
- }
436
-
437
- async getSnapManifest(component: Component, snap: Snap): Promise<VersionPackageManifest | undefined> {
438
- const idWithCorrectVersion = component.id.changeVersion(snap.hash);
439
-
440
- // @todo: this is a hack. see below the right way to do it.
441
- const version = await this.scope.legacyScope.getVersionInstance(idWithCorrectVersion);
442
- const builderData = version.extensions.findCoreExtension(BuilderAspect.id)?.data?.aspectsData;
443
- const currentData = builderData?.find((a) => a.aspectId === PkgAspect.id)?.data;
444
-
445
- // @todo: this is the proper way to communicate with the builder aspect. however, getting
446
- // the entire Component for each one of the snaps is terrible in terms of the performance.
447
-
448
- // const updatedComponent = await this.componentAspect.getHost().get(idWithCorrectVersion, true);
449
- // if (!updatedComponent) {
450
- // throw new BitError(`snap ${snap.hash} for component ${component.id.toString()} is missing`);
451
- // }
452
- // const currentData = this.getComponentBuildData(updatedComponent);
453
-
454
- // If for some reason the version has no package.json manifest, return undefined
455
- if (!currentData?.pkgJson) {
456
- return undefined;
457
- }
458
- const pkgJson = currentData?.pkgJson ?? {};
459
- const checksum = currentData?.checksum;
460
- if (!checksum) {
461
- this.logger.error(`checksum for ${component.id.toString()} is missing`);
462
- return undefined;
463
- }
464
- const dist = {
465
- shasum: checksum,
466
- tarball: this.componentAspect.getRoute(idWithCorrectVersion, routePath),
467
- };
468
-
469
- const manifest = {
470
- ...pkgJson,
471
- dist,
472
- };
473
- return manifest;
474
- }
475
-
476
- async getPackageTarFile(component: Component): Promise<AbstractVinyl> {
477
- const artifacts = await this.builder.getArtifactsVinylByAspectAndName(
478
- component,
479
- PkgAspect.id,
480
- TAR_FILE_ARTIFACT_NAME
481
- );
482
- if (!artifacts.length) throw new PackageTarFiletNotFound(component.id);
483
-
484
- return artifacts[0];
485
- }
486
-
487
- async transformPackageJson(
488
- component: Component,
489
- packageJsonObject: Record<string, any>
490
- ): Promise<Record<string, any>> {
491
- const newProps = this.getPackageJsonModifications(component);
492
- return Object.assign(packageJsonObject, newProps);
493
- }
494
- }
495
-
496
- PkgAspect.addRuntime(PkgMain);
@@ -1,85 +0,0 @@
1
- import { BuildContext, BuiltTaskResult, BuildTask } from '@teambit/builder';
2
- import { Compiler } from '@teambit/compiler';
3
- import { Capsule } from '@teambit/isolator';
4
- import { EnvsMain } from '@teambit/envs';
5
- import { Logger } from '@teambit/logger';
6
- import PackageJsonFile from '@teambit/legacy/dist/consumer/component/package-json-file';
7
- import fs from 'fs-extra';
8
- import path from 'path';
9
- import { writeNpmIgnore } from './write-npm-ignore';
10
-
11
- /**
12
- * prepare packages for publishing.
13
- */
14
- export class PreparePackagesTask implements BuildTask {
15
- readonly name = 'PreparePackages';
16
- readonly location = 'end';
17
- constructor(readonly aspectId: string, private logger: Logger, private envs: EnvsMain) {}
18
-
19
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
20
- async execute(context: BuildContext): Promise<BuiltTaskResult> {
21
- await this.writeNpmIgnoreFile(context);
22
- const result = {
23
- componentsResults: [],
24
- };
25
-
26
- return result;
27
- }
28
-
29
- private async writeNpmIgnoreFile(context: BuildContext) {
30
- await Promise.all(
31
- context.capsuleNetwork.seedersCapsules.map(async (capsule) => {
32
- await writeNpmIgnore(capsule, this.envs);
33
- })
34
- );
35
- }
36
-
37
- /**
38
- * remove the source files and copy the dists files
39
- * into the root of the capsule.
40
- * this is needed when components import from other components internal paths. without this task,
41
- * the internal paths are the source, so node will throw an error when trying to use them. this
42
- * task makes sure that the internal paths point to the consumable code (dists).
43
- */
44
- private async executeDistAsRootTask(context: BuildContext) {
45
- if (!context.env.getCompiler) return;
46
- const compilerInstance: Compiler = context.env.getCompiler();
47
- const distDir = compilerInstance.distDir;
48
-
49
- await Promise.all(
50
- context.capsuleNetwork.graphCapsules.map(async (capsule) => {
51
- await this.removeSourceFiles(capsule, distDir);
52
- await this.moveDistToRoot(capsule, distDir);
53
- await this.updatePackageJson(capsule, compilerInstance, distDir);
54
- })
55
- );
56
- }
57
-
58
- private async removeSourceFiles(capsule: Capsule, distDir: string) {
59
- const excludeDirs = [distDir, 'node_modules', 'public', 'bin'].map((dir) => `${dir}/**`);
60
- const excludeFiles = ['package.json'];
61
- const allFiles = capsule.getAllFilesPaths('.', { ignore: [...excludeDirs, ...excludeFiles] });
62
- this.logger.debug(`delete the following files:\n${allFiles.join('\n')}`);
63
- await Promise.all(allFiles.map((file) => fs.remove(path.join(capsule.path, file))));
64
- }
65
-
66
- private async moveDistToRoot(capsule: Capsule, distDir: string) {
67
- const from = path.join(capsule.path, distDir);
68
- const to = capsule.path;
69
- this.logger.debug(`move from ${from} to: ${to}`);
70
- // for some reason `fs.move` throws an error "dest already exists.".
71
- fs.moveSync(from, to);
72
- }
73
-
74
- /**
75
- * by default, the "main" prop points to the dist file (e.g. "dist/index./js").
76
- * here, we have to change it because there is no dist dir anymore.
77
- */
78
- private async updatePackageJson(capsule: Capsule, compiler: Compiler, distDir: string) {
79
- const distMainFile = compiler.getDistPathBySrcPath(capsule.component.state._consumer.mainFile);
80
- const distMainFileWithoutDistDir = distMainFile.replace(`${distDir}${path.sep}`, '');
81
- const packageJson = PackageJsonFile.loadFromCapsuleSync(capsule.path);
82
- packageJson.addOrUpdateProperty('main', distMainFileWithoutDistDir);
83
- await packageJson.write();
84
- }
85
- }
@@ -1,44 +0,0 @@
1
- import { BuildContext, BuiltTaskResult, BuildTask } from '@teambit/builder';
2
- import { Logger } from '@teambit/logger';
3
- import { Capsule } from '@teambit/isolator';
4
- import { Publisher } from './publisher';
5
- import { Packer } from './packer';
6
-
7
- /**
8
- * publish build task is running "publish --dry-run" to avoid later npm errors during export
9
- */
10
- export class PublishDryRunTask implements BuildTask {
11
- readonly name = 'PublishDryRun';
12
- readonly location = 'end';
13
- dependencies: string[];
14
- constructor(
15
- readonly aspectId: string,
16
- private publisher: Publisher,
17
- private packer: Packer,
18
- private logger: Logger
19
- ) {}
20
-
21
- async execute(context: BuildContext): Promise<BuiltTaskResult> {
22
- this.publisher.options.dryRun = true;
23
- const capsules = context.capsuleNetwork.seedersCapsules;
24
- // const capsulesToPublish = capsules.filter((c) => this.publisher.shouldPublish(c.component.config.extensions));
25
- const capsulesToPublish: Capsule[] = [];
26
- capsules.forEach((c) => {
27
- const shouldPublish = this.publisher.shouldPublish(c.component.config.extensions);
28
- if (shouldPublish) {
29
- capsulesToPublish.push(c);
30
- }
31
- });
32
- this.logger.info(`going to run publish dry-run on ${capsulesToPublish.length} out of ${capsules.length}`);
33
-
34
- const publishResults = await this.publisher.publishMultipleCapsules(capsulesToPublish);
35
-
36
- this.logger.info(`going to run pack dry-run on ${capsules.length} capsules`);
37
- const packResults = await this.packer.packMultipleCapsules(capsules, { override: true }, true, true);
38
-
39
- return {
40
- componentsResults: publishResults.concat(packResults),
41
- artifacts: [],
42
- };
43
- }
44
- }
package/publish.task.ts DELETED
@@ -1,33 +0,0 @@
1
- import { BuildContext, BuiltTaskResult, BuildTask, TaskLocation } from '@teambit/builder';
2
- import { Logger } from '@teambit/logger';
3
- import { Capsule } from '@teambit/isolator';
4
- import { Publisher } from './publisher';
5
-
6
- /**
7
- * publish components by running "npm publish"
8
- */
9
- export class PublishTask implements BuildTask {
10
- readonly name = 'PublishComponents';
11
- readonly location: TaskLocation = 'end';
12
- constructor(readonly aspectId: string, private publisher: Publisher, private logger: Logger) {}
13
-
14
- async execute(context: BuildContext): Promise<BuiltTaskResult> {
15
- this.publisher.options.dryRun = false;
16
- const capsules = context.capsuleNetwork.seedersCapsules;
17
- // const capsulesToPublish = capsules.filter((c) => this.publisher.shouldPublish(c.component.config.extensions));
18
- const capsulesToPublish: Capsule[] = [];
19
- capsules.forEach((c) => {
20
- const shouldPublish = this.publisher.shouldPublish(c.component.config.extensions);
21
- if (shouldPublish) {
22
- capsulesToPublish.push(c);
23
- }
24
- });
25
- this.logger.info(`going to run publish on ${capsulesToPublish.length} out of ${capsules.length}`);
26
- const publishResults = await this.publisher.publishMultipleCapsules(capsulesToPublish);
27
-
28
- return {
29
- componentsResults: publishResults,
30
- artifacts: [],
31
- };
32
- }
33
- }