_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/angular_devkit/architect/node/node-modules-architect-host.ts_10669_11819
async function getBuilder(builderPath: string): Promise<any> { switch (path.extname(builderPath)) { case '.mjs': // Load the ESM configuration file using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. return (await loadEsmModule<{ default: unknown }>(pathToFileURL(builderPath))).default; case '.cjs': return localRequire(builderPath); default: // The file could be either CommonJS or ESM. // CommonJS is tried first then ESM if loading fails. try { return localRequire(builderPath); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'ERR_REQUIRE_ESM') { // Load the ESM configuration file using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. return (await loadEsmModule<{ default: unknown }>(pathToFileURL(builderPath))).default; } throw e; } } }
{ "end_byte": 11819, "start_byte": 10669, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/node/node-modules-architect-host.ts" }
angular-cli/packages/angular_devkit/architect/node/jobs/job-registry_spec.ts_0_788
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { jobs } from '@angular-devkit/architect'; import * as path from 'path'; import { lastValueFrom } from 'rxjs'; import { NodeModuleJobRegistry } from './job-registry'; const root = path.join(__dirname, '../../../../../tests/angular_devkit/architect/node/jobs'); describe('NodeModuleJobScheduler', () => { it('works', async () => { const registry = new NodeModuleJobRegistry(); const scheduler = new jobs.SimpleScheduler(registry); const job = scheduler.schedule(path.join(root, 'add'), [1, 2, 3]); expect(await lastValueFrom(job.output)).toBe(6); }); });
{ "end_byte": 788, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/node/jobs/job-registry_spec.ts" }
angular-cli/packages/angular_devkit/architect/node/jobs/job-registry.ts_0_2086
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { jobs } from '@angular-devkit/architect'; import { JsonValue, schema } from '@angular-devkit/core'; import { Observable, of } from 'rxjs'; export class NodeModuleJobRegistry< MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue, > implements jobs.Registry<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT> { protected _resolve(name: string): string | null { try { return require.resolve(name); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') { return null; } throw e; } } /** * Get a job description for a named job. * * @param name The name of the job. * @returns A description, or null if the job is not registered. */ get<A extends MinimumArgumentValueT, I extends MinimumInputValueT, O extends MinimumOutputValueT>( name: jobs.JobName, ): Observable<jobs.JobHandler<A, I, O> | null> { const [moduleName, exportName] = name.split(/#/, 2); const resolvedPath = this._resolve(moduleName); if (!resolvedPath) { return of(null); } const pkg = require(resolvedPath); const handler = pkg[exportName || 'default']; if (!handler) { return of(null); } function _getValue(...fields: unknown[]) { return fields.find((x) => schema.isJsonSchema(x)) || true; } const argument = _getValue(pkg.argument, handler.argument); const input = _getValue(pkg.input, handler.input); const output = _getValue(pkg.output, handler.output); const channels = _getValue(pkg.channels, handler.channels); return of( Object.assign(handler.bind(undefined), { jobDescription: { argument, input, output, channels, }, }), ); } }
{ "end_byte": 2086, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/node/jobs/job-registry.ts" }
angular-cli/packages/angular_devkit/architect/src/api_spec.ts_0_1867
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Target, targetFromTargetString, targetStringFromTarget } from './api'; describe('Architect API', () => { const goldens: { [t: string]: Target } = { 'a:b:c': { project: 'a', target: 'b', configuration: 'c' }, 'a:b': { project: 'a', target: 'b' }, ':b': { project: '', target: 'b' }, ':b:c': { project: '', target: 'b', configuration: 'c' }, ':': { project: '', target: '' }, '::': { project: '', target: '', configuration: '' }, 'a:b:': { project: 'a', target: 'b', configuration: '' }, 'a::c': { project: 'a', target: '', configuration: 'c' }, 'a:b:c:': { project: 'a', target: 'b', configuration: 'c' }, 'a:b:c:d': { project: 'a', target: 'b', configuration: 'c' }, 'a:b:c:d:': { project: 'a', target: 'b', configuration: 'c' }, }; describe('targetFromTargetString', () => { for (const ts of Object.getOwnPropertyNames(goldens)) { const t: Target = goldens[ts]; it(`works for ${JSON.stringify(ts)}`, () => { expect(targetFromTargetString(ts)).toEqual(t); }); } it('errors out for invalid strings', () => { expect(() => targetFromTargetString('')).toThrow(); expect(() => targetFromTargetString('a')).toThrow(); }); }); describe('targetStringFromTarget', () => { for (const ts of Object.getOwnPropertyNames(goldens)) { const t: Target = goldens[ts]; it(`works for ${JSON.stringify(t)}`, () => { // We have some invalid goldens. Remove everything after the second :. const goldenTs = ts.replace(/(\w+:\w+(:\w*)?).*/, '$1'); expect(targetStringFromTarget(t)).toEqual(goldenTs); }); } }); });
{ "end_byte": 1867, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/api_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/options_spec.ts_0_1361
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { mergeOptions } from './options'; describe('mergeOptions', () => { it('overwrites literal values', () => { expect( mergeOptions( { onlyBase: 'base', a: 'foo', b: 42, c: true, }, { onlyOverride: 'override', a: 'bar', b: 43, c: false, }, ), ).toEqual({ onlyBase: 'base', a: 'bar', b: 43, c: false, onlyOverride: 'override', }); }); it('merges object values one layer deep', () => { expect( mergeOptions( { obj: { nested: { fromBase: true, }, fromBase: true, overridden: false, }, }, { obj: { nested: { fromOverride: true, }, overridden: true, fromOverride: true, }, }, ), ).toEqual({ obj: { nested: { fromOverride: true, }, fromBase: true, overridden: true, fromOverride: true, }, }); }); });
{ "end_byte": 1361, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/options_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/create-builder.ts_0_8636
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { json, logging } from '@angular-devkit/core'; import { Observable, Subscription, defaultIfEmpty, firstValueFrom, from, isObservable, mergeMap, of, tap, throwError, } from 'rxjs'; import { BuilderContext, BuilderHandlerFn, BuilderInfo, BuilderInput, BuilderOutput, BuilderProgressState, ScheduleOptions, Target, TypedBuilderProgress, fromAsyncIterable, isBuilderOutput, targetStringFromTarget, } from './api'; import { Builder, BuilderSymbol, BuilderVersionSymbol } from './internal'; import { JobInboundMessageKind, createJobHandler } from './jobs'; import { scheduleByName, scheduleByTarget } from './schedule-by-name'; // eslint-disable-next-line max-lines-per-function export function createBuilder<OptT = json.JsonObject, OutT extends BuilderOutput = BuilderOutput>( fn: BuilderHandlerFn<OptT>, ): Builder<OptT & json.JsonObject> { const cjh = createJobHandler; // eslint-disable-next-line max-lines-per-function const handler = cjh<json.JsonObject, BuilderInput, OutT>((options, context) => { const scheduler = context.scheduler; const progressChannel = context.createChannel('progress'); const logChannel = context.createChannel('log'); const addTeardown = context.addTeardown.bind(context); let currentState: BuilderProgressState = BuilderProgressState.Stopped; let current = 0; let status = ''; let total = 1; function log(entry: logging.LogEntry) { logChannel.next(entry); } function progress(progress: TypedBuilderProgress, context: BuilderContext) { currentState = progress.state; if (progress.state === BuilderProgressState.Running) { current = progress.current; total = progress.total !== undefined ? progress.total : total; if (progress.status === undefined) { progress.status = status; } else { status = progress.status; } } progressChannel.next({ ...(progress as json.JsonObject), ...(context.target && { target: context.target }), ...(context.builder && { builder: context.builder }), id: context.id, }); } return new Observable<OutT>((observer) => { const subscriptions: Subscription[] = []; const inputSubscription = context.inboundBus.subscribe((i) => { switch (i.kind) { case JobInboundMessageKind.Input: onInput(i.value); break; } }); function onInput(i: BuilderInput) { const builder = i.info as BuilderInfo; const loggerName = i.target ? targetStringFromTarget(i.target as Target) : builder.builderName; const logger = new logging.Logger(loggerName); subscriptions.push(logger.subscribe((entry) => log(entry))); const context: BuilderContext = { builder, workspaceRoot: i.workspaceRoot, currentDirectory: i.currentDirectory, target: i.target as Target, logger: logger, id: i.id, async scheduleTarget( target: Target, overrides: json.JsonObject = {}, scheduleOptions: ScheduleOptions = {}, ) { const run = await scheduleByTarget(target, overrides, { scheduler, logger: scheduleOptions.logger || logger.createChild(''), workspaceRoot: i.workspaceRoot, currentDirectory: i.currentDirectory, }); // We don't want to subscribe errors and complete. subscriptions.push(run.progress.subscribe((event) => progressChannel.next(event))); return run; }, async scheduleBuilder( builderName: string, options: json.JsonObject = {}, scheduleOptions: ScheduleOptions = {}, ) { const run = await scheduleByName(builderName, options, { scheduler, target: scheduleOptions.target, logger: scheduleOptions.logger || logger.createChild(''), workspaceRoot: i.workspaceRoot, currentDirectory: i.currentDirectory, }); // We don't want to subscribe errors and complete. subscriptions.push(run.progress.subscribe((event) => progressChannel.next(event))); return run; }, async getTargetOptions(target: Target) { return firstValueFrom( scheduler.schedule<Target, json.JsonValue, json.JsonObject>( '..getTargetOptions', target, ).output, ); }, async getProjectMetadata(target: Target | string) { return firstValueFrom( scheduler.schedule<Target | string, json.JsonValue, json.JsonObject>( '..getProjectMetadata', target, ).output, ); }, async getBuilderNameForTarget(target: Target) { return firstValueFrom( scheduler.schedule<Target, json.JsonValue, string>( '..getBuilderNameForTarget', target, ).output, ); }, async validateOptions<T extends json.JsonObject = json.JsonObject>( options: json.JsonObject, builderName: string, ) { return firstValueFrom( scheduler.schedule<[string, json.JsonObject], json.JsonValue, T>( '..validateOptions', [builderName, options], ).output, ); }, reportRunning() { switch (currentState) { case BuilderProgressState.Waiting: case BuilderProgressState.Stopped: progress({ state: BuilderProgressState.Running, current: 0, total }, context); break; } }, reportStatus(status: string) { switch (currentState) { case BuilderProgressState.Running: progress({ state: currentState, status, current, total }, context); break; case BuilderProgressState.Waiting: progress({ state: currentState, status }, context); break; } }, reportProgress(current: number, total?: number, status?: string) { switch (currentState) { case BuilderProgressState.Running: progress({ state: currentState, current, total, status }, context); } }, addTeardown, }; context.reportRunning(); let result; try { result = fn(i.options as unknown as OptT, context); if (isBuilderOutput(result)) { result = of(result); } else if (!isObservable(result) && isAsyncIterable(result)) { result = fromAsyncIterable(result); } else { result = from(result); } } catch (e) { result = throwError(e); } // Manage some state automatically. progress({ state: BuilderProgressState.Running, current: 0, total: 1 }, context); subscriptions.push( result .pipe( defaultIfEmpty({ success: false } as unknown), tap(() => { progress({ state: BuilderProgressState.Running, current: total }, context); progress({ state: BuilderProgressState.Stopped }, context); }), mergeMap(async (value) => { // Allow the log queue to flush await new Promise<void>(setImmediate); return value; }), ) .subscribe( (message) => observer.next(message as OutT), (error) => observer.error(error), () => observer.complete(), ), ); } return () => { subscriptions.forEach((x) => x.unsubscribe()); inputSubscription.unsubscribe(); }; }); }); return { handler, [BuilderSymbol]: true, [BuilderVersionSymbol]: require('../package.json').version, }; } function isAsyncIterable<T>(obj: unknown): obj is AsyncIterable<T> { return !!obj && typeof (obj as AsyncIterable<T>)[Symbol.asyncIterator] === 'function'; }
{ "end_byte": 8636, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/create-builder.ts" }
angular-cli/packages/angular_devkit/architect/src/api.ts_0_4532
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { json, logging } from '@angular-devkit/core'; import { Observable, ObservableInput, Subscriber, from, switchMap } from 'rxjs'; import { Schema as RealBuilderInput, Target as RealTarget } from './input-schema'; import { Registry } from './jobs'; import { Schema as RealBuilderOutput } from './output-schema'; import { State as BuilderProgressState, Schema as RealBuilderProgress } from './progress-schema'; export type Target = json.JsonObject & RealTarget; export { BuilderProgressState }; // Type short hands. export type BuilderRegistry = Registry<json.JsonObject, BuilderInput, BuilderOutput>; /** * An API typed BuilderProgress. The interface generated from the schema is too permissive, * so this API is the one we show in our API. Please note that not all fields are in there; this * is in addition to fields in the schema. */ export type TypedBuilderProgress = | { state: BuilderProgressState.Stopped } | { state: BuilderProgressState.Error; error: json.JsonValue } | { state: BuilderProgressState.Waiting; status?: string } | { state: BuilderProgressState.Running; status?: string; current: number; total?: number }; /** * Declaration of those types as JsonObject compatible. JsonObject is not compatible with * optional members, so those wouldn't be directly assignable to our internal Json typings. * Forcing the type to be both a JsonObject and the type from the Schema tells Typescript they * are compatible (which they are). * These types should be used everywhere. */ export type BuilderInput = json.JsonObject & RealBuilderInput; export type BuilderOutput = json.JsonObject & RealBuilderOutput; export type BuilderProgress = json.JsonObject & RealBuilderProgress & TypedBuilderProgress; /** * A progress report is what the tooling will receive. It contains the builder info and the target. * Although these are serializable, they are only exposed through the tooling interface, not the * builder interface. The watch dog sends BuilderProgress and the Builder has a set of functions * to manage the state. */ export type BuilderProgressReport = BuilderProgress & { target?: Target; builder: BuilderInfo; }; /** * A Run, which is what is returned by scheduleBuilder or scheduleTarget functions. This should * be reconstructed across memory boundaries (it's not serializable but all internal information * are). */ export interface BuilderRun { /** * Unique amongst runs. This is the same ID as the context generated for the run. It can be * used to identify multiple unique runs. There is no guarantee that a run is a single output; * a builder can rebuild on its own and will generate multiple outputs. */ id: number; /** * The builder information. */ info: BuilderInfo; /** * The next output from a builder. This is recommended when scheduling a builder and only being * interested in the result of that single run, not of a watch-mode builder. */ result: Promise<BuilderOutput>; /** * The last output from a builder. This is recommended when scheduling a builder and only being * interested in the result of that last run. */ lastOutput: Promise<BuilderOutput>; /** * The output(s) from the builder. A builder can have multiple outputs. * This always replay the last output when subscribed. */ output: Observable<BuilderOutput>; /** * The progress report. A progress also contains an ID, which can be different than this run's * ID (if the builder calls scheduleBuilder or scheduleTarget). * This will always replay the last progress on new subscriptions. */ progress: Observable<BuilderProgressReport>; /** * Stop the builder from running. Returns a promise that resolves when the builder is stopped. * Some builders might not handle stopping properly and should have a timeout here. */ stop(): Promise<void>; } /** * Additional optional scheduling options. */ export interface ScheduleOptions { /** * Logger to pass to the builder. Note that messages will stop being forwarded, and if you want * to log a builder scheduled from your builder you should forward log events yourself. */ logger?: logging.Logger; /** * Target to pass to the builder. */ target?: Target; } /** * The context received as a second argument in your builder. */
{ "end_byte": 4532, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/api.ts" }
angular-cli/packages/angular_devkit/architect/src/api.ts_4533_13061
export interface BuilderContext { /** * Unique amongst contexts. Contexts instances are not guaranteed to be the same (but it could * be the same context), and all the fields in a context could be the same, yet the builder's * context could be different. This is the same ID as the corresponding run. */ id: number; /** * The builder info that called your function. Since the builder info is from the builder.json * (or the host), it could contain information that is different than expected. */ builder: BuilderInfo; /** * A logger that appends messages to a log. This could be a separate interface or completely * ignored. `console.log` could also be completely ignored. */ logger: logging.LoggerApi; /** * The absolute workspace root of this run. This is a system path and will not be normalized; * ie. on Windows it will starts with `C:\\` (or whatever drive). */ workspaceRoot: string; /** * The current directory the user is in. This could be outside the workspace root. This is a * system path and will not be normalized; ie. on Windows it will starts with `C:\\` (or * whatever drive). */ currentDirectory: string; /** * The target that was used to run this builder. * Target is optional if a builder was ran using `scheduleBuilder()`. */ target?: Target; /** * Schedule a target in the same workspace. This can be the same target that is being executed * right now, but targets of the same name are serialized. * Running the same target and waiting for it to end will result in a deadlocking scenario. * Targets are considered the same if the project, the target AND the configuration are the same. * @param target The target to schedule. * @param overrides A set of options to override the workspace set of options. * @param scheduleOptions Additional optional scheduling options. * @return A promise of a run. It will resolve when all the members of the run are available. */ scheduleTarget( target: Target, overrides?: json.JsonObject, scheduleOptions?: ScheduleOptions, ): Promise<BuilderRun>; /** * Schedule a builder by its name. This can be the same builder that is being executed. * @param builderName The name of the builder, ie. its `packageName:builderName` tuple. * @param options All options to use for the builder (by default empty object). There is no * additional options added, e.g. from the workspace. * @param scheduleOptions Additional optional scheduling options. * @return A promise of a run. It will resolve when all the members of the run are available. */ scheduleBuilder( builderName: string, options?: json.JsonObject, scheduleOptions?: ScheduleOptions, ): Promise<BuilderRun>; /** * Resolve and return options for a specified target. If the target isn't defined in the * workspace this will reject the promise. This object will be read directly from the workspace * but not validated against the builder of the target. * @param target The target to resolve the options of. * @return A non-validated object resolved from the workspace. */ getTargetOptions(target: Target): Promise<json.JsonObject>; getProjectMetadata(projectName: string): Promise<json.JsonObject>; getProjectMetadata(target: Target): Promise<json.JsonObject>; /** * Resolves and return a builder name. The exact format of the name is up to the host, * so it should not be parsed to gather information (it's free form). This string can be * used to validate options or schedule a builder directly. * @param target The target to resolve the builder name. */ getBuilderNameForTarget(target: Target): Promise<string>; /** * Validates the options against a builder schema. This uses the same methods as the * scheduleTarget and scheduleBrowser methods to validate and apply defaults to the options. * It can be generically typed, if you know which interface it is supposed to validate against. * @param options A generic option object to validate. * @param builderName The name of a builder to use. This can be gotten for a target by using the * getBuilderForTarget() method on the context. */ validateOptions<T extends json.JsonObject = json.JsonObject>( options: json.JsonObject, builderName: string, ): Promise<T>; /** * Set the builder to running. This should be used if an external event triggered a re-run, * e.g. a file watched was changed. */ reportRunning(): void; /** * Update the status string shown on the interface. * @param status The status to set it to. An empty string can be used to remove the status. */ reportStatus(status: string): void; /** * Update the progress for this builder run. * @param current The current progress. This will be between 0 and total. * @param total A new total to set. By default at the start of a run this is 1. If omitted it * will use the same value as the last total. * @param status Update the status string. If omitted the status string is not modified. */ reportProgress(current: number, total?: number, status?: string): void; /** * Add teardown logic to this Context, so that when it's being stopped it will execute teardown. */ addTeardown(teardown: () => Promise<void> | void): void; } /** * An accepted return value from a builder. Can be either an Observable, a Promise or a vector. */ export type BuilderOutputLike = ObservableInput<BuilderOutput> | BuilderOutput; // eslint-disable-next-line @typescript-eslint/no-explicit-any export function isBuilderOutput(obj: any): obj is BuilderOutput { if (!obj || typeof obj.then === 'function' || typeof obj.subscribe === 'function') { return false; } if (typeof obj[Symbol.asyncIterator] === 'function') { return false; } return typeof obj.success === 'boolean'; } export function fromAsyncIterable<T>(iterable: AsyncIterable<T>): Observable<T> { return new Observable((subscriber) => { handleAsyncIterator(subscriber, iterable[Symbol.asyncIterator]()).then( () => subscriber.complete(), (error) => subscriber.error(error), ); }); } async function handleAsyncIterator<T>( subscriber: Subscriber<T>, iterator: AsyncIterator<T>, ): Promise<void> { const teardown = new Promise<void>((resolve) => subscriber.add(() => resolve())); try { while (!subscriber.closed) { const result = await Promise.race([teardown, iterator.next()]); if (!result || result.done) { break; } subscriber.next(result.value); } } finally { await iterator.return?.(); } } /** * A builder handler function. The function signature passed to `createBuilder()`. */ export interface BuilderHandlerFn<A> { /** * Builders are defined by users to perform any kind of task, like building, testing or linting, * and should use this interface. * @param input The options (a JsonObject), validated by the schema and received by the * builder. This can include resolved options from the CLI or the workspace. * @param context A context that can be used to interact with the Architect framework. * @return One or many builder output. */ (input: A, context: BuilderContext): BuilderOutputLike; } /** * A Builder general information. This is generated by the host and is expanded by the host, but * the public API contains those fields. */ export type BuilderInfo = json.JsonObject & { builderName: string; description: string; optionSchema: json.schema.JsonSchema; }; /** * Returns a string of "project:target[:configuration]" for the target object. */ export function targetStringFromTarget({ project, target, configuration }: Target) { return `${project}:${target}${configuration !== undefined ? ':' + configuration : ''}`; } /** * Return a Target tuple from a specifier string. * Supports abbreviated target specifiers (examples: `::`, `::development`, or `:build:production`). */ export function targetFromTargetString( specifier: string, abbreviatedProjectName?: string, abbreviatedTargetName?: string, ): Target { const tuple = specifier.split(':', 3); if (tuple.length < 2) { throw new Error('Invalid target string: ' + JSON.stringify(specifier)); } return { project: tuple[0] || abbreviatedProjectName || '', target: tuple[1] || abbreviatedTargetName || '', ...(tuple[2] !== undefined && { configuration: tuple[2] }), }; }
{ "end_byte": 13061, "start_byte": 4533, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/api.ts" }
angular-cli/packages/angular_devkit/architect/src/api.ts_13063_14609
/** * Schedule a target, and forget about its run. This will return an observable of outputs, that * as a teardown will stop the target from running. This means that the Run object this returns * should not be shared. * * The reason this is not part of the Context interface is to keep the Context as normal form as * possible. This is really an utility that people would implement in their project. * * @param context The context of your current execution. * @param target The target to schedule. * @param overrides Overrides that are used in the target. * @param scheduleOptions Additional scheduling options. */ export function scheduleTargetAndForget( context: BuilderContext, target: Target, overrides?: json.JsonObject, scheduleOptions?: ScheduleOptions, ): Observable<BuilderOutput> { let resolve: (() => void) | null = null; const promise = new Promise<void>((r) => (resolve = r)); context.addTeardown(() => promise); return from(context.scheduleTarget(target, overrides, scheduleOptions)).pipe( switchMap( (run) => new Observable<BuilderOutput>((observer) => { const subscription = run.output.subscribe(observer); return () => { subscription.unsubscribe(); // We can properly ignore the floating promise as it's a "reverse" promise; the teardown // is waiting for the resolve. // eslint-disable-next-line @typescript-eslint/no-floating-promises run.stop().then(resolve); }; }), ), ); }
{ "end_byte": 14609, "start_byte": 13063, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/api.ts" }
angular-cli/packages/angular_devkit/architect/src/architect.ts_0_8625
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { json, logging } from '@angular-devkit/core'; import { Observable, concatMap, first, from, ignoreElements, last, map, merge, of, onErrorResumeNext, shareReplay, takeUntil, } from 'rxjs'; import { BuilderInfo, BuilderInput, BuilderOutput, BuilderRegistry, BuilderRun, Target, targetStringFromTarget, } from './api'; import { ArchitectHost, BuilderDescription, BuilderJobHandler } from './internal'; import { FallbackRegistry, JobHandler, JobHandlerContext, JobInboundMessage, JobInboundMessageKind, JobName, JobOutboundMessageKind, Registry, Scheduler, SimpleJobRegistry, SimpleScheduler, createJobHandler, } from './jobs'; import { mergeOptions } from './options'; import { scheduleByName, scheduleByTarget } from './schedule-by-name'; const inputSchema = require('./input-schema.json'); const outputSchema = require('./output-schema.json'); function _createJobHandlerFromBuilderInfo( info: BuilderInfo, target: Target | undefined, host: ArchitectHost, registry: json.schema.SchemaRegistry, baseOptions: json.JsonObject, ): Observable<BuilderJobHandler> { const jobDescription: BuilderDescription = { name: target ? `{${targetStringFromTarget(target)}}` : info.builderName, argument: { type: 'object' }, input: inputSchema, output: outputSchema, info, }; function handler(argument: json.JsonObject, context: JobHandlerContext) { // Add input validation to the inbound bus. const inboundBusWithInputValidation = context.inboundBus.pipe( concatMap(async (message) => { if (message.kind === JobInboundMessageKind.Input) { const v = message.value as BuilderInput; const options = mergeOptions(baseOptions, v.options); // Validate v against the options schema. const validation = await registry.compile(info.optionSchema); const validationResult = await validation(options); const { data, success, errors } = validationResult; if (!success) { throw new json.schema.SchemaValidationException(errors); } return { ...message, value: { ...v, options: data } } as JobInboundMessage<BuilderInput>; } else { return message as JobInboundMessage<BuilderInput>; } }), // Using a share replay because the job might be synchronously sending input, but // asynchronously listening to it. shareReplay(1), ); // Make an inboundBus that completes instead of erroring out. // We'll merge the errors into the output instead. const inboundBus = onErrorResumeNext(inboundBusWithInputValidation); const output = from(host.loadBuilder(info)).pipe( concatMap((builder) => { if (builder === null) { throw new Error(`Cannot load builder for builderInfo ${JSON.stringify(info, null, 2)}`); } return builder.handler(argument, { ...context, inboundBus }).pipe( map((output) => { if (output.kind === JobOutboundMessageKind.Output) { // Add target to it. return { ...output, value: { ...output.value, ...(target ? { target } : 0), } as unknown as json.JsonObject, }; } else { return output; } }), ); }), // Share subscriptions to the output, otherwise the handler will be re-run. shareReplay(), ); // Separate the errors from the inbound bus into their own observable that completes when the // builder output does. const inboundBusErrors = inboundBusWithInputValidation.pipe( ignoreElements(), takeUntil(onErrorResumeNext(output.pipe(last()))), ); // Return the builder output plus any input errors. return merge(inboundBusErrors, output); } return of(Object.assign(handler, { jobDescription }) as BuilderJobHandler); } export interface ScheduleOptions { logger?: logging.Logger; } /** * A JobRegistry that resolves builder targets from the host. */ class ArchitectBuilderJobRegistry implements BuilderRegistry { constructor( protected _host: ArchitectHost, protected _registry: json.schema.SchemaRegistry, protected _jobCache?: Map<string, Observable<BuilderJobHandler | null>>, protected _infoCache?: Map<string, Observable<BuilderInfo | null>>, ) {} protected _resolveBuilder(name: string): Observable<BuilderInfo | null> { const cache = this._infoCache; if (cache) { const maybeCache = cache.get(name); if (maybeCache !== undefined) { return maybeCache; } const info = from(this._host.resolveBuilder(name)).pipe(shareReplay(1)); cache.set(name, info); return info; } return from(this._host.resolveBuilder(name)); } protected _createBuilder( info: BuilderInfo, target?: Target, options?: json.JsonObject, ): Observable<BuilderJobHandler | null> { const cache = this._jobCache; if (target) { const maybeHit = cache && cache.get(targetStringFromTarget(target)); if (maybeHit) { return maybeHit; } } else { const maybeHit = cache && cache.get(info.builderName); if (maybeHit) { return maybeHit; } } const result = _createJobHandlerFromBuilderInfo( info, target, this._host, this._registry, options || {}, ); if (cache) { if (target) { cache.set(targetStringFromTarget(target), result.pipe(shareReplay(1))); } else { cache.set(info.builderName, result.pipe(shareReplay(1))); } } return result; } get<A extends json.JsonObject, I extends BuilderInput, O extends BuilderOutput>( name: string, ): Observable<JobHandler<A, I, O> | null> { const m = name.match(/^([^:]+):([^:]+)$/i); if (!m) { return of(null); } return from(this._resolveBuilder(name)).pipe( concatMap((builderInfo) => (builderInfo ? this._createBuilder(builderInfo) : of(null))), first(null, null), ) as Observable<JobHandler<A, I, O> | null>; } } /** * A JobRegistry that resolves targets from the host. */ class ArchitectTargetJobRegistry extends ArchitectBuilderJobRegistry { override get<A extends json.JsonObject, I extends BuilderInput, O extends BuilderOutput>( name: string, ): Observable<JobHandler<A, I, O> | null> { const m = name.match(/^{([^:]+):([^:]+)(?::([^:]*))?}$/i); if (!m) { return of(null); } const target = { project: m[1], target: m[2], configuration: m[3], }; return from( Promise.all([ this._host.getBuilderNameForTarget(target), this._host.getOptionsForTarget(target), ]), ).pipe( concatMap(([builderStr, options]) => { if (builderStr === null || options === null) { return of(null); } return this._resolveBuilder(builderStr).pipe( concatMap((builderInfo) => { if (builderInfo === null) { return of(null); } return this._createBuilder(builderInfo, target, options); }), ); }), first(null, null), ) as Observable<JobHandler<A, I, O> | null>; } } function _getTargetOptionsFactory(host: ArchitectHost) { return createJobHandler<Target, json.JsonValue, json.JsonObject>( (target) => { return host.getOptionsForTarget(target).then((options) => { if (options === null) { throw new Error(`Invalid target: ${JSON.stringify(target)}.`); } return options; }); }, { name: '..getTargetOptions', output: { type: 'object' }, argument: inputSchema.properties.target, }, ); } function _getProjectMetadataFactory(host: ArchitectHost) { return createJobHandler<Target, json.JsonValue, json.JsonObject>( (target) => { return host.getProjectMetadata(target).then((options) => { if (options === null) { throw new Error(`Invalid target: ${JSON.stringify(target)}.`); } return options; }); }, { name: '..getProjectMetadata', output: { type: 'object' }, argument: { oneOf: [{ type: 'string' }, inputSchema.properties.target], }, }, ); }
{ "end_byte": 8625, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/architect.ts" }
angular-cli/packages/angular_devkit/architect/src/architect.ts_8627_12375
function _getBuilderNameForTargetFactory(host: ArchitectHost) { return createJobHandler<Target, never, string>( async (target) => { const builderName = await host.getBuilderNameForTarget(target); if (!builderName) { throw new Error(`No builder were found for target ${targetStringFromTarget(target)}.`); } return builderName; }, { name: '..getBuilderNameForTarget', output: { type: 'string' }, argument: inputSchema.properties.target, }, ); } function _validateOptionsFactory(host: ArchitectHost, registry: json.schema.SchemaRegistry) { return createJobHandler<[string, json.JsonObject], never, json.JsonObject>( async ([builderName, options]) => { // Get option schema from the host. const builderInfo = await host.resolveBuilder(builderName); if (!builderInfo) { throw new Error(`No builder info were found for builder ${JSON.stringify(builderName)}.`); } const validation = await registry.compile(builderInfo.optionSchema); const { data, success, errors } = await validation(options); if (!success) { throw new json.schema.SchemaValidationException(errors); } return data as json.JsonObject; }, { name: '..validateOptions', output: { type: 'object' }, argument: { type: 'array', items: [{ type: 'string' }, { type: 'object' }], }, }, ); } export class Architect { private readonly _scheduler: Scheduler; private readonly _jobCache = new Map<string, Observable<BuilderJobHandler>>(); private readonly _infoCache = new Map<string, Observable<BuilderInfo>>(); constructor( private _host: ArchitectHost, registry: json.schema.SchemaRegistry = new json.schema.CoreSchemaRegistry(), additionalJobRegistry?: Registry, ) { const privateArchitectJobRegistry = new SimpleJobRegistry(); // Create private jobs. privateArchitectJobRegistry.register(_getTargetOptionsFactory(_host)); privateArchitectJobRegistry.register(_getBuilderNameForTargetFactory(_host)); privateArchitectJobRegistry.register(_validateOptionsFactory(_host, registry)); privateArchitectJobRegistry.register(_getProjectMetadataFactory(_host)); const jobRegistry = new FallbackRegistry([ new ArchitectTargetJobRegistry(_host, registry, this._jobCache, this._infoCache), new ArchitectBuilderJobRegistry(_host, registry, this._jobCache, this._infoCache), privateArchitectJobRegistry, ...(additionalJobRegistry ? [additionalJobRegistry] : []), ] as Registry[]); this._scheduler = new SimpleScheduler(jobRegistry, registry); } has(name: JobName) { return this._scheduler.has(name); } scheduleBuilder( name: string, options: json.JsonObject, scheduleOptions: ScheduleOptions = {}, ): Promise<BuilderRun> { // The below will match 'project:target:configuration' if (!/^[^:]+:[^:]+(:[^:]+)?$/.test(name)) { throw new Error('Invalid builder name: ' + JSON.stringify(name)); } return scheduleByName(name, options, { scheduler: this._scheduler, logger: scheduleOptions.logger || new logging.NullLogger(), currentDirectory: this._host.getCurrentDirectory(), workspaceRoot: this._host.getWorkspaceRoot(), }); } scheduleTarget( target: Target, overrides: json.JsonObject = {}, scheduleOptions: ScheduleOptions = {}, ): Promise<BuilderRun> { return scheduleByTarget(target, overrides, { scheduler: this._scheduler, logger: scheduleOptions.logger || new logging.NullLogger(), currentDirectory: this._host.getCurrentDirectory(), workspaceRoot: this._host.getWorkspaceRoot(), }); } }
{ "end_byte": 12375, "start_byte": 8627, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/architect.ts" }
angular-cli/packages/angular_devkit/architect/src/index.ts_0_391
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as jobs from './jobs'; export * from './api'; export { Architect, type ScheduleOptions } from './architect'; export { createBuilder } from './create-builder'; export { jobs };
{ "end_byte": 391, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/index.ts" }
angular-cli/packages/angular_devkit/architect/src/index_spec.ts_0_641
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { json, logging, schema } from '@angular-devkit/core'; import { firstValueFrom, lastValueFrom, map, take, tap, timer, toArray } from 'rxjs'; import { promisify } from 'util'; import { TestingArchitectHost } from '../testing/testing-architect-host'; import { BuilderOutput, BuilderRun } from './api'; import { Architect } from './architect'; import { createBuilder } from './create-builder'; const flush = promisify(setImmediate);
{ "end_byte": 641, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/index_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/index_spec.ts_643_8913
describe('architect', () => { let testArchitectHost: TestingArchitectHost; let architect: Architect; let called = 0; let options: {} = {}; const target1 = { project: 'test', target: 'test', }; const target2 = { project: 'test', target: 'abc', }; beforeEach(async () => { const registry = new schema.CoreSchemaRegistry(); registry.addPostTransform(schema.transforms.addUndefinedDefaults); testArchitectHost = new TestingArchitectHost(); architect = new Architect(testArchitectHost, registry); options = {}; called = 0; testArchitectHost.addBuilder( 'package:test', createBuilder(async (o) => { called++; options = o; return new Promise<BuilderOutput>((resolve) => { setTimeout(() => resolve({ success: true }), 10); }); }), ); testArchitectHost.addBuilder( 'package:test-options', createBuilder((o) => { options = o; return { success: true }; }), ); testArchitectHost.addTarget(target1, 'package:test'); testArchitectHost.addTarget(target2, 'package:test'); }); it('works', async () => { testArchitectHost.addBuilder( 'package:test', createBuilder(() => ({ success: true })), ); const run = await architect.scheduleBuilder('package:test', {}); expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); await run.stop(); }); it('works with async builders', async () => { testArchitectHost.addBuilder( 'package:test', createBuilder(async () => ({ success: true })), ); const run = await architect.scheduleBuilder('package:test', {}); expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); await run.stop(); }); it('supports async generator builders', async () => { testArchitectHost.addBuilder( 'package:test', createBuilder(async function* () { yield { success: true }; }), ); const run = await architect.scheduleBuilder('package:test', {}); expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); await run.stop(); }); it('runs builders parallel', async () => { const run = await architect.scheduleBuilder('package:test', {}); const run2 = await architect.scheduleBuilder('package:test', {}); await flush(); expect(called).toBe(2); expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); expect(await run2.result).toEqual(jasmine.objectContaining({ success: true })); expect(called).toBe(2); await run.stop(); }); it('runs targets parallel', async () => { const run = await architect.scheduleTarget(target1, {}); const run2 = await architect.scheduleTarget(target1, {}); await flush(); expect(called).toBe(2); expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); expect(await run2.result).toEqual(jasmine.objectContaining({ success: true })); expect(called).toBe(2); await run.stop(); }); it('passes options to builders', async () => { const o = { helloBuilder: 'world' }; const run = await architect.scheduleBuilder('package:test-options', o); expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); expect(options).toEqual(o); await run.stop(); }); it('passes options to targets', async () => { const o = { helloTarget: 'world' }; const run = await architect.scheduleTarget(target1, o); expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); expect(options).toEqual(o); await run.stop(); }); it(`errors when target configuration does not exist`, async () => { await expectAsync(architect.scheduleBuilder('test:test:invalid', {})).toBeRejectedWithError( 'Job name "test:test:invalid" does not exist.', ); }); it('errors when builder cannot be resolved', async () => { try { await architect.scheduleBuilder('non:existent', {}); expect('to throw').not.toEqual('to throw'); } catch {} }); it('works with watching observable builders', async () => { let results = 0; testArchitectHost.addBuilder( 'package:test-watch', createBuilder((_, context) => { called++; return timer(10, 10).pipe( take(10), map(() => { context.reportRunning(); return { success: true }; }), tap(() => results++), ); }), ); const run = await architect.scheduleBuilder('package:test-watch', {}); await run.result; expect(called).toBe(1); expect(results).toBe(1); const all = await lastValueFrom(run.output.pipe(toArray())); expect(called).toBe(1); expect(results).toBe(10); expect(all.length).toBe(10); }); it('works with watching async generator builders', async () => { let results = 0; testArchitectHost.addBuilder( 'package:test-watch-gen', createBuilder(async function* (_, context) { called++; for (let x = 0; x < 10; x++) { await new Promise(setImmediate); context.reportRunning(); yield { success: true }; results++; } }), ); const run = await architect.scheduleBuilder('package:test-watch-gen', {}); await run.result; expect(called).toBe(1); expect(results).toBe(1); const all = await lastValueFrom(run.output.pipe(toArray())); expect(called).toBe(1); expect(results).toBe(10); expect(all.length).toBe(10); }); it('propagates all logging entries', async () => { const logCount = 100; testArchitectHost.addBuilder( 'package:test-logging', createBuilder(async (_, context) => { for (let i = 0; i < logCount; ++i) { context.logger.info(i.toString()); } return { success: true }; }), ); const logger = new logging.Logger('test-logger'); const logs: string[] = []; logger.subscribe({ next(entry) { logs.push(entry.message); }, }); const run = await architect.scheduleBuilder('package:test-logging', {}, { logger }); expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); await run.stop(); for (let i = 0; i < logCount; ++i) { expect(logs[i]).toBe(i.toString()); } }); it('reports errors in the builder', async () => { testArchitectHost.addBuilder( 'package:error', createBuilder(() => { throw new Error('Error in the builder.'); }), ); let run: BuilderRun | undefined = undefined; try { try { // This should not throw. run = await architect.scheduleBuilder('package:error', {}); } catch (err) { expect(err).toBeUndefined(); throw err; } // This should throw. await run.result; expect('to throw').not.toEqual('to throw'); } catch {} if (run) { await run.stop(); } }); it('reports errors in the builder (async)', async () => { testArchitectHost.addBuilder( 'package:error', createBuilder(() => { return Promise.reject(new Error('Error async')); }), ); let run: BuilderRun | undefined = undefined; try { try { // This should not throw. run = await architect.scheduleBuilder('package:error', {}); } catch (err) { expect(err).toBeUndefined(); throw err; } // This should throw. await run.result; expect('to throw').not.toEqual('to throw'); } catch {} if (run) { await run.stop(); } }); it('reports errors in options', async () => { const builderName = 'options:error'; const builder = createBuilder(() => ({ success: true })); const optionSchema = { type: 'object', additionalProperties: false }; testArchitectHost.addBuilder(builderName, builder, '', optionSchema); const run = await architect.scheduleBuilder(builderName, { extraProp: true }); await expectAsync(run.result).toBeRejectedWith( jasmine.objectContaining({ message: jasmine.stringMatching('extraProp') }), ); await run.stop(); });
{ "end_byte": 8913, "start_byte": 643, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/index_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/index_spec.ts_8917_12547
it('exposes getTargetOptions() properly', async () => { const goldenOptions = { value: 'value', }; let options = {} as object; const target = { project: 'project', target: 'target', }; testArchitectHost.addTarget(target, 'package:target', goldenOptions); testArchitectHost.addBuilder( 'package:getTargetOptions', createBuilder(async (_, context) => { options = await context.getTargetOptions(target); return { success: true }; }), ); const run = await architect.scheduleBuilder('package:getTargetOptions', {}); const output = await lastValueFrom(run.output); expect(output.success).toBe(true); expect(options).toEqual(goldenOptions); await run.stop(); // Use an invalid target and check for error. target.target = 'invalid'; options = {}; // This should not error. const run2 = await architect.scheduleBuilder('package:getTargetOptions', {}); // But this should. try { await lastValueFrom(run2.output); expect('THE ABOVE LINE SHOULD NOT ERROR').toBe('false'); } catch {} await run2.stop(); }); it('exposes getBuilderNameForTarget()', async () => { const builderName = 'ImBlue:DabadeeDabada'; testArchitectHost.addBuilder( builderName, createBuilder(() => ({ success: true })), ); const target = { project: 'some-project', target: 'some-target', }; testArchitectHost.addTarget(target, builderName); let actualBuilderName = ''; testArchitectHost.addBuilder( 'package:do-it', createBuilder(async (_, context) => { actualBuilderName = await context.getBuilderNameForTarget(target); return { success: true }; }), ); const run = await architect.scheduleBuilder('package:do-it', {}); const output = await lastValueFrom(run.output); expect(output.success).toBe(true); expect(actualBuilderName).toEqual(builderName); await run.stop(); // Use an invalid target and check for error. target.target = 'invalid'; actualBuilderName = ''; // This should not error. const run2 = await architect.scheduleBuilder('package:do-it', {}); // But this should. try { await lastValueFrom(run2.output); expect('THE ABOVE LINE SHOULD NOT ERROR').toBe('false'); } catch {} await run2.stop(); }); it('exposes validateOptions()', async () => { const builderName = 'Hello:World'; testArchitectHost.addBuilder( builderName, createBuilder(() => ({ success: true })), '', { type: 'object', properties: { p0: { type: 'number', default: 123 }, p1: { type: 'string' }, }, required: ['p1'], }, ); let actualOptions: json.JsonObject = {}; testArchitectHost.addBuilder( 'package:do-it', createBuilder(async (options, context) => { actualOptions = await context.validateOptions(options, builderName); return { success: true }; }), ); const run = await architect.scheduleBuilder('package:do-it', { p1: 'hello' }); const output = await firstValueFrom(run.output); expect(output.success).toBe(true); expect(actualOptions).toEqual({ p0: 123, p1: 'hello', }); await run.stop(); // Should also error. const run2 = await architect.scheduleBuilder('package:do-it', {}); await expectAsync(lastValueFrom(run2.output)).toBeRejectedWith( jasmine.objectContaining({ message: jasmine.stringMatching('p1') }), ); await run2.stop(); }); });
{ "end_byte": 12547, "start_byte": 8917, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/index_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/internal.ts_0_3357
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { json } from '@angular-devkit/core'; import { BuilderInfo, BuilderInput, BuilderOutput, Target } from './api'; import { JobDescription, JobHandler } from './jobs'; // Internal types that should not be exported directly. These are used by the host and architect // itself. Host implementations should import the host.ts file. /** * BuilderSymbol used for knowing if a function was created using createBuilder(). This is a * property set on the function that should be `true`. * Using Symbol.for() as it's a global registry that's the same for all installations of * Architect (if some libraries depends directly on architect instead of sharing the files). */ export const BuilderSymbol = Symbol.for('@angular-devkit/architect:builder'); /** * BuilderVersionSymbol used for knowing which version of the library createBuilder() came from. * This is to make sure we don't try to use an incompatible builder. * Using Symbol.for() as it's a global registry that's the same for all installations of * Architect (if some libraries depends directly on architect instead of sharing the files). */ export const BuilderVersionSymbol = Symbol.for('@angular-devkit/architect:version'); /** * A Specialization of the JobHandler type. This exposes BuilderDescription as the job description * type. */ export type BuilderJobHandler< A extends json.JsonObject = json.JsonObject, I extends BuilderInput = BuilderInput, O extends BuilderOutput = BuilderOutput, > = JobHandler<A, I, O> & { jobDescription: BuilderDescription }; /** * A Builder description, which is used internally. Adds the builder info which is the * metadata attached to a builder in Architect. */ export interface BuilderDescription extends JobDescription { info: BuilderInfo; } /** * A Builder instance. Use createBuilder() to create one of these. */ export interface Builder<OptionT extends json.JsonObject = json.JsonObject> { // A fully compatible job handler. handler: JobHandler<json.JsonObject, BuilderInput, BuilderOutput>; // Metadata associated with this builder. [BuilderSymbol]: true; [BuilderVersionSymbol]: string; } export interface ArchitectHost<BuilderInfoT extends BuilderInfo = BuilderInfo> { /** * Get the builder name for a target. * @param target The target to inspect. */ getBuilderNameForTarget(target: Target): Promise<string | null>; /** * Resolve a builder. This needs to return a string which will be used in a dynamic `import()` * clause. This should throw if no builder can be found. The dynamic import will throw if * it is unsupported. * @param builderName The name of the builder to be used. * @returns All the info needed for the builder itself. */ resolveBuilder(builderName: string): Promise<BuilderInfoT | null>; loadBuilder(info: BuilderInfoT): Promise<Builder | null>; getCurrentDirectory(): Promise<string>; getWorkspaceRoot(): Promise<string>; getOptionsForTarget(target: Target): Promise<json.JsonObject | null>; getProjectMetadata(projectName: string): Promise<json.JsonObject | null>; getProjectMetadata(target: Target): Promise<json.JsonObject | null>; }
{ "end_byte": 3357, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/internal.ts" }
angular-cli/packages/angular_devkit/architect/src/schedule-by-name.ts_0_3738
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { json, logging } from '@angular-devkit/core'; import { EMPTY, Subscription, catchError, first, firstValueFrom, ignoreElements, lastValueFrom, map, shareReplay, } from 'rxjs'; import { BuilderInfo, BuilderInput, BuilderOutput, BuilderProgressReport, BuilderRun, Target, targetStringFromTarget, } from './api'; import { JobOutboundMessageKind, JobState, Scheduler } from './jobs'; const progressSchema = require('./progress-schema.json'); let _uniqueId = 0; export async function scheduleByName( name: string, buildOptions: json.JsonObject, options: { target?: Target; scheduler: Scheduler; logger: logging.LoggerApi; workspaceRoot: string | Promise<string>; currentDirectory: string | Promise<string>; }, ): Promise<BuilderRun> { const childLoggerName = options.target ? `{${targetStringFromTarget(options.target)}}` : name; const logger = options.logger.createChild(childLoggerName); const job = options.scheduler.schedule<{}, BuilderInput, BuilderOutput>(name, {}); let stateSubscription: Subscription; const workspaceRoot = await options.workspaceRoot; const currentDirectory = await options.currentDirectory; const description = await firstValueFrom(job.description); const info = description.info as BuilderInfo; const id = ++_uniqueId; const message = { id, currentDirectory, workspaceRoot, info: info, options: buildOptions, ...(options.target ? { target: options.target } : {}), }; // Wait for the job to be ready. if (job.state !== JobState.Started) { stateSubscription = job.outboundBus.subscribe({ next: (event) => { if (event.kind === JobOutboundMessageKind.Start) { job.input.next(message); } }, error: () => {}, }); } else { job.input.next(message); } const logChannelSub = job.getChannel<logging.LogEntry>('log').subscribe({ next: (entry) => { logger.next(entry); }, error: () => {}, }); const outboundBusSub = job.outboundBus.subscribe({ error() {}, complete() { outboundBusSub.unsubscribe(); logChannelSub.unsubscribe(); stateSubscription.unsubscribe(); }, }); const output = job.output.pipe( map( (output) => ({ ...output, ...(options.target ? { target: options.target } : 0), info, }) as unknown as BuilderOutput, ), shareReplay(), ); // Start the builder. output.pipe(first()).subscribe({ error: () => {}, }); return { id, info, // This is a getter so that it always returns the next output, and not the same one. get result() { return firstValueFrom(output); }, get lastOutput() { return lastValueFrom(output); }, output, progress: job .getChannel<BuilderProgressReport>('progress', progressSchema) .pipe(shareReplay(1)), stop() { job.stop(); return job.outboundBus .pipe( ignoreElements(), catchError(() => EMPTY), ) .toPromise(); }, }; } export async function scheduleByTarget( target: Target, overrides: json.JsonObject, options: { scheduler: Scheduler; logger: logging.LoggerApi; workspaceRoot: string | Promise<string>; currentDirectory: string | Promise<string>; }, ): Promise<BuilderRun> { return scheduleByName(`{${targetStringFromTarget(target)}}`, overrides, { ...options, target, logger: options.logger, }); }
{ "end_byte": 3738, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/schedule-by-name.ts" }
angular-cli/packages/angular_devkit/architect/src/options.ts_0_923
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { json } from '@angular-devkit/core'; import { BuilderInput } from './api'; type OverrideOptions = BuilderInput['options']; export function mergeOptions( baseOptions: json.JsonObject, overrideOptions: OverrideOptions, ): json.JsonObject { if (!overrideOptions) { return { ...baseOptions }; } const options = { ...baseOptions, ...overrideOptions, }; // For object-object overrides, we merge one layer deep. for (const key of Object.keys(overrideOptions)) { const override = overrideOptions[key]; const base = baseOptions[key]; if (json.isJsonObject(base) && json.isJsonObject(override)) { options[key] = { ...base, ...override }; } } return options; }
{ "end_byte": 923, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/options.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/architecture.md_0_5936
# Overview Jobs is a high-order API that adds inputs, runtime type checking, sequencing, and other functionality on top of RxJS' `Observable`s. # Background An `Observable` (at a higher level) is a function that receives a `Subscriber`, and outputs multiple values, and finishes once it calls the `Subscriber.prototype.complete()` method (in JavaScript): ```javascript const output1To10EverySecond = function (subscriber) { let t = 0; const i = setInterval(() => { t++; subscriber.next(t); if (t === 10) { subscriber.complete(t); } }, 1000); return () => clearInterval(i); }; const stream$ = new Observable(output1To10EverySecond); // Start the function, and output 1 to 100, once per line. stream$.subscribe((x) => console.log(x)); ``` This, of course, can be typed in TypeScript, but those types are not enforced at runtime. # Glossary - `job handler`. The function that implements the job's logic. - `raw input`. The input observable sending messages to the job. These messages are of type `JobInboundMessage`. - `raw output`. The output observer returned from the `job handler`. Messages on this observable are of type `JobOutboundMessage`. # Description A `JobHandler`, similar to observables, is a function that receives an argument and a context, and returns an `Observable` of messages, which can include outputs that are typed at runtime (using a Json Schema): ```javascript const output1ToXEverySecond = function (x, context) { return new Observable((subscriber) => { let t = 0; // Notify our users that the actual work is started. subscriber.next({ kind: JobOutboundMessageKind.Start }); const i = setInterval(() => { t++; subscriber.next({ kind: JobOutboundMessageKind.Output, value: t }); if (t === x) { subscriber.next({ kind: JobOutboundMessageKind.End }); subscriber.complete(); } }, 1000); return () => { clearInterval(i); }; }); }; // For now, jobs can not be called without a registry and scheduler. const registry = new SimpleJobRegistry(); registry.register('output-from-1-to-x', output1ToXEverySecond, { argument: { type: 'number' }, output: { type: 'number' }, }); const scheduler = new SimpleScheduler(registry); // Need to keep the same name that the registry would understand. // Count from 1 to 10. const job = scheduler.schedule('output-from-1-to-x', 10); // A Job<> instance has more members, but we only want the output values here. job.output.subscribe((x) => console.log(x)); ``` This seems like a lot of boilerplate in comparison, but there are a few advantages; 1. lifecycle. Jobs can tell when they start doing work and when work is done. 1. everything is typed, even at runtime. 1. the context also contains an input Observable that receives typed input messages, including input values, and stop requests. 1. jobs can also schedule other jobs and wait for them, even if they don't know if a job is implemented in the system. ## Diagram A simpler way to think about jobs in contrast to observables is that job are closer to a Unix process. It has an argument (command line flags), receive inputs (STDIN and interrupt signals), and output values (STDOUT) as well as diagnostic (STDERR). They can be plugged one into another (piping), and can be transformed, synchronized and scheduled (fork, exec, cron). ```plain - given A the type of the argument - given I the type of the input - given O the type of the output ,______________________ JobInboundMessage<I> --> | handler(argument: A) | --> JobOutboundMessage<O> - JobOutboundMessageKind.Output - ... ``` `JobInboundMessage` includes: 1. `JobInboundMessageKind.Ping`. A simple message that should be answered with `JobOutboundMessageKind.Pong` when the job is responsive. The `id` field of the message should be used when returning `Pong`. 1. `JobInboundMessageKind.Stop`. The job should be stopped. This is used when cancelling/unsubscribing from the `output` (or by calling `stop()`). Any inputs or outputs after this message will be ignored. 1. `JobInboundMessageKind.Input` is used when sending inputs to a job. These correspond to the `next` methods of an `Observer` and are reported to the job through its `context.input` Observable. There is no way to communicate an error to the job. `JobOutboundMessage` includes: 1. `JobOutboundMessageKind.Ready`. The `Job<>` was created, its dependencies are done, and the library is validating Argument and calling the internal job code. 1. `JobOutboundMessageKind.Start`. The job code itself should send that message when started. `createJobHandler()` will do it automatically. 1. `JobOutboundMessageKind.End`. The job has ended. This is done by the job itself and should always be sent when completed. The scheduler will listen to this message to set the state and unblock dependent jobs. `createJobHandler()` automatically send this message. 1. `JobOutboundMessageKind.Pong`. The job should answer a `JobInboundMessageKind.Ping` message with this. Automatically done by `createJobHandler()`. 1. `JobOutboundMessageKind.Output`. An `Output` has been generated by the job. 1. `JobOutboundMessageKind.ChannelMessage`, `JobOutboundMessageKind.ChannelError` and `JobOutboundMessageKind.ChannelComplete` are used for output channels. These correspond to the `next`, `error` and `complete` methods of an `Observer` and are available to the callee through the `job.channels` map of Observable. Utilities should have some filtering and dispatching to separate observables, as a convenience for the user. An example of this would be the `Job.prototype.output` observable which only contains the value contained by messages of type `JobOutboundMessageKind.Output`.
{ "end_byte": 5936, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/architecture.md" }
angular-cli/packages/angular_devkit/architect/src/jobs/architecture.md_5936_9957
# Higher Order Jobs Because jobs are expected to be pure functions, they can be composed or transformed to create more complex behaviour, similar to how RxJS operators can transform observables. ```javascript // Runs a job on the hour, every hour, regardless of how long the job takes. // This creates a job function that can be registered by itself. function scheduleJobOnTheHour(jobFunction) { return function (argument, context) { return new Observable((observer) => { let timeout = 0; function _timeoutToNextHour() { // Just wait until the next hour. const t = new Date(); const secondsToNextHour = 3600 - t.getSeconds() - t.getMinutes() * 60; timeout = setTimeout(_scheduleJobAndWaitAnHour, secondsToNextHour); } function _scheduleJobAndWaitAnHour() { jobFunction(argument, context).subscribe( (message) => observer.next(message), (error) => observer.error(error), // Do not forward completion, but use it to schedule the next job run. () => { _timeoutToNextHour(); }, ); } // Kick off by waiting for next hour. _timeoutToNextHour(); return () => clearTimeout(timeout); }); }; } ``` Another way to compose jobs is to schedule jobs based on their name, from other jobs. ```javascript // Runs a job on the hour, every hour, regardless of how long the job takes. // This creates a high order job by getting a job name and an argument, and scheduling the job // every hour. function scheduleJobOnTheHour(job, context) { const { name, argument } = job; // Destructure our input. return new Observable((observer) => { let timeout = 0; function _timeoutToNextHour() { // Just wait until the next hour. const t = new Date(); const secondsToNextHour = 3600 - t.getSeconds() - t.getMinutes() * 60; timeout = setTimeout(_scheduleJobAndWaitAnHour, secondsToNextHour); } function _scheduleJobAndWaitAnHour() { const subJob = context.scheduler.schedule(name, argument); // We do not forward the input to the sub-job but that would be a valid example as well. subJob.outboundBus.subscribe( (message) => observer.next(message), (error) => observer.error(error), // Do not forward completion, but use it to schedule the next job run. () => { _timeoutToNextHour(); }, ); } // Kick off by waiting for next hour. _timeoutToNextHour(); return () => clearTimeout(timeout); }); } const registry = new SimpleJobRegistry(); registry.register('schedule-job-on-the-hour', scheduleJobOnTheHour, { argument: { properties: { name: { type: 'string' }, argument: { type: true }, }, }, }); // Implementation left to the reader. registry.register('copy-files-from-a-to-b', require('some-package/copy-job')); const scheduler = new SimpleScheduler(registry); // A rudimentary backup system. const job = scheduler.schedule('schedule-job-on-the-hour', { name: 'copy-files-from-a-to-b', argument: { from: '/some-directory/to/backup', to: '/volumes/usb-key', }, }); job.output.subscribe((x) => console.log(x)); ``` # Limitations Jobs input, output and argument must be serializable to JSONs. This is a big limitation in usage, but comes with the benefit that jobs can be serialized and called across memory boundaries. An example would be an operator that takes a module path and run the job from that path in a separate process. Or even a separate server, using HTTP calls. Another limitation is that the boilerplate is complex. Manually managing start/end life cycle, and other messages such as ping/pong, etc. is tedious and requires a lot of code. A good way to keep this limitation under control is to provide helpers to create `JobHandler`s which manage those messages for the developer. A simple handler could be to get a `Promise` and return the output of that promise automatically.
{ "end_byte": 9957, "start_byte": 5936, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/architecture.md" }
angular-cli/packages/angular_devkit/architect/src/jobs/simple-registry_spec.ts_0_909
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { lastValueFrom } from 'rxjs'; import { createJobHandler } from './create-job-handler'; import { SimpleJobRegistry } from './simple-registry'; describe('SimpleJobRegistry', () => { let registry: SimpleJobRegistry; beforeEach(() => { registry = new SimpleJobRegistry(); }); it('works for a simple case', async () => { registry.register( 'add', createJobHandler((arg: number[]) => arg.reduce((a, c) => a + c, 0)), { argument: { items: { type: 'number' } }, output: { type: 'number' }, }, ); expect(await lastValueFrom(registry.get('add'))).not.toBeNull(); expect(await lastValueFrom(registry.get('add2'))).toBeNull(); }); });
{ "end_byte": 909, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/simple-registry_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/simple-registry.ts_0_4821
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonValue, schema } from '@angular-devkit/core'; import { Observable, of } from 'rxjs'; import { JobDescription, JobHandler, JobName, Registry, isJobHandler } from './api'; import { JobNameAlreadyRegisteredException } from './exception'; /** * SimpleJobRegistry job registration options. */ // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface RegisterJobOptions extends Partial<JobDescription> {} /** * A simple job registry that keep a map of JobName => JobHandler internally. */ export class SimpleJobRegistry< MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue, > implements Registry<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT> { private _jobNames = new Map< JobName, JobHandler<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT> >(); get< A extends MinimumArgumentValueT = MinimumArgumentValueT, I extends MinimumInputValueT = MinimumInputValueT, O extends MinimumOutputValueT = MinimumOutputValueT, >(name: JobName): Observable<JobHandler<A, I, O> | null> { return of((this._jobNames.get(name) as unknown as JobHandler<A, I, O> | null) || null); } /** * Register a job handler. The name must be unique. * * @param name The name of the job. * @param handler The function that will be called for the job. * @param options An optional list of options to override the handler. {@see RegisterJobOptions} */ register< A extends MinimumArgumentValueT, I extends MinimumInputValueT, O extends MinimumOutputValueT, >(name: JobName, handler: JobHandler<A, I, O>, options?: RegisterJobOptions): void; /** * Register a job handler. The name must be unique. * * @param handler The function that will be called for the job. * @param options An optional list of options to override the handler. {@see RegisterJobOptions} */ register<ArgumentT extends JsonValue, InputT extends JsonValue, OutputT extends JsonValue>( handler: JobHandler<ArgumentT, InputT, OutputT>, // This version MUST contain a name. options?: RegisterJobOptions & { name: string }, ): void; register<ArgumentT extends JsonValue, InputT extends JsonValue, OutputT extends JsonValue>( nameOrHandler: JobName | JobHandler<ArgumentT, InputT, OutputT>, handlerOrOptions: JobHandler<ArgumentT, InputT, OutputT> | RegisterJobOptions = {}, options: RegisterJobOptions = {}, ): void { // Switch on the arguments. if (typeof nameOrHandler == 'string') { if (!isJobHandler(handlerOrOptions)) { // This is an error. throw new TypeError('Expected a JobHandler as second argument.'); } this._register(nameOrHandler, handlerOrOptions, options); } else if (isJobHandler(nameOrHandler)) { if (typeof handlerOrOptions !== 'object') { // This is an error. throw new TypeError('Expected an object options as second argument.'); } const name = options.name || nameOrHandler.jobDescription.name || handlerOrOptions.name; if (name === undefined) { throw new TypeError('Expected name to be a string.'); } this._register(name, nameOrHandler, options); } else { throw new TypeError('Unrecognized arguments.'); } } protected _register< ArgumentT extends JsonValue, InputT extends JsonValue, OutputT extends JsonValue, >( name: JobName, handler: JobHandler<ArgumentT, InputT, OutputT>, options: RegisterJobOptions, ): void { if (this._jobNames.has(name)) { // We shouldn't allow conflicts. throw new JobNameAlreadyRegisteredException(name); } // Merge all fields with the ones in the handler (to make sure we respect the handler). const argument = schema.mergeSchemas(handler.jobDescription.argument, options.argument); const input = schema.mergeSchemas(handler.jobDescription.input, options.input); const output = schema.mergeSchemas(handler.jobDescription.output, options.output); // Create the job description. const jobDescription: JobDescription = { name, argument, output, input, }; const jobHandler = Object.assign(handler.bind(undefined), { jobDescription, }) as unknown as JobHandler<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT>; this._jobNames.set(name, jobHandler); } /** * Returns the job names of all jobs. */ getJobNames(): JobName[] { return [...this._jobNames.keys()]; } }
{ "end_byte": 4821, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/simple-registry.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/strategy_spec.ts_0_6059
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { promisify } from 'util'; import { JobState } from './api'; import { createJobHandler } from './create-job-handler'; import { SimpleJobRegistry } from './simple-registry'; import { SimpleScheduler } from './simple-scheduler'; import * as strategy from './strategy'; const flush = promisify(setImmediate); describe('strategy.serialize()', () => { let registry: SimpleJobRegistry; let scheduler: SimpleScheduler; beforeEach(() => { registry = new SimpleJobRegistry(); scheduler = new SimpleScheduler(registry); }); it('works', async () => { let started = 0; let finished = 0; registry.register( strategy.serialize()( createJobHandler((input: number[]) => { started++; return new Promise<number>((resolve) => setTimeout(() => { finished++; resolve(input.reduce((a, c) => a + c, 0)); }, 10), ); // eslint-disable-next-line @typescript-eslint/no-explicit-any }) as any, ), { argument: { items: { type: 'number' } }, output: { type: 'number' }, name: 'add', }, ); const job1 = scheduler.schedule('add', [1, 2, 3, 4]); const job2 = scheduler.schedule('add', [1, 2, 3, 4, 5]); expect(started).toBe(0); expect(finished).toBe(0); job1.output.subscribe(); await flush(); expect(started).toBe(1); job2.output.subscribe(); await flush(); expect(started).toBe(1); // Job2 starts when Job1 ends. expect(finished).toBe(0); await Promise.all([ job1.output.toPromise().then((s) => { expect(finished).toBe(1); expect(s).toBe(10); }), job2.output.toPromise().then((s) => { expect(finished).toBe(2); expect(s).toBe(15); }), ]); expect(started).toBe(2); expect(finished).toBe(2); }); it('works across jobs', async () => { let started = 0; let finished = 0; const strategy1 = strategy.serialize(); registry.register( strategy1( createJobHandler((input: number[]) => { started++; return new Promise<number>((resolve) => setTimeout(() => { finished++; resolve(input.reduce((a, c) => a + c, 0)); }, 10), ); // eslint-disable-next-line @typescript-eslint/no-explicit-any }) as any, ), { argument: { items: { type: 'number' } }, output: { type: 'number' }, name: 'add', }, ); registry.register( strategy1( createJobHandler((input: number[]) => { started++; return new Promise<number>((resolve) => setTimeout(() => { finished++; resolve(input.reduce((a, c) => a + c, 100)); }, 10), ); // eslint-disable-next-line @typescript-eslint/no-explicit-any }) as any, ), { argument: { items: { type: 'number' } }, output: { type: 'number' }, name: 'add100', }, ); const job1 = scheduler.schedule('add', [1, 2, 3, 4]); const job2 = scheduler.schedule('add100', [1, 2, 3, 4, 5]); expect(started).toBe(0); expect(finished).toBe(0); job1.output.subscribe(); await flush(); expect(started).toBe(1); job2.output.subscribe(); await flush(); expect(started).toBe(1); // Job2 starts when Job1 ends. expect(finished).toBe(0); await Promise.all([ job1.output.toPromise().then((s) => { expect(finished).toBe(1); expect(s).toBe(10); }), job2.output.toPromise().then((s) => { expect(finished).toBe(2); expect(s).toBe(115); }), ]); expect(started).toBe(2); expect(finished).toBe(2); }); }); describe('strategy.reuse()', () => { let registry: SimpleJobRegistry; let scheduler: SimpleScheduler; beforeEach(() => { registry = new SimpleJobRegistry(); scheduler = new SimpleScheduler(registry); }); it('works', async () => { let started = 0; let finished = 0; registry.register( strategy.reuse()( createJobHandler((input: number[]) => { started++; return new Promise<number>((resolve) => setTimeout(() => { finished++; resolve(input.reduce((a, c) => a + c, 0)); }, 10), ); // eslint-disable-next-line @typescript-eslint/no-explicit-any }) as any, ), { argument: { items: { type: 'number' } }, output: { type: 'number' }, name: 'add', }, ); const job1 = scheduler.schedule('add', [1, 2, 3, 4]); const job2 = scheduler.schedule('add', []); expect(started).toBe(0); expect(finished).toBe(0); job1.output.subscribe(); await flush(); expect(started).toBe(1); expect(finished).toBe(0); job2.output.subscribe(); expect(started).toBe(1); // job2 is reusing job1. expect(finished).toBe(0); let result = await job1.output.toPromise(); expect(result).toBe(10); expect(started).toBe(1); expect(finished).toBe(1); expect(job1.state).toBe(JobState.Ended); expect(job2.state).toBe(JobState.Ended); const job3 = scheduler.schedule('add', [1, 2, 3, 4, 5]); const job4 = scheduler.schedule('add', []); job3.output.subscribe(); await flush(); expect(started).toBe(2); expect(finished).toBe(1); job4.output.subscribe(); expect(started).toBe(2); // job4 is reusing job3. expect(finished).toBe(1); result = await job3.output.toPromise(); expect(result).toBe(15); expect(started).toBe(2); expect(finished).toBe(2); expect(job3.state).toBe(JobState.Ended); expect(job4.state).toBe(JobState.Ended); }); });
{ "end_byte": 6059, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/strategy_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/strategy_spec.ts_6061_8764
describe('strategy.memoize()', () => { let registry: SimpleJobRegistry; let scheduler: SimpleScheduler; beforeEach(() => { registry = new SimpleJobRegistry(); scheduler = new SimpleScheduler(registry); }); it('works', async () => { let started = 0; let finished = 0; registry.register( strategy.memoize()( createJobHandler((input: number[]) => { started++; return new Promise<number>((resolve) => setTimeout(() => { finished++; resolve(input.reduce((a, c) => a + c, 0)); }, 10), ); // eslint-disable-next-line @typescript-eslint/no-explicit-any }) as any, ), { argument: { items: { type: 'number' } }, output: { type: 'number' }, name: 'add', }, ); const job1 = scheduler.schedule('add', [1, 2, 3, 4]); const job2 = scheduler.schedule('add', [1, 2, 3, 4]); const job3 = scheduler.schedule('add', [1, 2, 3, 4, 5]); const job4 = scheduler.schedule('add', [1, 2, 3, 4, 5]); expect(started).toBe(0); expect(finished).toBe(0); job1.output.subscribe(); await flush(); expect(started).toBe(1); expect(finished).toBe(0); job2.output.subscribe(); expect(started).toBe(1); // job2 is reusing job1. expect(finished).toBe(0); job3.output.subscribe(); await flush(); expect(started).toBe(2); expect(finished).toBe(0); job4.output.subscribe(); expect(started).toBe(2); // job4 is reusing job3. expect(finished).toBe(0); await Promise.all([ job1.output.toPromise().then((s) => { // This is hard since job3 and job1 might finish out of order. expect(finished).toBeGreaterThanOrEqual(1); expect(s).toBe(10); }), job2.output.toPromise().then((s) => { // This is hard since job3 and job1 might finish out of order. expect(finished).toBeGreaterThanOrEqual(1); expect(job1.state).toBe(JobState.Ended); expect(job2.state).toBe(JobState.Ended); expect(s).toBe(10); }), job3.output.toPromise().then((s) => { // This is hard since job3 and job1 might finish out of order. expect(finished).toBeGreaterThanOrEqual(1); expect(s).toBe(15); }), job4.output.toPromise().then((s) => { expect(job3.state).toBe(JobState.Ended); expect(job4.state).toBe(JobState.Ended); // This is hard since job3 and job1 might finish out of order. expect(finished).toBeGreaterThanOrEqual(1); expect(s).toBe(15); }), ]); expect(started).toBe(2); expect(finished).toBe(2); }); });
{ "end_byte": 8764, "start_byte": 6061, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/strategy_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/api.ts_0_8102
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonObject, JsonValue, schema } from '@angular-devkit/core'; import { Observable, Observer } from 'rxjs'; import { DeepReadonly } from './types'; /** * A job name is just a string (needs to be serializable). */ export type JobName = string; /** * The job handler function, which is a method that's executed for the job. */ export interface JobHandler< ArgT extends JsonValue, InputT extends JsonValue, OutputT extends JsonValue, > { ( argument: ArgT, context: JobHandlerContext<ArgT, InputT, OutputT>, ): Observable<JobOutboundMessage<OutputT>>; jobDescription: Partial<JobDescription>; } /** * The context in which the job is run. */ export interface JobHandlerContext< MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue, > { readonly description: JobDescription; readonly scheduler: Scheduler<JsonValue, JsonValue, JsonValue>; // In this context, JsonValue is comparable to `any`. readonly dependencies: Job<JsonValue, JsonValue, JsonValue>[]; readonly inboundBus: Observable<JobInboundMessage<MinimumInputValueT>>; } /** * Metadata associated with a job. */ export interface JobDescription extends JsonObject { readonly name: JobName; readonly argument: DeepReadonly<schema.JsonSchema>; readonly input: DeepReadonly<schema.JsonSchema>; readonly output: DeepReadonly<schema.JsonSchema>; } /** * Messages that can be sent TO a job. The job needs to listen to those. */ export enum JobInboundMessageKind { Ping = 'ip', Stop = 'is', // Channel specific messages. Input = 'in', // Input channel does not allow completion / error. Erroring this will just close the Subject // but not notify the job. } /** Base interface for the all job inbound messages. */ export interface JobInboundMessageBase extends JsonObject { /** * The kind of message this is. */ readonly kind: JobInboundMessageKind; } /** * A ping to the job. The job should reply with a pong as soon as possible. */ export interface JobInboundMessagePing extends JobInboundMessageBase { readonly kind: JobInboundMessageKind.Ping; /** * An ID that should be returned in the corresponding Pong. */ readonly id: number; } /** * Stop the job. This is handled by the job itself and jobs might not handle it. It will also * unsubscribe from the Observable<>. * This is equivalent to SIGTERM. */ export interface JobInboundMessageStop extends JobInboundMessageBase { readonly kind: JobInboundMessageKind.Stop; } /** * A Job wants to send a message to a channel. This can be marshaled, and the Job object * has helpers to transform this into an observable. The context also can create RxJS subjects that * marshall messages through a channel. */ export interface JobInboundMessageInput<InputT extends JsonValue> extends JobInboundMessageBase { readonly kind: JobInboundMessageKind.Input; /** * The input being sent to the job. */ readonly value: InputT; } export type JobInboundMessage<InputT extends JsonValue> = | JobInboundMessagePing | JobInboundMessageStop | JobInboundMessageInput<InputT>; /** * Kind of messages that can be outputted from a job. */ export enum JobOutboundMessageKind { // Lifecycle specific messages. OnReady = 'c', Start = 's', End = 'e', Pong = 'p', // Feedback messages. Output = 'o', // Channel specific messages. ChannelCreate = 'cn', ChannelMessage = 'cm', ChannelError = 'ce', ChannelComplete = 'cc', } /** Base interface for the all job messages. */ export interface JobOutboundMessageBase { /** * The job description. */ readonly description: JobDescription; /** * The kind of message this is. */ readonly kind: JobOutboundMessageKind; } /** * The job has been created and will validate its input. */ export interface JobOutboundMessageOnReady extends JobOutboundMessageBase { readonly kind: JobOutboundMessageKind.OnReady; } /** * The job started. This is done by the job itself. */ export interface JobOutboundMessageStart extends JobOutboundMessageBase { readonly kind: JobOutboundMessageKind.Start; } /** * An output value is available. */ export interface JobOutboundMessageOutput<OutputT extends JsonValue> extends JobOutboundMessageBase { readonly kind: JobOutboundMessageKind.Output; /** * The message being outputted from the job. */ readonly value: OutputT; } /** * Base interface for all job message related to channels. */ export interface JobOutboundMessageChannelBase extends JobOutboundMessageBase { /** * The name of the channel. */ readonly name: string; } /** * A job wants to send a message to a channel. This can be marshaled, and the Job object * has helpers to transform this into an observable. The context also can create RxJS subjects that * marshall messages through a channel. */ export interface JobOutboundMessageChannelMessage extends JobOutboundMessageChannelBase { readonly kind: JobOutboundMessageKind.ChannelMessage; /** * The message being sent to the channel. */ readonly message: JsonValue; } /** * A job wants to send an error to one of its channel. This is the equivalent of throwing through * an Observable. The side channel will not receive any more messages after this, and will not * complete. */ export interface JobOutboundMessageChannelError extends JobOutboundMessageChannelBase { readonly kind: JobOutboundMessageKind.ChannelError; /** * The error message being sent to the channel. */ readonly error: JsonValue; } /** * A job wants to create a new channel. */ export interface JobOutboundMessageChannelCreate extends JobOutboundMessageChannelBase { readonly kind: JobOutboundMessageKind.ChannelCreate; } /** * A job wants to close the channel, as completed. This is done automatically when the job ends, * or can be done from the job to close it. A closed channel might be reopened, but the user * need to recall getChannel(). */ export interface JobOutboundMessageChannelComplete extends JobOutboundMessageChannelBase { readonly kind: JobOutboundMessageKind.ChannelComplete; } /** * OnEnd of the job run. */ export interface JobOutboundMessageEnd extends JobOutboundMessageBase { readonly kind: JobOutboundMessageKind.End; } /** * A pong response from a ping input. The id is the same as the one passed in. */ export interface JobOutboundMessagePong extends JobOutboundMessageBase { readonly kind: JobOutboundMessageKind.Pong; /** * The ID that was passed in the `Ping` messages. */ readonly id: number; } /** * Generic message type. */ export type JobOutboundMessage<OutputT extends JsonValue> = | JobOutboundMessageOnReady | JobOutboundMessageStart | JobOutboundMessageOutput<OutputT> | JobOutboundMessageChannelCreate | JobOutboundMessageChannelMessage | JobOutboundMessageChannelError | JobOutboundMessageChannelComplete | JobOutboundMessageEnd | JobOutboundMessagePong; /** * The state of a job. These are changed as the job reports a new state through its messages. */ export enum JobState { /** * The job was queued and is waiting to start. */ Queued = 'queued', /** * The job description was found, its dependencies (see "Synchronizing and Dependencies") * are done running, and the job's argument is validated and the job's code will be executed. */ Ready = 'ready', /** * The job has been started. The job implementation is expected to send this as soon as its * work is starting. */ Started = 'started', /** * The job has ended and is done running. */ Ended = 'ended', /** * An error occured and the job stopped because of internal state. */ Errored = 'errored', } /** * A Job instance, returned from scheduling a job. A Job instance is _not_ serializable. */
{ "end_byte": 8102, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/api.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/api.ts_8103_12563
export interface Job< ArgumentT extends JsonValue = JsonValue, InputT extends JsonValue = JsonValue, OutputT extends JsonValue = JsonValue, > { /** * Description of the job. Resolving the job's description can be done asynchronously, so this * is an observable that will resolve when it's ready. */ readonly description: Observable<JobDescription>; /** * Argument sent when scheduling the job. This is a copy of the argument. */ readonly argument: ArgumentT; /** * The input to the job. This goes through the input channel as messages. */ readonly input: Observer<InputT>; /** * Outputs of this job. */ readonly output: Observable<OutputT>; /** * The current state of the job. */ readonly state: JobState; /** * Get a channel that validates against the schema. Messages will be filtered by the schema. * @param name The name of the channel. * @param schema A schema to use to validate messages. */ getChannel<T extends JsonValue>(name: string, schema?: schema.JsonSchema): Observable<T>; /** * Pings the job and wait for the resulting Pong before completing. */ ping(): Observable<never>; /** * Stops the job from running. This is different than unsubscribing from the output as in it * sends the JobInboundMessageKind.Stop raw input to the job. */ stop(): void; /** * The JobInboundMessage messages TO the job. */ readonly inboundBus: Observer<JobInboundMessage<InputT>>; /** * The JobOutboundMessage FROM the job. */ readonly outboundBus: Observable<JobOutboundMessage<OutputT>>; } /** * Options for scheduling jobs. */ export interface ScheduleJobOptions { /** * Jobs that need to finish before scheduling this job. These dependencies will be passed * to the job itself in its context. */ dependencies?: Job | Job[]; } export interface Registry< MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue, > { /** * Get a job handler. * @param name The name of the job to get a handler from. */ get<A extends MinimumArgumentValueT, I extends MinimumInputValueT, O extends MinimumOutputValueT>( name: JobName, ): Observable<JobHandler<A, I, O> | null>; } /** * An interface that can schedule jobs. */ export interface Scheduler< MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue, > { /** * Get a job description for a named job. * * @param name The name of the job. * @returns A description, or null if no description is available for this job. */ getDescription(name: JobName): Observable<JobDescription | null>; /** * Returns true if the job name has been registered. * @param name The name of the job. * @returns True if the job exists, false otherwise. */ has(name: JobName): Observable<boolean>; /** * Pause the scheduler, temporary queueing _new_ jobs. Returns a resume function that should be * used to resume execution. If multiple `pause()` were called, all their resume functions must * be called before the Scheduler actually starts new jobs. Additional calls to the same resume * function will have no effect. * * Jobs already running are NOT paused. This is pausing the scheduler only. * * @returns A function that can be run to resume the scheduler. If multiple `pause()` calls * were made, all their return function must be called (in any order) before the * scheduler can resume. */ pause(): () => void; /** * Schedule a job to be run, using its name. * @param name The name of job to be run. * @param argument The argument to send to the job when starting it. * @param options Scheduling options. * @returns The job being run. */ schedule< A extends MinimumArgumentValueT, I extends MinimumInputValueT, O extends MinimumOutputValueT, >( name: JobName, argument: A, options?: ScheduleJobOptions, ): Job<A, I, O>; } export function isJobHandler<A extends JsonValue, I extends JsonValue, O extends JsonValue>( value: unknown, ): value is JobHandler<A, I, O> { const job = value as JobHandler<A, I, O>; return ( typeof job == 'function' && typeof job.jobDescription == 'object' && job.jobDescription !== null ); }
{ "end_byte": 12563, "start_byte": 8103, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/api.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/simple-scheduler_spec.ts_0_7243
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { EMPTY, Observable, lastValueFrom, map, of, take, timer, toArray } from 'rxjs'; import { promisify } from 'util'; import { JobHandlerContext, JobOutboundMessage, JobOutboundMessageKind, JobState } from './api'; import { createJobHandler } from './create-job-handler'; import { SimpleJobRegistry } from './simple-registry'; import { JobArgumentSchemaValidationError, JobOutputSchemaValidationError, SimpleScheduler, } from './simple-scheduler'; const flush = promisify(setImmediate); describe('SimpleScheduler', () => { let registry: SimpleJobRegistry; let scheduler: SimpleScheduler; beforeEach(() => { registry = new SimpleJobRegistry(); scheduler = new SimpleScheduler(registry); }); it('works for a simple case', async () => { registry.register( 'add', createJobHandler((arg: number[]) => arg.reduce((a, c) => a + c, 0)), { argument: { items: { type: 'number' } }, output: { type: 'number' }, }, ); const sum = await scheduler.schedule('add', [1, 2, 3, 4]).output.toPromise(); expect(sum).toBe(10); }); it('calls jobs in parallel', async () => { let started = 0; let finished = 0; registry.register( 'add', createJobHandler((argument: number[]) => { started++; return new Promise<number>((resolve) => setTimeout(() => { finished++; resolve(argument.reduce((a, c) => a + c, 0)); }, 10), ); }), { argument: { items: { type: 'number' } }, output: { type: 'number' }, }, ); const job1 = scheduler.schedule('add', [1, 2, 3, 4]); const job2 = scheduler.schedule('add', [1, 2, 3, 4, 5]); expect(started).toBe(0); const p1 = job1.output.toPromise(); await flush(); expect(started).toBe(1); const p2 = job2.output.toPromise(); await flush(); expect(started).toBe(2); expect(finished).toBe(0); const [sum, sum2] = await Promise.all([p1, p2]); expect(started).toBe(2); expect(finished).toBe(2); expect(sum).toBe(10); expect(sum2).toBe(15); }); it('validates arguments', async () => { registry.register( 'add', createJobHandler((arg: number[]) => arg.reduce((a, c) => a + c, 0)), { argument: { items: { type: 'number' } }, output: { type: 'number' }, }, ); await scheduler.schedule('add', [1, 2, 3, 4]).output.toPromise(); await expectAsync( scheduler.schedule('add', ['1', 2, 3, 4]).output.toPromise(), ).toBeRejectedWithError(JobArgumentSchemaValidationError); }); it('validates outputs', async () => { registry.register( 'add', createJobHandler(() => 'hello world'), { output: { type: 'number' }, }, ); await expectAsync( scheduler.schedule('add', [1, 2, 3, 4]).output.toPromise(), ).toBeRejectedWithError(JobOutputSchemaValidationError); }); it('works with dependencies', async () => { const done: number[] = []; registry.register( 'job', createJobHandler<number, number, number>((argument) => { return new Promise((resolve) => setImmediate(() => { done.push(argument); resolve(argument); }), ); }), { argument: true, output: true }, ); // Run jobs. const job1 = scheduler.schedule('job', 1); const job2 = scheduler.schedule('job', 2); const job3 = scheduler.schedule('job', 3); // Run a job to wait for 1. const job4 = scheduler.schedule('job', 4, { dependencies: job1 }); // Run a job to wait for 2. const job5 = scheduler.schedule('job', 5, { dependencies: job2 }); // Run a job to wait for 3. const job6 = scheduler.schedule('job', 6, { dependencies: job3 }); // Run a job to wait for 4, 5 and 6. const job7 = scheduler.schedule('job', 7, { dependencies: [job4, job5, job6] }); expect(done.length).toBe(0); await job1.output.toPromise(); expect(done).toContain(1); expect(done).not.toContain(4); expect(done).not.toContain(7); await job5.output.toPromise(); expect(done).toContain(1); expect(done).toContain(2); expect(done).not.toContain(4); expect(done).toContain(5); expect(done).not.toContain(7); await job7.output.toPromise(); expect(done.length).toBe(7); // Might be out of order. expect(done).toEqual(jasmine.arrayContaining([1, 2, 3, 4, 5, 6, 7])); // Verify at least partial order. expect(done[done.length - 1]).toBe(7); expect(done.indexOf(4)).toBeGreaterThan(done.indexOf(1)); expect(done.indexOf(5)).toBeGreaterThan(done.indexOf(2)); expect(done.indexOf(6)).toBeGreaterThan(done.indexOf(3)); }); it('does not start dependencies until the last one is subscribed to', async () => { // This test creates the following graph of dependencies: // 1 <-.-- 2 <-.-- 4 <-.---------.-- 6 // +-- 3 <-+-- 5 <-' // Which can result only in the execution orders: [1, 2, 3, 4, 5, 6] // Only subscribe to the last one. const started: number[] = []; const done: number[] = []; registry.register( 'job', createJobHandler<number, number, number>((argument: number) => { started.push(argument); return new Promise((resolve) => setTimeout(() => { done.push(argument); resolve(argument); }, 10), ); }), { argument: true, output: true }, ); // Run jobs. const job1 = scheduler.schedule('job', 1); const job2 = scheduler.schedule('job', 2, { dependencies: job1 }); const job3 = scheduler.schedule('job', 3, { dependencies: job2 }); const job4 = scheduler.schedule('job', 4, { dependencies: [job2, job3] }); const job5 = scheduler.schedule('job', 5, { dependencies: [job1, job2, job4] }); const job6 = scheduler.schedule('job', 6, { dependencies: [job4, job5] }); // Just subscribe to the last job in the lot. job6.outboundBus.subscribe(); await flush(); // Expect the first one to start. expect(started).toEqual([1]); // Wait for the first one to finish. await job1.output.toPromise(); await flush(); // Expect the second one to have started, and the first one to be done. expect(started).toEqual([1, 2]); expect(done).toEqual([1]); // Rinse and repeat. await job2.output.toPromise(); await flush(); expect(started).toEqual([1, 2, 3]); expect(done).toEqual([1, 2]); await job3.output.toPromise(); await flush(); expect(started).toEqual([1, 2, 3, 4]); expect(done).toEqual([1, 2, 3]); await job4.output.toPromise(); await flush(); expect(started).toEqual([1, 2, 3, 4, 5]); expect(done).toEqual([1, 2, 3, 4]); // Just skip job 5. await job6.output.toPromise(); await flush(); expect(done).toEqual(started); });
{ "end_byte": 7243, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/simple-scheduler_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/simple-scheduler_spec.ts_7247_14545
it('can be paused', async () => { let resume: (() => void) | null = null; registry.register( 'job', createJobHandler((argument, context) => { return Promise.resolve() .then(() => { expect(resume).toBeNull(); resume = context.scheduler.pause(); }) .then(() => argument); }), ); // Run the job once. Wait for it to finish. We should have a `resume()` and the scheduler will // be paused. const p0 = scheduler.schedule('job', 0).output.toPromise(); expect(await p0).toBe(0); // This will wait. const p1 = scheduler.schedule('job', 1).output.toPromise(); await Promise.resolve(); expect(resume).not.toBeNull(); resume!(); resume = null; // Running p1. expect(await p1).toBe(1); expect(resume).not.toBeNull(); const p2 = scheduler.schedule('job', 2).output.toPromise(); await Promise.resolve(); resume!(); resume = null; expect(await p2).toBe(2); expect(resume).not.toBeNull(); resume!(); // Should not error since all jobs have run. await Promise.resolve(); }); it('can be paused (multiple)', async () => { const done: number[] = []; registry.register( 'jobA', createJobHandler((argument: number) => { done.push(argument); return Promise.resolve().then(() => argument); }), ); // Pause manually. const resume = scheduler.pause(); const p10 = scheduler.schedule('jobA', 10).output.toPromise(); const p11 = scheduler.schedule('jobA', 11).output.toPromise(); const p12 = scheduler.schedule('jobA', 12).output.toPromise(); await flush(); expect(done).toEqual([]); resume(); await flush(); expect(done).not.toEqual([]); expect(await p10).toBe(10); expect(await p11).toBe(11); expect(await p12).toBe(12); expect(done).toEqual([10, 11, 12]); }); it('can be cancelled by unsubscribing from the raw output', async () => { const done: number[] = []; const resolves: (() => void)[] = []; let keepGoing = true; registry.register( 'job', createJobHandler((argument: number) => { return new Observable<number>((observer) => { function fn() { if (keepGoing) { const p = new Promise<void>((r) => resolves.push(r)); observer.next(argument); done.push(argument); argument++; // eslint-disable-next-line @typescript-eslint/no-floating-promises p.then(fn); } else { done.push(-1); observer.complete(); } } setImmediate(fn); return () => { keepGoing = false; }; }); }), ); const job = scheduler.schedule('job', 0); await new Promise((r) => setTimeout(r, 10)); expect(job.state).toBe(JobState.Queued); const subscription = job.output.subscribe(); await new Promise((r) => setTimeout(r, 10)); expect(job.state).toBe(JobState.Started); expect(done).toEqual([0]); expect(resolves.length).toBe(1); resolves[0](); await new Promise((r) => setTimeout(r, 10)); expect(done).toEqual([0, 1]); expect(resolves.length).toBe(2); resolves[1](); await new Promise((r) => setTimeout(r, 10)); expect(done).toEqual([0, 1, 2]); expect(resolves.length).toBe(3); subscription.unsubscribe(); resolves[2](); job.stop(); await job.output.toPromise(); expect(keepGoing).toBe(false); expect(done).toEqual([0, 1, 2, -1]); expect(job.state).toBe(JobState.Ended); }); it('sequences raw outputs properly for all use cases', async () => { registry.register( 'job-sync', createJobHandler<number, number, number>((arg) => arg + 1), ); registry.register( 'job-promise', createJobHandler<number, number, number>((arg) => { return Promise.resolve(arg + 1); }), ); registry.register( 'job-obs-sync', createJobHandler<number, number, number>((arg) => of(arg + 1)), ); registry.register( 'job-obs-async', createJobHandler<number, number, number>((arg) => { return timer(1).pipe( take(3), take(1), map(() => arg + 1), ); }), ); const job1 = scheduler.schedule('job-sync', 100); const job1OutboundBus = await job1.outboundBus .pipe( // Descriptions are going to differ, so get rid of those. map((x) => ({ ...x, description: null })), toArray(), ) .toPromise(); const job2 = scheduler.schedule('job-promise', 100); const job2OutboundBus = await job2.outboundBus .pipe( // Descriptions are going to differ, so get rid of those. map((x) => ({ ...x, description: null })), toArray(), ) .toPromise(); const job3 = scheduler.schedule('job-obs-sync', 100); const job3OutboundBus = await job3.outboundBus .pipe( // Descriptions are going to differ, so get rid of those. map((x) => ({ ...x, description: null })), toArray(), ) .toPromise(); const job4 = scheduler.schedule('job-obs-async', 100); const job4OutboundBus = await job4.outboundBus .pipe( // Descriptions are going to differ, so get rid of those. map((x) => ({ ...x, description: null })), toArray(), ) .toPromise(); // The should all report the same stuff. expect(job1OutboundBus).toEqual(job4OutboundBus); expect(job2OutboundBus).toEqual(job4OutboundBus); expect(job3OutboundBus).toEqual(job4OutboundBus); }); describe('channels', () => { it('works', async () => { registry.register( 'job', createJobHandler<number, number, number>((argument, context) => { const channel = context.createChannel('any'); channel.next('hello world'); channel.complete(); return 0; }), ); const job = scheduler.schedule('job', 0); let sideValue = ''; // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const c = job.getChannel('any') as Observable<string>; c.subscribe((x) => (sideValue = x)); expect(await job.output.toPromise()).toBe(0); expect(sideValue).toBe('hello world'); }); it('validates', async () => { registry.register( 'job', createJobHandler<number, number, number>((argument, context) => { const channel = context.createChannel('any'); channel.next('hello world'); channel.complete(); return 0; }), { argument: true, output: true, }, ); const job = scheduler.schedule('job', 0); let sideValue = ''; // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const c = job.getChannel('any', { type: 'number' }) as Observable<string>; expect(c).toBeDefined(null); if (c) { c.subscribe((x) => (sideValue = x)); } expect(await job.output.toPromise()).toBe(0); expect(sideValue).not.toBe('hello world'); }); });
{ "end_byte": 14545, "start_byte": 7247, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/simple-scheduler_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/simple-scheduler_spec.ts_14549_20131
describe('lifecycle messages', () => { it('sequences double start once', async () => { const fn = (_: never, { description }: JobHandlerContext) => { return new Observable<JobOutboundMessage<never>>((observer) => { observer.next({ kind: JobOutboundMessageKind.Start, description }); observer.next({ kind: JobOutboundMessageKind.Start, description }); observer.next({ kind: JobOutboundMessageKind.End, description }); observer.complete(); }); }; registry.register('job', Object.assign(fn, { jobDescription: {} })); const allOutput = await lastValueFrom( scheduler.schedule('job', 0).outboundBus.pipe(toArray()), ); expect(allOutput.map((x) => ({ ...x, description: null }))).toEqual([ { kind: JobOutboundMessageKind.OnReady, description: null }, { kind: JobOutboundMessageKind.Start, description: null }, { kind: JobOutboundMessageKind.End, description: null }, ]); }); it('add an End if there is not one', async () => { const fn = () => EMPTY; registry.register('job', Object.assign(fn, { jobDescription: {} })); const allOutput = await lastValueFrom( scheduler.schedule('job', 0).outboundBus.pipe(toArray()), ); expect(allOutput.map((x) => ({ ...x, description: null }))).toEqual([ { kind: JobOutboundMessageKind.OnReady, description: null }, { kind: JobOutboundMessageKind.End, description: null }, ]); }); it('only one End', async () => { const fn = (_: never, { description }: JobHandlerContext) => { return new Observable<JobOutboundMessage<never>>((observer) => { observer.next({ kind: JobOutboundMessageKind.End, description }); observer.next({ kind: JobOutboundMessageKind.End, description }); observer.complete(); }); }; registry.register('job', Object.assign(fn, { jobDescription: {} })); const allOutput = await lastValueFrom( scheduler.schedule('job', 0).outboundBus.pipe(toArray()), ); expect(allOutput.map((x) => ({ ...x, description: null }))).toEqual([ { kind: JobOutboundMessageKind.OnReady, description: null }, { kind: JobOutboundMessageKind.End, description: null }, ]); }); }); describe('input', () => { it('works', async () => { registry.register( 'job', createJobHandler<number, number, number>((argument, context) => { return new Observable<number>((subscriber) => { context.input.subscribe((x) => { if (x === null) { subscriber.complete(); } else { subscriber.next(parseInt('' + x) + argument); } }); }); }), ); const job = scheduler.schedule('job', 100); const outputs: number[] = []; job.output.subscribe((x) => outputs.push(x as number)); job.input.next(1); job.input.next('2'); job.input.next(3); job.input.next(null); expect(await job.output.toPromise()).toBe(103); expect(outputs).toEqual([101, 102, 103]); }); it('validates', async () => { const handler = createJobHandler<number, number, number>( (argument, context) => { return new Observable<number>((subscriber) => { context.input.subscribe((x) => { if (x === null) { subscriber.complete(); } else { subscriber.next(parseInt('' + x) + argument); } }); }); }, { input: { anyOf: [{ type: 'number' }, { type: 'null' }] }, }, ); registry.register('job', handler); const job = scheduler.schedule('job', 100); const outputs: number[] = []; job.output.subscribe((x) => outputs.push(x as number)); job.input.next(1); job.input.next('2'); job.input.next(3); job.input.next(null); expect(await job.output.toPromise()).toBe(103); expect(outputs).toEqual([101, 103]); }); it('works deferred', async () => { // This is a more complex test. The job returns an output deferred from the input registry.register( 'job', createJobHandler<number, number, number>((argument, context) => { return new Observable<number>((subscriber) => { context.input.subscribe((x) => { if (x === null) { setTimeout(() => subscriber.complete(), 10); } else { setTimeout(() => subscriber.next(parseInt('' + x) + argument), x); } }); }); }), ); const job = scheduler.schedule('job', 100); const outputs: number[] = []; job.output.subscribe((x) => outputs.push(x as number)); job.input.next(1); job.input.next(2); job.input.next(3); job.input.next(null); expect(await job.output.toPromise()).toBe(103); expect(outputs).toEqual(jasmine.arrayWithExactContents([101, 102, 103])); }); }); it('propagates errors', async () => { registry.register( 'job', createJobHandler(() => { // eslint-disable-next-line no-throw-literal throw 1; }), ); const job = scheduler.schedule('job', 0); try { await job.output.toPromise(); expect('THE ABOVE LINE SHOULD NOT ERROR').toBe('false'); } catch (error) { expect(error).toBe(1); } }); });
{ "end_byte": 20131, "start_byte": 14549, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/simple-scheduler_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/README.md_0_5517
# Description Jobs is the Angular DevKit subsystem for scheduling and running generic functions with clearly typed inputs and outputs. A `Job` instance is a function associated with metadata. You can schedule a job, synchronize it with other jobs, and use it to schedule other jobs. The whole API is serializable, allowing you to use a Node Stream or message channel to communicate between the job and the job scheduler. Jobs are lazy, cold, and guaranteed to execute exactly once when scheduled. Subscribing to a job returns messages from the point where the job is at. ## Argument, Input, Output and Channels A job receives a single argument when scheduled and can also listen to an input channel. It can emit multiple outputs, and can also provide multiple output channels that emit asynchronous JSON messages, which can be typed. The I/O model is like that of an executable, where the argument corresponds to arguments on the command line, the input channel to STDIN, the output channel to STDOUT, and the channels would be additional output streams. ## LifeCycle A `Job` goes through multiple LifeCycle messages before its completion; 1. `JobState.Queued`. The job was queued and is waiting. This is the default state from the scheduler. 1. `JobState.Ready`. The job's dependencies (see ["Synchronizing and Dependencies"](#Dependencies)) are done running, the argument is validated, and the job is ready to execute. 1. `JobState.Started`. The argument has been validated, the job has been called and is running. This is handled by the job itself (or `createJobHandler()`). 1. `JobState.Ended`. The job has ended and is done running. This is handled by the job itself (or `createJobHandler()`). 1. `JobState.Errored`. A unrecoverable error happened. Each state (except `Queued`) corresponds to a `JobOutboundMessage` on the `outboundBus` observable that triggers the state change. The `Scheduler` emits the `Ready` and `Errored` messages; the job implementation should not emit them, and if it does they are filtered out. You can listen for these messages or use the corresponding state member. The job implementation should emit the `Start` and `End` messages when it is starting the job logic itself. Only the first `Start` and `End` messages will be forwarded. Any more will be filtered out. The `Queued` state is set as the job is scheduled, so there is no need to listen for the message. ## `Job<OutputType>` Object The `Job` object that is returned when you schedule a job provides access to the job's status and utilities for tracking and modifying the job. 1. `id`. A unique symbol that can be used as a Map key. 1. `description`. The description of the job from the scheduler. See `JobDescription` object. 1. `argument`. The argument value that was used to start the job. 1. `input`. An `Observer` that can be used to send validated inputs to the job itself. 1. `output`. An `Observable<OutputType>` that filters out messages to get only the returned output of a job. 1. `promise`. A promise that waits for the last output of a job. Returns the last value outputted (or no value if there's no last value). 1. `state`. The current state of the job (see `LifeCycle`). 1. `channels`. A map of side channels the user can listen to as `Observable`. 1. `ping()`. A function that can be used to ping the job, receiving a `Promise` for when the ping is answered. 1. `stop()`. Sends a `stop` input to the job, which suggests to stop the job. The job itself can choose to ignore this message. 1. `inboundBus`. The raw input `Observer<JobInboundMessage>`. This can be used to send messages to the `context.inboundBus` observable in the job. These are `JobInboundMessage` messages. See ["Communicating With Jobs"](#Communicating). 1. `outboundBus`. The raw output `Observable<JobOutput>`. This can be used to listen to messages from the job. See ["Communicating With Jobs"](#Communicating). ## `JobHandlerContext<I, O>` Object The `JobHandlerContext<>` is passed to the job handler code in addition to its argument. The context contains the following members: 1. `description`. The description of the job. Its name and schemas. 1. `scheduler`. A `Scheduler<>` instance that can be used to create additional jobs. 1. `dependencies`. A generic list of other job instances that were run as dependencies when scheduling this job. Their `id` is not guaranteed to match the `id` of the `Job<>` instance itself (those `Job<>`s might just be proxies). The state of those `Job<>` is guaranteed to be `JobState.Ended`, as `JobState.Errored` would have prevented this handler from running. 1. `inboundBus`. The raw input observable, complement of the `inboundBus` observer from the `Job<>`. # Examples An example of a job that adds all input together and return the output value. We use a simple synchronous job registry and a simple job scheduler. ```typescript import { jobs } from '@angular-devkit/core'; const add = jobs.createJobHandle<number[], number>((input) => input.reduce((total, curr) => total + curr, 0), ); // Register the job in a SimpleJobRegistry. Different registries have different API. const registry = new jobs.SimpleJobRegistry(); const scheduler = new jobs.SimpleScheduler(registry); registry.register(add, { name: 'add', input: { type: 'array', items: { type: 'number' } }, output: { type: 'number' }, }); scheduler .schedule('add', [1, 2, 3, 4]) .promise.then((output) => console.log('1 + 2 + 3 + 4 is ' + output)); ```
{ "end_byte": 5517, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/README.md" }
angular-cli/packages/angular_devkit/architect/src/jobs/README.md_5517_13076
# Creating Jobs A job is at its core a function with a description object attached to it. The description object stores the JSON schemas used to validate the types of the argument passed in, the input and output values. By default, a job accepts and can output any JSON object. ```typescript import { Observable } from 'rxjs'; import { jobs } from '@angular-devkit/core'; const argument = { type: 'array', items: { type: 'number' }, }; const output = { type: 'number', }; export function add(argument: number[]): Observable<jobs.JobOutboundMessage<number>> { return new Observable((o) => { o.next({ kind: jobs.JobOutboundMessageKind.Start }); o.next({ kind: jobs.JobOutboundMessageKind.Output, output: argument.reduce((total, curr) => total + curr, 0), }); o.next({ kind: jobs.JobOutboundMessageKind.End }); o.complete(); }); } // Add a property to `add` to make it officially a JobHandler. The Job system does not recognize // any function as a JobHandler. add.jobDescription = { argument: argument, output: output, }; // Call the job with an array as argument, and log its output. declare const scheduler: jobs.Scheduler; scheduler.schedule('add', [1, 2, 3, 4]).output.subscribe((x) => console.log(x)); // Will output 10. ``` This is a lot of boilerplate, so we made some helpers to improve readability and manage argument, input and output automatically: ```typescript // Add is a JobHandler function, like the above. export const add = jobs.createJobHandler<number[], number>((argument) => argument.reduce((total, curr) => total + curr, 0), ); // Schedule like above. ``` You can also return a Promise or an Observable, as jobs are asynchronous. This helper will set start and end messages appropriately. It will also manage channels automatically (see below). A more complex job can be declared like this: ```typescript import { Observable } from 'rxjs'; import { jobs } from '@angular-devkit/core'; // Show progress with each count in a separate output channel. Output "more" in a channel. export const count = jobs.createJobHandler<number, number>( // Receive a context that contains additional methods to create channels. (argument: number, { createChannel }) => new Observable<number>((o) => { const side = createChannel('side', { type: 'string', const: 'more' }); const progress = createChannel('progress', { type: 'number' }); let i = 0; function doCount() { o.next(i++); progress.next(i / argument); side.next('more'); if (i < argument) { setTimeout(doCount, 100); } else { o.complete(); } } setTimeout(doCount, 100); }), { argument: { type: 'number' }, output: { type: 'number' }, }, ); // Get a hold of a scheduler that refers to the job above. declare const scheduler: jobs.Scheduler; const job = scheduler.schedule('count', 0); job.getChannel('side').subscribe((x) => console.log(x)); // You can type a channel too. Messages will be filtered out. job.getChannel<number>('progress', { type: 'number' }).subscribe((x) => console.log(x)); ``` ## <a name="Communicating"></a>Communicating With Jobs Jobs can be started and updated in a separate process or thread, and as such communication with a job should avoid using global objects (which might not be shared). The jobs API and schedulers provide 2 communication streams (one for input and the other for output), named `inboundBus` and `outboundBus`. ### Raw Input Stream The `schedule()` function returns a `Job<>` interface that contains a `inboundBus` member of type `Observer<JobInboundMessage>`. All messages sent _to_ the job goes through this stream. The `kind` member of the `JobInboundMessage` interface dictates what kind of message it is sending: 1. `JobInboundMessageKind.Ping`. A simple message that should be answered with `JobOutboundMessageKind.Pong` when the job is responsive. The `id` field of the message should be used when returning `Pong`. 1. `JobInboundMessageKind.Stop`. The job should be stopped. This is used when cancelling/unsubscribing from the `output` (or by calling `stop()`). Any inputs or outputs after this message will be ignored. 1. `JobInboundMessageKind.Input` is used when sending inputs to a job. These correspond to the `next` methods of an `Observer` and are reported to the job through its `context.input` Observable. There is no way to communicate an error to the job. Using the `createJobHandler()` helper, all those messages are automatically handled by the boilerplate code. If you need direct access to raw inputs, you should subscribe to the `context.inboundBus` Observable. ### Raw Output Stream The `Job<>` interface also contains a `outboundBus` member (of type `Observable<JobOutboundMessage<O>>` where `O` is the typed output of the job) which is the output complement of `inboundBus`. All messages sent _from_ the job goes through this stream. The `kind` member of the `JobOutboundMessage<O>` interface dictates what kind of message it is sending: 1. `JobOutboundMessageKind.Create`. The `Job<>` was created, its dependencies are done, and the library is validating Argument and calling the internal job code. 1. `JobOutboundMessageKind.Start`. The job code itself should send that message when started. `createJobHandler()` will do it automatically. 1. `JobOutboundMessageKind.End`. The job has ended. This is done by the job itself and should always be sent when completed. The scheduler will listen to this message to set the state and unblock dependent jobs. `createJobHandler()` automatically send this message. 1. `JobOutboundMessageKind.Pong`. The job should answer a `JobInboundMessageKind.Ping` message with this. Automatically done by `createJobHandler()`. 1. `JobOutboundMessageKind.Output`. An `Output` has been generated by the job. 1. `JobOutboundMessageKind.ChannelMessage`, `JobOutboundMessageKind.ChannelError` and `JobOutboundMessageKind.ChannelComplete` are used for output channels. These correspond to the `next`, `error` and `complete` methods of an `Observer` and are available to the callee through the `job.channels` map of Observable. Those messages can be accessed directly through the `job.outboundBus` member. The job itself should return an `Observable<JobOutboundMessage<O>>`. The `createJobHandler()` helper handles most of use cases of this and makes it easier for jobs to handle this. ## Job Dispatchers Dispatchers are a helper that redirect to different jobs given conditions. To create a job dispatcher, use the `createDispatcher()` function: ```typescript import { jobs } from '@angular-devkit/core'; // A dispatcher that installs node modules given a user's preference. const dispatcher = jobs.createDispatcher({ name: 'node-install', argument: { properties: { moduleName: { type: 'string' } } }, output: { type: 'boolean' }, }); const npmInstall = jobs.createJobHandler(/* ... */, { name: 'npm-install' }); const yarnInstall = jobs.createJobHandler(/* ... */, { name: 'yarn-install' }); const pnpmInstall = jobs.createJobHandler(/* ... */, { name: 'pnpm-install' }); declare const registry: jobs.SimpleJobRegistry; registry.register(dispatcher); registry.register(npmInstall); registry.register(yarnInstall); registry.register(pnpmInstall); // Default to npm. dispatcher.setDefaultDelegate(npmInstall.name); // If the user is asking for yarn over npm, uses it. dispatcher.addConditionalDelegate(() => userWantsYarn, yarnInstall.name); ```
{ "end_byte": 13076, "start_byte": 5517, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/README.md" }
angular-cli/packages/angular_devkit/architect/src/jobs/README.md_13076_21254
## Execution Strategy Jobs are always run in parallel and will always start, but many helper functions are provided when creating a job to help you control the execution strategy; 1. `serialize()`. Multiple runs of this job will be queued with each others. 1. `memoize(replayMessages = false)` will create a job, or reuse the same job when inputs are matching. If the inputs don't match, a new job will be started and its outputs will be stored. These strategies can be used when creating the job: ```typescript // Same input and output as above. export const add = jobs.strategy.memoize()( jobs.createJobHandler<number[], number>((argument) => argument.reduce((total, curr) => total + curr, 0), ), ); ``` Strategies can be reused to synchronize between jobs. For example, given jobs `jobA` and `jobB`, you can reuse the strategy to serialize both jobs together; ```typescript const strategy = jobs.strategy.serialize(); const jobA = strategy(jobs.createJobHandler(...)); const jobB = strategy(jobs.createJobHandler(...)); ``` Even further, we can have package A and package B run in serialization, and B and C also be serialized. Running A and C will run in parallel, while running B will wait for both A and C to finish. ```typescript const strategy1 = jobs.strategy.serialize(); const strategy2 = jobs.strategy.serialize(); const jobA = strategy1(jobs.createJobHandler(...)); const jobB = strategy1(strategy2(jobs.createJobHandler(...))); const jobC = strategy2(jobs.createJobHandler(...)); ``` # Scheduling Jobs Jobs can be scheduled using a `Scheduler` interface, which contains a `schedule()` method: ```typescript interface Scheduler { /** * Schedule a job to be run, using its name. * @param name The name of job to be run. * @param argument The argument to send to the job when starting it. * @param options Scheduling options. * @returns The Job being run. */ schedule<I extends MinimumInputValueT, O extends MinimumOutputValueT>( name: JobName, argument: I, options?: ScheduleJobOptions, ): Job<JsonValue, O>; } ``` The scheduler also has a `getDescription()` method to get a `JobDescription` object for a certain name; that description contains schemas for the argument, input, output, and other channels: ```typescript interface Scheduler { /** * Get a job description for a named job. * * @param name The name of the job. * @returns A description, or null if the job cannot be scheduled. */ getDescription(name: JobName): JobDescription | null; /** * Returns true if the job name has been registered. * @param name The name of the job. * @returns True if the job exists, false otherwise. */ has(name: JobName): boolean; } ``` Finally, the scheduler interface has a `pause()` method to stop scheduling. This will queue all jobs and wait for the unpause function to be called before unblocking all the jobs scheduled. This does not affect already running jobs. ```typescript interface Scheduler { /** * Pause the scheduler, temporary queueing _new_ jobs. Returns a resume function that should be * used to resume execution. If multiple `pause()` were called, all their resume functions must * be called before the Scheduler actually starts new jobs. Additional calls to the same resume * function will have no effect. * * Jobs already running are NOT paused. This is pausing the scheduler only. * * @returns A function that can be run to resume the scheduler. If multiple `pause()` calls * were made, all their return function must be called (in any order) before the * scheduler can resume. */ pause(): () => void; } ``` ## <a name="Dependencies"></a>Synchronizing and Dependencies When scheduling jobs, it is often necessary to run jobs after certain other jobs are finished. This is done through the `dependencies` options in the `schedule()` method. These jobs will also be passed to the job being scheduled, through its context. This can be useful if, for example, the output of those jobs are of a known type, or have known side channels. An example of this would be a compiler that needs to know the output directory of other compilers before it, in a tool chain. ### Dependencies When scheduling jobs, the user can add a `dependencies` field to the scheduling options. The scheduler will wait for those dependencies to finish before running the job, and pass those jobs in the context of the job. ### Accessing Dependencies Jobs are called with a `JobHandlerContext` as a second argument, which contains a `dependencies: Job<JsonValue>[]` member which contains all dependencies that were used when scheduling the job. Those aren't fully typed as they are determined by the user, and not the job itself. They also can contain jobs that are not finished, and the job should use the `state` member of the job itself before trying to access its content. ### Scheduler Sub Jobs The `JobHandlerContext` also contains a `scheduler` member which can be used to schedule jobs using the same scheduler that was used for the job. This allows jobs to call other jobs and wait for them to end. ## Available Schedulers The Core Angular DevKit library provides 2 implementations for the `Scheduler` interface: ## SimpleJobRegistry Available in the jobs namespace. A registry that accept job registration, and can also schedule jobs. ```typescript import { jobs } from '@angular-devkit/core'; const add = jobs.createJobHandler<number[], number>((argument) => argument.reduce((total, curr) => total + curr, 0), ); // Register the job in a SimpleJobRegistry. Different registries have different API. const registry = new jobs.SimpleJobRegistry(); const scheduler = new SimpleJobScheduler(registry); registry.register(add, { name: 'add', argument: { type: 'array', items: { type: 'number' } }, output: { type: 'number' }, }); scheduler.schedule('add', [1, 2, 3, 4]); ``` ## NodeModuleJobRegistry Available through `@angular-devkit/core/node`. A scheduler that loads jobs using their node package names. These jobs need to use the `createJobHandler()` helper and report their argument/input/output schemas that way. ```typescript declare const registry: NodeModuleJobRegistry; const scheduler = new SimpleJobScheduler(registry); scheduler.schedule('some-node-package#someExport', 'input'); ``` # Gotchas 1. Deadlocking Dependencies It is impossible to add dependencies to an already running job, but it is entirely possible to get locked between jobs. Be aware of your own dependencies. 1. Using `job.promise` `job.promise` waits for the job to ends. Don't rely on it unless you know the job is not watching and running for a long time. If you aren't sure, use `job.output.pipe(first()).toPromise()` instead which will return the first next output, regardless of whether the job watches and rerun or not. # FAQ 1. Laziness A job is lazy until executed, but its messages will be replayed when resubscribed. 1. Serialize Strategy vs Dependencies Strategies are functions that transform the execution of a job, and can be used when declaring the job, or registering it. Dependencies, on the other hand, are listed when scheduling a job to order jobs during scheduling. A job has no control over the way it's scheduled, and its dependencies. It can, however, declare that it shouldn't run at the same time as itself. Alternatively, a user could schedule a job twice and imply that the second run should wait for the first to finish. In practice, this would be equivalent to having the job be serialized, but the important detail is in _whom_ is defining the rules; using the `serialize()` strategy, the job implementation is, while when using dependencies, the user is. The user does not need to know how to job needs to synchronize with itself, and the job does not need to know how it synchronizes with other jobs that it doesn't know about. That's part of the strength of this system as every job can be developed in a vacuum, only caring about its contracts (argument, input and output) and its own synchronization.
{ "end_byte": 21254, "start_byte": 13076, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/README.md" }
angular-cli/packages/angular_devkit/architect/src/jobs/types.ts_0_649
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export type DeepReadonly<T> = T extends (infer R)[] ? DeepReadonlyArray<R> : T extends Function ? T : T extends object ? DeepReadonlyObject<T> : T; // This should be ReadonlyArray but it has implications. export type DeepReadonlyArray<T> = Array<DeepReadonly<T>>; export type DeepReadonlyObject<T> = { readonly [P in keyof T]: DeepReadonly<T[P]>; }; export type Readwrite<T> = { -readonly [P in keyof T]: T[P]; };
{ "end_byte": 649, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/types.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/strategy.ts_0_4482
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonObject, JsonValue, isJsonObject } from '@angular-devkit/core'; import { Observable, Subject, concat, finalize, ignoreElements, of, share, shareReplay, tap, } from 'rxjs'; import { JobDescription, JobHandler, JobHandlerContext, JobInboundMessage, JobOutboundMessage, JobOutboundMessageKind, } from './api'; export type JobStrategy< A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue, > = ( handler: JobHandler<A, I, O>, options?: Partial<Readonly<JobDescription>>, ) => JobHandler<A, I, O>; /** * Creates a JobStrategy that serializes every call. This strategy can be mixed between jobs. */ export function serialize< A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue, >(): JobStrategy<A, I, O> { let latest: Observable<JobOutboundMessage<O>> = of(); return (handler, options) => { const newHandler = (argument: A, context: JobHandlerContext<A, I, O>) => { const previous = latest; latest = concat( previous.pipe(ignoreElements()), new Observable<JobOutboundMessage<O>>((o) => handler(argument, context).subscribe(o)), ).pipe(shareReplay(0)); return latest; }; return Object.assign(newHandler, { jobDescription: Object.assign({}, handler.jobDescription, options), }); }; } /** * Creates a JobStrategy that will always reuse a running job, and restart it if the job ended. * @param replayMessages Replay ALL messages if a job is reused, otherwise just hook up where it * is. */ export function reuse< A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue, >(replayMessages = false): JobStrategy<A, I, O> { let inboundBus = new Subject<JobInboundMessage<I>>(); let run: Observable<JobOutboundMessage<O>> | null = null; let state: JobOutboundMessage<O> | null = null; return (handler, options) => { const newHandler = (argument: A, context: JobHandlerContext<A, I, O>) => { // Forward inputs. const subscription = context.inboundBus.subscribe(inboundBus); if (run) { return concat( // Update state. of(state), run, ).pipe(finalize(() => subscription.unsubscribe())); } run = handler(argument, { ...context, inboundBus: inboundBus.asObservable() }).pipe( tap( (message) => { if ( message.kind == JobOutboundMessageKind.Start || message.kind == JobOutboundMessageKind.OnReady || message.kind == JobOutboundMessageKind.End ) { state = message; } }, undefined, () => { subscription.unsubscribe(); inboundBus = new Subject<JobInboundMessage<I>>(); run = null; }, ), replayMessages ? shareReplay() : share(), ); return run; }; return Object.assign(newHandler, handler, options || {}); }; } /** * Creates a JobStrategy that will reuse a running job if the argument matches. * @param replayMessages Replay ALL messages if a job is reused, otherwise just hook up where it * is. */ export function memoize< A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue, >(replayMessages = false): JobStrategy<A, I, O> { const runs = new Map<string, Observable<JobOutboundMessage<O>>>(); return (handler, options) => { const newHandler = (argument: A, context: JobHandlerContext<A, I, O>) => { const argumentJson = JSON.stringify( isJsonObject(argument) ? Object.keys(argument) .sort() .reduce((result, key) => { result[key] = argument[key]; return result; }, {} as JsonObject) : argument, ); const maybeJob = runs.get(argumentJson); if (maybeJob) { return maybeJob; } const run = handler(argument, context).pipe(replayMessages ? shareReplay() : share()); runs.set(argumentJson, run); return run; }; return Object.assign(newHandler, handler, options || {}); }; }
{ "end_byte": 4482, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/strategy.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/simple-scheduler.ts_0_8220
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonValue, schema } from '@angular-devkit/core'; import { EMPTY, MonoTypeOperatorFunction, Observable, Observer, Subject, Subscription, concat, concatMap, filter, first, from, ignoreElements, map, merge, of, shareReplay, switchMap, tap, } from 'rxjs'; import { Job, JobDescription, JobHandler, JobInboundMessage, JobInboundMessageKind, JobName, JobOutboundMessage, JobOutboundMessageKind, JobOutboundMessageOutput, JobState, Registry, ScheduleJobOptions, Scheduler, } from './api'; import { JobDoesNotExistException } from './exception'; export class JobArgumentSchemaValidationError extends schema.SchemaValidationException { constructor(errors?: schema.SchemaValidatorError[]) { super(errors, 'Job Argument failed to validate. Errors: '); } } export class JobInboundMessageSchemaValidationError extends schema.SchemaValidationException { constructor(errors?: schema.SchemaValidatorError[]) { super(errors, 'Job Inbound Message failed to validate. Errors: '); } } export class JobOutputSchemaValidationError extends schema.SchemaValidationException { constructor(errors?: schema.SchemaValidatorError[]) { super(errors, 'Job Output failed to validate. Errors: '); } } interface JobHandlerWithExtra extends JobHandler<JsonValue, JsonValue, JsonValue> { jobDescription: JobDescription; argumentV: Promise<schema.SchemaValidator>; outputV: Promise<schema.SchemaValidator>; inputV: Promise<schema.SchemaValidator>; } function _jobShare<T>(): MonoTypeOperatorFunction<T> { // This is the same code as a `shareReplay()` operator, but uses a dumber Subject rather than a // ReplaySubject. return (source: Observable<T>): Observable<T> => { let refCount = 0; let subject: Subject<T>; let hasError = false; let isComplete = false; let subscription: Subscription; return new Observable<T>((subscriber) => { let innerSub: Subscription; refCount++; if (!subject) { subject = new Subject<T>(); innerSub = subject.subscribe(subscriber); subscription = source.subscribe({ next(value) { subject.next(value); }, error(err) { hasError = true; subject.error(err); }, complete() { isComplete = true; subject.complete(); }, }); } else { innerSub = subject.subscribe(subscriber); } return () => { refCount--; innerSub.unsubscribe(); if (subscription && refCount === 0 && (isComplete || hasError)) { subscription.unsubscribe(); } }; }); }; } /** * Simple scheduler. Should be the base of all registries and schedulers. */ export class SimpleScheduler< MinimumArgumentT extends JsonValue = JsonValue, MinimumInputT extends JsonValue = JsonValue, MinimumOutputT extends JsonValue = JsonValue, > implements Scheduler<MinimumArgumentT, MinimumInputT, MinimumOutputT> { private _internalJobDescriptionMap = new Map<JobName, JobHandlerWithExtra>(); private _queue: (() => void)[] = []; private _pauseCounter = 0; constructor( protected _jobRegistry: Registry<MinimumArgumentT, MinimumInputT, MinimumOutputT>, protected _schemaRegistry: schema.SchemaRegistry = new schema.CoreSchemaRegistry(), ) {} private _getInternalDescription(name: JobName): Observable<JobHandlerWithExtra | null> { const maybeHandler = this._internalJobDescriptionMap.get(name); if (maybeHandler !== undefined) { return of(maybeHandler); } const handler = this._jobRegistry.get<MinimumArgumentT, MinimumInputT, MinimumOutputT>(name); return handler.pipe( switchMap((handler) => { if (handler === null) { return of(null); } const description: JobDescription = { // Make a copy of it to be sure it's proper JSON. ...(JSON.parse(JSON.stringify(handler.jobDescription)) as JobDescription), name: handler.jobDescription.name || name, argument: handler.jobDescription.argument || true, input: handler.jobDescription.input || true, output: handler.jobDescription.output || true, channels: handler.jobDescription.channels || {}, }; const handlerWithExtra = Object.assign(handler.bind(undefined), { jobDescription: description, argumentV: this._schemaRegistry.compile(description.argument), inputV: this._schemaRegistry.compile(description.input), outputV: this._schemaRegistry.compile(description.output), }) as JobHandlerWithExtra; this._internalJobDescriptionMap.set(name, handlerWithExtra); return of(handlerWithExtra); }), ); } /** * Get a job description for a named job. * * @param name The name of the job. * @returns A description, or null if the job is not registered. */ getDescription(name: JobName) { return concat( this._getInternalDescription(name).pipe(map((x) => x && x.jobDescription)), of(null), ).pipe(first()); } /** * Returns true if the job name has been registered. * @param name The name of the job. * @returns True if the job exists, false otherwise. */ has(name: JobName) { return this.getDescription(name).pipe(map((x) => x !== null)); } /** * Pause the scheduler, temporary queueing _new_ jobs. Returns a resume function that should be * used to resume execution. If multiple `pause()` were called, all their resume functions must * be called before the Scheduler actually starts new jobs. Additional calls to the same resume * function will have no effect. * * Jobs already running are NOT paused. This is pausing the scheduler only. */ pause() { let called = false; this._pauseCounter++; return () => { if (!called) { called = true; if (--this._pauseCounter == 0) { // Resume the queue. const q = this._queue; this._queue = []; q.forEach((fn) => fn()); } } }; } /** * Schedule a job to be run, using its name. * @param name The name of job to be run. * @param argument The argument to send to the job when starting it. * @param options Scheduling options. * @returns The Job being run. */ schedule<A extends MinimumArgumentT, I extends MinimumInputT, O extends MinimumOutputT>( name: JobName, argument: A, options?: ScheduleJobOptions, ): Job<A, I, O> { if (this._pauseCounter > 0) { const waitable = new Subject<never>(); this._queue.push(() => waitable.complete()); return this._scheduleJob<A, I, O>(name, argument, options || {}, waitable); } return this._scheduleJob<A, I, O>(name, argument, options || {}, EMPTY); } /** * Filter messages. * @private */ private _filterJobOutboundMessages<O extends MinimumOutputT>( message: JobOutboundMessage<O>, state: JobState, ) { switch (message.kind) { case JobOutboundMessageKind.OnReady: return state == JobState.Queued; case JobOutboundMessageKind.Start: return state == JobState.Ready; case JobOutboundMessageKind.End: return state == JobState.Started || state == JobState.Ready; } return true; } /** * Return a new state. This is just to simplify the reading of the _createJob method. * @private */ private _updateState<O extends MinimumOutputT>( message: JobOutboundMessage<O>, state: JobState, ): JobState { switch (message.kind) { case JobOutboundMessageKind.OnReady: return JobState.Ready; case JobOutboundMessageKind.Start: return JobState.Started; case JobOutboundMessageKind.End: return JobState.Ended; } return state; } /** * Create the job. * @private */ // eslint-disable-next-line max-lines-per-function
{ "end_byte": 8220, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/simple-scheduler.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/simple-scheduler.ts_8223_16739
private _createJob<A extends MinimumArgumentT, I extends MinimumInputT, O extends MinimumOutputT>( name: JobName, argument: A, handler: Observable<JobHandlerWithExtra | null>, inboundBus: Observer<JobInboundMessage<I>>, outboundBus: Observable<JobOutboundMessage<O>>, ): Job<A, I, O> { const schemaRegistry = this._schemaRegistry; const channelsSubject = new Map<string, Subject<JsonValue>>(); const channels = new Map<string, Observable<JsonValue>>(); let state = JobState.Queued; let pingId = 0; // Create the input channel by having a filter. const input = new Subject<JsonValue>(); input .pipe( concatMap((message) => handler.pipe( switchMap(async (handler) => { if (handler === null) { throw new JobDoesNotExistException(name); } const validator = await handler.inputV; return validator(message); }), ), ), filter((result) => result.success), map((result) => result.data as I), ) .subscribe((value) => inboundBus.next({ kind: JobInboundMessageKind.Input, value })); outboundBus = concat( outboundBus, // Add an End message at completion. This will be filtered out if the job actually send an // End. handler.pipe( switchMap((handler) => { if (handler) { return of<JobOutboundMessage<O>>({ kind: JobOutboundMessageKind.End, description: handler.jobDescription, }); } else { return EMPTY as Observable<JobOutboundMessage<O>>; } }), ), ).pipe( filter((message) => this._filterJobOutboundMessages(message, state)), // Update internal logic and Job<> members. tap( (message) => { // Update the state. state = this._updateState(message, state); switch (message.kind) { case JobOutboundMessageKind.ChannelCreate: { const maybeSubject = channelsSubject.get(message.name); // If it doesn't exist or it's closed on the other end. if (!maybeSubject) { const s = new Subject<JsonValue>(); channelsSubject.set(message.name, s); channels.set(message.name, s.asObservable()); } break; } case JobOutboundMessageKind.ChannelMessage: { const maybeSubject = channelsSubject.get(message.name); if (maybeSubject) { maybeSubject.next(message.message); } break; } case JobOutboundMessageKind.ChannelComplete: { const maybeSubject = channelsSubject.get(message.name); if (maybeSubject) { maybeSubject.complete(); channelsSubject.delete(message.name); } break; } case JobOutboundMessageKind.ChannelError: { const maybeSubject = channelsSubject.get(message.name); if (maybeSubject) { maybeSubject.error(message.error); channelsSubject.delete(message.name); } break; } } }, () => { state = JobState.Errored; }, ), // Do output validation (might include default values so this might have side // effects). We keep all messages in order. concatMap((message) => { if (message.kind !== JobOutboundMessageKind.Output) { return of(message); } return handler.pipe( switchMap(async (handler) => { if (handler === null) { throw new JobDoesNotExistException(name); } const validate = await handler.outputV; const output = await validate(message.value); if (!output.success) { throw new JobOutputSchemaValidationError(output.errors); } return { ...message, output: output.data as O, } as JobOutboundMessageOutput<O>; }), ) as Observable<JobOutboundMessage<O>>; }), _jobShare(), ); const output = outboundBus.pipe( filter((x) => x.kind == JobOutboundMessageKind.Output), map((x) => x.value), shareReplay(1), ); // Return the Job. return { get state() { return state; }, argument, description: handler.pipe( switchMap((handler) => { if (handler === null) { throw new JobDoesNotExistException(name); } else { return of(handler.jobDescription); } }), ), output, getChannel<T extends JsonValue>( name: JobName, schema: schema.JsonSchema = true, ): Observable<T> { let maybeObservable = channels.get(name); if (!maybeObservable) { const s = new Subject<T>(); channelsSubject.set(name, s as unknown as Subject<JsonValue>); channels.set(name, s.asObservable()); maybeObservable = s.asObservable(); } return maybeObservable.pipe( // Keep the order of messages. concatMap((message) => { return from(schemaRegistry.compile(schema)).pipe( switchMap((validate) => validate(message)), filter((x) => x.success), map((x) => x.data as T), ); }), ); }, ping() { const id = pingId++; inboundBus.next({ kind: JobInboundMessageKind.Ping, id }); return outboundBus.pipe( filter((x) => x.kind === JobOutboundMessageKind.Pong && x.id == id), first(), ignoreElements(), ); }, stop() { inboundBus.next({ kind: JobInboundMessageKind.Stop }); }, input, inboundBus, outboundBus, }; } protected _scheduleJob< A extends MinimumArgumentT, I extends MinimumInputT, O extends MinimumOutputT, >( name: JobName, argument: A, options: ScheduleJobOptions, waitable: Observable<never>, ): Job<A, I, O> { // Get handler first, since this can error out if there's no handler for the job name. const handler = this._getInternalDescription(name); const optionsDeps = (options && options.dependencies) || []; const dependencies = Array.isArray(optionsDeps) ? optionsDeps : [optionsDeps]; const inboundBus = new Subject<JobInboundMessage<I>>(); const outboundBus = concat( // Wait for dependencies, make sure to not report messages from dependencies. Subscribe to // all dependencies at the same time so they run concurrently. merge(...dependencies.map((x) => x.outboundBus)).pipe(ignoreElements()), // Wait for pause() to clear (if necessary). waitable, from(handler).pipe( switchMap( (handler) => new Observable<JobOutboundMessage<O>>((subscriber: Observer<JobOutboundMessage<O>>) => { if (!handler) { throw new JobDoesNotExistException(name); } // Validate the argument. return from(handler.argumentV) .pipe( switchMap((validate) => validate(argument)), switchMap((output) => { if (!output.success) { throw new JobArgumentSchemaValidationError(output.errors); } const argument: A = output.data as A; const description = handler.jobDescription; subscriber.next({ kind: JobOutboundMessageKind.OnReady, description }); const context = { description, dependencies: [...dependencies], inboundBus: inboundBus.asObservable(), scheduler: this as Scheduler<MinimumArgumentT, MinimumInputT, MinimumOutputT>, }; return handler(argument, context); }), ) .subscribe(subscriber as Observer<JobOutboundMessage<JsonValue>>); }), ), ), ); return this._createJob(name, argument, handler, inboundBus, outboundBus); } }
{ "end_byte": 16739, "start_byte": 8223, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/simple-scheduler.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/create-job-handler.ts_0_7196
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { BaseException, JsonValue, isPromise, logging } from '@angular-devkit/core'; import { Observable, Observer, Subject, Subscription, from, isObservable, of, switchMap, tap, } from 'rxjs'; import { JobDescription, JobHandler, JobHandlerContext, JobInboundMessageKind, JobOutboundMessage, JobOutboundMessageKind, } from './api'; export class ChannelAlreadyExistException extends BaseException { constructor(name: string) { super(`Channel ${JSON.stringify(name)} already exist.`); } } /** * Interface for the JobHandler context that is used when using `createJobHandler()`. It extends * the basic `JobHandlerContext` with additional functionality. */ export interface SimpleJobHandlerContext< A extends JsonValue, I extends JsonValue, O extends JsonValue, > extends JobHandlerContext<A, I, O> { createChannel: (name: string) => Observer<JsonValue>; input: Observable<I>; addTeardown(teardown: () => Promise<void> | void): void; } /** * A simple version of the JobHandler. This simplifies a lot of the interaction with the job * scheduler and registry. For example, instead of returning a JobOutboundMessage observable, you * can directly return an output. */ export type SimpleJobHandlerFn<A extends JsonValue, I extends JsonValue, O extends JsonValue> = ( input: A, context: SimpleJobHandlerContext<A, I, O>, ) => O | Promise<O> | Observable<O>; /** * Make a simple job handler that sets start and end from a function that's synchronous. * * @param fn The function to create a handler for. * @param options An optional set of properties to set on the handler. Some fields might be * required by registry or schedulers. */ export function createJobHandler<A extends JsonValue, I extends JsonValue, O extends JsonValue>( fn: SimpleJobHandlerFn<A, I, O>, options: Partial<JobDescription> = {}, ): JobHandler<A, I, O> { const handler = (argument: A, context: JobHandlerContext<A, I, O>) => { const description = context.description; const inboundBus = context.inboundBus; const inputChannel = new Subject<I>(); let subscription: Subscription; const teardownLogics: Array<() => PromiseLike<void> | void> = []; let tearingDown = false; return new Observable<JobOutboundMessage<O>>((subject) => { function complete() { if (subscription) { subscription.unsubscribe(); } subject.next({ kind: JobOutboundMessageKind.End, description }); subject.complete(); inputChannel.complete(); } // Handle input. const inboundSub = inboundBus.subscribe((message) => { switch (message.kind) { case JobInboundMessageKind.Ping: subject.next({ kind: JobOutboundMessageKind.Pong, description, id: message.id }); break; case JobInboundMessageKind.Stop: // Run teardown logic then complete. tearingDown = true; if (teardownLogics.length) { Promise.all(teardownLogics.map((fn) => fn())).then( () => complete(), () => complete(), ); } else { complete(); } break; case JobInboundMessageKind.Input: if (!tearingDown) { inputChannel.next(message.value); } break; } }); // Execute the function with the additional context. const channels = new Map<string, Subject<JsonValue>>(); const newContext: SimpleJobHandlerContext<A, I, O> = { ...context, input: inputChannel.asObservable(), addTeardown(teardown: () => Promise<void> | void): void { teardownLogics.push(teardown); }, createChannel(name: string) { if (channels.has(name)) { throw new ChannelAlreadyExistException(name); } const channelSubject = new Subject<JsonValue>(); const channelSub = channelSubject.subscribe( (message) => { subject.next({ kind: JobOutboundMessageKind.ChannelMessage, description, name, message, }); }, (error) => { subject.next({ kind: JobOutboundMessageKind.ChannelError, description, name, error }); // This can be reopened. channels.delete(name); }, () => { subject.next({ kind: JobOutboundMessageKind.ChannelComplete, description, name }); // This can be reopened. channels.delete(name); }, ); channels.set(name, channelSubject); if (subscription) { subscription.add(channelSub); } return channelSubject; }, }; subject.next({ kind: JobOutboundMessageKind.Start, description }); let result = fn(argument, newContext); // If the result is a promise, simply wait for it to complete before reporting the result. if (isPromise(result)) { result = from(result); } else if (!isObservable(result)) { result = of(result); } subscription = result.subscribe( (value: O) => subject.next({ kind: JobOutboundMessageKind.Output, description, value }), (error) => subject.error(error), () => complete(), ); subscription.add(inboundSub); return subscription; }); }; return Object.assign(handler, { jobDescription: options }); } /** * Lazily create a job using a function. * @param loader A factory function that returns a promise/observable of a JobHandler. * @param options Same options as createJob. */ export function createJobFactory<A extends JsonValue, I extends JsonValue, O extends JsonValue>( loader: () => Promise<JobHandler<A, I, O>>, options: Partial<JobDescription> = {}, ): JobHandler<A, I, O> { const handler = (argument: A, context: JobHandlerContext<A, I, O>) => { return from(loader()).pipe(switchMap((fn) => fn(argument, context))); }; return Object.assign(handler, { jobDescription: options }); } /** * Creates a job that logs out input/output messages of another Job. The messages are still * propagated to the other job. */ export function createLoggerJob<A extends JsonValue, I extends JsonValue, O extends JsonValue>( job: JobHandler<A, I, O>, logger: logging.LoggerApi, ): JobHandler<A, I, O> { const handler = (argument: A, context: JobHandlerContext<A, I, O>) => { context.inboundBus .pipe(tap((message) => logger.info(`Input: ${JSON.stringify(message)}`))) .subscribe(); return job(argument, context).pipe( tap( (message) => logger.info(`Message: ${JSON.stringify(message)}`), (error) => logger.warn(`Error: ${JSON.stringify(error)}`), () => logger.info(`Completed`), ), ); }; return Object.assign(handler, job); }
{ "end_byte": 7196, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/create-job-handler.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/index.ts_0_494
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as strategy from './strategy'; export * from './api'; export * from './create-job-handler'; export * from './exception'; export * from './dispatcher'; export * from './fallback-registry'; export * from './simple-registry'; export * from './simple-scheduler'; export { strategy };
{ "end_byte": 494, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/index.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/fallback-registry.ts_0_1344
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonValue } from '@angular-devkit/core'; import { Observable, concatMap, first, from } from 'rxjs'; import { JobHandler, JobName, Registry } from './api'; /** * A simple job registry that keep a map of JobName => JobHandler internally. */ export class FallbackRegistry< MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue, > implements Registry<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT> { constructor( protected _fallbacks: Registry< MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT >[] = [], ) {} addFallback(registry: Registry) { this._fallbacks.push(registry); } get< A extends MinimumArgumentValueT = MinimumArgumentValueT, I extends MinimumInputValueT = MinimumInputValueT, O extends MinimumOutputValueT = MinimumOutputValueT, >(name: JobName): Observable<JobHandler<A, I, O> | null> { return from(this._fallbacks).pipe( concatMap((fb) => fb.get<A, I, O>(name)), first((x) => x !== null, null), ); } }
{ "end_byte": 1344, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/fallback-registry.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/exception.ts_0_627
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { BaseException } from '@angular-devkit/core'; import { JobName } from './api'; export class JobNameAlreadyRegisteredException extends BaseException { constructor(name: JobName) { super(`Job named ${JSON.stringify(name)} already exists.`); } } export class JobDoesNotExistException extends BaseException { constructor(name: JobName) { super(`Job name ${JSON.stringify(name)} does not exist.`); } }
{ "end_byte": 627, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/exception.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/dispatcher_spec.ts_0_1401
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonValue } from '@angular-devkit/core'; import { lastValueFrom } from 'rxjs'; import { JobHandler } from './api'; import { createJobHandler } from './create-job-handler'; import { createDispatcher } from './dispatcher'; import { SimpleJobRegistry } from './simple-registry'; import { SimpleScheduler } from './simple-scheduler'; describe('createDispatcher', () => { it('works', async () => { const registry = new SimpleJobRegistry(); const scheduler = new SimpleScheduler(registry); const dispatcher = createDispatcher({ name: 'add', argument: { items: { type: 'number' } }, output: { type: 'number' }, }); const add0 = createJobHandler((input: number[]) => input.reduce((a, c) => a + c, 0), { name: 'add0', }); const add100 = createJobHandler((input: number[]) => input.reduce((a, c) => a + c, 100), { name: 'add100', }); registry.register(dispatcher); registry.register(add0); registry.register(add100); dispatcher.setDefaultJob(add0 as JobHandler<JsonValue, JsonValue, number>); const sum = scheduler.schedule('add', [1, 2, 3, 4]); expect(await lastValueFrom(sum.output)).toBe(10); }); });
{ "end_byte": 1401, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/dispatcher_spec.ts" }
angular-cli/packages/angular_devkit/architect/src/jobs/dispatcher.ts_0_2770
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonValue } from '@angular-devkit/core'; import { Job, JobDescription, JobHandler, JobHandlerContext, JobName, isJobHandler } from './api'; import { JobDoesNotExistException } from './exception'; import { Readwrite } from './types'; /** * A JobDispatcher can be used to dispatch between multiple jobs. */ export interface JobDispatcher<A extends JsonValue, I extends JsonValue, O extends JsonValue> extends JobHandler<A, I, O> { /** * Set the default job if all conditionals failed. * @param name The default name if all conditions are false. */ setDefaultJob(name: JobName | null | JobHandler<JsonValue, JsonValue, JsonValue>): void; /** * Add a conditional job that will be selected if the input fits a predicate. * @param predicate * @param name */ addConditionalJob(predicate: (args: A) => boolean, name: string): void; } /** * OnReady a dispatcher that can dispatch to a sub job, depending on conditions. * @param options */ export function createDispatcher<A extends JsonValue, I extends JsonValue, O extends JsonValue>( options: Partial<Readwrite<JobDescription>> = {}, ): JobDispatcher<A, I, O> { let defaultDelegate: JobName | null = null; const conditionalDelegateList: [(args: JsonValue) => boolean, JobName][] = []; const job: JobHandler<JsonValue, JsonValue, JsonValue> = Object.assign( (argument: JsonValue, context: JobHandlerContext) => { const maybeDelegate = conditionalDelegateList.find(([predicate]) => predicate(argument)); let delegate: Job<JsonValue, JsonValue, JsonValue> | null = null; if (maybeDelegate) { delegate = context.scheduler.schedule(maybeDelegate[1], argument); } else if (defaultDelegate) { delegate = context.scheduler.schedule(defaultDelegate, argument); } else { throw new JobDoesNotExistException('<null>'); } context.inboundBus.subscribe(delegate.inboundBus); return delegate.outboundBus; }, { jobDescription: options, }, ); return Object.assign(job, { setDefaultJob(name: JobName | null | JobHandler<JsonValue, JsonValue, JsonValue>) { if (isJobHandler(name)) { name = name.jobDescription.name === undefined ? null : name.jobDescription.name; } defaultDelegate = name; }, addConditionalJob(predicate: (args: JsonValue) => boolean, name: JobName) { conditionalDelegateList.push([predicate, name]); }, // TODO: Remove return-only generic from createDispatcher() API. }) as unknown as JobDispatcher<A, I, O>; }
{ "end_byte": 2770, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/dispatcher.ts" }
angular-cli/packages/angular_devkit/build_webpack/README.md_0_956
# Webpack Builder for Architect This package allows you to run Webpack and Webpack Dev Server using Architect. To use it on your Angular CLI app, follow these steps: - run `npm install @angular-devkit/build-webpack`. - create a webpack configuration. - add the following targets inside `angular.json`. ``` "projects": { "app": { // ... "architect": { // ... "build-webpack": { "builder": "@angular-devkit/build-webpack:webpack", "options": { "webpackConfig": "webpack.config.js" } }, "serve-webpack": { "builder": "@angular-devkit/build-webpack:webpack-dev-server", "options": { "webpackConfig": "webpack.config.js" } } } ``` - run `ng run app:build-webpack` to build, and `ng run app:serve-webpack` to serve. All options, including `watch` and `stats`, are looked up inside the webpack configuration.
{ "end_byte": 956, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/README.md" }
angular-cli/packages/angular_devkit/build_webpack/BUILD.bazel_0_3516
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license load("@npm//@angular/build-tooling/bazel/api-golden:index.bzl", "api_golden_test_npm_package") load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") load("//tools:ts_json_schema.bzl", "ts_json_schema") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_json_schema( name = "webpack_schema", src = "src/builders/webpack/schema.json", ) ts_json_schema( name = "webpack_dev_server_schema", src = "src/builders/webpack-dev-server/schema.json", ) ts_library( name = "build_webpack", package_name = "@angular-devkit/build-webpack", srcs = glob( include = ["src/**/*.ts"], exclude = [ "src/test-utils.ts", "src/**/*_spec.ts", ], ) + [ "//packages/angular_devkit/build_webpack:src/builders/webpack-dev-server/schema.ts", "//packages/angular_devkit/build_webpack:src/builders/webpack/schema.ts", ], data = [ "builders.json", "package.json", "src/builders/webpack-dev-server/schema.json", "src/builders/webpack/schema.json", ], module_name = "@angular-devkit/build-webpack", module_root = "src/index.d.ts", deps = [ "//packages/angular_devkit/architect", "@npm//@types/node", "@npm//rxjs", "@npm//webpack", "@npm//webpack-dev-server", ], ) ts_library( name = "build_webpack_test_lib", testonly = True, srcs = glob( include = [ "src/**/*_spec.ts", ], ), data = glob( include = [ "test/**/*", ], ), deps = [ ":build_webpack", "//packages/angular_devkit/architect", "//packages/angular_devkit/architect/node", "//packages/angular_devkit/architect/testing", "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "//packages/ngtools/webpack", "@npm//@angular/common", "@npm//@angular/compiler", "@npm//@angular/compiler-cli", "@npm//@angular/core", "@npm//@angular/platform-browser", "@npm//@angular/platform-browser-dynamic", "@npm//tslib", "@npm//zone.js", ], ) jasmine_node_test( name = "build_webpack_test", srcs = [":build_webpack_test_lib"], # Turns off nodejs require patches and turns on the linker, which sets up up node_modules # so that standard node module resolution work. templated_args = ["--nobazel_patch_module_resolver"], deps = [ "@npm//jasmine", "@npm//source-map", ], ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", pkg_deps = [ "//packages/angular_devkit/architect:package.json", ], tags = ["release-package"], deps = [ ":README.md", ":build_webpack", ":builders.json", ":license", ], ) api_golden_test_npm_package( name = "build_webpack_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular_cli/goldens/public-api/angular_devkit/build_webpack", npm_package = "angular_cli/packages/angular_devkit/build_webpack/npm_package", )
{ "end_byte": 3516, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/BUILD.bazel" }
angular-cli/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.cjs_0_563
const path = require('path'); module.exports = { mode: 'development', entry: path.resolve(__dirname, './src/main.js'), module: { rules: [ // rxjs 6 requires directory imports which are not support in ES modules. // Disabling `fullySpecified` allows Webpack to ignore this but this is // not ideal because it currently disables ESM behavior import for all JS files. { test: /\.[m]?js$/, resolve: { fullySpecified: false } }, ], }, output: { path: path.resolve(__dirname, './dist'), filename: 'bundle.js', }, };
{ "end_byte": 563, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.cjs" }
angular-cli/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.mjs_0_634
import { resolve } from 'path'; import { fileURLToPath } from 'url'; export default { mode: 'development', entry: resolve(fileURLToPath(import.meta.url), '../src/main.js'), module: { rules: [ // rxjs 6 requires directory imports which are not support in ES modules. // Disabling `fullySpecified` allows Webpack to ignore this but this is // not ideal because it currently disables ESM behavior import for all JS files. { test: /\.[m]?js$/, resolve: { fullySpecified: false } }, ], }, output: { path: resolve(fileURLToPath(import.meta.url), '../dist'), filename: 'bundle.js', }, };
{ "end_byte": 634, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.mjs" }
angular-cli/packages/angular_devkit/build_webpack/test/basic-app/src/main.js_0_28
console.log('hello world');
{ "end_byte": 28, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/basic-app/src/main.js" }
angular-cli/packages/angular_devkit/build_webpack/test/angular-app/webpack.config.js_0_1199
const ngToolsWebpack = require('@ngtools/webpack'); const path = require('path'); const workspaceRoot = path.resolve(__dirname, './'); const projectRoot = path.resolve(__dirname, './'); module.exports = { mode: 'development', resolve: { extensions: ['.ts', '.js'], }, entry: { main: path.resolve(projectRoot, './src/main.ts'), polyfills: path.resolve(projectRoot, './src/polyfills.ts'), }, output: { path: path.resolve(workspaceRoot, './dist'), filename: `[name].js`, }, plugins: [ new ngToolsWebpack.AngularWebpackPlugin({ tsconfig: path.resolve(projectRoot, './src/tsconfig.app.json'), }), ], module: { rules: [ // rxjs 6 requires directory imports which are not support in ES modules. // Disabling `fullySpecified` allows Webpack to ignore this but this is // not ideal because it currently disables ESM behavior import for all JS files. { test: /\.[m]?js$/, resolve: { fullySpecified: false } }, { test: /\.css$/, type: 'asset/source' }, { test: /\.html$/, type: 'asset/source' }, { test: /\.ts$/, loader: '@ngtools/webpack' }, ], }, devServer: { historyApiFallback: true, }, };
{ "end_byte": 1199, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/angular-app/webpack.config.js" }
angular-cli/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts_0_419
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic() .bootstrapModule(AppModule) .catch((err) => console.log(err));
{ "end_byte": 419, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts" }
angular-cli/packages/angular_devkit/build_webpack/test/angular-app/src/polyfills.ts_0_1647
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in https://angular.dev/reference/versions#browser-support */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** * Required to support Web Animations `@angular/platform-browser/animations`. * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation **/ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */
{ "end_byte": 1647, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/angular-app/src/polyfills.ts" }
angular-cli/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.html_0_1214
<!--The content below is only a placeholder and can be replaced.--> <div style="text-align: center"> <h1>Welcome to {{ title }}!</h1> <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==" /> </div> <h2>Here are some links to help you start:</h2> <ul> <li> <h2><a target="_blank" rel="noopener" href="https://angular.dev/tutorials/learn-angular">Learn Angular</a></h2> </li> <li> <h2> <a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki" >CLI Documentation</a > </h2> </li> <li> <h2><a target="_blank" rel="noopener" href="https://blog.angular.dev">Angular blog</a></h2> </li> </ul> <p i18n>i18n test</p>
{ "end_byte": 1214, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.html" }
angular-cli/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.spec.ts_0_1119
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [AppComponent], }); }); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it(`should have as title 'app'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('app'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!'); }); });
{ "end_byte": 1119, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.spec.ts" }
angular-cli/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.module.ts_0_502
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [], bootstrap: [AppComponent], }) export class AppModule {}
{ "end_byte": 502, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.module.ts" }
angular-cli/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.ts_0_433
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'app'; }
{ "end_byte": 433, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.ts" }
angular-cli/packages/angular_devkit/build_webpack/src/utils.ts_0_3546
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { existsSync } from 'fs'; import * as path from 'path'; import { URL, pathToFileURL } from 'url'; import { Compilation, Configuration } from 'webpack'; export interface EmittedFiles { id?: string; name?: string; file: string; initial: boolean; asset?: boolean; extension: string; } export function getEmittedFiles(compilation: Compilation): EmittedFiles[] { const files: EmittedFiles[] = []; const chunkFileNames = new Set<string>(); // adds all chunks to the list of emitted files such as lazy loaded modules for (const chunk of compilation.chunks) { for (const file of chunk.files) { if (chunkFileNames.has(file)) { continue; } chunkFileNames.add(file); files.push({ id: chunk.id?.toString(), name: chunk.name, file, extension: path.extname(file), initial: chunk.isOnlyInitial(), }); } } // add all other files for (const file of Object.keys(compilation.assets)) { // Chunk files have already been added to the files list above if (chunkFileNames.has(file)) { continue; } files.push({ file, extension: path.extname(file), initial: false, asset: true }); } return files; } /** * This uses a dynamic import to load a module which may be ESM. * CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript * will currently, unconditionally downlevel dynamic import into a require call. * require calls cannot load ESM code and will result in a runtime error. To workaround * this, a Function constructor is used to prevent TypeScript from changing the dynamic import. * Once TypeScript provides support for keeping the dynamic import this workaround can * be dropped. * * @param modulePath The path of the module to load. * @returns A Promise that resolves to the dynamically imported module. */ function loadEsmModule<T>(modulePath: string | URL): Promise<T> { return new Function('modulePath', `return import(modulePath);`)(modulePath) as Promise<T>; } export async function getWebpackConfig(configPath: string): Promise<Configuration> { if (!existsSync(configPath)) { throw new Error(`Webpack configuration file ${configPath} does not exist.`); } switch (path.extname(configPath)) { case '.mjs': // Load the ESM configuration file using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. return (await loadEsmModule<{ default: Configuration }>(pathToFileURL(configPath))).default; case '.cjs': return require(configPath); default: // The file could be either CommonJS or ESM. // CommonJS is tried first then ESM if loading fails. try { return require(configPath); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'ERR_REQUIRE_ESM') { // Load the ESM configuration file using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. return (await loadEsmModule<{ default: Configuration }>(pathToFileURL(configPath))) .default; } throw e; } } }
{ "end_byte": 3546, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/src/utils.ts" }
angular-cli/packages/angular_devkit/build_webpack/src/index.ts_0_332
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './builders/webpack'; export * from './builders/webpack-dev-server'; export type { EmittedFiles } from './utils';
{ "end_byte": 332, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/src/index.ts" }
angular-cli/packages/angular_devkit/build_webpack/src/builders/webpack/index.ts_0_3972
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import { resolve as pathResolve } from 'path'; import { Observable, from, isObservable, of, switchMap } from 'rxjs'; import webpack from 'webpack'; import { EmittedFiles, getEmittedFiles, getWebpackConfig } from '../../utils'; import { Schema as RealWebpackBuilderSchema } from './schema'; export type WebpackBuilderSchema = RealWebpackBuilderSchema; export interface WebpackLoggingCallback { (stats: webpack.Stats, config: webpack.Configuration): void; } export interface WebpackFactory { (config: webpack.Configuration): Observable<webpack.Compiler> | webpack.Compiler; } export type BuildResult = BuilderOutput & { emittedFiles?: EmittedFiles[]; webpackStats?: webpack.StatsCompilation; outputPath: string; }; export function runWebpack( config: webpack.Configuration, context: BuilderContext, options: { logging?: WebpackLoggingCallback; webpackFactory?: WebpackFactory; shouldProvideStats?: boolean; } = {}, ): Observable<BuildResult> { const { logging: log = (stats, config) => { if (config.stats !== false) { const statsOptions = config.stats === true ? undefined : config.stats; context.logger.info(stats.toString(statsOptions)); } }, shouldProvideStats = true, } = options; const createWebpack = (c: webpack.Configuration) => { if (options.webpackFactory) { const result = options.webpackFactory(c); if (isObservable(result)) { return result; } else { return of(result); } } else { return of(webpack(c)); } }; return createWebpack({ ...config, watch: false }).pipe( switchMap( (webpackCompiler) => new Observable<BuildResult>((obs) => { const callback = (err?: Error | null, stats?: webpack.Stats) => { if (err) { return obs.error(err); } if (!stats) { return; } // Log stats. log(stats, config); const statsOptions = typeof config.stats === 'boolean' ? undefined : config.stats; const result = { success: !stats.hasErrors(), webpackStats: shouldProvideStats ? stats.toJson(statsOptions) : undefined, emittedFiles: getEmittedFiles(stats.compilation), outputPath: stats.compilation.outputOptions.path, } as unknown as BuildResult; if (config.watch) { obs.next(result); } else { webpackCompiler.close(() => { obs.next(result); obs.complete(); }); } }; try { if (config.watch) { const watchOptions = config.watchOptions || {}; const watching = webpackCompiler.watch(watchOptions, callback); // Teardown logic. Close the watcher when unsubscribed from. return () => { watching.close(() => {}); webpackCompiler.close(() => {}); }; } else { webpackCompiler.run(callback); } } catch (err) { if (err) { context.logger.error( `\nAn error occurred during the build:\n${err instanceof Error ? err.stack : err}`, ); } throw err; } }), ), ); } export default createBuilder<WebpackBuilderSchema>((options, context) => { const configPath = pathResolve(context.workspaceRoot, options.webpackConfig); return from(getWebpackConfig(configPath)).pipe( switchMap((config) => runWebpack(config, context)), ); });
{ "end_byte": 3972, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/src/builders/webpack/index.ts" }
angular-cli/packages/angular_devkit/build_webpack/src/builders/webpack/index_spec.ts_0_4445
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Architect } from '@angular-devkit/architect'; import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; import { TestingArchitectHost } from '@angular-devkit/architect/testing'; import { join, normalize, schema, workspaces } from '@angular-devkit/core'; import { NodeJsSyncHost, createConsoleLogger } from '@angular-devkit/core/node'; import * as path from 'path'; import { BuildResult } from './index'; describe('Webpack Builder basic test', () => { let testArchitectHost: TestingArchitectHost; let architect: Architect; let vfHost: NodeJsSyncHost; async function createArchitect(workspaceRoot: string) { vfHost = new NodeJsSyncHost(); const registry = new schema.CoreSchemaRegistry(); registry.addPostTransform(schema.transforms.addUndefinedDefaults); const { workspace } = await workspaces.readWorkspace( workspaceRoot, workspaces.createWorkspaceHost(vfHost), ); testArchitectHost = new TestingArchitectHost( workspaceRoot, workspaceRoot, new WorkspaceNodeModulesArchitectHost(workspace, workspaceRoot), ); architect = new Architect(testArchitectHost, registry); } describe('basic app', () => { const ngJsonPath = path.join(__dirname, '../../../test/basic-app/angular.json'); const workspaceRoot = path.dirname(require.resolve(ngJsonPath)); const outputPath = join(normalize(workspaceRoot), 'dist'); beforeEach(async () => { await createArchitect(workspaceRoot); }); it('works with CJS config', async () => { const run = await architect.scheduleTarget( { project: 'app', target: 'build' }, { webpackConfig: 'webpack.config.cjs' }, ); const output = await run.result; expect(output.success).toBe(true); expect(await vfHost.exists(join(outputPath, 'bundle.js')).toPromise()).toBe(true); await run.stop(); }); it('works with ESM config', async () => { const run = await architect.scheduleTarget( { project: 'app', target: 'build' }, { webpackConfig: 'webpack.config.mjs' }, ); const output = await run.result; expect(output.success).toBe(true); expect(await vfHost.exists(join(outputPath, 'bundle.js')).toPromise()).toBe(true); await run.stop(); }); it('works and returns emitted files', async () => { const run = await architect.scheduleTarget({ project: 'app', target: 'build' }); const output = (await run.result) as BuildResult; expect(output.success).toBe(true); expect(output.emittedFiles).toContain({ id: 'main', name: 'main', initial: true, file: 'bundle.js', extension: '.js', }); await run.stop(); }); }); describe('Angular app', () => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 150000; const ngJsonPath = path.join(__dirname, '../../../test/angular-app/angular.json'); const workspaceRoot = path.dirname(require.resolve(ngJsonPath)); const outputPath = join(normalize(workspaceRoot), 'dist'); beforeEach(async () => { await createArchitect(workspaceRoot); }); it('works', async () => { const run = await architect.scheduleTarget( { project: 'app', target: 'build-webpack' }, {}, { logger: createConsoleLogger() }, ); const output = await run.result; expect(output.success).toBe(true); expect(await vfHost.exists(join(outputPath, 'main.js')).toPromise()).toBe(true); expect(await vfHost.exists(join(outputPath, 'polyfills.js')).toPromise()).toBe(true); await run.stop(); }); it('works and returns emitted files', async () => { const run = await architect.scheduleTarget({ project: 'app', target: 'build-webpack' }); const output = (await run.result) as BuildResult; expect(output.success).toBe(true); expect(output.emittedFiles).toContain( { id: 'main', name: 'main', initial: true, file: 'main.js', extension: '.js' }, { id: 'polyfills', name: 'polyfills', initial: true, file: 'polyfills.js', extension: '.js', }, ); await run.stop(); }); }); });
{ "end_byte": 4445, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/src/builders/webpack/index_spec.ts" }
angular-cli/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index.ts_0_4363
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { BuilderContext, createBuilder } from '@angular-devkit/architect'; import { resolve as pathResolve } from 'path'; import { Observable, from, isObservable, of, switchMap } from 'rxjs'; import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import { getEmittedFiles, getWebpackConfig } from '../../utils'; import { BuildResult, WebpackFactory, WebpackLoggingCallback } from '../webpack'; import { Schema as WebpackDevServerBuilderSchema } from './schema'; export type WebpackDevServerFactory = typeof WebpackDevServer; export type DevServerBuildOutput = BuildResult & { port: number; family: string; address: string; }; export function runWebpackDevServer( config: webpack.Configuration, context: BuilderContext, options: { shouldProvideStats?: boolean; devServerConfig?: WebpackDevServer.Configuration; logging?: WebpackLoggingCallback; webpackFactory?: WebpackFactory; webpackDevServerFactory?: WebpackDevServerFactory; } = {}, ): Observable<DevServerBuildOutput> { const createWebpack = (c: webpack.Configuration) => { if (options.webpackFactory) { const result = options.webpackFactory(c); if (isObservable(result)) { return result; } else { return of(result); } } else { return of(webpack(c)); } }; const createWebpackDevServer = ( webpack: webpack.Compiler | webpack.MultiCompiler, config: WebpackDevServer.Configuration, ) => { if (options.webpackDevServerFactory) { return new options.webpackDevServerFactory(config, webpack); } return new WebpackDevServer(config, webpack); }; const { logging: log = (stats, config) => { if (config.stats !== false) { const statsOptions = config.stats === true ? undefined : config.stats; context.logger.info(stats.toString(statsOptions)); } }, shouldProvideStats = true, } = options; return createWebpack({ ...config, watch: false }).pipe( switchMap( (webpackCompiler) => new Observable<DevServerBuildOutput>((obs) => { const devServerConfig = options.devServerConfig || config.devServer || {}; devServerConfig.host ??= 'localhost'; let result: Partial<DevServerBuildOutput>; const statsOptions = typeof config.stats === 'boolean' ? undefined : config.stats; webpackCompiler.hooks.done.tap('build-webpack', (stats) => { // Log stats. log(stats, config); obs.next({ ...result, webpackStats: shouldProvideStats ? stats.toJson(statsOptions) : undefined, emittedFiles: getEmittedFiles(stats.compilation), success: !stats.hasErrors(), outputPath: stats.compilation.outputOptions.path, } as unknown as DevServerBuildOutput); }); const devServer = createWebpackDevServer(webpackCompiler, devServerConfig); devServer.startCallback((err) => { if (err) { obs.error(err); return; } const address = devServer.server?.address(); if (!address) { obs.error(new Error(`Dev-server address info is not defined.`)); return; } result = { success: true, port: typeof address === 'string' ? 0 : address.port, family: typeof address === 'string' ? '' : address.family, address: typeof address === 'string' ? address : address.address, }; }); // Teardown logic. Close the server when unsubscribed from. return () => { devServer.stopCallback(() => {}); webpackCompiler.close(() => {}); }; }), ), ); } export default createBuilder<WebpackDevServerBuilderSchema, DevServerBuildOutput>( (options, context) => { const configPath = pathResolve(context.workspaceRoot, options.webpackConfig); return from(getWebpackConfig(configPath)).pipe( switchMap((config) => runWebpackDevServer(config, context)), ); }, );
{ "end_byte": 4363, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index.ts" }
angular-cli/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index_spec.ts_0_2981
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Architect } from '@angular-devkit/architect'; import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; import { TestingArchitectHost } from '@angular-devkit/architect/testing'; import { schema, workspaces } from '@angular-devkit/core'; import { NodeJsSyncHost } from '@angular-devkit/core/node'; import * as path from 'path'; import { DevServerBuildOutput } from './index'; describe('Dev Server Builder', () => { let testArchitectHost: TestingArchitectHost; let architect: Architect; let vfHost: NodeJsSyncHost; const webpackTargetSpec = { project: 'app', target: 'serve' }; async function createArchitect(workspaceRoot: string) { vfHost = new NodeJsSyncHost(); const registry = new schema.CoreSchemaRegistry(); registry.addPostTransform(schema.transforms.addUndefinedDefaults); const { workspace } = await workspaces.readWorkspace( workspaceRoot, workspaces.createWorkspaceHost(vfHost), ); testArchitectHost = new TestingArchitectHost( workspaceRoot, workspaceRoot, new WorkspaceNodeModulesArchitectHost(workspace, workspaceRoot), ); architect = new Architect(testArchitectHost, registry); } beforeEach(async () => { const ngJsonPath = path.join(__dirname, '../../../test/basic-app/angular.json'); const workspaceRoot = path.dirname(require.resolve(ngJsonPath)); await createArchitect(workspaceRoot); }); it('works with CJS config', async () => { const run = await architect.scheduleTarget(webpackTargetSpec, { webpackConfig: 'webpack.config.cjs', }); const output = (await run.result) as DevServerBuildOutput; expect(output.success).toBe(true); const response = await fetch(`http://localhost:${output.port}/bundle.js`); expect(await response.text()).toContain(`console.log('hello world')`); await run.stop(); }, 30000); it('works with ESM config', async () => { const run = await architect.scheduleTarget(webpackTargetSpec, { webpackConfig: 'webpack.config.mjs', }); const output = (await run.result) as DevServerBuildOutput; expect(output.success).toBe(true); const response = await fetch(`http://localhost:${output.port}/bundle.js`); expect(await response.text()).toContain(`console.log('hello world')`); await run.stop(); }, 30000); it('works and returns emitted files', async () => { const run = await architect.scheduleTarget(webpackTargetSpec); const output = (await run.result) as DevServerBuildOutput; expect(output.success).toBe(true); expect(output.emittedFiles).toContain({ id: 'main', name: 'main', initial: true, file: 'bundle.js', extension: '.js', }); await run.stop(); }, 30000); });
{ "end_byte": 2981, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index_spec.ts" }
angular-cli/packages/angular_devkit/schematics_cli/README.md_0_1519
# Schematics CLI This package contains the executable for running a [Schematic](/packages/angular_devkit/schematics/README.md). # Usage ``` $ schematics [CollectionName:]SchematicName [options, ...] By default, if the collection name is not specified, use the internal collection provided by the Schematics CLI. Options: --debug Debug mode. This is true by default if the collection is a relative path (in that case, turn off with --debug=false). --allow-private Allow private schematics to be run from the command line. Default to false. --dry-run Do not output anything, but instead just show what actions would be performed. Default to true if debug is also true. --force Force overwriting files that would otherwise be an error. --list-schematics List all schematics from the collection, by name. A collection name should be suffixed by a colon. Example: '@angular-devkit/schematics-cli:'. --no-interactive Disables interactive input prompts. --verbose Show more information. --help Show this message. Any additional option is passed to the Schematics depending on its schema. ``` # Examples 1. Create a new NPM package that contains a blank schematic. ```sh $ schematics blank <name> ``` 2. Walkthrough example that demonstrates how to build a schematic. ```sh $ schematics schematic --name <name> ```
{ "end_byte": 1519, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/README.md" }
angular-cli/packages/angular_devkit/schematics_cli/BUILD.bazel_0_2907
load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") load("//tools:ts_json_schema.bzl", "ts_json_schema") # Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license licenses(["notice"]) package(default_visibility = ["//visibility:public"]) # @angular-devkit/schematics-cli ts_library( name = "schematics_cli", package_name = "@angular-devkit/schematics-cli", srcs = glob( include = ["**/*.ts"], exclude = [ "**/*_spec.ts", "schematic/files/**", "blank/project-files/**", "blank/schematic-files/**", # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces "node_modules/**", ], ) + [ # @external_begin # These files are generated from the JSON schema "//packages/angular_devkit/schematics_cli:blank/schema.ts", "//packages/angular_devkit/schematics_cli:schematic/schema.ts", # @external_end ], data = [ "blank/schema.json", "collection.json", "package.json", "schematic/schema.json", ] + glob( include = [ "blank/project-files/**/*", "blank/schematic-files/**/*", "schematic/files/**/*", ], ), module_name = "@angular-devkit/schematics-cli", module_root = "bin/schematics.d.ts", deps = [ "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/tasks", "//packages/angular_devkit/schematics/tools", "@npm//@inquirer/prompts", "@npm//@types/node", "@npm//@types/yargs-parser", "@npm//ansi-colors", "@npm//symbol-observable", "@npm//yargs-parser", ], ) ts_library( name = "schematics_cli_test_lib", testonly = True, srcs = glob( include = [ "bin/**/*_spec.ts", ], ), deps = [ ":schematics_cli", ], ) jasmine_node_test( name = "schematics_cli_test", srcs = [":schematics_cli_test_lib"], ) ts_json_schema( name = "blank_schema", src = "blank/schema.json", ) ts_json_schema( name = "schematic_schema", src = "schematic/schema.json", ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", pkg_deps = [ "//packages/angular_devkit/schematics:package.json", "//packages/angular_devkit/core:package.json", ], tags = ["release-package"], deps = [ ":README.md", ":license", ":schematics_cli", ], )
{ "end_byte": 2907, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/BUILD.bazel" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/factory.ts_0_1427
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { strings } from '@angular-devkit/core'; import { Rule, apply, applyTemplates, mergeWith, move, partitionApplyMerge, url, } from '@angular-devkit/schematics'; import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; import { Schema } from './schema'; export default function (options: Schema): Rule { const schematicsVersion = require('@angular-devkit/schematics/package.json').version; const coreVersion = require('@angular-devkit/core/package.json').version; return (_, context) => { context.addTask( new NodePackageInstallTask({ workingDirectory: options.name, packageManager: options.packageManager, }), ); return mergeWith( apply(url('./files'), [ // The `package.json` name is kept to allow renovate to update the dependency versions move('package.json', 'package.json.template'), partitionApplyMerge( (p) => !/\/src\/.*?\/files\//.test(p), applyTemplates({ ...options, coreVersion, schematicsVersion, dot: '.', dasherize: strings.dasherize, }), ), move(options.name), ]), ); }; }
{ "end_byte": 1427, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/factory.ts" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/README.md_0_639
# Getting Started With Schematics This repository is a basic Schematic implementation that serves as a starting point to create and publish Schematics to NPM. ### Testing To test locally, install `@angular-devkit/schematics-cli` globally and use the `schematics` command line tool. That tool acts the same as the `generate` command of the Angular CLI, but also has a debug mode. Check the documentation with ```bash schematics --help ``` ### Unit Testing `npm run test` will run the unit tests, using Jasmine as a runner and test framework. ### Publishing To publish, simply do: ```bash npm run build npm publish ``` That's it!
{ "end_byte": 639, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/README.md" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/src/my-other-schematic/index.ts_0_1335
import { Rule, SchematicContext, Tree, chain, schematic } from '@angular-devkit/schematics'; // A factory is a RuleFactory. It takes the options that might have been coming from the command // line or another schematic. These can be defined in a schema.json, which will validate export default function (options: any): Rule { // The chain rule allows us to chain multiple rules and apply them one after the other. return chain([ (tree: Tree, context: SchematicContext) => { // Show the options for this Schematics. context.logger.info('My Other Schematic: ' + JSON.stringify(options)); // Create a single file. Since this tree is not branched, we are working in the // same staging area as the other schematic, and as such cannot create the same // file twice. tree.create('hola', 'mundo'); }, // The schematic Rule calls the schematic from the same collection, with the options // passed in. Please note that if the schematic has a schema, the options will be // validated and could throw, e.g. if a required option is missing. schematic('my-schematic', { option: true }), (tree: Tree) => { // But since we're working off the same staging area, we can move the file created // by the schematic above. tree.rename('hello', 'allo'); }, ]); }
{ "end_byte": 1335, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/src/my-other-schematic/index.ts" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/src/my-other-schematic/index_spec.ts_0_519
import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import * as path from 'path'; const collectionPath = path.join(__dirname, '../collection.json'); describe('my-other-schematic', () => { it('works', async () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = await runner.runSchematic('my-other-schematic', {}, Tree.empty()); expect(tree.files.sort()).toEqual(['/allo', '/hola']); }); });
{ "end_byte": 519, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/src/my-other-schematic/index_spec.ts" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/src/my-full-schematic/index.ts_0_2477
import { Rule, SchematicContext, Tree, apply, chain, mergeWith, schematic, template, url, } from '@angular-devkit/schematics'; // Instead of `any`, it would make sense here to get a schema-to-dts package and output the // interfaces so you get type-safe options. export default function (options: any): Rule { // The chain rule allows us to chain multiple rules and apply them one after the other. return chain([ (_tree: Tree, context: SchematicContext) => { // Show the options for this Schematics. context.logger.info('My Full Schematic: ' + JSON.stringify(options)); }, // The schematic Rule calls the schematic from the same collection, with the options // passed in. Please note that if the schematic has a schema, the options will be // validated and could throw, e.g. if a required option is missing. schematic('my-other-schematic', { option: true }), // The mergeWith() rule merge two trees; one that's coming from a Source (a Tree with no // base), and the one as input to the rule. You can think of it like rebasing a Source on // top of your current set of changes. In this case, the Source is that apply function. // The apply() source takes a Source, and apply rules to it. In our case, the Source is // url(), which takes an URL and returns a Tree that contains all the files from that URL // in it. In this case, we use the relative path `./files`, and so two files are going to // be created (test1, and test2). // We then apply the template() rule, which takes a tree and apply two templates to it: // path templates: this template replaces instances of __X__ in paths with the value of // X from the options passed to template(). If the value of X is a // function, the function will be called. If the X is undefined or it // returns null (not empty string), the file or path will be removed. // content template: this is similar to EJS, but does so in place (there's no special // extension), does not support additional functions if you don't pass // them in, and only work on text files (we use an algorithm to detect // if a file is binary or not). mergeWith( apply(url('./files'), [ template({ INDEX: options.index, name: options.name, }), ]), ), ]); }
{ "end_byte": 2477, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/src/my-full-schematic/index.ts" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/src/my-full-schematic/index_spec.ts_0_902
import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import * as path from 'path'; // SchematicTestRunner needs an absolute path to the collection to test. const collectionPath = path.join(__dirname, '../collection.json'); describe('my-full-schematic', () => { it('requires required option', async () => { // We test that const runner = new SchematicTestRunner('schematics', collectionPath); await expectAsync( runner.runSchematic('my-full-schematic', {}, Tree.empty()) ).toBeRejected(); }); it('works', async () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = await runner.runSchematic('my-full-schematic', { name: 'str' }, Tree.empty()); // Listing files expect(tree.files.sort()).toEqual(['/allo', '/hola', '/test1', '/test2']); }); });
{ "end_byte": 902, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/src/my-full-schematic/index_spec.ts" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/src/my-full-schematic/files/test__INDEX___0_29
This is test #<%= INDEX %>.
{ "end_byte": 29, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/src/my-full-schematic/files/test__INDEX__" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/src/my-full-schematic/files/test2_0_127
<% if (name) { %> Hello <%= name %>, I'm a schematic. <% } else { %> Why don't you give me your name with --name? <% } %>
{ "end_byte": 127, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/src/my-full-schematic/files/test2" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/src/my-schematic/index.ts_0_1457
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; // You don't have to export the function as default. You can also have more than one rule factory // per file. export function mySchematic(options: any): Rule { return (tree: Tree, context: SchematicContext) => { // Show the options for this Schematics. // The logging here is at the discretion of the tooling. It can be ignored or only showing // info/warnings/errors. If you use console.log() there is not guarantee it will be // propagated to a user in any way (for example, an IDE running this schematic might // have a logging window but no support for console.log). context.logger.info('My Schematic: ' + JSON.stringify(options)); // Create a single file. This is the simplest example of transforming the tree. // If a file with that name already exists, the generation will NOT fail until the tool // is trying to commit this to disk. This is because we allow you to work on what is // called a "staging" area, and only finalize those changes when the schematics is // done. This allows you to create files without having to verify if they exist // already, then rename them later. Templating works in a similar fashion. tree.create('hello', 'world'); // At the end, you can either return a Tree (that will be used), or an observable of a // Tree (if you have some asynchronous tasks). return tree; }; }
{ "end_byte": 1457, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/src/my-schematic/index.ts" }
angular-cli/packages/angular_devkit/schematics_cli/schematic/files/src/my-schematic/index_spec.ts_0_492
import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import * as path from 'path'; const collectionPath = path.join(__dirname, '../collection.json'); describe('my-schematic', () => { it('works', async () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = await runner.runSchematic('my-schematic', {}, Tree.empty()); expect(tree.files).toEqual(['/hello']); }); });
{ "end_byte": 492, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/schematic/files/src/my-schematic/index_spec.ts" }
angular-cli/packages/angular_devkit/schematics_cli/bin/schematics.ts_0_6375
#!/usr/bin/env node /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // symbol polyfill must go first import 'symbol-observable'; import { JsonValue, logging, schema } from '@angular-devkit/core'; import { ProcessOutput, createConsoleLogger } from '@angular-devkit/core/node'; import { UnsuccessfulWorkflowExecution } from '@angular-devkit/schematics'; import { NodeWorkflow } from '@angular-devkit/schematics/tools'; import ansiColors from 'ansi-colors'; import { existsSync } from 'node:fs'; import * as path from 'node:path'; import yargsParser, { camelCase, decamelize } from 'yargs-parser'; /** * Parse the name of schematic passed in argument, and return a {collection, schematic} named * tuple. The user can pass in `collection-name:schematic-name`, and this function will either * return `{collection: 'collection-name', schematic: 'schematic-name'}`, or it will error out * and show usage. * * In the case where a collection name isn't part of the argument, the default is to use the * schematics package (@angular-devkit/schematics-cli) as the collection. * * This logic is entirely up to the tooling. * * @param str The argument to parse. * @return {{collection: string, schematic: (string)}} */ function parseSchematicName(str: string | null): { collection: string; schematic: string | null } { let collection = '@angular-devkit/schematics-cli'; let schematic = str; if (schematic?.includes(':')) { const lastIndexOfColon = schematic.lastIndexOf(':'); [collection, schematic] = [ schematic.slice(0, lastIndexOfColon), schematic.substring(lastIndexOfColon + 1), ]; } return { collection, schematic }; } function removeLeadingSlash(value: string): string { return value[0] === '/' ? value.slice(1) : value; } export interface MainOptions { args: string[]; stdout?: ProcessOutput; stderr?: ProcessOutput; } function _listSchematics(workflow: NodeWorkflow, collectionName: string, logger: logging.Logger) { try { const collection = workflow.engine.createCollection(collectionName); logger.info(collection.listSchematicNames().join('\n')); } catch (error) { logger.fatal(error instanceof Error ? error.message : `${error}`); return 1; } return 0; } function _createPromptProvider(): schema.PromptProvider { return async (definitions) => { let prompts: typeof import('@inquirer/prompts') | undefined; const answers: Record<string, JsonValue> = {}; for (const definition of definitions) { // Only load prompt package if needed prompts ??= await import('@inquirer/prompts'); switch (definition.type) { case 'confirmation': answers[definition.id] = await prompts.confirm({ message: definition.message, default: definition.default as boolean | undefined, }); break; case 'list': if (!definition.items?.length) { continue; } answers[definition.id] = await ( definition.multiselect ? prompts.checkbox : prompts.select )({ message: definition.message, default: definition.default, validate: (values) => { if (!definition.validator) { return true; } return definition.validator(Object.values(values).map(({ value }) => value)); }, choices: definition.items.map((item) => typeof item == 'string' ? { name: item, value: item, } : { name: item.label, value: item.value, }, ), }); break; case 'input': { let finalValue: JsonValue | undefined; answers[definition.id] = await prompts.input({ message: definition.message, default: definition.default as string | undefined, async validate(value) { if (definition.validator === undefined) { return true; } let lastValidation: ReturnType<typeof definition.validator> = false; for (const type of definition.propertyTypes) { let potential; switch (type) { case 'string': potential = String(value); break; case 'integer': case 'number': potential = Number(value); break; default: potential = value; break; } lastValidation = await definition.validator(potential); // Can be a string if validation fails if (lastValidation === true) { finalValue = potential; return true; } } return lastValidation; }, }); // Use validated value if present. // This ensures the correct type is inserted into the final schema options. if (finalValue !== undefined) { answers[definition.id] = finalValue; } break; } } } return answers; }; } function findUp(names: string | string[], from: string) { if (!Array.isArray(names)) { names = [names]; } const root = path.parse(from).root; let currentDir = from; while (currentDir && currentDir !== root) { for (const name of names) { const p = path.join(currentDir, name); if (existsSync(p)) { return p; } } currentDir = path.dirname(currentDir); } return null; } /** * return package manager' name by lock file */ function getPackageManagerName() { // order by check priority const LOCKS: Record<string, string> = { 'package-lock.json': 'npm', 'yarn.lock': 'yarn', 'pnpm-lock.yaml': 'pnpm', }; const lockPath = findUp(Object.keys(LOCKS), process.cwd()); if (lockPath) { return LOCKS[path.basename(lockPath)]; } return 'npm'; } // eslint-disable-next-line max-lines-per-function
{ "end_byte": 6375, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/bin/schematics.ts" }
angular-cli/packages/angular_devkit/schematics_cli/bin/schematics.ts_6376_14123
export async function main({ args, stdout = process.stdout, stderr = process.stderr, }: MainOptions): Promise<0 | 1> { const { cliOptions, schematicOptions, _ } = parseArgs(args); // Create a separate instance to prevent unintended global changes to the color configuration const colors = ansiColors.create(); /** Create the DevKit Logger used through the CLI. */ const logger = createConsoleLogger(!!cliOptions.verbose, stdout, stderr, { info: (s) => s, debug: (s) => s, warn: (s) => colors.bold.yellow(s), error: (s) => colors.bold.red(s), fatal: (s) => colors.bold.red(s), }); if (cliOptions.help) { logger.info(getUsage()); return 0; } /** Get the collection an schematic name from the first argument. */ const { collection: collectionName, schematic: schematicName } = parseSchematicName( _.shift() || null, ); const isLocalCollection = collectionName.startsWith('.') || collectionName.startsWith('/'); /** Gather the arguments for later use. */ const debugPresent = cliOptions.debug !== null; const debug = debugPresent ? !!cliOptions.debug : isLocalCollection; const dryRunPresent = cliOptions['dry-run'] !== null; const dryRun = dryRunPresent ? !!cliOptions['dry-run'] : debug; const force = !!cliOptions.force; const allowPrivate = !!cliOptions['allow-private']; /** Create the workflow scoped to the working directory that will be executed with this run. */ const workflow = new NodeWorkflow(process.cwd(), { force, dryRun, resolvePaths: [process.cwd(), __dirname], schemaValidation: true, packageManager: getPackageManagerName(), }); /** If the user wants to list schematics, we simply show all the schematic names. */ if (cliOptions['list-schematics']) { return _listSchematics(workflow, collectionName, logger); } if (!schematicName) { logger.info(getUsage()); return 1; } if (debug) { logger.info( `Debug mode enabled${isLocalCollection ? ' by default for local collections' : ''}.`, ); } // Indicate to the user when nothing has been done. This is automatically set to off when there's // a new DryRunEvent. let nothingDone = true; // Logging queue that receives all the messages to show the users. This only get shown when no // errors happened. let loggingQueue: string[] = []; let error = false; /** * Logs out dry run events. * * All events will always be executed here, in order of discovery. That means that an error would * be shown along other events when it happens. Since errors in workflows will stop the Observable * from completing successfully, we record any events other than errors, then on completion we * show them. * * This is a simple way to only show errors when an error occur. */ workflow.reporter.subscribe((event) => { nothingDone = false; // Strip leading slash to prevent confusion. const eventPath = removeLeadingSlash(event.path); switch (event.kind) { case 'error': error = true; logger.error( `ERROR! ${eventPath} ${event.description == 'alreadyExist' ? 'already exists' : 'does not exist'}.`, ); break; case 'update': loggingQueue.push(`${colors.cyan('UPDATE')} ${eventPath} (${event.content.length} bytes)`); break; case 'create': loggingQueue.push(`${colors.green('CREATE')} ${eventPath} (${event.content.length} bytes)`); break; case 'delete': loggingQueue.push(`${colors.yellow('DELETE')} ${eventPath}`); break; case 'rename': loggingQueue.push( `${colors.blue('RENAME')} ${eventPath} => ${removeLeadingSlash(event.to)}`, ); break; } }); /** * Listen to lifecycle events of the workflow to flush the logs between each phases. */ workflow.lifeCycle.subscribe((event) => { if (event.kind == 'workflow-end' || event.kind == 'post-tasks-start') { if (!error) { // Flush the log queue and clean the error state. loggingQueue.forEach((log) => logger.info(log)); } loggingQueue = []; error = false; } }); workflow.registry.addPostTransform(schema.transforms.addUndefinedDefaults); // Show usage of deprecated options workflow.registry.useXDeprecatedProvider((msg) => logger.warn(msg)); // Pass the rest of the arguments as the smart default "argv". Then delete it. workflow.registry.addSmartDefaultProvider('argv', (schema) => 'index' in schema ? _[Number(schema['index'])] : _, ); // Add prompts. if (cliOptions.interactive && isTTY()) { workflow.registry.usePromptProvider(_createPromptProvider()); } /** * Execute the workflow, which will report the dry run events, run the tasks, and complete * after all is done. * * The Observable returned will properly cancel the workflow if unsubscribed, error out if ANY * step of the workflow failed (sink or task), with details included, and will only complete * when everything is done. */ try { await workflow .execute({ collection: collectionName, schematic: schematicName, options: schematicOptions, allowPrivate: allowPrivate, debug: debug, logger: logger, }) .toPromise(); if (nothingDone) { logger.info('Nothing to be done.'); } else if (dryRun) { logger.info( `Dry run enabled${ dryRunPresent ? '' : ' by default in debug mode' }. No files written to disk.`, ); } return 0; } catch (err) { if (err instanceof UnsuccessfulWorkflowExecution) { // "See above" because we already printed the error. logger.fatal('The Schematic workflow failed. See above.'); } else if (debug && err instanceof Error) { logger.fatal(`An error occured:\n${err.stack}`); } else { logger.fatal(`Error: ${err instanceof Error ? err.message : err}`); } return 1; } } /** * Get usage of the CLI tool. */ function getUsage(): string { return ` schematics [collection-name:]schematic-name [options, ...] By default, if the collection name is not specified, use the internal collection provided by the Schematics CLI. Options: --debug Debug mode. This is true by default if the collection is a relative path (in that case, turn off with --debug=false). --allow-private Allow private schematics to be run from the command line. Default to false. --dry-run Do not output anything, but instead just show what actions would be performed. Default to true if debug is also true. --force Force overwriting files that would otherwise be an error. --list-schematics List all schematics from the collection, by name. A collection name should be suffixed by a colon. Example: '@angular-devkit/schematics-cli:'. --no-interactive Disables interactive input prompts. --verbose Show more information. --help Show this message. Any additional option is passed to the Schematics depending on its schema. `; } /** Parse the command line. */ const booleanArgs = [ 'allow-private', 'debug', 'dry-run', 'force', 'help', 'list-schematics', 'verbose', 'interactive', ] as const; type ElementType<T extends ReadonlyArray<unknown>> = T extends ReadonlyArray<infer ElementType> ? ElementType : never; interface Options { _: string[]; schematicOptions: Record<string, unknown>; cliOptions: Partial<Record<ElementType<typeof booleanArgs>, boolean | null>>; } /** Parse the command line. */
{ "end_byte": 14123, "start_byte": 6376, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/bin/schematics.ts" }
angular-cli/packages/angular_devkit/schematics_cli/bin/schematics.ts_14124_15969
function parseArgs(args: string[]): Options { const { _, ...options } = yargsParser(args, { boolean: booleanArgs as unknown as string[], default: { 'interactive': true, 'debug': null, 'dry-run': null, }, configuration: { 'dot-notation': false, 'boolean-negation': true, 'strip-aliased': true, 'camel-case-expansion': false, }, }); // Camelize options as yargs will return the object in kebab-case when camel casing is disabled. const schematicOptions: Options['schematicOptions'] = {}; const cliOptions: Options['cliOptions'] = {}; const isCliOptions = ( key: ElementType<typeof booleanArgs> | string, ): key is ElementType<typeof booleanArgs> => booleanArgs.includes(key as ElementType<typeof booleanArgs>); for (const [key, value] of Object.entries(options)) { if (/[A-Z]/.test(key)) { throw new Error(`Unknown argument ${key}. Did you mean ${decamelize(key)}?`); } if (isCliOptions(key)) { cliOptions[key] = value; } else { schematicOptions[camelCase(key)] = value; } } return { _: _.map((v) => v.toString()), schematicOptions, cliOptions, }; } function isTTY(): boolean { const isTruthy = (value: undefined | string) => { // Returns true if value is a string that is anything but 0 or false. return value !== undefined && value !== '0' && value.toUpperCase() !== 'FALSE'; }; // If we force TTY, we always return true. const force = process.env['NG_FORCE_TTY']; if (force !== undefined) { return isTruthy(force); } return !!process.stdout.isTTY && !isTruthy(process.env['CI']); } if (require.main === module) { const args = process.argv.slice(2); main({ args }) .then((exitCode) => (process.exitCode = exitCode)) .catch((e) => { throw e; }); }
{ "end_byte": 15969, "start_byte": 14124, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/bin/schematics.ts" }
angular-cli/packages/angular_devkit/schematics_cli/bin/schematics_spec.ts_0_2561
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { main } from './schematics'; // We only care about the write method in these mocks of NodeJS.WriteStream. class MockWriteStream { lines: string[] = []; write(str: string) { // Strip color control characters. this.lines.push(str.replace(/[^\x20-\x7F]\[\d+m/g, '')); return true; } } describe('schematics-cli binary', () => { let stdout: MockWriteStream, stderr: MockWriteStream; beforeEach(() => { stdout = new MockWriteStream(); stderr = new MockWriteStream(); }); it('list-schematics works', async () => { const args = ['--list-schematics']; const res = await main({ args, stdout, stderr }); expect(stdout.lines).toMatch(/blank/); expect(stdout.lines).toMatch(/schematic/); expect(res).toEqual(0); }); it('errors when using camel case listSchematics', async () => { const args = ['--listSchematics']; await expectAsync(main({ args, stdout, stderr })).toBeRejectedWithError( 'Unknown argument listSchematics. Did you mean list-schematics?', ); }); it('dry-run works', async () => { const args = ['blank', 'foo', '--dry-run']; const res = await main({ args, stdout, stderr }); expect(stdout.lines).toMatch(/CREATE foo\/README.md/); expect(stdout.lines).toMatch(/CREATE foo\/.gitignore/); expect(stdout.lines).toMatch(/CREATE foo\/src\/foo\/index.ts/); expect(stdout.lines).toMatch(/CREATE foo\/src\/foo\/index_spec.ts/); expect(stdout.lines).toMatch(/Dry run enabled./); expect(res).toEqual(0); }); it('dry-run is default when debug mode', async () => { const args = ['blank', 'foo', '--debug']; const res = await main({ args, stdout, stderr }); expect(stdout.lines).toMatch(/Debug mode enabled./); expect(stdout.lines).toMatch(/CREATE foo\/README.md/); expect(stdout.lines).toMatch(/CREATE foo\/.gitignore/); expect(stdout.lines).toMatch(/CREATE foo\/src\/foo\/index.ts/); expect(stdout.lines).toMatch(/CREATE foo\/src\/foo\/index_spec.ts/); expect(stdout.lines).toMatch(/Dry run enabled by default in debug mode./); expect(res).toEqual(0); }); it('error when no name is provided', async () => { const args = ['blank']; const res = await main({ args, stdout, stderr }); expect(stderr.lines).toMatch(/Error: name option is required/); expect(res).toEqual(1); }); });
{ "end_byte": 2561, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/bin/schematics_spec.ts" }
angular-cli/packages/angular_devkit/schematics_cli/blank/factory.ts_0_3199
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonObject, Path, isJsonObject, normalize, strings } from '@angular-devkit/core'; import { Rule, SchematicContext, SchematicsException, Tree, apply, applyTemplates, chain, mergeWith, move, url, } from '@angular-devkit/schematics'; import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; import { Schema } from './schema'; function addSchematicToCollectionJson( collectionPath: Path, schematicName: string, description: JsonObject, ): Rule { return (tree: Tree) => { const collectionJson = tree.readJson(collectionPath); if (!isJsonObject(collectionJson) || !isJsonObject(collectionJson.schematics)) { throw new Error('Invalid collection.json; schematics needs to be an object.'); } collectionJson['schematics'][schematicName] = description; tree.overwrite(collectionPath, JSON.stringify(collectionJson, undefined, 2)); }; } export default function (options: Schema): Rule { const schematicsVersion = require('@angular-devkit/schematics/package.json').version; const coreVersion = require('@angular-devkit/core/package.json').version; // Verify if we need to create a full project, or just add a new schematic. return (tree: Tree, context: SchematicContext) => { if (!options.name) { throw new SchematicsException('name option is required.'); } let collectionPath: Path | undefined; try { const packageJson = tree.readJson('/package.json') as { schematics: unknown; }; if (typeof packageJson.schematics === 'string') { const p = normalize(packageJson.schematics); if (tree.exists(p)) { collectionPath = p; } } } catch {} let source = apply(url('./schematic-files'), [ applyTemplates({ ...options, coreVersion, schematicsVersion, dot: '.', camelize: strings.camelize, dasherize: strings.dasherize, }), ]); // Simply create a new schematic project. if (!collectionPath) { collectionPath = normalize('/' + options.name + '/src/collection.json'); source = apply(url('./project-files'), [ move('package.json', 'package.json.template'), applyTemplates({ ...(options as object), coreVersion, schematicsVersion, dot: '.', camelize: strings.camelize, dasherize: strings.dasherize, }), mergeWith(source), move(options.name), ]); context.addTask( new NodePackageInstallTask({ workingDirectory: options.name, packageManager: options.packageManager, }), ); } return chain([ mergeWith(source), addSchematicToCollectionJson(collectionPath, strings.dasherize(options.name), { description: 'A blank schematic.', factory: './' + strings.dasherize(options.name) + '/index#' + strings.camelize(options.name), }), ]); }; }
{ "end_byte": 3199, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/blank/factory.ts" }
angular-cli/packages/angular_devkit/schematics_cli/blank/project-files/README.md_0_639
# Getting Started With Schematics This repository is a basic Schematic implementation that serves as a starting point to create and publish Schematics to NPM. ### Testing To test locally, install `@angular-devkit/schematics-cli` globally and use the `schematics` command line tool. That tool acts the same as the `generate` command of the Angular CLI, but also has a debug mode. Check the documentation with ```bash schematics --help ``` ### Unit Testing `npm run test` will run the unit tests, using Jasmine as a runner and test framework. ### Publishing To publish, simply do: ```bash npm run build npm publish ``` That's it!
{ "end_byte": 639, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/blank/project-files/README.md" }
angular-cli/packages/angular_devkit/schematics_cli/blank/schematic-files/src/__name@dasherize__/index.ts.template_0_328
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; // You don't have to export the function as default. You can also have more than one rule factory // per file. export function <%= camelize(name) %>(_options: any): Rule { return (tree: Tree, _context: SchematicContext) => { return tree; }; }
{ "end_byte": 328, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/blank/schematic-files/src/__name@dasherize__/index.ts.template" }
angular-cli/packages/angular_devkit/schematics_cli/blank/schematic-files/src/__name@dasherize__/index_spec.ts.template_0_504
import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import * as path from 'path'; const collectionPath = path.join(__dirname, '../collection.json'); describe('<%= dasherize(name) %>', () => { it('works', async () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = await runner.runSchematic('<%= dasherize(name) %>', {}, Tree.empty()); expect(tree.files).toEqual([]); }); });
{ "end_byte": 504, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/blank/schematic-files/src/__name@dasherize__/index_spec.ts.template" }
angular-cli/packages/angular_devkit/schematics/README.md_0_12744
# Schematics > A scaffolding library for the modern web. ## Description Schematics are generators that transform an existing filesystem. They can create files, refactor existing files, or move files around. What distinguishes Schematics from other generators, such as Yeoman or Yarn Create, is that schematics are purely descriptive; no changes are applied to the actual filesystem until everything is ready to be committed. There is no side effect, by design, in Schematics. # Glossary | Term | Description | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Schematics** | A generator that executes descriptive code without side effects on an existing file system. | | **Collection** | A list of schematics metadata. Schematics can be referred by name inside a collection. | | **Tool** | The code using the Schematics library. | | **Tree** | A staging area for changes, containing the original file system, and a list of changes to apply to it. | | **Rule** | A function that applies actions to a `Tree`. It returns a new `Tree` that will contain all transformations to be applied. | | **Source** | A function that creates an entirely new `Tree` from an empty filesystem. For example, a file source could read files from disk and create a Create Action for each of those. | | **Action** | An atomic operation to be validated and committed to a filesystem or a `Tree`. Actions are created by schematics. | | **Sink** | The final destination of all `Action`s. | | **Task** | A Task is a way to execute an external command or script in a schematic. A Task can be used to perform actions such as installing dependencies, running tests, or building a project. A Task is created by using the `SchematicContext` object and can be scheduled to run before or after the schematic `Tree` is applied. | # Tooling Schematics is a library, and does not work by itself. A [reference CLI](https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/bin/schematics.ts) is available on this repository, and is published on NPM at [@angular-devkit/schematics-cli](https://www.npmjs.com/package/@angular-devkit/schematics-cli). This document explains the library usage and the tooling API, but does not go into the tool implementation itself. The tooling is responsible for the following tasks: 1. Create the Schematic Engine, and pass in a Collection and Schematic loader. 1. Understand and respect the Schematics metadata and dependencies between collections. Schematics can refer to dependencies, and it's the responsibility of the tool to honor those dependencies. The reference CLI uses NPM packages for its collections. 1. Create the Options object. Options can be anything, but the schematics can specify a JSON Schema that should be respected. The reference CLI, for example, parses the arguments as a JSON object and validates it with the Schema specified by the collection. 1. Schematics provides some JSON Schema formats for validation that tooling should add. These validate paths, html selectors and app names. Please check the reference CLI for how these can be added. 1. Call the schematics with the original Tree. The tree should represent the initial state of the filesystem. The reference CLI uses the current directory for this. 1. Create a Sink and commit the result of the schematics to the Sink. Many sinks are provided by the library; FileSystemSink and DryRunSink are examples. 1. Output any logs propagated by the library, including debugging information. The tooling API is composed of the following pieces: ## Engine The `SchematicEngine` is responsible for loading and constructing `Collection`s and `Schematics`. When creating an engine, the tooling provides an `EngineHost` interface that understands how to create a `CollectionDescription` from a name, and how to create a `SchematicDescription`. # Schematics (Generators) Schematics are generators and part of a `Collection`. ## Collection A Collection is defined by a `collection.json` file (in the reference CLI). This JSON defines the following properties: | Prop Name | Type | Description | | ----------- | -------- | --------------------------- | | **name** | `string` | The name of the collection. | | **version** | `string` | Unused field. | ## Schematic # Operators, Sources and Rules A `Source` is a generator of a `Tree`; it creates an entirely new root tree from nothing. A `Rule` is a transformation from one `Tree` to another. A `Schematic` (at the root) is a `Rule` that is normally applied on the filesystem. ## Operators `FileOperator`s apply changes to a single `FileEntry` and return a new `FileEntry`. The result follows these rules: 1. If the `FileEntry` returned is null, a `DeleteAction` will be added to the action list. 1. If the path changed, a `RenameAction` will be added to the action list. 1. If the content changed, an `OverwriteAction` will be added to the action list. It is impossible to create files using a `FileOperator`. ## Provided Operators The Schematics library provides multiple `Operator` factories by default that cover basic use cases: | FileOperator | Description | | -------------------------------- | -------------------------------------------------------------------- | | `contentTemplate<T>(options: T)` | Apply a content template (see the [Templating](#templating) section) | | `pathTemplate<T>(options: T)` | Apply a path template (see the [Templating](#templating) section) | ## Provided Sources The Schematics library additionally provides multiple `Source` factories by default: | Source | Description | | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `empty()` | Creates a source that returns an empty `Tree`. | | `source(tree: Tree)` | Creates a `Source` that returns the `Tree` passed in as argument. | | `url(url: string)` | Loads a list of files from the given URL and returns a `Tree` with the files as `CreateAction` applied to an empty `Tree`. | | `apply(source: Source, rules: Rule[])` | Apply a list of `Rule`s to a source, and return the resulting `Source`. | ## Provided Rules The schematics library also provides `Rule` factories by default: | Rule | Description | | ------------------------------------------- | -------------------------------------------------------------------------------------- | | `noop()` | Returns the input `Tree` as is. | | `chain(rules: Rule[])` | Returns a `Rule` that's the concatenation of other `Rule`s. | | `forEach(op: FileOperator)` | Returns a `Rule` that applies an operator to every file of the input `Tree`. | | `move(root: string)` | Moves all the files from the input to a subdirectory. | | `merge(other: Tree)` | Merge the input `Tree` with the other `Tree`. | | `contentTemplate<T>(options: T)` | Apply a content template (see the Template section) to the entire `Tree`. | | `pathTemplate<T>(options: T)` | Apply a path template (see the Template section) to the entire `Tree`. | | `template<T>(options: T)` | Apply both path and content templates (see the Template section) to the entire `Tree`. | | `filter(predicate: FilePredicate<boolean>)` | Returns the input `Tree` with files that do not pass the `FilePredicate`. | # Templating As referenced above, some functions are based upon a file templating system, which consists of path and content templating. The system operates on placeholders defined inside files or their paths as loaded in the `Tree` and fills these in as defined in the following, using values passed into the `Rule` which applies the templating (i.e. `template<T>(options: T)`). ## Path Templating | Placeholder | Description | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `__variable__` | Replaced with the value of `variable`. | | `__variable@function__` | Replaced with the result of the call `function(variable)`. Can be chained to the left (`__variable@function1@function2__ ` etc). | ## Content Templating | Placeholder | Description | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `<%= expression %>` | Replaced with the result of the call of the given expression. This only supports direct expressions, no structural (for/if/...) JavaScript. | | `<%- expression %>` | Same as above, but the value of the result will be escaped for HTML when inserted (i.e. replacing '<' with '\&lt;') | | `<% inline code %>` | Inserts the given code into the template structure, allowing to insert structural JavaScript. | | `<%# text %>` | A comment, which gets entirely dropped. |
{ "end_byte": 12744, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/README.md" }
angular-cli/packages/angular_devkit/schematics/README.md_12744_14766
# Examples ## Simple An example of a simple Schematics which creates a "hello world" file, using an option to determine its path: ```typescript import { Tree } from '@angular-devkit/schematics'; export default function MySchematic(options: any) { return (tree: Tree) => { tree.create(options.path + '/hi', 'Hello world!'); return tree; }; } ``` A few things from this example: 1. The function receives the list of options from the tooling. 1. It returns a [`Rule`](src/engine/interface.ts#L73), which is a transformation from a `Tree` to another `Tree`. ## Templating A simplified example of a Schematics which creates a file containing a new Class, using an option to determine its name: ```typescript // files/__name@dasherize__.ts export class <%= classify(name) %> { } ``` ```typescript // index.ts import { strings } from '@angular-devkit/core'; import { Rule, SchematicContext, SchematicsException, Tree, apply, branchAndMerge, mergeWith, template, url, } from '@angular-devkit/schematics'; import { Schema as ClassOptions } from './schema'; export default function (options: ClassOptions): Rule { return (tree: Tree, context: SchematicContext) => { if (!options.name) { throw new SchematicsException('Option (name) is required.'); } const templateSource = apply(url('./files'), [ template({ ...strings, ...options, }), ]); return branchAndMerge(mergeWith(templateSource)); }; } ``` Additional things from this example: 1. `strings` provides the used `dasherize` and `classify` functions, among others. 1. The files are on-disk in the same root directory as the `index.ts` and loaded into a `Tree`. 1. Then the `template` `Rule` fills in the specified templating placeholders. For this, it only knows about the variables and functions passed to it via the options-object. 1. Finally, the resulting `Tree`, containing the new file, is merged with the existing files of the project which the Schematic is run on.
{ "end_byte": 14766, "start_byte": 12744, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/README.md" }
angular-cli/packages/angular_devkit/schematics/BUILD.bazel_0_2642
load("@npm//@angular/build-tooling/bazel/api-golden:index.bzl", "api_golden_test_npm_package") load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") # Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license package(default_visibility = ["//visibility:public"]) licenses(["notice"]) # @angular-devkit/schematics ts_library( name = "schematics", package_name = "@angular-devkit/schematics", srcs = glob( include = ["src/**/*.ts"], exclude = [ "src/**/*_spec.ts", ], ), data = [ "package.json", ], module_name = "@angular-devkit/schematics", module_root = "src/index.d.ts", deps = [ "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", # TODO: get rid of this for 6.0 "@npm//@types/node", "@npm//jsonc-parser", "@npm//magic-string", "@npm//rxjs", ], ) # @external_begin ts_library( name = "schematics_test_lib", testonly = True, srcs = glob(["src/**/*_spec.ts"]), deps = [ ":schematics", "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "//packages/angular_devkit/schematics/testing", "@npm//rxjs", ], ) jasmine_node_test( name = "schematics_test", srcs = [":schematics_test_lib"], deps = [ "@npm//jasmine", "@npm//source-map", ], ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", pkg_deps = [ "//packages/angular_devkit/core:package.json", ], tags = ["release-package"], deps = [ ":README.md", ":collection-schema.json", ":license", ":schematics", "//packages/angular_devkit/schematics/tasks", "//packages/angular_devkit/schematics/tasks:package.json", "//packages/angular_devkit/schematics/testing", "//packages/angular_devkit/schematics/testing:package.json", "//packages/angular_devkit/schematics/tools:package.json", ], ) api_golden_test_npm_package( name = "schematics_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular_cli/goldens/public-api/angular_devkit/schematics", npm_package = "angular_cli/packages/angular_devkit/schematics/npm_package", types = ["@npm//@types/node"], ) # @external_end
{ "end_byte": 2642, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/BUILD.bazel" }
angular-cli/packages/angular_devkit/schematics/tasks/BUILD.bazel_0_849
load("//tools:defaults.bzl", "ts_library") # Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "tasks", srcs = glob( include = ["**/*.ts"], exclude = [ "node/**/*.ts", "**/*_spec.ts", ], ), data = ["package.json"], module_name = "@angular-devkit/schematics/tasks", module_root = "index.d.ts", deps = [ "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "//packages/angular_devkit/schematics", "@npm//@types/node", "@npm//ora", "@npm//rxjs", "@npm//typescript", ], )
{ "end_byte": 849, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/BUILD.bazel" }
angular-cli/packages/angular_devkit/schematics/tasks/index.ts_0_468
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export { NodePackageInstallTask } from './package-manager/install-task'; export { NodePackageLinkTask } from './package-manager/link-task'; export { RepositoryInitializerTask } from './repo-init/init-task'; export { RunSchematicTask } from './run-schematic/task';
{ "end_byte": 468, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/index.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/package-manager/executor.ts_0_5033
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { BaseException } from '@angular-devkit/core'; import { SpawnOptions, spawn } from 'child_process'; import ora from 'ora'; import * as path from 'path'; import { Observable } from 'rxjs'; import { TaskExecutor, UnsuccessfulWorkflowExecution } from '../../src'; import { NodePackageTaskFactoryOptions, NodePackageTaskOptions } from './options'; interface PackageManagerProfile { commands: { installAll?: string; installPackage: string; }; } const packageManagers: { [name: string]: PackageManagerProfile } = { 'npm': { commands: { installAll: 'install', installPackage: 'install', }, }, 'cnpm': { commands: { installAll: 'install', installPackage: 'install', }, }, 'yarn': { commands: { installAll: 'install', installPackage: 'add', }, }, 'bun': { commands: { installAll: 'install', installPackage: 'add', }, }, 'pnpm': { commands: { installAll: 'install', installPackage: 'install', }, }, }; export class UnknownPackageManagerException extends BaseException { constructor(name: string) { super(`Unknown package manager "${name}".`); } } export default function ( factoryOptions: NodePackageTaskFactoryOptions = {}, ): TaskExecutor<NodePackageTaskOptions> { const packageManagerName = factoryOptions.packageManager || 'npm'; const packageManagerProfile = packageManagers[packageManagerName]; if (!packageManagerProfile) { throw new UnknownPackageManagerException(packageManagerName); } const rootDirectory = factoryOptions.rootDirectory || process.cwd(); return (options: NodePackageTaskOptions = { command: 'install' }) => { let taskPackageManagerProfile = packageManagerProfile; let taskPackageManagerName = packageManagerName; if (factoryOptions.allowPackageManagerOverride && options.packageManager) { taskPackageManagerProfile = packageManagers[options.packageManager]; if (!taskPackageManagerProfile) { throw new UnknownPackageManagerException(options.packageManager); } taskPackageManagerName = options.packageManager; } const bufferedOutput: { stream: NodeJS.WriteStream; data: Buffer }[] = []; const spawnOptions: SpawnOptions = { shell: true, cwd: path.join(rootDirectory, options.workingDirectory || ''), }; if (options.hideOutput) { spawnOptions.stdio = options.quiet ? ['ignore', 'ignore', 'pipe'] : 'pipe'; } else { spawnOptions.stdio = options.quiet ? ['ignore', 'ignore', 'inherit'] : 'inherit'; } const args: string[] = []; if (options.packageName) { if (options.command === 'install') { args.push(taskPackageManagerProfile.commands.installPackage); } args.push(options.packageName); } else if (options.command === 'install' && taskPackageManagerProfile.commands.installAll) { args.push(taskPackageManagerProfile.commands.installAll); } if (!options.allowScripts) { // Yarn requires special handling since Yarn 2+ no longer has the `--ignore-scripts` flag if (taskPackageManagerName === 'yarn') { spawnOptions.env = { ...process.env, // Supported with yarn 1 'npm_config_ignore_scripts': 'true', // Supported with yarn 2+ 'YARN_ENABLE_SCRIPTS': 'false', }; } else { args.push('--ignore-scripts'); } } if (factoryOptions.registry) { args.push(`--registry="${factoryOptions.registry}"`); } if (factoryOptions.force) { args.push('--force'); } return new Observable((obs) => { const spinner = ora({ text: `Installing packages (${taskPackageManagerName})...`, // Workaround for https://github.com/sindresorhus/ora/issues/136. discardStdin: process.platform != 'win32', }).start(); const childProcess = spawn(taskPackageManagerName, args, spawnOptions).on( 'close', (code: number) => { if (code === 0) { spinner.succeed('Packages installed successfully.'); spinner.stop(); obs.next(); obs.complete(); } else { if (options.hideOutput) { bufferedOutput.forEach(({ stream, data }) => stream.write(data)); } spinner.fail('Package install failed, see above.'); obs.error(new UnsuccessfulWorkflowExecution()); } }, ); if (options.hideOutput) { childProcess.stdout?.on('data', (data: Buffer) => bufferedOutput.push({ stream: process.stdout, data: data }), ); childProcess.stderr?.on('data', (data: Buffer) => bufferedOutput.push({ stream: process.stderr, data: data }), ); } }); }; }
{ "end_byte": 5033, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/package-manager/executor.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/package-manager/install-task.ts_0_2114
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { TaskConfiguration, TaskConfigurationGenerator } from '../../src'; import { NodePackageName, NodePackageTaskOptions } from './options'; interface NodePackageInstallTaskOptions { packageManager?: string; packageName?: string; workingDirectory?: string; quiet?: boolean; hideOutput?: boolean; allowScripts?: boolean; } export class NodePackageInstallTask implements TaskConfigurationGenerator<NodePackageTaskOptions> { quiet = true; hideOutput = true; allowScripts = false; workingDirectory?: string; packageManager?: string; packageName?: string; constructor(workingDirectory?: string); constructor(options: NodePackageInstallTaskOptions); constructor(options?: string | NodePackageInstallTaskOptions) { if (typeof options === 'string') { this.workingDirectory = options; } else if (typeof options === 'object') { if (options.quiet != undefined) { this.quiet = options.quiet; } if (options.hideOutput != undefined) { this.hideOutput = options.hideOutput; } if (options.workingDirectory != undefined) { this.workingDirectory = options.workingDirectory; } if (options.packageManager != undefined) { this.packageManager = options.packageManager; } if (options.packageName != undefined) { this.packageName = options.packageName; } if (options.allowScripts !== undefined) { this.allowScripts = options.allowScripts; } } } toConfiguration(): TaskConfiguration<NodePackageTaskOptions> { return { name: NodePackageName, options: { command: 'install', quiet: this.quiet, hideOutput: this.hideOutput, workingDirectory: this.workingDirectory, packageManager: this.packageManager, packageName: this.packageName, allowScripts: this.allowScripts, }, }; } }
{ "end_byte": 2114, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/package-manager/install-task.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/package-manager/link-task.ts_0_918
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { TaskConfiguration, TaskConfigurationGenerator } from '../../src'; import { NodePackageName, NodePackageTaskOptions } from './options'; /** * @deprecated since version 18. Create a custom task if required. */ export class NodePackageLinkTask implements TaskConfigurationGenerator<NodePackageTaskOptions> { quiet = true; constructor( public packageName?: string, public workingDirectory?: string, ) {} toConfiguration(): TaskConfiguration<NodePackageTaskOptions> { return { name: NodePackageName, options: { command: 'link', quiet: this.quiet, workingDirectory: this.workingDirectory, packageName: this.packageName, }, }; } }
{ "end_byte": 918, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/package-manager/link-task.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/package-manager/options.ts_0_650
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export const NodePackageName = 'node-package'; export interface NodePackageTaskFactoryOptions { rootDirectory?: string; packageManager?: string; allowPackageManagerOverride?: boolean; registry?: string; force?: boolean; } export interface NodePackageTaskOptions { command: string; quiet?: boolean; hideOutput?: boolean; workingDirectory?: string; packageName?: string; packageManager?: string; allowScripts?: boolean; }
{ "end_byte": 650, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/package-manager/options.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/run-schematic/executor.ts_0_1184
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicContext, TaskExecutor } from '../../src'; import { RunSchematicTaskOptions } from './options'; export default function (): TaskExecutor<RunSchematicTaskOptions<{}>> { return (options: RunSchematicTaskOptions<{}> | undefined, context: SchematicContext) => { if (!options?.name) { throw new Error( 'RunSchematicTask requires an options object with a non-empty name property.', ); } const maybeWorkflow = context.engine.workflow; const collection = options.collection || context.schematic.collection.description.name; if (!maybeWorkflow) { throw new Error('Need Workflow to support executing schematics as post tasks.'); } return maybeWorkflow.execute({ collection: collection, schematic: options.name, options: options.options, // Allow private when calling from the same collection. allowPrivate: collection == context.schematic.collection.description.name, }); }; }
{ "end_byte": 1184, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/run-schematic/executor.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/run-schematic/task.ts_0_1140
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { TaskConfiguration, TaskConfigurationGenerator } from '../../src'; import { RunSchematicName, RunSchematicTaskOptions } from './options'; export class RunSchematicTask<T> implements TaskConfigurationGenerator<RunSchematicTaskOptions<T>> { protected _collection: string | null; protected _schematic: string; protected _options: T; constructor(s: string, o: T); constructor(c: string, s: string, o: T); constructor(c: string | null, s: string | T, o?: T) { if (arguments.length == 2 || typeof s !== 'string') { o = s as T; s = c as string; c = null; } this._collection = c; this._schematic = s; this._options = o as T; } toConfiguration(): TaskConfiguration<RunSchematicTaskOptions<T>> { return { name: RunSchematicName, options: { collection: this._collection, name: this._schematic, options: this._options, }, }; } }
{ "end_byte": 1140, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/run-schematic/task.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/run-schematic/options.ts_0_361
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export const RunSchematicName = 'run-schematic'; export interface RunSchematicTaskOptions<T> { collection: string | null; name: string; options: T; }
{ "end_byte": 361, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/run-schematic/options.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/node/BUILD.bazel_0_801
load("//tools:defaults.bzl", "ts_library") # Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "node", srcs = glob( include = ["**/*.ts"], exclude = [ "**/*_spec.ts", ], ), module_name = "@angular-devkit/schematics/tasks/node", module_root = "index.d.ts", deps = [ "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/tasks", "@npm//@types/node", "@npm//rxjs", ], )
{ "end_byte": 801, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/node/BUILD.bazel" }
angular-cli/packages/angular_devkit/schematics/tasks/node/index.ts_0_1304
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { TaskExecutor, TaskExecutorFactory } from '../../src'; import { NodePackageName, NodePackageTaskFactoryOptions } from '../package-manager/options'; import { RepositoryInitializerName, RepositoryInitializerTaskFactoryOptions, } from '../repo-init/options'; import { RunSchematicName } from '../run-schematic/options'; export class BuiltinTaskExecutor { static readonly NodePackage: TaskExecutorFactory<NodePackageTaskFactoryOptions> = { name: NodePackageName, create: (options) => import('../package-manager/executor').then((mod) => mod.default(options)) as Promise< TaskExecutor<{}> >, }; static readonly RepositoryInitializer: TaskExecutorFactory<RepositoryInitializerTaskFactoryOptions> = { name: RepositoryInitializerName, create: (options) => import('../repo-init/executor').then((mod) => mod.default(options)), }; static readonly RunSchematic: TaskExecutorFactory<{}> = { name: RunSchematicName, create: () => import('../run-schematic/executor').then((mod) => mod.default()) as Promise<TaskExecutor<{}>>, }; }
{ "end_byte": 1304, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/node/index.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/repo-init/executor.ts_0_2794
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { tags } from '@angular-devkit/core'; import { SpawnOptions, spawn } from 'child_process'; import * as path from 'path'; import { SchematicContext, TaskExecutor } from '../../src'; import { RepositoryInitializerTaskFactoryOptions, RepositoryInitializerTaskOptions, } from './options'; export default function ( factoryOptions: RepositoryInitializerTaskFactoryOptions = {}, ): TaskExecutor<RepositoryInitializerTaskOptions> { const rootDirectory = factoryOptions.rootDirectory || process.cwd(); return async (options: RepositoryInitializerTaskOptions = {}, context: SchematicContext) => { const authorName = options.authorName; const authorEmail = options.authorEmail; const execute = (args: string[], ignoreErrorStream?: boolean) => { const outputStream = 'ignore'; const errorStream = ignoreErrorStream ? 'ignore' : process.stderr; const spawnOptions: SpawnOptions = { stdio: [process.stdin, outputStream, errorStream], shell: true, cwd: path.join(rootDirectory, options.workingDirectory || ''), env: { ...process.env, ...(authorName ? { GIT_AUTHOR_NAME: authorName, GIT_COMMITTER_NAME: authorName } : {}), ...(authorEmail ? { GIT_AUTHOR_EMAIL: authorEmail, GIT_COMMITTER_EMAIL: authorEmail } : {}), }, }; return new Promise<void>((resolve, reject) => { spawn('git', args, spawnOptions).on('close', (code: number) => { if (code === 0) { resolve(); } else { reject(code); } }); }); }; const hasCommand = await execute(['--version']).then( () => true, () => false, ); if (!hasCommand) { return; } const insideRepo = await execute(['rev-parse', '--is-inside-work-tree'], true).then( () => true, () => false, ); if (insideRepo) { context.logger.info(tags.oneLine` Directory is already under version control. Skipping initialization of git. `); return; } // if git is not found or an error was thrown during the `git` // init process just swallow any errors here // NOTE: This will be removed once task error handling is implemented try { await execute(['init']); await execute(['add', '.']); if (options.commit) { const message = options.message || 'initial commit'; await execute(['commit', `-m "${message}"`]); } context.logger.info('Successfully initialized git.'); } catch {} }; }
{ "end_byte": 2794, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/repo-init/executor.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/repo-init/init-task.ts_0_1134
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { TaskConfiguration, TaskConfigurationGenerator } from '../../src'; import { RepositoryInitializerName, RepositoryInitializerTaskOptions } from './options'; export interface CommitOptions { message?: string; name?: string; email?: string; } export class RepositoryInitializerTask implements TaskConfigurationGenerator<RepositoryInitializerTaskOptions> { constructor( public workingDirectory?: string, public commitOptions?: CommitOptions, ) {} toConfiguration(): TaskConfiguration<RepositoryInitializerTaskOptions> { return { name: RepositoryInitializerName, options: { commit: !!this.commitOptions, workingDirectory: this.workingDirectory, authorName: this.commitOptions && this.commitOptions.name, authorEmail: this.commitOptions && this.commitOptions.email, message: this.commitOptions && this.commitOptions.message, }, }; } }
{ "end_byte": 1134, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/repo-init/init-task.ts" }
angular-cli/packages/angular_devkit/schematics/tasks/repo-init/options.ts_0_517
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export const RepositoryInitializerName = 'repo-init'; export interface RepositoryInitializerTaskFactoryOptions { rootDirectory?: string; } export interface RepositoryInitializerTaskOptions { workingDirectory?: string; commit?: boolean; message?: string; authorName?: string; authorEmail?: string; }
{ "end_byte": 517, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tasks/repo-init/options.ts" }
angular-cli/packages/angular_devkit/schematics/tools/export-ref_spec.ts_0_2090
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as path from 'path'; import { ExportStringRef } from './export-ref'; import { CollectionCannotBeResolvedException } from '.'; describe('ExportStringRef', () => { // Depending on how the package is built the module might be either .js or .ts. // To make expectations easier, we strip the extension. const stripExtension = (p: string) => p.replace(/\.(j|t)s$/, ''); it('works', () => { // META const ref = new ExportStringRef('./export-ref#ExportStringRef', __dirname); expect(ref.ref).toBe(ExportStringRef); expect(ref.path).toBe(__dirname); expect(stripExtension(ref.module)).toBe(path.join(__dirname, 'export-ref')); }); it('works without an inner ref', () => { // META const ref = new ExportStringRef(path.join(__dirname, 'export-ref')); expect(ref.ref).toBe(undefined); expect(ref.path).toBe(__dirname); expect(stripExtension(ref.module)).toBe(path.join(__dirname, 'export-ref')); }); it('returns the exports', () => { // META const ref = new ExportStringRef('./export-ref#ExportStringRef', __dirname, false); expect(ref.ref).toEqual({ ExportStringRef }); expect(ref.path).toBe(__dirname); expect(stripExtension(ref.module)).toBe(path.join(__dirname, 'export-ref')); }); // the below doesn't work under Bazel xit('works on package names', () => { // META const ref = new ExportStringRef( '@angular-devkit/schematics/tools#CollectionCannotBeResolvedException', ); expect(ref.ref).toEqual(CollectionCannotBeResolvedException); expect(ref.path).toBe(__dirname); expect(stripExtension(ref.module)).toBe(path.join(__dirname, 'index')); }); it('works on directory', () => { // META const ref = new ExportStringRef(__dirname); expect(ref.path).toBe(__dirname); expect(stripExtension(ref.module)).toBe(path.join(__dirname, 'index')); }); });
{ "end_byte": 2090, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/export-ref_spec.ts" }
angular-cli/packages/angular_devkit/schematics/tools/file-system-engine-host_spec.ts_0_604
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable @typescript-eslint/no-explicit-any, import/no-extraneous-dependencies */ import { normalize, virtualFs } from '@angular-devkit/core'; import { HostSink, HostTree, SchematicEngine } from '@angular-devkit/schematics'; import { FileSystemEngineHost } from '@angular-devkit/schematics/tools'; import * as path from 'path'; import { from, lastValueFrom, of as observableOf } from 'rxjs';
{ "end_byte": 604, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/file-system-engine-host_spec.ts" }
angular-cli/packages/angular_devkit/schematics/tools/file-system-engine-host_spec.ts_606_9373
describe('FileSystemEngineHost', () => { // We need to resolve a file that actually exists, and not just a folder. const root = path.join( path.dirname(require.resolve(__filename)), '../../../../tests/angular_devkit/schematics/tools/file-system-engine-host', ); it('works', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('works'); const schematic1 = engine.createSchematic('schematic1', testCollection); expect(schematic1.description.name).toBe('schematic1'); }); it('understands aliases', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('aliases'); const schematic1 = engine.createSchematic('alias1', testCollection); expect(schematic1).not.toBeNull(); expect(schematic1.description.name).toBe('schematic1'); }); it('understands multiple aliases for a single schematic', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('aliases-many'); const schematic1 = engine.createSchematic('alias1', testCollection); expect(schematic1).not.toBeNull(); expect(schematic1.description.name).toBe('schematic1'); const schematic2 = engine.createSchematic('alias2', testCollection); expect(schematic2).not.toBeNull(); expect(schematic2.description.name).toBe('schematic1'); const schematic3 = engine.createSchematic('alias3', testCollection); expect(schematic3).not.toBeNull(); expect(schematic3.description.name).toBe('schematic1'); }); it('allows dupe aliases for a single schematic', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('aliases-dupe'); const schematic1 = engine.createSchematic('alias1', testCollection); expect(schematic1).not.toBeNull(); expect(schematic1.description.name).toBe('schematic1'); const schematic2 = engine.createSchematic('alias2', testCollection); expect(schematic2).not.toBeNull(); expect(schematic2.description.name).toBe('schematic1'); const schematic3 = engine.createSchematic('alias3', testCollection); expect(schematic3).not.toBeNull(); expect(schematic3.description.name).toBe('schematic1'); }); it('lists schematics but not aliases', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('aliases'); const names = testCollection.listSchematicNames(); expect(names).not.toBeNull(); expect(names[0]).toBe('schematic1'); expect(names[1]).toBe('schematic2'); }); it('extends a collection with string', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('extends-basic-string'); expect(testCollection.baseDescriptions).not.toBeUndefined(); expect(testCollection.baseDescriptions && testCollection.baseDescriptions.length).toBe(1); const schematic1 = engine.createSchematic('schematic1', testCollection); expect(schematic1).not.toBeNull(); expect(schematic1.description.name).toBe('schematic1'); const schematic2 = engine.createSchematic('schematic2', testCollection); expect(schematic2).not.toBeNull(); expect(schematic2.description.name).toBe('schematic2'); const names = testCollection.listSchematicNames(); expect(names.length).toBe(2); }); it('extends a collection with array', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('extends-basic'); expect(testCollection.baseDescriptions).not.toBeUndefined(); expect(testCollection.baseDescriptions && testCollection.baseDescriptions.length).toBe(1); const schematic1 = engine.createSchematic('schematic1', testCollection); expect(schematic1).not.toBeNull(); expect(schematic1.description.name).toBe('schematic1'); const schematic2 = engine.createSchematic('schematic2', testCollection); expect(schematic2).not.toBeNull(); expect(schematic2.description.name).toBe('schematic2'); const names = testCollection.listSchematicNames(); expect(names.length).toBe(2); }); it('extends a collection with full depth', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('extends-deep'); expect(testCollection.baseDescriptions).not.toBeUndefined(); expect(testCollection.baseDescriptions && testCollection.baseDescriptions.length).toBe(2); const schematic1 = engine.createSchematic('schematic1', testCollection); expect(schematic1).not.toBeNull(); expect(schematic1.description.name).toBe('schematic1'); const schematic2 = engine.createSchematic('schematic2', testCollection); expect(schematic2).not.toBeNull(); expect(schematic2.description.name).toBe('schematic2'); const names = testCollection.listSchematicNames(); expect(names.length).toBe(2); }); it('replaces base schematics when extending', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('extends-replace'); expect(testCollection.baseDescriptions).not.toBeUndefined(); expect(testCollection.baseDescriptions && testCollection.baseDescriptions.length).toBe(1); const schematic1 = engine.createSchematic('schematic1', testCollection); expect(schematic1).not.toBeNull(); expect(schematic1.description.name).toBe('schematic1'); expect(schematic1.description.description).toBe('replaced'); const names = testCollection.listSchematicNames(); expect(names).not.toBeNull(); expect(names.length).toBe(1); }); it('extends multiple collections', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const testCollection = engine.createCollection('extends-multiple'); expect(testCollection.baseDescriptions).not.toBeUndefined(); expect(testCollection.baseDescriptions && testCollection.baseDescriptions.length).toBe(4); const schematic1 = engine.createSchematic('schematic1', testCollection); expect(schematic1).not.toBeNull(); expect(schematic1.description.name).toBe('schematic1'); expect(schematic1.description.description).toBe('replaced'); const schematic2 = engine.createSchematic('schematic2', testCollection); expect(schematic2).not.toBeNull(); expect(schematic2.description.name).toBe('schematic2'); const names = testCollection.listSchematicNames(); expect(names).not.toBeNull(); expect(names.length).toBe(2); }); it('errors on simple circular collections', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); expect(() => engine.createCollection('extends-circular')).toThrow(); }); it('errors on complex circular collections', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); expect(() => engine.createCollection('extends-circular-multiple')).toThrow(); }); it('errors on deep circular collections', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); expect(() => engine.createCollection('extends-circular-deep')).toThrow(); }); it('errors on invalid aliases', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); expect(() => engine.createCollection('invalid-aliases')).toThrow(); }); it('errors on invalid aliases (2)', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); expect(() => engine.createCollection('invalid-aliases-2')).toThrow(); }); it(`does not list hidden schematics when 'includeHidden' is not specified`, () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const collection = engine.createCollection('hidden-schematics'); expect(collection.listSchematicNames(/** includeHidden */)).toEqual([ 'schematic-1', 'schematic-2', ]); });
{ "end_byte": 9373, "start_byte": 606, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/file-system-engine-host_spec.ts" }