_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular-cli/packages/angular_devkit/core/node/host_spec.ts_0_4316 | /**
* @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 * as fs from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { normalize, virtualFs } from '../src';
import { NodeJsAsyncHost, NodeJsSyncHost } from './host';
// TODO: replace this with an "it()" macro that's reusable globally.
let linuxOnlyIt: typeof it = it;
if (process.platform.startsWith('win') || process.platform.startsWith('darwin')) {
linuxOnlyIt = xit;
}
describe('NodeJsAsyncHost', () => {
let root: string;
let host: virtualFs.Host<fs.Stats>;
beforeEach(() => {
root = fs.mkdtempSync(join(fs.realpathSync(tmpdir()), 'core-node-spec-'));
host = new virtualFs.ScopedHost(new NodeJsAsyncHost(), normalize(root));
});
afterEach(async () => host.delete(normalize('/')).toPromise());
it('should get correct result for exists', async () => {
const filePath = normalize('not-found');
expect(await host.exists(filePath).toPromise()).toBeFalse();
await host.write(filePath, virtualFs.stringToFileBuffer('content')).toPromise();
expect(await host.exists(filePath).toPromise()).toBeTrue();
});
linuxOnlyIt(
'can watch',
async () => {
const content = virtualFs.stringToFileBuffer('hello world');
const content2 = virtualFs.stringToFileBuffer('hello world 2');
const allEvents: virtualFs.HostWatchEvent[] = [];
fs.mkdirSync(root + '/sub1');
fs.writeFileSync(root + '/sub1/file1', 'hello world');
const obs = host.watch(normalize('/sub1'), { recursive: true });
expect(obs).toBeDefined();
const subscription = obs!.subscribe((event) => {
allEvents.push(event);
});
await new Promise((resolve) => setTimeout(resolve, 100));
// Discard the events registered so far.
allEvents.splice(0);
await host.write(normalize('/sub1/sub2/file3'), content).toPromise();
await host.write(normalize('/sub1/file2'), content2).toPromise();
await host.delete(normalize('/sub1/file1')).toPromise();
await new Promise((resolve) => setTimeout(resolve, 2000));
expect(allEvents.length).toBe(3);
subscription.unsubscribe();
},
30000,
);
});
describe('NodeJsSyncHost', () => {
let root: string;
let host: virtualFs.SyncDelegateHost<fs.Stats>;
beforeEach(() => {
root = fs.mkdtempSync(join(fs.realpathSync(tmpdir()), 'core-node-spec-'));
host = new virtualFs.SyncDelegateHost(
new virtualFs.ScopedHost(new NodeJsSyncHost(), normalize(root)),
);
});
afterEach(() => {
host.delete(normalize('/'));
});
linuxOnlyIt(
'can watch',
async () => {
const content = virtualFs.stringToFileBuffer('hello world');
const content2 = virtualFs.stringToFileBuffer('hello world 2');
const allEvents: virtualFs.HostWatchEvent[] = [];
fs.mkdirSync(root + '/sub1');
fs.writeFileSync(root + '/sub1/file1', 'hello world');
const obs = host.watch(normalize('/sub1'), { recursive: true });
expect(obs).toBeDefined();
const subscription = obs!.subscribe((event) => {
allEvents.push(event);
});
await new Promise((resolve) => setTimeout(resolve, 100));
// Discard the events registered so far.
allEvents.splice(0);
host.write(normalize('/sub1/sub2/file3'), content);
host.write(normalize('/sub1/file2'), content2);
host.delete(normalize('/sub1/file1'));
await new Promise((resolve) => setTimeout(resolve, 2000));
expect(allEvents.length).toBe(3);
subscription.unsubscribe();
},
30000,
);
linuxOnlyIt(
'rename to a non-existing dir',
() => {
fs.mkdirSync(root + '/rename');
fs.writeFileSync(root + '/rename/a.txt', 'hello world');
host.rename(normalize('/rename/a.txt'), normalize('/rename/b/c/d/a.txt'));
if (fs.existsSync(root + '/rename/b/c/d/a.txt')) {
const resContent = host.read(normalize('/rename/b/c/d/a.txt'));
const content = virtualFs.fileBufferToString(resContent);
expect(content).toEqual('hello world');
}
},
30000,
);
});
| {
"end_byte": 4316,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/node/host_spec.ts"
} |
angular-cli/packages/angular_devkit/core/node/cli-logger.ts_0_2634 | /**
* @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 { filter } from 'rxjs';
import { logging } from '../src';
export interface ProcessOutput {
write(buffer: string | Buffer): boolean;
}
/**
* A Logger that sends information to STDOUT and STDERR.
*/
export function createConsoleLogger(
verbose = false,
stdout: ProcessOutput = process.stdout,
stderr: ProcessOutput = process.stderr,
colors?: Partial<Record<logging.LogLevel, (s: string) => string>>,
): logging.Logger {
const logger = new logging.IndentLogger('cling');
logger.pipe(filter((entry) => entry.level !== 'debug' || verbose)).subscribe((entry) => {
const color = colors && colors[entry.level];
let output = stdout;
switch (entry.level) {
case 'warn':
case 'fatal':
case 'error':
output = stderr;
break;
}
// If we do console.log(message) or process.stdout.write(message + '\n'), the process might
// stop before the whole message is written and the stream is flushed. This happens when
// streams are asynchronous.
//
// NodeJS IO streams are different depending on platform and usage. In POSIX environment,
// for example, they're asynchronous when writing to a pipe, but synchronous when writing
// to a TTY. In windows, it's the other way around. You can verify which is which with
// stream.isTTY and platform, but this is not good enough.
// In the async case, one should wait for the callback before sending more data or
// continuing the process. In our case it would be rather hard to do (but not impossible).
//
// Instead we take the easy way out and simply chunk the message and call the write
// function while the buffer drain itself asynchronously. With a smaller chunk size than
// the buffer, we are mostly certain that it works. In this case, the chunk has been picked
// as half a page size (4096/2 = 2048), minus some bytes for the color formatting.
// On POSIX it seems the buffer is 2 pages (8192), but just to be sure (could be different
// by platform).
//
// For more details, see https://nodejs.org/api/process.html#process_a_note_on_process_i_o
const chunkSize = 2000; // Small chunk.
let message = entry.message;
while (message) {
const chunk = message.slice(0, chunkSize);
message = message.slice(chunkSize);
output.write(color ? color(chunk) : chunk);
}
output.write('\n');
});
return logger;
}
| {
"end_byte": 2634,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/node/cli-logger.ts"
} |
angular-cli/packages/angular_devkit/core/node/BUILD.bazel_0_1226 | # 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//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "ts_library")
licenses(["notice"])
package(default_visibility = ["//visibility:public"])
ts_library(
name = "node",
srcs = glob(
include = ["**/*.ts"],
exclude = [
"testing/**/*.ts",
"**/*_spec.ts",
],
),
module_name = "@angular-devkit/core/node",
module_root = "index.d.ts",
deps = [
"//packages/angular_devkit/core",
"@npm//@types/node",
"@npm//chokidar",
"@npm//rxjs",
],
)
# @external_begin
ts_library(
name = "node_test_lib",
testonly = True,
srcs = glob(
include = [
"**/*_spec.ts",
],
exclude = [
"testing/**/*.ts",
],
),
deps = [
":node",
"//packages/angular_devkit/core",
"@npm//rxjs",
],
)
jasmine_node_test(
name = "node_test",
srcs = [":node_test_lib"],
deps = [
"@npm//chokidar",
],
)
# @external_end
| {
"end_byte": 1226,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/node/BUILD.bazel"
} |
angular-cli/packages/angular_devkit/core/node/host.ts_0_7530 | /**
* @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 {
PathLike,
Stats,
constants,
existsSync,
promises as fsPromises,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
writeFileSync,
} from 'node:fs';
import { dirname as pathDirname } from 'node:path';
import { Observable, map, mergeMap, from as observableFrom, publish, refCount } from 'rxjs';
import { Path, PathFragment, dirname, fragment, getSystemPath, normalize, virtualFs } from '../src';
async function exists(path: PathLike): Promise<boolean> {
try {
await fsPromises.access(path, constants.F_OK);
return true;
} catch {
return false;
}
}
// This will only be initialized if the watch() method is called.
// Otherwise chokidar appears only in type positions, and shouldn't be referenced
// in the JavaScript output.
let FSWatcher: typeof import('chokidar').FSWatcher;
function loadFSWatcher() {
if (!FSWatcher) {
try {
FSWatcher = require('chokidar').FSWatcher;
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') {
throw new Error(
'As of angular-devkit version 8.0, the "chokidar" package ' +
'must be installed in order to use watch() features.',
);
}
throw e;
}
}
}
/**
* An implementation of the Virtual FS using Node as the background. There are two versions; one
* synchronous and one asynchronous.
*/
export class NodeJsAsyncHost implements virtualFs.Host<Stats> {
get capabilities(): virtualFs.HostCapabilities {
return { synchronous: false };
}
write(path: Path, content: virtualFs.FileBuffer): Observable<void> {
return observableFrom(fsPromises.mkdir(getSystemPath(dirname(path)), { recursive: true })).pipe(
mergeMap(() => fsPromises.writeFile(getSystemPath(path), new Uint8Array(content))),
);
}
read(path: Path): Observable<virtualFs.FileBuffer> {
return observableFrom(fsPromises.readFile(getSystemPath(path))).pipe(
map((buffer) => new Uint8Array(buffer).buffer as virtualFs.FileBuffer),
);
}
delete(path: Path): Observable<void> {
return observableFrom(
fsPromises.rm(getSystemPath(path), { force: true, recursive: true, maxRetries: 3 }),
);
}
rename(from: Path, to: Path): Observable<void> {
return observableFrom(fsPromises.rename(getSystemPath(from), getSystemPath(to)));
}
list(path: Path): Observable<PathFragment[]> {
return observableFrom(fsPromises.readdir(getSystemPath(path))).pipe(
map((names) => names.map((name) => fragment(name))),
);
}
exists(path: Path): Observable<boolean> {
return observableFrom(exists(getSystemPath(path)));
}
isDirectory(path: Path): Observable<boolean> {
return this.stat(path).pipe(map((stat) => stat.isDirectory()));
}
isFile(path: Path): Observable<boolean> {
return this.stat(path).pipe(map((stat) => stat.isFile()));
}
// Some hosts may not support stat.
stat(path: Path): Observable<virtualFs.Stats<Stats>> {
return observableFrom(fsPromises.stat(getSystemPath(path)));
}
// Some hosts may not support watching.
watch(
path: Path,
_options?: virtualFs.HostWatchOptions,
): Observable<virtualFs.HostWatchEvent> | null {
return new Observable<virtualFs.HostWatchEvent>((obs) => {
loadFSWatcher();
const watcher = new FSWatcher({ persistent: true });
watcher.add(getSystemPath(path));
watcher
.on('change', (path) => {
obs.next({
path: normalize(path),
time: new Date(),
type: virtualFs.HostWatchEventType.Changed,
});
})
.on('add', (path) => {
obs.next({
path: normalize(path),
time: new Date(),
type: virtualFs.HostWatchEventType.Created,
});
})
.on('unlink', (path) => {
obs.next({
path: normalize(path),
time: new Date(),
type: virtualFs.HostWatchEventType.Deleted,
});
});
return () => {
void watcher.close();
};
}).pipe(publish(), refCount());
}
}
/**
* An implementation of the Virtual FS using Node as the backend, synchronously.
*/
export class NodeJsSyncHost implements virtualFs.Host<Stats> {
get capabilities(): virtualFs.HostCapabilities {
return { synchronous: true };
}
write(path: Path, content: virtualFs.FileBuffer): Observable<void> {
return new Observable((obs) => {
mkdirSync(getSystemPath(dirname(path)), { recursive: true });
writeFileSync(getSystemPath(path), new Uint8Array(content));
obs.next();
obs.complete();
});
}
read(path: Path): Observable<virtualFs.FileBuffer> {
return new Observable((obs) => {
const buffer = readFileSync(getSystemPath(path));
obs.next(new Uint8Array(buffer).buffer as virtualFs.FileBuffer);
obs.complete();
});
}
delete(path: Path): Observable<void> {
return new Observable<void>((obs) => {
rmSync(getSystemPath(path), { force: true, recursive: true, maxRetries: 3 });
obs.complete();
});
}
rename(from: Path, to: Path): Observable<void> {
return new Observable((obs) => {
const toSystemPath = getSystemPath(to);
mkdirSync(pathDirname(toSystemPath), { recursive: true });
renameSync(getSystemPath(from), toSystemPath);
obs.next();
obs.complete();
});
}
list(path: Path): Observable<PathFragment[]> {
return new Observable((obs) => {
const names = readdirSync(getSystemPath(path));
obs.next(names.map((name) => fragment(name)));
obs.complete();
});
}
exists(path: Path): Observable<boolean> {
return new Observable((obs) => {
obs.next(existsSync(getSystemPath(path)));
obs.complete();
});
}
isDirectory(path: Path): Observable<boolean> {
return this.stat(path).pipe(map((stat) => stat.isDirectory()));
}
isFile(path: Path): Observable<boolean> {
return this.stat(path).pipe(map((stat) => stat.isFile()));
}
// Some hosts may not support stat.
stat(path: Path): Observable<virtualFs.Stats<Stats>> {
return new Observable((obs) => {
obs.next(statSync(getSystemPath(path)));
obs.complete();
});
}
// Some hosts may not support watching.
watch(
path: Path,
_options?: virtualFs.HostWatchOptions,
): Observable<virtualFs.HostWatchEvent> | null {
return new Observable<virtualFs.HostWatchEvent>((obs) => {
loadFSWatcher();
const watcher = new FSWatcher({ persistent: false });
watcher.add(getSystemPath(path));
watcher
.on('change', (path) => {
obs.next({
path: normalize(path),
time: new Date(),
type: virtualFs.HostWatchEventType.Changed,
});
})
.on('add', (path) => {
obs.next({
path: normalize(path),
time: new Date(),
type: virtualFs.HostWatchEventType.Created,
});
})
.on('unlink', (path) => {
obs.next({
path: normalize(path),
time: new Date(),
type: virtualFs.HostWatchEventType.Deleted,
});
});
return () => {
void watcher.close();
};
}).pipe(publish(), refCount());
}
}
| {
"end_byte": 7530,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/node/host.ts"
} |
angular-cli/packages/angular_devkit/core/node/index.ts_0_258 | /**
* @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 './cli-logger';
export * from './host';
| {
"end_byte": 258,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/node/index.ts"
} |
angular-cli/packages/angular_devkit/core/node/testing/BUILD.bazel_0_730 | 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 = "testing",
srcs = glob(
include = ["**/*.ts"],
exclude = [
"**/*_spec.ts",
],
),
module_name = "@angular-devkit/core/node/testing",
module_root = "index.d.ts",
deps = [
"//packages/angular_devkit/core",
"//packages/angular_devkit/core/node",
"@npm//@types/jasmine",
"@npm//@types/node",
"@npm//rxjs",
],
)
| {
"end_byte": 730,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/node/testing/BUILD.bazel"
} |
angular-cli/packages/angular_devkit/core/node/testing/index.ts_0_1502 | /**
* @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 fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { Path, getSystemPath, join, normalize, virtualFs } from '../../src';
import { NodeJsSyncHost } from '../host';
/**
* A Sync Scoped Host that creates a temporary directory and scope to it.
*/
export class TempScopedNodeJsSyncHost extends virtualFs.ScopedHost<fs.Stats> {
protected _sync?: virtualFs.SyncDelegateHost<fs.Stats>;
protected override _root: Path;
constructor() {
const root = normalize(path.join(os.tmpdir(), `devkit-host-${+Date.now()}-${process.pid}`));
fs.mkdirSync(getSystemPath(root));
super(new NodeJsSyncHost(), root);
this._root = root;
}
get files(): Path[] {
const sync = this.sync;
function _visit(p: Path): Path[] {
return sync
.list(p)
.map((fragment) => join(p, fragment))
.reduce((files, path) => {
if (sync.isDirectory(path)) {
return files.concat(_visit(path));
} else {
return files.concat(path);
}
}, [] as Path[]);
}
return _visit(normalize('/'));
}
get root() {
return this._root;
}
get sync() {
if (!this._sync) {
this._sync = new virtualFs.SyncDelegateHost<fs.Stats>(this);
}
return this._sync;
}
}
| {
"end_byte": 1502,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/node/testing/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/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 json from './json/index';
import * as logging from './logger/index';
import * as workspaces from './workspace';
export * from './exception';
export * from './json/index';
export * from './utils/index';
export * from './virtual-fs/index';
export { json, logging, workspaces };
| {
"end_byte": 494,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/exception.ts_0_995 | /**
* @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 class BaseException extends Error {
constructor(message = '') {
super(message);
}
}
export class UnknownException extends BaseException {
constructor(message: string) {
super(message);
}
}
// Exceptions
export class FileDoesNotExistException extends BaseException {
constructor(path: string) {
super(`Path "${path}" does not exist.`);
}
}
export class FileAlreadyExistException extends BaseException {
constructor(path: string) {
super(`Path "${path}" already exist.`);
}
}
export class PathIsDirectoryException extends BaseException {
constructor(path: string) {
super(`Path "${path}" is a directory.`);
}
}
export class PathIsFileException extends BaseException {
constructor(path: string) {
super(`Path "${path}" is a file.`);
}
}
| {
"end_byte": 995,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/exception.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/logger_spec.ts_0_2251 | /**
* @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 { lastValueFrom, toArray } from 'rxjs';
import { JsonValue } from '../json/utils';
import { Logger } from './logger';
describe('Logger', () => {
it('works', (done: DoneFn) => {
const logger = new Logger('test');
lastValueFrom(logger.pipe(toArray()))
.then((observed: JsonValue[]) => {
expect(observed).toEqual([
jasmine.objectContaining({ message: 'hello', level: 'debug', name: 'test' }),
jasmine.objectContaining({ message: 'world', level: 'info', name: 'test' }),
]);
})
.then(
() => done(),
(err) => done.fail(err),
);
logger.debug('hello');
logger.info('world');
logger.complete();
});
it('works with children', (done: DoneFn) => {
const logger = new Logger('test');
let hasCompleted = false;
lastValueFrom(logger.pipe(toArray()))
.then((observed: JsonValue[]) => {
expect(observed).toEqual([
jasmine.objectContaining({ message: 'hello', level: 'debug', name: 'child' }) as any,
jasmine.objectContaining({ message: 'world', level: 'info', name: 'child' }) as any,
]);
expect(hasCompleted).toBe(true);
})
.then(
() => done(),
(err) => done.fail(err),
);
const childLogger = new Logger('child', logger);
childLogger.subscribe(undefined, undefined, () => (hasCompleted = true));
childLogger.debug('hello');
childLogger.info('world');
logger.complete();
});
it('misses messages if not subscribed', (done: DoneFn) => {
const logger = new Logger('test');
logger.debug('woah');
lastValueFrom(logger.pipe(toArray()))
.then((observed: JsonValue[]) => {
expect(observed).toEqual([
jasmine.objectContaining({ message: 'hello', level: 'debug', name: 'test' }) as any,
]);
})
.then(
() => done(),
(err) => done.fail(err),
);
logger.debug('hello');
logger.complete();
});
});
| {
"end_byte": 2251,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/logger_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/null-logger.ts_0_648 | /**
* @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 { EMPTY } from 'rxjs';
import { Logger, LoggerApi } from './logger';
export class NullLogger extends Logger {
constructor(parent: Logger | null = null) {
super('', parent);
this._observable = EMPTY;
}
override asApi(): LoggerApi {
return {
createChild: () => new NullLogger(this),
log() {},
debug() {},
info() {},
warn() {},
error() {},
fatal() {},
} as LoggerApi;
}
}
| {
"end_byte": 648,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/null-logger.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/level.ts_0_1735 | /**
* @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 } from '../json/utils';
import { LogLevel, Logger } from './logger';
export class LevelTransformLogger extends Logger {
constructor(
public override readonly name: string,
public override readonly parent: Logger | null = null,
public readonly levelTransform: (level: LogLevel) => LogLevel,
) {
super(name, parent);
}
override log(level: LogLevel, message: string, metadata: JsonObject = {}): void {
return super.log(this.levelTransform(level), message, metadata);
}
override createChild(name: string): Logger {
return new LevelTransformLogger(name, this, this.levelTransform);
}
}
export class LevelCapLogger extends LevelTransformLogger {
static levelMap: { [cap: string]: { [level: string]: string } } = {
debug: { debug: 'debug', info: 'debug', warn: 'debug', error: 'debug', fatal: 'debug' },
info: { debug: 'debug', info: 'info', warn: 'info', error: 'info', fatal: 'info' },
warn: { debug: 'debug', info: 'info', warn: 'warn', error: 'warn', fatal: 'warn' },
error: { debug: 'debug', info: 'info', warn: 'warn', error: 'error', fatal: 'error' },
fatal: { debug: 'debug', info: 'info', warn: 'warn', error: 'error', fatal: 'fatal' },
};
constructor(
public override readonly name: string,
public override readonly parent: Logger | null = null,
public readonly levelCap: LogLevel,
) {
super(name, parent, (level: LogLevel) => {
return (LevelCapLogger.levelMap[levelCap][level] || level) as LogLevel;
});
}
}
| {
"end_byte": 1735,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/level.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/indent.ts_0_1509 | /**
* @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 { map } from 'rxjs';
import { Logger } from './logger';
/**
* Keep an map of indentation => array of indentations based on the level.
* This is to optimize calculating the prefix based on the indentation itself. Since most logs
* come from similar levels, and with similar indentation strings, this will be shared by all
* loggers. Also, string concatenation is expensive so performing concats for every log entries
* is expensive; this alleviates it.
*/
const indentationMap: { [indentationType: string]: string[] } = {};
export class IndentLogger extends Logger {
constructor(name: string, parent: Logger | null = null, indentation = ' ') {
super(name, parent);
indentationMap[indentation] = indentationMap[indentation] || [''];
const indentMap = indentationMap[indentation];
this._observable = this._observable.pipe(
map((entry) => {
const l = entry.path.filter((x) => !!x).length;
if (l >= indentMap.length) {
let current = indentMap[indentMap.length - 1];
while (l >= indentMap.length) {
current += indentation;
indentMap.push(current);
}
}
entry.message = indentMap[l] + entry.message.split(/\n/).join('\n' + indentMap[l]);
return entry;
}),
);
}
}
| {
"end_byte": 1509,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/indent.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/logger.ts_0_5295 | /**
* @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 { EMPTY, Observable, Operator, PartialObserver, Subject, Subscription } from 'rxjs';
import { JsonObject } from '../json/utils';
export interface LoggerMetadata extends JsonObject {
name: string;
path: string[];
}
export interface LogEntry extends LoggerMetadata {
level: LogLevel;
message: string;
timestamp: number;
}
export interface LoggerApi {
createChild(name: string): Logger;
log(level: LogLevel, message: string, metadata?: JsonObject): void;
debug(message: string, metadata?: JsonObject): void;
info(message: string, metadata?: JsonObject): void;
warn(message: string, metadata?: JsonObject): void;
error(message: string, metadata?: JsonObject): void;
fatal(message: string, metadata?: JsonObject): void;
}
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
export class Logger extends Observable<LogEntry> implements LoggerApi {
protected readonly _subject: Subject<LogEntry> = new Subject<LogEntry>();
protected _metadata: LoggerMetadata;
private _obs: Observable<LogEntry> = EMPTY;
private _subscription: Subscription | null = null;
protected get _observable() {
return this._obs;
}
protected set _observable(v: Observable<LogEntry>) {
if (this._subscription) {
this._subscription.unsubscribe();
}
this._obs = v;
if (this.parent) {
this._subscription = this.subscribe(
(value: LogEntry) => {
if (this.parent) {
this.parent._subject.next(value);
}
},
(error: Error) => {
if (this.parent) {
this.parent._subject.error(error);
}
},
() => {
if (this._subscription) {
this._subscription.unsubscribe();
}
this._subscription = null;
},
);
}
}
constructor(
public readonly name: string,
public readonly parent: Logger | null = null,
) {
super();
const path: string[] = [];
let p = parent;
while (p) {
path.push(p.name);
p = p.parent;
}
this._metadata = { name, path };
this._observable = this._subject.asObservable();
if (this.parent && this.parent._subject) {
// When the parent completes, complete us as well.
this.parent._subject.subscribe(undefined, undefined, () => this.complete());
}
}
asApi(): LoggerApi {
return {
createChild: (name: string) => this.createChild(name),
log: (level: LogLevel, message: string, metadata?: JsonObject) => {
return this.log(level, message, metadata);
},
debug: (message: string, metadata?: JsonObject) => this.debug(message, metadata),
info: (message: string, metadata?: JsonObject) => this.info(message, metadata),
warn: (message: string, metadata?: JsonObject) => this.warn(message, metadata),
error: (message: string, metadata?: JsonObject) => this.error(message, metadata),
fatal: (message: string, metadata?: JsonObject) => this.fatal(message, metadata),
};
}
createChild(name: string) {
return new (this.constructor as typeof Logger)(name, this);
}
complete() {
this._subject.complete();
}
log(level: LogLevel, message: string, metadata: JsonObject = {}): void {
const entry: LogEntry = Object.assign({}, metadata, this._metadata, {
level,
message,
timestamp: +Date.now(),
});
this._subject.next(entry);
}
next(entry: LogEntry): void {
this._subject.next(entry);
}
debug(message: string, metadata: JsonObject = {}) {
return this.log('debug', message, metadata);
}
info(message: string, metadata: JsonObject = {}) {
return this.log('info', message, metadata);
}
warn(message: string, metadata: JsonObject = {}) {
return this.log('warn', message, metadata);
}
error(message: string, metadata: JsonObject = {}) {
return this.log('error', message, metadata);
}
fatal(message: string, metadata: JsonObject = {}) {
return this.log('fatal', message, metadata);
}
override toString() {
return `<Logger(${this.name})>`;
}
override lift<R>(operator: Operator<LogEntry, R>): Observable<R> {
return this._observable.lift(operator);
}
override subscribe(): Subscription;
override subscribe(observer: PartialObserver<LogEntry>): Subscription;
override subscribe(
next?: (value: LogEntry) => void,
error?: (error: Error) => void,
complete?: () => void,
): Subscription;
override subscribe(
_observerOrNext?: PartialObserver<LogEntry> | ((value: LogEntry) => void),
_error?: (error: Error) => void,
_complete?: () => void,
): Subscription {
// eslint-disable-next-line prefer-spread
return this._observable.subscribe.apply(
this._observable,
// eslint-disable-next-line prefer-rest-params
arguments as unknown as Parameters<Observable<LogEntry>['subscribe']>,
);
}
override forEach(
next: (value: LogEntry) => void,
promiseCtor: PromiseConstructorLike = Promise,
): Promise<void> {
return this._observable.forEach(next, promiseCtor);
}
}
| {
"end_byte": 5295,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/logger.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/indent_spec.ts_0_1514 | /**
* @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 { lastValueFrom, toArray } from 'rxjs';
import { IndentLogger } from './indent';
import { LogEntry, Logger } from './logger';
describe('IndentSpec', () => {
it('works', (done: DoneFn) => {
const logger = new IndentLogger('test');
lastValueFrom(logger.pipe(toArray()))
.then((observed: LogEntry[]) => {
expect(observed).toEqual([
jasmine.objectContaining({ message: 'test', level: 'info', name: 'test' }) as any,
jasmine.objectContaining({ message: ' test2', level: 'info', name: 'test2' }) as any,
jasmine.objectContaining({ message: ' test3', level: 'info', name: 'test3' }) as any,
jasmine.objectContaining({ message: ' test4', level: 'info', name: 'test4' }) as any,
jasmine.objectContaining({ message: 'test5', level: 'info', name: 'test' }) as any,
]);
})
.then(
() => done(),
(err) => done.fail(err),
);
const logger2 = new Logger('test2', logger);
const logger3 = new Logger('test3', logger2);
const logger4 = new Logger('test4', logger);
logger.info('test');
logger2.info('test2');
logger3.info('test3');
logger4.info('test4');
logger.info('test5');
logger.complete();
});
});
| {
"end_byte": 1514,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/indent_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/null-logger_spec.ts_0_1207 | /**
* @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, toArray } from 'rxjs';
import { LogEntry, Logger } from './logger';
import { NullLogger } from './null-logger';
describe('NullLogger', () => {
it('works', (done: DoneFn) => {
const logger = new NullLogger();
lastValueFrom(logger.pipe(toArray()))
.then((observed: LogEntry[]) => {
expect(observed).toEqual([]);
})
.then(
() => done(),
(err) => done.fail(err),
);
logger.debug('hello');
logger.info('world');
logger.complete();
});
it('nullifies children', (done: DoneFn) => {
const logger = new Logger('test');
lastValueFrom(logger.pipe(toArray()))
.then((observed: LogEntry[]) => {
expect(observed).toEqual([]);
})
.then(
() => done(),
(err) => done.fail(err),
);
const nullLogger = new NullLogger(logger);
const child = new Logger('test', nullLogger);
child.debug('hello');
child.info('world');
logger.complete();
});
});
| {
"end_byte": 1207,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/null-logger_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/index.ts_0_348 | /**
* @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 './indent';
export * from './level';
export * from './logger';
export * from './null-logger';
export * from './transform-logger';
| {
"end_byte": 348,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/transform-logger.ts_0_558 | /**
* @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 { Observable } from 'rxjs';
import { LogEntry, Logger } from './logger';
export class TransformLogger extends Logger {
constructor(
name: string,
transform: (stream: Observable<LogEntry>) => Observable<LogEntry>,
parent: Logger | null = null,
) {
super(name, parent);
this._observable = transform(this._observable);
}
}
| {
"end_byte": 558,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/transform-logger.ts"
} |
angular-cli/packages/angular_devkit/core/src/logger/transform-logger_spec.ts_0_1093 | /**
* @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 { filter, lastValueFrom, map, toArray } from 'rxjs';
import { LogEntry } from './logger';
import { TransformLogger } from './transform-logger';
describe('TransformLogger', () => {
it('works', (done: DoneFn) => {
const logger = new TransformLogger('test', (stream) => {
return stream.pipe(
filter((entry) => entry.message != 'hello'),
map((entry) => ((entry.message += '1'), entry)),
);
});
lastValueFrom(logger.pipe(toArray()))
.then((observed: LogEntry[]) => {
expect(observed).toEqual([
jasmine.objectContaining({ message: 'world1', level: 'info', name: 'test' }) as any,
]);
})
.then(
() => done(),
(err) => done.fail(err),
);
logger.debug('hello');
logger.info('world');
logger.complete();
});
});
| {
"end_byte": 1093,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/logger/transform-logger_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/core.ts_0_5015 | /**
* @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 { basename, getSystemPath, join, normalize } from '../virtual-fs';
import { WorkspaceDefinition } from './definitions';
import { WorkspaceHost } from './host';
import { readJsonWorkspace } from './json/reader';
import { writeJsonWorkspace } from './json/writer';
const formatLookup = new WeakMap<WorkspaceDefinition, WorkspaceFormat>();
/**
* Supported workspace formats
*/
export enum WorkspaceFormat {
JSON,
}
/**
* @private
*/
export function _test_addWorkspaceFile(name: string, format: WorkspaceFormat): void {
workspaceFiles[name] = format;
}
/**
* @private
*/
export function _test_removeWorkspaceFile(name: string): void {
delete workspaceFiles[name];
}
// NOTE: future additions could also perform content analysis to determine format/version
const workspaceFiles: Record<string, WorkspaceFormat> = {
'angular.json': WorkspaceFormat.JSON,
'.angular.json': WorkspaceFormat.JSON,
};
/**
* Reads and constructs a `WorkspaceDefinition`. If the function is provided with a path to a
* directory instead of a file, a search of the directory's files will commence to attempt to
* locate a known workspace file. Currently the following are considered known workspace files:
* - `angular.json`
* - `.angular.json`
*
* @param path The path to either a workspace file or a directory containing a workspace file.
* @param host The `WorkspaceHost` to use to access the file and directory data.
* @param format An optional `WorkspaceFormat` value. Used if the path specifies a non-standard
* file name that would prevent automatically discovering the format.
*
*
* @return An `Promise` of the read result object with the `WorkspaceDefinition` contained within
* the `workspace` property.
*/
export async function readWorkspace(
path: string,
host: WorkspaceHost,
format?: WorkspaceFormat,
// return type will eventually have a `diagnostics` property as well
): Promise<{ workspace: WorkspaceDefinition }> {
if (await host.isDirectory(path)) {
// TODO: Warn if multiple found (requires diagnostics support)
const directory = normalize(path);
let found = false;
for (const [name, nameFormat] of Object.entries(workspaceFiles)) {
if (format !== undefined && format !== nameFormat) {
continue;
}
const potential = getSystemPath(join(directory, name));
if (await host.isFile(potential)) {
path = potential;
format = nameFormat;
found = true;
break;
}
}
if (!found) {
throw new Error(
'Unable to locate a workspace file for workspace path. Are you missing an `angular.json`' +
' or `.angular.json` file?',
);
}
} else if (format === undefined) {
const filename = basename(normalize(path));
if (filename in workspaceFiles) {
format = workspaceFiles[filename];
}
}
if (format === undefined) {
throw new Error('Unable to determine format for workspace path.');
}
let workspace;
switch (format) {
case WorkspaceFormat.JSON:
workspace = await readJsonWorkspace(path, host);
break;
default:
throw new Error('Unsupported workspace format.');
}
formatLookup.set(workspace, WorkspaceFormat.JSON);
return { workspace };
}
/**
* Writes a `WorkspaceDefinition` to the underlying storage via the provided `WorkspaceHost`.
* If the `WorkspaceDefinition` was created via the `readWorkspace` function, metadata will be
* used to determine the path and format of the Workspace. In all other cases, the `path` and
* `format` options must be specified as they would be otherwise unknown.
*
* @param workspace The `WorkspaceDefinition` that will be written.
* @param host The `WorkspaceHost` to use to access/write the file and directory data.
* @param path The path to a file location for the output. Required if `readWorkspace` was not
* used to create the `WorkspaceDefinition`. Optional otherwise; will override the
* `WorkspaceDefinition` metadata if provided.
* @param format The `WorkspaceFormat` to use for output. Required if `readWorkspace` was not
* used to create the `WorkspaceDefinition`. Optional otherwise; will override the
* `WorkspaceDefinition` metadata if provided.
*
*
* @return An `Promise` of type `void`.
*/
export async function writeWorkspace(
workspace: WorkspaceDefinition,
host: WorkspaceHost,
path?: string,
format?: WorkspaceFormat,
): Promise<void> {
if (format === undefined) {
format = formatLookup.get(workspace);
if (format === undefined) {
throw new Error('A format is required for custom workspace objects.');
}
}
switch (format) {
case WorkspaceFormat.JSON:
return writeJsonWorkspace(workspace, host, path);
default:
throw new Error('Unsupported workspace format.');
}
}
| {
"end_byte": 5015,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/core.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/core_spec.ts_0_8638 | /**
* @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-empty-function */
import { getSystemPath, join, normalize } from '../virtual-fs';
import {
WorkspaceFormat,
_test_addWorkspaceFile,
_test_removeWorkspaceFile,
readWorkspace,
writeWorkspace,
} from './core';
import { WorkspaceDefinition } from './definitions';
import { WorkspaceHost } from './host';
describe('readWorkspace', () => {
it('attempts to read from specified file path [angular.json]', async () => {
const requestedPath = '/path/to/workspace/angular.json';
const host: WorkspaceHost = {
async readFile(path) {
expect(path).toBe(requestedPath);
return '{ "version": 1 }';
},
async writeFile() {},
async isFile(path) {
return path === requestedPath;
},
async isDirectory(path) {
if (path !== requestedPath) {
fail();
}
return false;
},
};
await readWorkspace(requestedPath, host);
});
it('attempts to read from specified file path [.angular.json]', async () => {
const requestedPath = '/path/to/workspace/.angular.json';
const host: WorkspaceHost = {
async readFile(path) {
expect(path).toBe(requestedPath);
return '{ "version": 1 }';
},
async writeFile() {},
async isFile(path) {
return path === requestedPath;
},
async isDirectory(path) {
if (path !== requestedPath) {
fail();
}
return false;
},
};
await readWorkspace(requestedPath, host);
});
it('attempts to read from specified non-standard file path with format', async () => {
const requestedPath = '/path/to/workspace/abc.json';
const host: WorkspaceHost = {
async readFile(path) {
expect(path).toBe(requestedPath);
return '{ "version": 1 }';
},
async writeFile() {},
async isFile(path) {
return path === requestedPath;
},
async isDirectory(path) {
if (path !== requestedPath) {
fail();
}
return false;
},
};
await readWorkspace(requestedPath, host, WorkspaceFormat.JSON);
});
it('errors when reading from specified non-standard file path without format', async () => {
const requestedPath = '/path/to/workspace/abc.json';
const host: WorkspaceHost = {
async readFile(path) {
expect(path).toBe(requestedPath);
return '{ "version": 1 }';
},
async writeFile() {},
async isFile(path) {
return path === requestedPath;
},
async isDirectory(path) {
if (path !== requestedPath) {
fail();
}
return false;
},
};
await expectAsync(readWorkspace(requestedPath, host)).toBeRejectedWithError(
/Unable to determine format for workspace path/,
);
});
it('errors when reading from specified file path with invalid specified format', async () => {
const requestedPath = '/path/to/workspace/angular.json';
const host: WorkspaceHost = {
async readFile(path) {
expect(path).toBe(requestedPath);
return '{ "version": 1 }';
},
async writeFile() {},
async isFile(path) {
return path === requestedPath;
},
async isDirectory(path) {
if (path !== requestedPath) {
fail();
}
return false;
},
};
await expectAsync(
readWorkspace(requestedPath, host, 12 as WorkspaceFormat),
).toBeRejectedWithError(/Unsupported workspace format/);
});
it('attempts to find/read from directory path', async () => {
const requestedPath = getSystemPath(normalize('/path/to/workspace'));
const expectedFile = getSystemPath(join(normalize(requestedPath), '.angular.json'));
const isFileChecks: string[] = [];
const host: WorkspaceHost = {
async readFile(path) {
expect(path).not.toBe(requestedPath);
expect(path).toBe(expectedFile);
return '{ "version": 1 }';
},
async writeFile() {},
async isFile(path) {
isFileChecks.push(path);
return path === expectedFile;
},
async isDirectory(path) {
if (path === requestedPath) {
return true;
}
fail();
return false;
},
};
await readWorkspace(requestedPath, host);
isFileChecks.sort();
expect(isFileChecks).toEqual(
[
getSystemPath(join(normalize(requestedPath), 'angular.json')),
getSystemPath(join(normalize(requestedPath), '.angular.json')),
].sort(),
);
});
it('attempts to find/read only files for specified format from directory path', async () => {
const requestedPath = '/path/to/workspace';
const isFileChecks: string[] = [];
const readFileChecks: string[] = [];
const host: WorkspaceHost = {
async readFile(path) {
expect(path).not.toBe(requestedPath);
readFileChecks.push(path);
return '{ "version": 1 }';
},
async writeFile() {},
async isFile(path) {
isFileChecks.push(path);
return true;
},
async isDirectory(path) {
if (path === requestedPath) {
return true;
}
fail();
return false;
},
};
_test_addWorkspaceFile('wrong.format', 99 as WorkspaceFormat);
try {
await readWorkspace(requestedPath, host, WorkspaceFormat.JSON);
} finally {
_test_removeWorkspaceFile('wrong.format');
}
isFileChecks.sort();
expect(isFileChecks).toEqual([getSystemPath(join(normalize(requestedPath), 'angular.json'))]);
readFileChecks.sort();
expect(readFileChecks).toEqual([getSystemPath(join(normalize(requestedPath), 'angular.json'))]);
});
it('errors when no file found from specified directory path', async () => {
const requestedPath = '/path/to/workspace';
const host: WorkspaceHost = {
async readFile(path) {
expect(path).not.toBe(requestedPath);
return '{ "version": 1 }';
},
async writeFile() {},
async isFile() {
return false;
},
async isDirectory(path) {
if (path === requestedPath) {
return true;
}
fail();
return false;
},
};
await expectAsync(readWorkspace(requestedPath, host)).toBeRejectedWithError(
/Unable to locate a workspace file/,
);
});
});
describe('writeWorkspace', () => {
it('attempts to write to specified file path', async () => {
const requestedPath = '/path/to/workspace/angular.json';
let writtenPath: string | undefined;
const host: WorkspaceHost = {
async readFile() {
fail();
return '';
},
async writeFile(path) {
expect(writtenPath).toBeUndefined();
writtenPath = path;
},
async isFile() {
fail();
return false;
},
async isDirectory() {
fail();
return false;
},
};
await writeWorkspace({} as WorkspaceDefinition, host, requestedPath, WorkspaceFormat.JSON);
expect(writtenPath).toBe(requestedPath);
});
it('errors when writing to specified file path with invalid specified format', async () => {
const requestedPath = '/path/to/workspace/angular.json';
const host: WorkspaceHost = {
async readFile() {
fail();
return '';
},
async writeFile() {
fail();
},
async isFile() {
fail();
return false;
},
async isDirectory() {
fail();
return false;
},
};
await expectAsync(
writeWorkspace({} as WorkspaceDefinition, host, requestedPath, 12 as WorkspaceFormat),
).toBeRejectedWithError(/Unsupported workspace format/);
});
it('errors when writing custom workspace without specified format', async () => {
const requestedPath = '/path/to/workspace/angular.json';
const host: WorkspaceHost = {
async readFile() {
fail();
return '';
},
async writeFile() {
fail();
},
async isFile() {
fail();
return false;
},
async isDirectory() {
fail();
return false;
},
};
await expectAsync(
writeWorkspace({} as WorkspaceDefinition, host, requestedPath),
).toBeRejectedWithError(/A format is required/);
});
});
| {
"end_byte": 8638,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/core_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/host_spec.ts_0_1798 | /**
* @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 { test } from '../virtual-fs/host';
import { WorkspaceHost, createWorkspaceHost } from './host';
describe('createWorkspaceHost', () => {
let testHost: test.TestHost;
let workspaceHost: WorkspaceHost;
beforeEach(() => {
testHost = new test.TestHost({
'abc.txt': 'abcdefg',
'foo/bar.json': '{}',
});
workspaceHost = createWorkspaceHost(testHost);
});
it('supports isFile', async () => {
expect(await workspaceHost.isFile('abc.txt')).toBeTruthy();
expect(await workspaceHost.isFile('foo/bar.json')).toBeTruthy();
expect(await workspaceHost.isFile('foo\\bar.json')).toBeTruthy();
expect(await workspaceHost.isFile('foo')).toBeFalsy();
expect(await workspaceHost.isFile('not.there')).toBeFalsy();
});
it('supports isDirectory', async () => {
expect(await workspaceHost.isDirectory('foo')).toBeTruthy();
expect(await workspaceHost.isDirectory('foo/')).toBeTruthy();
expect(await workspaceHost.isDirectory('foo\\')).toBeTruthy();
expect(await workspaceHost.isDirectory('abc.txt')).toBeFalsy();
expect(await workspaceHost.isDirectory('foo/bar.json')).toBeFalsy();
expect(await workspaceHost.isDirectory('not.there')).toBeFalsy();
});
it('supports readFile', async () => {
expect(await workspaceHost.readFile('abc.txt')).toBe('abcdefg');
});
it('supports writeFile', async () => {
await workspaceHost.writeFile('newfile', 'baz');
expect(testHost.files.sort() as string[]).toEqual(['/abc.txt', '/foo/bar.json', '/newfile']);
expect(testHost.$read('newfile')).toBe('baz');
});
});
| {
"end_byte": 1798,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/host_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/definitions_spec.ts_0_7786 | /**
* @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 {
ProjectDefinition,
ProjectDefinitionCollection,
TargetDefinition,
TargetDefinitionCollection,
} from './definitions';
describe('ProjectDefinitionCollection', () => {
it('can be created without initial values or a listener', () => {
const collection = new ProjectDefinitionCollection();
expect(collection.size).toBe(0);
});
it('can be created with initial values', () => {
const initial = {
'my-app': { root: 'my-app', extensions: {}, targets: new TargetDefinitionCollection() },
'my-lib': { root: 'my-lib', extensions: {}, targets: new TargetDefinitionCollection() },
};
initial['my-app'].targets.add({
name: 'build',
builder: 'build-builder',
});
const collection = new ProjectDefinitionCollection(initial);
expect(collection.size).toBe(2);
const app = collection.get('my-app');
expect(app).not.toBeUndefined();
if (app) {
expect(app.root).toBe('my-app');
expect(app.extensions).toEqual({});
expect(app.targets.size).toBe(1);
expect(app.targets.get('build')).not.toBeUndefined();
}
const lib = collection.get('my-lib');
expect(lib).not.toBeUndefined();
if (lib) {
expect(lib.root).toBe('my-lib');
expect(lib.extensions).toEqual({});
expect(lib.targets).toBeTruthy();
}
});
it('can be created with a listener', () => {
const listener = () => {
fail('listener should not execute on initialization');
};
const collection = new ProjectDefinitionCollection(undefined, listener);
expect(collection.size).toBe(0);
});
it('can be created with initial values and a listener', () => {
const initial = {
'my-app': { root: 'src/my-app', extensions: {}, targets: new TargetDefinitionCollection() },
'my-lib': { root: 'src/my-lib', extensions: {}, targets: new TargetDefinitionCollection() },
};
initial['my-app'].targets.add({
name: 'build',
builder: 'build-builder',
});
const listener = () => {
fail('listener should not execute on initialization');
};
const collection = new ProjectDefinitionCollection(initial, listener);
expect(collection.size).toBe(2);
const app = collection.get('my-app');
expect(app).not.toBeUndefined();
if (app) {
expect(app.root).toBe('src/my-app');
expect(app.extensions).toEqual({});
expect(app.targets.size).toBe(1);
expect(app.targets.get('build')).not.toBeUndefined();
}
const lib = collection.get('my-lib');
expect(lib).not.toBeUndefined();
if (lib) {
expect(lib.root).toBe('src/my-lib');
expect(lib.extensions).toEqual({});
expect(lib.targets).toBeTruthy();
}
});
it('listens to an addition via set', () => {
const listener = (name: string, value?: ProjectDefinition) => {
expect(name).toBe('my-app');
expect(value?.root).toBe('src/my-app');
};
const collection = new ProjectDefinitionCollection(undefined, listener);
collection.set('my-app', {
root: 'src/my-app',
extensions: {},
targets: new TargetDefinitionCollection(),
});
});
it('listens to an addition via add', () => {
const listener = (name: string, value?: ProjectDefinition) => {
expect(name).toBe('my-app');
expect(value?.root).toBe('src/my-app');
};
const collection = new ProjectDefinitionCollection(undefined, listener);
collection.add({
name: 'my-app',
root: 'src/my-app',
});
});
it('listens to a removal', () => {
const initial = {
'my-app': { root: 'src/my-app', extensions: {}, targets: new TargetDefinitionCollection() },
};
const listener = (name: string, value?: ProjectDefinition) => {
expect(name).toBe('my-app');
expect(value).toBeUndefined();
};
const collection = new ProjectDefinitionCollection(initial, listener);
collection.delete('my-app');
});
it('listens to a replacement', () => {
const initial = {
'my-app': { root: 'src/my-app', extensions: {}, targets: new TargetDefinitionCollection() },
};
const listener = (name: string, value?: ProjectDefinition) => {
expect(name).toBe('my-app');
expect(value?.root).toBe('src/my-app2');
};
const collection = new ProjectDefinitionCollection(initial, listener);
collection.set('my-app', {
root: 'src/my-app2',
extensions: {},
targets: new TargetDefinitionCollection(),
});
});
});
describe('TargetDefinitionCollection', () => {
it('can be created without initial values or a listener', () => {
const collection = new TargetDefinitionCollection();
expect(collection.size).toBe(0);
});
it('can be created with initial values', () => {
const initial = {
'build': { builder: 'builder:build' },
'test': { builder: 'builder:test' },
};
const collection = new TargetDefinitionCollection(initial);
expect(collection.size).toBe(2);
const build = collection.get('build');
expect(build).not.toBeUndefined();
expect(build?.builder).toBe('builder:build');
const test = collection.get('test');
expect(test).not.toBeUndefined();
expect(test?.builder).toBe('builder:test');
});
it('can be created with a listener', () => {
const listener = () => {
fail('listener should not execute on initialization');
};
const collection = new TargetDefinitionCollection(undefined, listener);
expect(collection.size).toBe(0);
});
it('can be created with initial values and a listener', () => {
const initial = {
'build': { builder: 'builder:build' },
'test': { builder: 'builder:test' },
};
const listener = () => {
fail('listener should not execute on initialization');
};
const collection = new TargetDefinitionCollection(initial, listener);
expect(collection.size).toBe(2);
const build = collection.get('build');
expect(build?.builder).toBe('builder:build');
const test = collection.get('test');
expect(test?.builder).toBe('builder:test');
});
it('listens to an addition via set', () => {
const listener = (name: string, value?: TargetDefinition) => {
expect(name).toBe('build');
expect(value?.builder).toBe('builder:build');
};
const collection = new TargetDefinitionCollection(undefined, listener);
collection.set('build', { builder: 'builder:build' });
});
it('listens to an addition via add', () => {
const listener = (name: string, value?: TargetDefinition) => {
expect(name).toBe('build');
expect(value?.builder).toBe('builder:build');
};
const collection = new TargetDefinitionCollection(undefined, listener);
collection.add({
name: 'build',
builder: 'builder:build',
});
});
it('listens to a removal', () => {
const initial = {
'build': { builder: 'builder:build' },
};
const listener = (name: string, value?: TargetDefinition) => {
expect(name).toBe('build');
};
const collection = new TargetDefinitionCollection(initial, listener);
collection.delete('build');
});
it('listens to a replacement', () => {
const initial = {
'build': { builder: 'builder:build' },
};
const listener = (name: string, value?: TargetDefinition) => {
expect(name).toBe('build');
expect(value?.builder).toBe('builder:test');
};
const collection = new TargetDefinitionCollection(initial, listener);
collection.set('build', { builder: 'builder:test' });
});
});
| {
"end_byte": 7786,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/definitions_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/host.ts_0_1575 | /**
* @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 { normalize, virtualFs } from '../virtual-fs';
export interface WorkspaceHost {
readFile(path: string): Promise<string>;
writeFile(path: string, data: string): Promise<void>;
isDirectory(path: string): Promise<boolean>;
isFile(path: string): Promise<boolean>;
// Potential future additions
// readDirectory?(path: string): Promise<string[]>;
}
export function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost {
const workspaceHost: WorkspaceHost = {
async readFile(path: string): Promise<string> {
const data = await lastValueFrom(host.read(normalize(path)));
return virtualFs.fileBufferToString(data);
},
async writeFile(path: string, data: string): Promise<void> {
return lastValueFrom(host.write(normalize(path), virtualFs.stringToFileBuffer(data)));
},
async isDirectory(path: string): Promise<boolean> {
try {
return await lastValueFrom(host.isDirectory(normalize(path)));
} catch {
// some hosts throw if path does not exist
return false;
}
},
async isFile(path: string): Promise<boolean> {
try {
return await lastValueFrom(host.isFile(normalize(path)));
} catch {
// some hosts throw if path does not exist
return false;
}
},
};
return workspaceHost;
}
| {
"end_byte": 1575,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/host.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/index.ts_0_374 | /**
* @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 './definitions';
export { type WorkspaceHost, createWorkspaceHost } from './host';
export { WorkspaceFormat, readWorkspace, writeWorkspace } from './core';
| {
"end_byte": 374,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/definitions.ts_0_5924 | /**
* @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 '../json';
export interface WorkspaceDefinition {
readonly extensions: Record<string, JsonValue | undefined>;
readonly projects: ProjectDefinitionCollection;
}
export interface ProjectDefinition {
readonly extensions: Record<string, JsonValue | undefined>;
readonly targets: TargetDefinitionCollection;
root: string;
prefix?: string;
sourceRoot?: string;
}
export interface TargetDefinition {
options?: Record<string, JsonValue | undefined>;
configurations?: Record<string, Record<string, JsonValue | undefined> | undefined>;
defaultConfiguration?: string;
builder: string;
}
export type DefinitionCollectionListener<V extends object> = (
name: string,
newValue: V | undefined,
collection: DefinitionCollection<V>,
) => void;
class DefinitionCollection<V extends object> implements ReadonlyMap<string, V> {
private _map: Map<string, V>;
constructor(
initial?: Record<string, V>,
private _listener?: DefinitionCollectionListener<V>,
) {
this._map = new Map(initial && Object.entries(initial));
}
delete(key: string): boolean {
const result = this._map.delete(key);
if (result) {
this._listener?.(key, undefined, this);
}
return result;
}
set(key: string, value: V): this {
const updatedValue = value !== this.get(key);
if (updatedValue) {
this._map.set(key, value);
this._listener?.(key, value, this);
}
return this;
}
forEach<T>(
callbackfn: (value: V, key: string, map: DefinitionCollection<V>) => void,
thisArg?: T,
): void {
this._map.forEach((value, key) => callbackfn(value, key, this), thisArg);
}
get(key: string): V | undefined {
return this._map.get(key);
}
has(key: string): boolean {
return this._map.has(key);
}
get size(): number {
return this._map.size;
}
[Symbol.iterator](): MapIterator<[string, V]> {
return this._map[Symbol.iterator]();
}
entries(): MapIterator<[string, V]> {
return this._map.entries();
}
keys(): MapIterator<string> {
return this._map.keys();
}
values(): MapIterator<V> {
return this._map.values();
}
}
function isJsonValue(value: unknown): value is JsonValue {
const visited = new Set();
switch (typeof value) {
case 'boolean':
case 'number':
case 'string':
return true;
case 'object':
if (value === null) {
return true;
}
visited.add(value);
for (const property of Object.values(value)) {
if (typeof value === 'object' && visited.has(property)) {
continue;
}
if (!isJsonValue(property)) {
return false;
}
}
return true;
default:
return false;
}
}
export class ProjectDefinitionCollection extends DefinitionCollection<ProjectDefinition> {
constructor(
initial?: Record<string, ProjectDefinition>,
listener?: DefinitionCollectionListener<ProjectDefinition>,
) {
super(initial, listener);
}
add(definition: {
name: string;
root: string;
sourceRoot?: string;
prefix?: string;
targets?: Record<string, TargetDefinition | undefined>;
[key: string]: unknown;
}): ProjectDefinition {
if (this.has(definition.name)) {
throw new Error('Project name already exists.');
}
this._validateName(definition.name);
const project: ProjectDefinition = {
root: definition.root,
prefix: definition.prefix,
sourceRoot: definition.sourceRoot,
targets: new TargetDefinitionCollection(),
extensions: {},
};
if (definition.targets) {
for (const [name, target] of Object.entries(definition.targets)) {
if (target) {
project.targets.set(name, target);
}
}
}
for (const [name, value] of Object.entries(definition)) {
switch (name) {
case 'name':
case 'root':
case 'sourceRoot':
case 'prefix':
case 'targets':
break;
default:
if (isJsonValue(value)) {
project.extensions[name] = value;
} else {
throw new TypeError(`"${name}" must be a JSON value.`);
}
break;
}
}
super.set(definition.name, project);
return project;
}
override set(name: string, value: ProjectDefinition): this {
this._validateName(name);
super.set(name, value);
return this;
}
private _validateName(name: string): void {
if (typeof name !== 'string' || !/^(?:@\w[\w.-]*\/)?\w[\w.-]*$/.test(name)) {
throw new Error('Project name must be a valid npm package name.');
}
}
}
export class TargetDefinitionCollection extends DefinitionCollection<TargetDefinition> {
constructor(
initial?: Record<string, TargetDefinition>,
listener?: DefinitionCollectionListener<TargetDefinition>,
) {
super(initial, listener);
}
add(
definition: {
name: string;
} & TargetDefinition,
): TargetDefinition {
if (this.has(definition.name)) {
throw new Error('Target name already exists.');
}
this._validateName(definition.name);
const target = {
builder: definition.builder,
options: definition.options,
configurations: definition.configurations,
defaultConfiguration: definition.defaultConfiguration,
};
super.set(definition.name, target);
return target;
}
override set(name: string, value: TargetDefinition): this {
this._validateName(name);
super.set(name, value);
return this;
}
private _validateName(name: string): void {
if (typeof name !== 'string') {
throw new TypeError('Target name must be a string.');
}
}
}
| {
"end_byte": 5924,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/definitions.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/utilities.ts_0_4586 | /**
* @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 { JsonArray, JsonObject, JsonValue, isJsonObject } from '../../json';
export type ChangeListener = (path: string[], newValue: JsonValue | undefined) => void;
type ChangeReporter = (
path: string[],
target: JsonObject | JsonArray,
oldValue: JsonValue | undefined,
newValue: JsonValue | undefined,
) => void;
// lib.es5 PropertyKey is string | number | symbol which doesn't overlap ProxyHandler PropertyKey which is string | symbol.
// See https://github.com/microsoft/TypeScript/issues/42894
type ProxyPropertyKey = string | symbol;
export function createVirtualAstObject<T extends object = JsonObject>(
root: JsonObject | JsonArray,
options: {
exclude?: string[];
include?: string[];
listener?: ChangeListener;
} = {},
): T {
const reporter: ChangeReporter = (path, target, oldValue, newValue) => {
if (!options.listener) {
return;
}
if (oldValue === newValue || JSON.stringify(oldValue) === JSON.stringify(newValue)) {
// same value
return;
}
if (Array.isArray(target)) {
// For arrays we remove the index and update the entire value as keeping
// track of changes by indices can be rather complex.
options.listener(path.slice(0, -1), target);
} else {
options.listener(path, newValue);
}
};
return create(
Array.isArray(root) ? [...root] : { ...root },
[],
reporter,
new Set(options.exclude),
options.include?.length ? new Set(options.include) : undefined,
) as T;
}
function create(
obj: JsonObject | JsonArray,
path: string[],
reporter: ChangeReporter,
excluded = new Set<ProxyPropertyKey>(),
included?: Set<ProxyPropertyKey>,
) {
return new Proxy(obj, {
getOwnPropertyDescriptor(target: {}, p: ProxyPropertyKey): PropertyDescriptor | undefined {
if (excluded.has(p) || (included && !included.has(p))) {
return undefined;
}
return Reflect.getOwnPropertyDescriptor(target, p);
},
has(target: {}, p: ProxyPropertyKey): boolean {
if (typeof p === 'symbol' || excluded.has(p)) {
return false;
}
return Reflect.has(target, p);
},
get(target: {}, p: ProxyPropertyKey): unknown {
if (excluded.has(p) || (included && !included.has(p))) {
return undefined;
}
const value = Reflect.get(target, p);
if (typeof p === 'symbol') {
return value;
}
if ((isJsonObject(value) && !(value instanceof Map)) || Array.isArray(value)) {
return create(value, [...path, p], reporter);
} else {
return value;
}
},
set(target: {}, p: ProxyPropertyKey, value: unknown): boolean {
if (excluded.has(p) || (included && !included.has(p))) {
return false;
}
if (value === undefined) {
// setting to undefined is equivalent to a delete.
return this.deleteProperty?.(target, p) ?? false;
}
if (typeof p === 'symbol') {
return Reflect.set(target, p, value);
}
const existingValue = getCurrentValue(target, p);
if (Reflect.set(target, p, value)) {
reporter([...path, p], target, existingValue, value as JsonValue);
return true;
}
return false;
},
deleteProperty(target: {}, p: ProxyPropertyKey): boolean {
if (excluded.has(p)) {
return false;
}
if (typeof p === 'symbol') {
return Reflect.deleteProperty(target, p);
}
const existingValue = getCurrentValue(target, p);
if (Reflect.deleteProperty(target, p)) {
reporter([...path, p], target, existingValue, undefined);
return true;
}
return true;
},
defineProperty(target: {}, p: ProxyPropertyKey, attributes: PropertyDescriptor): boolean {
if (typeof p === 'symbol') {
return Reflect.defineProperty(target, p, attributes);
}
return false;
},
ownKeys(target: {}): ProxyPropertyKey[] {
return Reflect.ownKeys(target).filter(
(p) => !excluded.has(p) && (!included || included.has(p)),
);
},
});
}
function getCurrentValue(target: object, property: string): JsonValue | undefined {
if (Array.isArray(target) && isFinite(+property)) {
return target[+property];
}
if (target && property in target) {
return (target as JsonObject)[property];
}
return undefined;
}
| {
"end_byte": 4586,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/utilities.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/writer.ts_0_5534 | /**
* @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 { applyEdits, modify } from 'jsonc-parser';
import { EOL } from 'node:os';
import { JsonObject, JsonValue } from '../../json';
import { ProjectDefinition, TargetDefinition, WorkspaceDefinition } from '../definitions';
import { WorkspaceHost } from '../host';
import {
JsonChange,
JsonWorkspaceDefinition,
JsonWorkspaceMetadata,
JsonWorkspaceSymbol,
} from './metadata';
export async function writeJsonWorkspace(
workspace: WorkspaceDefinition,
host: WorkspaceHost,
path?: string,
options: {
schema?: string;
} = {},
): Promise<void> {
const metadata = (workspace as JsonWorkspaceDefinition)[JsonWorkspaceSymbol];
if (metadata) {
if (!metadata.hasChanges) {
return;
}
// update existing JSON workspace
const data = updateJsonWorkspace(metadata);
return host.writeFile(path ?? metadata.filePath, data);
} else {
// serialize directly
if (!path) {
throw new Error('path option is required');
}
const obj = convertJsonWorkspace(workspace, options.schema);
const data = JSON.stringify(obj, null, 2);
return host.writeFile(path, data);
}
}
function convertJsonWorkspace(workspace: WorkspaceDefinition, schema?: string): JsonObject {
const obj = {
$schema: schema || './node_modules/@angular/cli/lib/config/schema.json',
version: 1,
...workspace.extensions,
...(isEmpty(workspace.projects)
? {}
: { projects: convertJsonProjectCollection(workspace.projects) }),
};
return obj;
}
function convertJsonProjectCollection(
collection: Iterable<[string, ProjectDefinition]>,
): JsonObject {
const projects = Object.create(null) as JsonObject;
for (const [projectName, project] of collection) {
projects[projectName] = convertJsonProject(project);
}
return projects;
}
function convertJsonProject(project: ProjectDefinition): JsonObject {
let targets: JsonObject | undefined;
if (project.targets.size > 0) {
targets = Object.create(null) as JsonObject;
for (const [targetName, target] of project.targets) {
targets[targetName] = convertJsonTarget(target);
}
}
const obj = {
...project.extensions,
root: project.root,
...(project.sourceRoot === undefined ? {} : { sourceRoot: project.sourceRoot }),
...(project.prefix === undefined ? {} : { prefix: project.prefix }),
...(targets === undefined ? {} : { architect: targets }),
};
return obj;
}
function isEmpty(obj: object | undefined): boolean {
return obj === undefined || Object.keys(obj).length === 0;
}
function convertJsonTarget(target: TargetDefinition): JsonObject {
return {
builder: target.builder,
...(isEmpty(target.options) ? {} : { options: target.options as JsonObject }),
...(isEmpty(target.configurations)
? {}
: { configurations: target.configurations as JsonObject }),
...(target.defaultConfiguration === undefined
? {}
: { defaultConfiguration: target.defaultConfiguration }),
};
}
function convertJsonTargetCollection(collection: Iterable<[string, TargetDefinition]>): JsonObject {
const targets = Object.create(null) as JsonObject;
for (const [projectName, target] of collection) {
targets[projectName] = convertJsonTarget(target);
}
return targets;
}
function normalizeValue(
value: JsonChange['value'] | undefined,
type: JsonChange['type'],
): JsonValue | undefined {
if (value === undefined) {
return undefined;
}
switch (type) {
case 'project':
return convertJsonProject(value as ProjectDefinition);
case 'projectcollection': {
const projects = convertJsonProjectCollection(value as Iterable<[string, ProjectDefinition]>);
return isEmpty(projects) ? undefined : projects;
}
case 'target':
return convertJsonTarget(value as TargetDefinition);
case 'targetcollection': {
const targets = convertJsonTargetCollection(value as Iterable<[string, TargetDefinition]>);
return isEmpty(targets) ? undefined : targets;
}
default:
return value as JsonValue;
}
}
function updateJsonWorkspace(metadata: JsonWorkspaceMetadata): string {
let { raw: content } = metadata;
const { changes, hasLegacyTargetsName } = metadata;
for (const { jsonPath, value, type } of changes.values()) {
// Determine which key to use if (architect or targets)
if (hasLegacyTargetsName && jsonPath[2] === 'targets') {
jsonPath[2] = 'architect';
}
// TODO: `modify` re-parses the content every time.
// See: https://github.com/microsoft/node-jsonc-parser/blob/35d94cd71bd48f9784453b2439262c938e21d49b/src/impl/edit.ts#L18
// Ideally this should accept a string or an AST to avoid the potentially expensive repeat parsing operation.
const edits = modify(content, jsonPath, normalizeValue(value, type), {
formattingOptions: {
insertSpaces: true,
tabSize: 2,
eol: getEOL(content),
},
});
content = applyEdits(content, edits);
}
return content;
}
function getEOL(content: string): string {
const CRLF = '\r\n';
const LF = '\n';
const newlines = content.match(/(?:\r?\n)/g);
if (newlines?.length) {
const crlf = newlines.filter((l) => l === CRLF).length;
const lf = newlines.length - crlf;
return crlf > lf ? CRLF : LF;
}
return EOL;
}
| {
"end_byte": 5534,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/writer.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/reader_spec.ts_0_4641 | /**
* @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 { readFileSync } from 'fs';
import { JsonObject } from '../../json';
import { stripIndent } from '../../utils/literals';
import { TargetDefinitionCollection, WorkspaceDefinition } from '../definitions';
import { JsonWorkspaceDefinition, JsonWorkspaceMetadata, JsonWorkspaceSymbol } from './metadata';
import { readJsonWorkspace } from './reader';
const basicFile = stripIndent`
{
"version": 1,
// Comment
"schematics": {
"@angular/schematics:component": {
"prefix": "abc"
}
},
"x-foo": {
"is": ["good", "great", "awesome"]
},
"x-bar": 5,
}`;
const representativeFile = readFileSync(require.resolve(__dirname + '/test/angular.json'), 'utf8');
function createTestHost(content: string, onWrite?: (path: string, data: string) => void) {
return {
async readFile() {
return content;
},
async writeFile(path: string, data: string) {
if (onWrite) {
onWrite(path, data);
}
},
async isFile() {
return true;
},
async isDirectory() {
return true;
},
};
}
function getMetadata(workspace: WorkspaceDefinition): JsonWorkspaceMetadata {
const metadata = (workspace as JsonWorkspaceDefinition)[JsonWorkspaceSymbol];
expect(metadata).toBeDefined();
return metadata;
}
describe('readJsonWorkpace Parsing', () => {
it('parses a basic file', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('basic', host);
expect(workspace.projects.size).toBe(0);
expect(workspace.extensions['x-bar']).toBe(5);
expect(workspace.extensions['schematics']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
});
it('parses a representative file', async () => {
const host = createTestHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
expect(Array.from(workspace.projects.keys())).toEqual(['my-app', 'my-app-e2e']);
expect(workspace.extensions['newProjectRoot']).toBe('projects');
expect(workspace.projects.get('my-app')!.extensions['schematics']).toEqual({
'@schematics/angular:component': { styleext: 'scss' },
});
expect(workspace.projects.get('my-app')!.root).toBe('');
expect(workspace.projects.get('my-app')!.targets.get('build')!.builder).toBe(
'@angular-devkit/build-angular:browser',
);
});
it(`doesn't remove falsy values when using the spread operator`, async () => {
const host = createTestHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
const prodConfig = workspace.projects.get('my-app')!.targets.get('build')!.configurations!
.production!;
expect({ ...prodConfig }).toEqual(prodConfig);
});
it('parses extensions only into extensions object', async () => {
const host = createTestHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
expect(workspace.extensions['newProjectRoot']).toBe('projects');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((workspace as any)['newProjectRoot']).toBeUndefined();
expect(workspace.projects.get('my-app')!.extensions['schematics']).toEqual({
'@schematics/angular:component': { styleext: 'scss' },
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((workspace.projects.get('my-app') as any)['schematics']).toBeUndefined();
});
it('errors on invalid version', async () => {
const host = createTestHost(stripIndent`
{
"version": 99,
// Comment
"x-bar": 5,
}
`);
await expectAsync(readJsonWorkspace('', host)).toBeRejectedWithError(
/Invalid format version detected/,
);
});
it('errors on missing version', async () => {
const host = createTestHost(stripIndent`
{
// Comment
"x-bar": 5,
}
`);
await expectAsync(readJsonWorkspace('', host)).toBeRejectedWithError(
/version specifier not found/,
);
});
it('warns on missing root property in a project', async () => {
const host = createTestHost(stripIndent`
{
"version": 1,
"projects": {
"foo": {}
}
}
`);
await expectAsync(readJsonWorkspace('', host)).toBeRejectedWithError(
/Project "foo" is missing a required property "root"/,
);
});
}); | {
"end_byte": 4641,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/reader_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/reader_spec.ts_4643_11758 | describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => {
it('tracks basic extension additions', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-baz'] = 101;
expect(workspace.extensions['x-baz']).toBe(101);
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/x-baz');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toBe(101);
}
});
it('tracks complex extension additions', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const value = { a: 1, b: 2, c: { d: 'abc' } };
workspace.extensions['x-baz'] = value;
expect(workspace.extensions['x-baz']).toEqual({ a: 1, b: 2, c: { d: 'abc' } });
value.b = 3;
expect(workspace.extensions['x-baz']).toEqual({ a: 1, b: 3, c: { d: 'abc' } });
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/x-baz');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ a: 1, b: 3, c: { d: 'abc' } });
}
});
it('tracks complex extension additions with Object.assign target', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const value = { a: 1, b: 2, c: { d: 'abc' } };
workspace.extensions['x-baz'] = value;
expect(workspace.extensions['x-baz']).toEqual({ a: 1, b: 2, c: { d: 'abc' } });
Object.assign(value, { x: 9, y: 8, z: 7 });
expect(workspace.extensions['x-baz']).toEqual({
a: 1,
b: 2,
c: { d: 'abc' },
x: 9,
y: 8,
z: 7,
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/x-baz');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 });
}
});
it('tracks complex extension additions with Object.assign return', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const value = { a: 1, b: 2, c: { d: 'abc' } };
workspace.extensions['x-baz'] = value;
expect(workspace.extensions['x-baz']).toEqual({ a: 1, b: 2, c: { d: 'abc' } });
workspace.extensions['x-baz'] = Object.assign(value, { x: 9, y: 8, z: 7 });
expect(workspace.extensions['x-baz']).toEqual({
a: 1,
b: 2,
c: { d: 'abc' },
x: 9,
y: 8,
z: 7,
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/x-baz');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 });
}
});
it('tracks complex extension additions with spread operator', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const value = { a: 1, b: 2, c: { d: 'abc' } };
workspace.extensions['x-baz'] = value;
expect(workspace.extensions['x-baz']).toEqual({ a: 1, b: 2, c: { d: 'abc' } });
workspace.extensions['x-baz'] = { ...value, ...{ x: 9, y: 8 }, z: 7 };
expect(workspace.extensions['x-baz']).toEqual({
a: 1,
b: 2,
c: { d: 'abc' },
x: 9,
y: 8,
z: 7,
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/x-baz');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 });
}
});
it('tracks modifying an existing extension object with spread operator', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-foo'] = {
...(workspace.extensions['x-foo'] as JsonObject),
...{ x: 9, y: 8 },
z: 7,
};
expect(workspace.extensions['x-foo']).toEqual({
is: ['good', 'great', 'awesome'],
x: 9,
y: 8,
z: 7,
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/x-foo');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ is: ['good', 'great', 'awesome'], x: 9, y: 8, z: 7 });
}
});
it('tracks modifying an existing extension object with Object.assign target', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('', host);
Object.assign(workspace.extensions['x-foo']!, { x: 9, y: 8 }, { z: 7 });
expect(workspace.extensions['x-foo']).toEqual({
is: ['good', 'great', 'awesome'],
x: 9,
y: 8,
z: 7,
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(3);
let change = metadata.findChangesForPath('/x-foo/x');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual(9);
}
change = metadata.findChangesForPath('/x-foo/y');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual(8);
}
change = metadata.findChangesForPath('/x-foo/z');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual(7);
}
});
it('tracks modifying an existing extension object with Object.assign return', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-foo'] = Object.assign(
workspace.extensions['x-foo']!,
{ x: 9, y: 8 },
{ z: 7 },
);
expect(workspace.extensions['x-foo']).toEqual({
is: ['good', 'great', 'awesome'],
x: 9,
y: 8,
z: 7,
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(3);
let change = metadata.findChangesForPath('/x-foo/x');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual(9);
}
change = metadata.findChangesForPath('/x-foo/y');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual(8);
}
change = metadata.findChangesForPath('/x-foo/z');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual(7);
}
}); | {
"end_byte": 11758,
"start_byte": 4643,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/reader_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/reader_spec.ts_11762_19370 | it('tracks add and remove of an existing extension object', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('basic', host);
workspace.extensions['schematics2'] = workspace.extensions['schematics'];
expect(workspace.extensions['schematics']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
expect(workspace.extensions['schematics2']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
let change = metadata.findChangesForPath('/schematics2');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'abc' } });
}
workspace.extensions['schematics'] = undefined;
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(2);
change = metadata.findChangesForPath('/schematics');
expect(change).not.toBeUndefined();
});
it('tracks moving and modifying an existing extension object', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('basic', host);
workspace.extensions['schematics2'] = workspace.extensions['schematics'];
expect(workspace.extensions['schematics']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
expect(workspace.extensions['schematics2']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
let change = metadata.findChangesForPath('/schematics2');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'abc' } });
}
workspace.extensions['schematics'] = undefined;
(workspace.extensions['schematics2'] as JsonObject)['@angular/schematics:component'] = {
prefix: 'xyz',
};
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(2);
change = metadata.findChangesForPath('/schematics');
expect(change).not.toBeUndefined();
change = metadata.findChangesForPath('/schematics2');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'xyz' } });
}
});
it('tracks copying and modifying an existing extension object', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('basic', host);
workspace.extensions['schematics2'] = workspace.extensions['schematics'];
expect(workspace.extensions['schematics']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
expect(workspace.extensions['schematics2']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
let change = metadata.findChangesForPath('/schematics2');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'abc' } });
}
(workspace.extensions['schematics2'] as JsonObject)['@angular/schematics:component'] = {
prefix: 'xyz',
};
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(2);
change = metadata.findChangesForPath('/schematics/@angular~1schematics:component');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ prefix: 'xyz' });
}
change = metadata.findChangesForPath('/schematics2');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'xyz' } });
}
});
it('tracks copying, modifying, and removing an existing extension object', async () => {
const host = createTestHost(basicFile);
const workspace = await readJsonWorkspace('basic', host);
workspace.extensions['schematics2'] = workspace.extensions['schematics'];
expect(workspace.extensions['schematics']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
expect(workspace.extensions['schematics2']).toEqual({
'@angular/schematics:component': { prefix: 'abc' },
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
let change = metadata.findChangesForPath('/schematics2');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'abc' } });
}
(workspace.extensions['schematics2'] as JsonObject)['@angular/schematics:component'] = {
prefix: 'xyz',
};
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(2);
change = metadata.findChangesForPath('/schematics/@angular~1schematics:component');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ prefix: 'xyz' });
}
change = metadata.findChangesForPath('/schematics2');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'xyz' } });
}
workspace.extensions['schematics'] = undefined;
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(2);
change = metadata.findChangesForPath('/schematics');
expect(change).not.toBeUndefined();
const orderedChanges = Array.from(metadata.changes.values());
change = orderedChanges[1];
expect(change).not.toBeUndefined();
});
it('tracks project additions with set', async () => {
const host = createTestHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
workspace.projects.set('new-app', {
root: 'src',
extensions: {},
targets: new TargetDefinitionCollection(),
});
const app = workspace.projects.get('new-app');
expect(app).not.toBeUndefined();
if (app) {
expect(app.extensions).toEqual({});
expect(app.root).toBe('src');
}
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/projects/new-app');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual(jasmine.objectContaining({ root: 'src' }));
}
});
it('tracks project additions with add', async () => {
const host = createTestHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
workspace.projects.add({
name: 'new-app',
root: 'src',
});
const app = workspace.projects.get('new-app');
expect(app).not.toBeUndefined();
if (app) {
expect(app.extensions).toEqual({});
expect(app.root).toBe('src');
}
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/projects/new-app');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toEqual(jasmine.objectContaining({ root: 'src' }));
}
});
}); | {
"end_byte": 19370,
"start_byte": 11762,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/reader_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/reader_spec.ts_19372_22800 | describe('JSON ProjectDefinition Tracks Project Changes', () => {
it('tracks property changes', async () => {
const host = createTestHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
const project = workspace.projects.get('my-app');
expect(project).not.toBeUndefined();
if (!project) {
return;
}
project.prefix = 'bar';
expect(project.prefix).toBe('bar');
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/projects/my-app/prefix');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toBe('bar');
}
});
it('tracks property additions', async () => {
const host = createTestHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
const project = workspace.projects.get('my-app');
expect(project).not.toBeUndefined();
if (!project) {
return;
}
expect(project.sourceRoot).toBeUndefined();
project.sourceRoot = 'xyz';
expect(project.sourceRoot).toBe('xyz');
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/projects/my-app/sourceRoot');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toBe('xyz');
}
});
it('tracks extension additions', async () => {
const host = createTestHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
const project = workspace.projects.get('my-app');
expect(project).not.toBeUndefined();
if (!project) {
return;
}
expect(project.extensions['abc-option']).toBeUndefined();
project.extensions['abc-option'] = 'valueA';
expect(project.extensions['abc-option']).toBe('valueA');
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/projects/my-app/abc-option');
expect(change).not.toBeUndefined();
if (change) {
expect(change.value).toBe('valueA');
}
});
it('tracks target additions with no original target collection', async () => {
const original = stripIndent`
{
"version": 1,
// Comment
"schematics": {
"@angular/schematics:component": {
"prefix": "abc"
}
},
"projects": {
"p1": {
"root": "p1-root"
}
},
"x-foo": {
"is": ["good", "great", "awesome"]
},
"x-bar": 5,
}
`;
const host = createTestHost(original);
const workspace = await readJsonWorkspace('', host);
const project = workspace.projects.get('p1');
expect(project).not.toBeUndefined();
if (!project) {
return;
}
project.targets.add({
name: 't1',
builder: 't1-builder',
});
const metadata = getMetadata(workspace);
expect(metadata.hasChanges).toBeTruthy();
expect(metadata.changeCount).toBe(1);
const change = metadata.findChangesForPath('/projects/p1/targets');
expect(change).not.toBeUndefined();
if (change) {
expect(change.type).toBe('targetcollection');
}
});
}); | {
"end_byte": 22800,
"start_byte": 19372,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/reader_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/reader.ts_0_5673 | /**
* @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 { Node, findNodeAtLocation, getNodeValue, parseTree } from 'jsonc-parser';
import { JsonValue, isJsonObject } from '../../json/utils';
import {
DefinitionCollectionListener,
ProjectDefinition,
ProjectDefinitionCollection,
TargetDefinition,
TargetDefinitionCollection,
WorkspaceDefinition,
} from '../definitions';
import { WorkspaceHost } from '../host';
import { JsonWorkspaceMetadata, JsonWorkspaceSymbol } from './metadata';
import { createVirtualAstObject } from './utilities';
const ANGULAR_WORKSPACE_EXTENSIONS = Object.freeze(['cli', 'newProjectRoot', 'schematics']);
const ANGULAR_PROJECT_EXTENSIONS = Object.freeze(['cli', 'schematics', 'projectType', 'i18n']);
interface ParserContext {
readonly host: WorkspaceHost;
readonly metadata: JsonWorkspaceMetadata;
readonly trackChanges: boolean;
readonly unprefixedWorkspaceExtensions: ReadonlySet<string>;
readonly unprefixedProjectExtensions: ReadonlySet<string>;
error(message: string, node: JsonValue): void;
warn(message: string, node: JsonValue): void;
}
export interface JsonWorkspaceOptions {
allowedProjectExtensions?: string[];
allowedWorkspaceExtensions?: string[];
}
export async function readJsonWorkspace(
path: string,
host: WorkspaceHost,
options: JsonWorkspaceOptions = {},
): Promise<WorkspaceDefinition> {
const raw = await host.readFile(path);
if (raw === undefined) {
throw new Error('Unable to read workspace file.');
}
const ast = parseTree(raw, undefined, { allowTrailingComma: true, disallowComments: false });
if (ast?.type !== 'object' || !ast.children) {
throw new Error('Invalid workspace file - expected JSON object.');
}
// Version check
const versionNode = findNodeAtLocation(ast, ['version']);
if (!versionNode) {
throw new Error('Unknown format - version specifier not found.');
}
const version = versionNode.value;
if (version !== 1) {
throw new Error(`Invalid format version detected - Expected:[ 1 ] Found: [ ${version} ]`);
}
const context: ParserContext = {
host,
metadata: new JsonWorkspaceMetadata(path, ast, raw),
trackChanges: true,
unprefixedWorkspaceExtensions: new Set([
...ANGULAR_WORKSPACE_EXTENSIONS,
...(options.allowedWorkspaceExtensions ?? []),
]),
unprefixedProjectExtensions: new Set([
...ANGULAR_PROJECT_EXTENSIONS,
...(options.allowedProjectExtensions ?? []),
]),
error(message, _node) {
// TODO: Diagnostic reporting support
throw new Error(message);
},
warn(message, _node) {
// TODO: Diagnostic reporting support
// eslint-disable-next-line no-console
console.warn(message);
},
};
const workspace = parseWorkspace(ast, context);
return workspace;
}
function parseWorkspace(workspaceNode: Node, context: ParserContext): WorkspaceDefinition {
const jsonMetadata = context.metadata;
let projects;
let extensions: Record<string, JsonValue> | undefined;
if (!context.trackChanges) {
extensions = Object.create(null);
}
// TODO: `getNodeValue` - looks potentially expensive since it walks the whole tree and instantiates the full object structure each time.
// Might be something to look at moving forward to optimize.
const workspaceNodeValue = getNodeValue(workspaceNode);
for (const [name, value] of Object.entries<JsonValue>(workspaceNodeValue)) {
if (name === '$schema' || name === 'version') {
// skip
} else if (name === 'projects') {
const nodes = findNodeAtLocation(workspaceNode, ['projects']);
if (!isJsonObject(value) || !nodes) {
context.error('Invalid "projects" field found; expected an object.', value);
continue;
}
projects = parseProjectsObject(nodes, context);
} else {
if (!context.unprefixedWorkspaceExtensions.has(name) && !/^[a-z]{1,3}-.*/.test(name)) {
context.warn(`Workspace extension with invalid name (${name}) found.`, name);
}
if (extensions) {
extensions[name] = value;
}
}
}
let collectionListener: DefinitionCollectionListener<ProjectDefinition> | undefined;
if (context.trackChanges) {
collectionListener = (name, newValue) => {
jsonMetadata.addChange(['projects', name], newValue, 'project');
};
}
const projectCollection = new ProjectDefinitionCollection(projects, collectionListener);
return {
[JsonWorkspaceSymbol]: jsonMetadata,
projects: projectCollection,
// If not tracking changes the `extensions` variable will contain the parsed
// values. Otherwise the extensions are tracked via a virtual AST object.
extensions:
extensions ??
createVirtualAstObject(workspaceNodeValue, {
exclude: ['$schema', 'version', 'projects'],
listener(path, value) {
jsonMetadata.addChange(path, value);
},
}),
} as WorkspaceDefinition;
}
function parseProjectsObject(
projectsNode: Node,
context: ParserContext,
): Record<string, ProjectDefinition> {
const projects: Record<string, ProjectDefinition> = Object.create(null);
for (const [name, value] of Object.entries<JsonValue>(getNodeValue(projectsNode))) {
const nodes = findNodeAtLocation(projectsNode, [name]);
if (!isJsonObject(value) || !nodes) {
context.warn('Skipping invalid project value; expected an object.', value);
continue;
}
projects[name] = parseProject(name, nodes, context);
}
return projects;
} | {
"end_byte": 5673,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/reader.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/reader.ts_5675_9984 | function parseProject(
projectName: string,
projectNode: Node,
context: ParserContext,
): ProjectDefinition {
const jsonMetadata = context.metadata;
let targets;
let hasTargets = false;
let extensions: Record<string, JsonValue> | undefined;
let properties: Record<'root' | 'sourceRoot' | 'prefix', string> | undefined;
if (!context.trackChanges) {
// If not tracking changes, the parser will store the values directly in standard objects
extensions = Object.create(null);
properties = Object.create(null);
}
const projectNodeValue = getNodeValue(projectNode);
if (!('root' in projectNodeValue)) {
throw new Error(`Project "${projectName}" is missing a required property "root".`);
}
for (const [name, value] of Object.entries<JsonValue>(projectNodeValue)) {
switch (name) {
case 'targets':
case 'architect': {
const nodes = findNodeAtLocation(projectNode, [name]);
if (!isJsonObject(value) || !nodes) {
context.error(`Invalid "${name}" field found; expected an object.`, value);
break;
}
hasTargets = true;
targets = parseTargetsObject(projectName, nodes, context);
jsonMetadata.hasLegacyTargetsName = name === 'architect';
break;
}
case 'prefix':
case 'root':
case 'sourceRoot':
if (typeof value !== 'string') {
context.warn(`Project property "${name}" should be a string.`, value);
}
if (properties) {
properties[name] = value as string;
}
break;
default:
if (!context.unprefixedProjectExtensions.has(name) && !/^[a-z]{1,3}-.*/.test(name)) {
context.warn(
`Project '${projectName}' contains extension with invalid name (${name}).`,
name,
);
}
if (extensions) {
extensions[name] = value;
}
break;
}
}
let collectionListener: DefinitionCollectionListener<TargetDefinition> | undefined;
if (context.trackChanges) {
collectionListener = (name, newValue, collection) => {
if (hasTargets) {
jsonMetadata.addChange(['projects', projectName, 'targets', name], newValue, 'target');
} else {
jsonMetadata.addChange(
['projects', projectName, 'targets'],
collection,
'targetcollection',
);
}
};
}
const base = {
targets: new TargetDefinitionCollection(targets, collectionListener),
// If not tracking changes the `extensions` variable will contain the parsed
// values. Otherwise the extensions are tracked via a virtual AST object.
extensions:
extensions ??
createVirtualAstObject(projectNodeValue, {
exclude: ['architect', 'prefix', 'root', 'sourceRoot', 'targets'],
listener(path, value) {
jsonMetadata.addChange(['projects', projectName, ...path], value);
},
}),
};
const baseKeys = new Set(Object.keys(base));
const project =
properties ??
createVirtualAstObject<ProjectDefinition>(projectNodeValue, {
include: ['prefix', 'root', 'sourceRoot', ...baseKeys],
listener(path, value) {
if (!baseKeys.has(path[0])) {
jsonMetadata.addChange(['projects', projectName, ...path], value);
}
},
});
return Object.assign(project, base) as ProjectDefinition;
}
function parseTargetsObject(
projectName: string,
targetsNode: Node,
context: ParserContext,
): Record<string, TargetDefinition> {
const jsonMetadata = context.metadata;
const targets: Record<string, TargetDefinition> = Object.create(null);
for (const [name, value] of Object.entries<JsonValue>(getNodeValue(targetsNode))) {
if (!isJsonObject(value)) {
context.warn('Skipping invalid target value; expected an object.', value);
continue;
}
if (context.trackChanges) {
targets[name] = createVirtualAstObject<TargetDefinition>(value, {
include: ['builder', 'options', 'configurations', 'defaultConfiguration'],
listener(path, value) {
jsonMetadata.addChange(['projects', projectName, 'targets', name, ...path], value);
},
});
} else {
targets[name] = value as unknown as TargetDefinition;
}
}
return targets;
} | {
"end_byte": 9984,
"start_byte": 5675,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/reader.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/metadata.ts_0_2446 | /**
* @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 { JSONPath, Node, findNodeAtLocation, getNodeValue } from 'jsonc-parser';
import { JsonValue } from '../../json';
import { ProjectDefinition, TargetDefinition, WorkspaceDefinition } from '../definitions';
export const JsonWorkspaceSymbol = Symbol.for('@angular/core:workspace-json');
export interface JsonWorkspaceDefinition extends WorkspaceDefinition {
[JsonWorkspaceSymbol]: JsonWorkspaceMetadata;
}
interface ChangeValues {
json: JsonValue;
project: ProjectDefinition;
target: TargetDefinition;
projectcollection: Iterable<[string, ProjectDefinition]>;
targetcollection: Iterable<[string, TargetDefinition]>;
}
export interface JsonChange {
value?: unknown;
type?: keyof ChangeValues;
jsonPath: string[];
}
function escapeKey(key: string): string | number {
return key.replace('~', '~0').replace('/', '~1');
}
export class JsonWorkspaceMetadata {
readonly changes = new Map<string, JsonChange>();
hasLegacyTargetsName = true;
constructor(
readonly filePath: string,
private readonly ast: Node,
readonly raw: string,
) {}
get hasChanges(): boolean {
return this.changes.size > 0;
}
get changeCount(): number {
return this.changes.size;
}
getNodeValueFromAst(path: JSONPath): unknown {
const node = findNodeAtLocation(this.ast, path);
return node && getNodeValue(node);
}
findChangesForPath(path: string): JsonChange | undefined {
return this.changes.get(path);
}
addChange<T extends keyof ChangeValues = keyof ChangeValues>(
jsonPath: string[],
value: ChangeValues[T] | undefined,
type?: T,
): void {
let currentPath = '';
for (let index = 0; index < jsonPath.length - 1; index++) {
currentPath = currentPath + '/' + escapeKey(jsonPath[index]);
if (this.changes.has(currentPath)) {
// Ignore changes on children as parent is updated.
return;
}
}
const pathKey = '/' + jsonPath.map((k) => escapeKey(k)).join('/');
for (const key of this.changes.keys()) {
if (key.startsWith(pathKey + '/')) {
// changes on the same or child paths are redundant.
this.changes.delete(key);
}
}
this.changes.set(pathKey, { jsonPath, type, value });
}
}
| {
"end_byte": 2446,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/metadata.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/writer_spec.ts_0_1517 | /**
* @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 { readFileSync } from 'fs';
import { join } from 'path';
import { JsonArray, JsonObject } from '../../json';
import { stripIndent } from '../../utils/literals';
import { ProjectDefinitionCollection, WorkspaceDefinition } from '../definitions';
import { readJsonWorkspace } from './reader';
import { writeJsonWorkspace } from './writer';
const basicFile = stripIndent`
{
"version": 1,
// Comment
"schematics": {
"@angular/schematics:component": {
"prefix": "abc"
}
},
"x-baz": 1,
"x-foo": {
"is": ["good", "great", "awesome"]
},
"x-bar": 5,
}`;
const representativeFile = readFileSync(require.resolve(__dirname + '/test/angular.json'), 'utf8');
function createTestCaseHost(inputData = '') {
const host = {
async readFile() {
return inputData;
},
async writeFile(path: string, data: string) {
try {
const testCase = readFileSync(
require.resolve(join(__dirname, 'test', 'cases', path) + '.json'),
'utf8',
);
expect(data.trim()).toEqual(testCase.trim());
} catch (e) {
fail(`Unable to load test case '${path}': ${e instanceof Error ? e.message : e}`);
}
},
async isFile() {
return true;
},
async isDirectory() {
return true;
},
};
return host;
} | {
"end_byte": 1517,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/writer_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/writer_spec.ts_1519_10480 | describe('writeJsonWorkpaceFile', () => {
it('does not modify a file without changes', async () => {
const host = {
async readFile() {
return representativeFile;
},
async writeFile() {
fail();
},
async isFile() {
return true;
},
async isDirectory() {
return true;
},
};
const workspace = await readJsonWorkspace('angular.json', host);
await writeJsonWorkspace(workspace, host);
});
it('writes an empty workspace', async () => {
const workspace: WorkspaceDefinition = {
extensions: {},
projects: new ProjectDefinitionCollection(),
};
await writeJsonWorkspace(workspace, createTestCaseHost(), 'Empty');
});
it('writes new workspace with extensions', async () => {
const workspace: WorkspaceDefinition = {
extensions: {
newProjectRoot: 'projects',
},
projects: new ProjectDefinitionCollection(),
};
await writeJsonWorkspace(workspace, createTestCaseHost(), 'Extensions1');
workspace.extensions['schematics'] = {
'@schematics/angular:component': { prefix: 'app' },
};
await writeJsonWorkspace(workspace, createTestCaseHost(), 'Extensions2');
});
it('writes new workspace with an empty project', async () => {
const workspace: WorkspaceDefinition = {
extensions: {},
projects: new ProjectDefinitionCollection(),
};
workspace.projects.add({
name: 'my-app',
root: 'projects/my-app',
});
await writeJsonWorkspace(workspace, createTestCaseHost(), 'ProjectEmpty');
});
it('writes new workspace with a full project', async () => {
const workspace: WorkspaceDefinition = {
extensions: {},
projects: new ProjectDefinitionCollection(),
};
workspace.projects.add({
name: 'my-app',
root: 'projects/my-app',
targets: {
build: {
builder: '@angular-devkit/build-angular:browser',
options: {
outputPath: `dist/my-app`,
index: `projects/my-app/src/index.html`,
main: `projects/my-app/src/main.ts`,
polyfills: `projects/my-app/src/polyfills.ts`,
tsConfig: `projects/my-app/tsconfig.app.json`,
assets: ['projects/my-app/src/favicon.ico', 'projects/my-app/src/assets'],
styles: [`projects/my-app/src/styles.scss`],
scripts: [],
es5BrowserSupport: true,
},
configurations: {
production: {
fileReplacements: [
{
replace: `projects/my-app/src/environments/environment.ts`,
with: `projects/my-app/src/environments/environment.prod.ts`,
},
],
optimization: true,
outputHashing: 'all',
sourceMap: false,
extractCss: true,
namedChunks: false,
aot: true,
extractLicenses: true,
vendorChunk: false,
buildOptimizer: true,
budgets: [
{
type: 'initial',
maximumWarning: '2mb',
maximumError: '5mb',
},
],
},
},
},
serve: {
builder: '@angular-devkit/build-angular:dev-server',
options: {
browserTarget: `my-app:build`,
},
configurations: {
production: {
browserTarget: `my-app:build:production`,
},
},
},
},
});
await writeJsonWorkspace(workspace, createTestCaseHost(), 'ProjectFull');
});
it('retains comments and formatting when modifying the workspace', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-baz'] = 10;
await writeJsonWorkspace(workspace, host, 'Retain');
});
it('adds a project to workspace without any projects', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.projects.add({
name: 'new',
root: 'src7',
});
await writeJsonWorkspace(workspace, host, 'AddProject1');
});
it('adds a project to workspace with existing projects', async () => {
const host = createTestCaseHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
workspace.projects.add({
name: 'new',
root: 'src',
});
await writeJsonWorkspace(workspace, host, 'AddProject2');
});
it('adds a project to workspace with existing projects when name is number like', async () => {
const host = createTestCaseHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
workspace.projects.add({
name: '1',
root: 'src',
});
await writeJsonWorkspace(workspace, host, 'AddProject3');
});
it('adds a project with targets', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.projects.add({
name: 'new',
root: 'src',
targets: {
build: {
builder: 'build-builder',
options: { one: 1, two: false },
configurations: {
staging: {
two: true,
},
},
},
},
});
await writeJsonWorkspace(workspace, host, 'AddProjectWithTargets');
});
it('adds a project with targets using reference to workspace', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.projects.add({
name: 'new',
root: 'src',
});
const project = workspace.projects.get('new');
if (!project) {
fail('project is missing');
return;
}
project.targets.add({
name: 'build',
builder: 'build-builder',
options: { one: 1, two: false },
configurations: {
staging: {
two: true,
},
},
});
// This should be the same as adding them in the project add call
await writeJsonWorkspace(workspace, host, 'AddProjectWithTargets');
});
it("modifies a project's properties", async () => {
const host = createTestCaseHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
const project = workspace.projects.get('my-app');
if (!project) {
fail('project is missing');
return;
}
project.root = 'src';
await writeJsonWorkspace(workspace, host, 'ProjectModifyProperties');
});
it("sets a project's properties", async () => {
const host = createTestCaseHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
const project = workspace.projects.get('my-app');
if (!project) {
fail('project is missing');
return;
}
project.sourceRoot = 'src';
await writeJsonWorkspace(workspace, host, 'ProjectSetProperties');
});
it('adds a target to an existing project', async () => {
const host = createTestCaseHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
const project = workspace.projects.get('my-app');
if (!project) {
fail('project is missing');
return;
}
project.targets.add({
name: 'new',
builder: 'new-builder',
});
await writeJsonWorkspace(workspace, host, 'ProjectAddTarget');
});
it('deletes a target from an existing project', async () => {
const host = createTestCaseHost(representativeFile);
const workspace = await readJsonWorkspace('', host);
const project = workspace.projects.get('my-app');
if (!project) {
fail('project is missing');
return;
}
project.targets.delete('extract-i18n');
await writeJsonWorkspace(workspace, host, 'ProjectDeleteTarget');
});
it('supports adding an empty array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-array'] = [];
await writeJsonWorkspace(workspace, host, 'AddArrayEmpty');
});
it('supports adding an array with values', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-array'] = [5, 'a', false, null, true, 9.9];
await writeJsonWorkspace(workspace, host, 'ArrayValues');
});
it('supports adding an empty array then pushing as an extension', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-array'] = [];
(workspace.extensions['x-array'] as string[]).push('value');
await writeJsonWorkspace(workspace, host, 'AddArrayPush');
}); | {
"end_byte": 10480,
"start_byte": 1519,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/writer_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/workspace/json/writer_spec.ts_10484_18418 | it('supports pushing to an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.push('value');
await writeJsonWorkspace(workspace, host, 'ArrayPush');
});
it('supports unshifting to an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.unshift('value');
await writeJsonWorkspace(workspace, host, 'ArrayUnshift');
});
it('supports shifting from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.shift();
await writeJsonWorkspace(workspace, host, 'ArrayShift');
});
it('supports splicing an existing array without new values', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.splice(2, 1);
await writeJsonWorkspace(workspace, host, 'ArraySplice1');
});
it('supports splicing an existing array with new values', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.splice(2, 0, 'value1', 'value2');
await writeJsonWorkspace(workspace, host, 'ArraySplice2');
});
it('supports popping from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.pop();
await writeJsonWorkspace(workspace, host, 'ArrayPop');
});
it('supports sorting from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.sort();
await writeJsonWorkspace(workspace, host, 'ArraySort');
});
it('replaces a value at zero index from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array[0] = 'value';
await writeJsonWorkspace(workspace, host, 'ArrayIndexZero');
});
it('replaces a value at inner index from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array[1] = 'value';
await writeJsonWorkspace(workspace, host, 'ArrayIndexInner');
});
it('replaces a value at last index from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array[array.length - 1] = 'value';
await writeJsonWorkspace(workspace, host, 'ArrayIndexLast');
});
it('deletes a value at zero index from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.splice(0, 1);
await writeJsonWorkspace(workspace, host, 'ArrayDeleteZero');
});
it('deletes a value at inner index from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.splice(1, 1);
await writeJsonWorkspace(workspace, host, 'ArrayDeleteInner');
});
it('deletes and then adds a value at inner index from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.splice(1, 1);
array.splice(1, 0, 'new');
await writeJsonWorkspace(workspace, host, 'ArrayDeleteInnerAdd');
});
it('deletes a value at last index from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.splice(array.length - 1, 1);
await writeJsonWorkspace(workspace, host, 'ArrayDeleteLast');
});
it('deletes and then adds a value at last index from an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray;
array.splice(array.length - 1, 1);
array.push('new');
await writeJsonWorkspace(workspace, host, 'ArrayDeleteLastAdd');
});
it('replaces an existing array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
(workspace.extensions['x-foo'] as JsonObject)['is'] = ['value'];
await writeJsonWorkspace(workspace, host, 'ArrayReplace1');
});
it('replaces an existing array with an empty array', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
(workspace.extensions['x-foo'] as JsonObject)['is'] = [];
await writeJsonWorkspace(workspace, host, 'ArrayReplace2');
});
it('replaces an existing object with a new object', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-foo'] = { replacement: true };
await writeJsonWorkspace(workspace, host, 'ObjectReplace1');
});
it('replaces an existing object with an empty object', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-foo'] = {};
await writeJsonWorkspace(workspace, host, 'ObjectReplace2');
});
it('replaces an existing object with a different value type', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-foo'] = null;
await writeJsonWorkspace(workspace, host, 'ObjectReplace3');
});
it('removes a property when property value is set to undefined', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
workspace.extensions['x-baz'] = undefined;
await writeJsonWorkspace(workspace, host, 'ObjectRemove');
});
it('removes a property when using delete operator', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
delete workspace.extensions['x-baz'];
await writeJsonWorkspace(workspace, host, 'ObjectRemove');
});
it('removes multiple properties when using delete operator', async () => {
const host = createTestCaseHost(basicFile);
const workspace = await readJsonWorkspace('', host);
delete workspace.extensions['x-baz'];
delete workspace.extensions.schematics;
await writeJsonWorkspace(workspace, host, 'ObjectRemoveMultiple');
});
}); | {
"end_byte": 18418,
"start_byte": 10484,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/workspace/json/writer_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/strings.ts_0_5264 | /**
* @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
*/
const STRING_DASHERIZE_REGEXP = /[ _]/g;
const STRING_DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g;
const STRING_CAMELIZE_REGEXP = /(-|_|\.|\s)+(.)?/g;
const STRING_UNDERSCORE_REGEXP_1 = /([a-z\d])([A-Z]+)/g;
const STRING_UNDERSCORE_REGEXP_2 = /-|\s+/g;
/**
* Converts a camelized string into all lower case separated by underscores.
*
```javascript
decamelize('innerHTML'); // 'inner_html'
decamelize('action_name'); // 'action_name'
decamelize('css-class-name'); // 'css-class-name'
decamelize('my favorite items'); // 'my favorite items'
```
@method decamelize
@param {String} str The string to decamelize.
@return {String} the decamelized string.
*/
export function decamelize(str: string): string {
return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase();
}
/**
Replaces underscores, spaces, or camelCase with dashes.
```javascript
dasherize('innerHTML'); // 'inner-html'
dasherize('action_name'); // 'action-name'
dasherize('css-class-name'); // 'css-class-name'
dasherize('my favorite items'); // 'my-favorite-items'
```
@method dasherize
@param {String} str The string to dasherize.
@return {String} the dasherized string.
*/
export function dasherize(str: string): string {
return decamelize(str).replace(STRING_DASHERIZE_REGEXP, '-');
}
/**
Returns the lowerCamelCase form of a string.
```javascript
camelize('innerHTML'); // 'innerHTML'
camelize('action_name'); // 'actionName'
camelize('css-class-name'); // 'cssClassName'
camelize('my favorite items'); // 'myFavoriteItems'
camelize('My Favorite Items'); // 'myFavoriteItems'
```
@method camelize
@param {String} str The string to camelize.
@return {String} the camelized string.
*/
export function camelize(str: string): string {
return str
.replace(STRING_CAMELIZE_REGEXP, (_match: string, _separator: string, chr: string) => {
return chr ? chr.toUpperCase() : '';
})
.replace(/^([A-Z])/, (match: string) => match.toLowerCase());
}
/**
Returns the UpperCamelCase form of a string.
@example
```javascript
'innerHTML'.classify(); // 'InnerHTML'
'action_name'.classify(); // 'ActionName'
'css-class-name'.classify(); // 'CssClassName'
'my favorite items'.classify(); // 'MyFavoriteItems'
'app.component'.classify(); // 'AppComponent'
```
@method classify
@param {String} str the string to classify
@return {String} the classified string
*/
export function classify(str: string): string {
return str
.split('.')
.map((part) => capitalize(camelize(part)))
.join('');
}
/**
More general than decamelize. Returns the lower_case_and_underscored
form of a string.
```javascript
'innerHTML'.underscore(); // 'inner_html'
'action_name'.underscore(); // 'action_name'
'css-class-name'.underscore(); // 'css_class_name'
'my favorite items'.underscore(); // 'my_favorite_items'
```
@method underscore
@param {String} str The string to underscore.
@return {String} the underscored string.
*/
export function underscore(str: string): string {
return str
.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2')
.replace(STRING_UNDERSCORE_REGEXP_2, '_')
.toLowerCase();
}
/**
Returns the Capitalized form of a string
```javascript
'innerHTML'.capitalize() // 'InnerHTML'
'action_name'.capitalize() // 'Action_name'
'css-class-name'.capitalize() // 'Css-class-name'
'my favorite items'.capitalize() // 'My favorite items'
```
@method capitalize
@param {String} str The string to capitalize.
@return {String} The capitalized string.
*/
export function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* Calculate the levenshtein distance of two strings.
* See https://en.wikipedia.org/wiki/Levenshtein_distance.
* Based off https://gist.github.com/andrei-m/982927 (for using the faster dynamic programming
* version).
*
* @param a String a.
* @param b String b.
* @returns A number that represents the distance between the two strings. The greater the number
* the more distant the strings are from each others.
*/
export function levenshtein(a: string, b: string): number {
if (a.length == 0) {
return b.length;
}
if (b.length == 0) {
return a.length;
}
const matrix: number[][] = [];
// increment along the first column of each row
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
// increment each column in the first row
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
// Fill in the rest of the matrix
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) == a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1, // substitution
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1, // deletion
);
}
}
}
return matrix[b.length][a.length];
}
| {
"end_byte": 5264,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/strings.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/object_spec.ts_0_1691 | /**
* @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 { deepCopy } from './object';
describe('object', () => {
describe('deepCopy', () => {
it('works with empty', () => {
const data = {};
expect(deepCopy(data)).toEqual(data);
});
it('works with objects', () => {
const data = { a: 1, b: { c: 'hello' } };
expect(deepCopy(data)).toEqual(data);
});
it('works with null', () => {
const data = null;
expect(deepCopy(data)).toEqual(data);
});
it('works with number', () => {
const data = 1;
expect(deepCopy(data)).toEqual(data);
});
it('works with simple classes', () => {
class Data {
constructor(
private _x = 1,
protected _y = 2,
public _z = 3,
) {}
}
const data = new Data();
expect(deepCopy(data)).toEqual(data);
expect(deepCopy(data) instanceof Data).toBe(true);
});
it('works with circular objects', () => {
const data1 = { a: 1 } as any;
const data = { b: data1 };
data1['circular'] = data;
const result = deepCopy(data) as any;
expect(result.b.a).toBe(1);
expect(result.b.circular.b.a).toBe(1);
expect(result.b).not.toBe(data1);
expect(result.b).toBe(result.b.circular.b);
});
it('works with null prototype', () => {
const data = Object.create(null);
data['a'] = 1;
expect(deepCopy(data)).toEqual(data);
});
});
});
| {
"end_byte": 1691,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/object_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/template.ts_0_6449 | /**
* @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 { Position, SourceNode } from 'source-map';
// Matches <%= expr %>. This does not support structural JavaScript (for/if/...).
const kInterpolateRe = /<%=([\s\S]+?)%>/g;
// Matches <%# text %>. It's a comment and will be entirely ignored.
const kCommentRe = /<%#([\s\S]+?)%>/g;
// Used to match template delimiters.
// <%- expr %>: HTML escape the value.
// <% ... %>: Structural template code.
const kEscapeRe = /<%-([\s\S]+?)%>/g;
const kEvaluateRe = /<%([\s\S]+?)%>/g;
/** Used to map characters to HTML entities. */
const kHtmlEscapes: { [char: string]: string } = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`',
};
// Used to match HTML entities and HTML characters.
const reUnescapedHtml = new RegExp(`[${Object.keys(kHtmlEscapes).join('')}]`, 'g');
// Options to pass to template.
export interface TemplateOptions {
sourceURL?: string;
sourceMap?: boolean;
module?: boolean | { exports: {} };
sourceRoot?: string;
fileName?: string;
}
function _positionFor(content: string, offset: number): Position {
let line = 1;
let column = 0;
for (let i = 0; i < offset - 1; i++) {
if (content[i] == '\n') {
line++;
column = 0;
} else {
column++;
}
}
return {
line,
column,
};
}
/**
* A simple AST for templates. There's only one level of AST nodes, but it's still useful
* to have the information you're looking for.
*/
export interface TemplateAst {
fileName: string;
content: string;
children: TemplateAstNode[];
}
/**
* The base, which contains positions.
*/
export interface TemplateAstBase {
start: Position;
end: Position;
}
/**
* A static content node.
*/
export interface TemplateAstContent extends TemplateAstBase {
kind: 'content';
content: string;
}
/**
* A comment node.
*/
export interface TemplateAstComment extends TemplateAstBase {
kind: 'comment';
text: string;
}
/**
* An evaluate node, which is the code between `<% ... %>`.
*/
export interface TemplateAstEvaluate extends TemplateAstBase {
kind: 'evaluate';
expression: string;
}
/**
* An escape node, which is the code between `<%- ... %>`.
*/
export interface TemplateAstEscape extends TemplateAstBase {
kind: 'escape';
expression: string;
}
/**
* An interpolation node, which is the code between `<%= ... %>`.
*/
export interface TemplateAstInterpolate extends TemplateAstBase {
kind: 'interpolate';
expression: string;
}
export type TemplateAstNode =
| TemplateAstContent
| TemplateAstEvaluate
| TemplateAstComment
| TemplateAstEscape
| TemplateAstInterpolate;
/**
* Given a source text (and a fileName), returns a TemplateAst.
*/
export function templateParser(sourceText: string, fileName: string): TemplateAst {
const children: TemplateAstNode[] = [];
// Compile the regexp to match each delimiter.
const reExpressions = [kEscapeRe, kCommentRe, kInterpolateRe, kEvaluateRe];
const reDelimiters = RegExp(reExpressions.map((x) => x.source).join('|') + '|$', 'g');
const parsed = sourceText.split(reDelimiters);
let offset = 0;
// Optimization that uses the fact that the end of a node is always the beginning of the next
// node, so we keep the positioning of the nodes in memory.
let start = _positionFor(sourceText, offset);
let end: Position | null;
const increment = reExpressions.length + 1;
for (let i = 0; i < parsed.length; i += increment) {
const [content, escape, comment, interpolate, evaluate] = parsed.slice(i, i + increment);
if (content) {
end = _positionFor(sourceText, offset + content.length);
offset += content.length;
children.push({ kind: 'content', content, start, end } as TemplateAstContent);
start = end;
}
if (escape) {
end = _positionFor(sourceText, offset + escape.length + 5);
offset += escape.length + 5;
children.push({ kind: 'escape', expression: escape, start, end } as TemplateAstEscape);
start = end;
}
if (comment) {
end = _positionFor(sourceText, offset + comment.length + 5);
offset += comment.length + 5;
children.push({ kind: 'comment', text: comment, start, end } as TemplateAstComment);
start = end;
}
if (interpolate) {
end = _positionFor(sourceText, offset + interpolate.length + 5);
offset += interpolate.length + 5;
children.push({
kind: 'interpolate',
expression: interpolate,
start,
end,
} as TemplateAstInterpolate);
start = end;
}
if (evaluate) {
end = _positionFor(sourceText, offset + evaluate.length + 5);
offset += evaluate.length + 5;
children.push({ kind: 'evaluate', expression: evaluate, start, end } as TemplateAstEvaluate);
start = end;
}
}
return {
fileName,
content: sourceText,
children,
};
}
/**
* Fastest implementation of the templating algorithm. It only add strings and does not bother
* with source maps.
*/
function templateFast(ast: TemplateAst, options?: TemplateOptions): string {
const module = options && options.module ? 'module.exports.default =' : '';
const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, "\\\\\\'");
return `
return ${module} function(obj) {
obj || (obj = {});
let __t;
let __p = '';
const __escapes = ${JSON.stringify(kHtmlEscapes)};
const __escapesre = new RegExp('${reHtmlEscape}', 'g');
const __e = function(s) {
return s ? s.replace(__escapesre, function(key) { return __escapes[key]; }) : '';
};
with (obj) {
${ast.children
.map((node) => {
switch (node.kind) {
case 'content':
return `__p += ${JSON.stringify(node.content)};`;
case 'interpolate':
return `__p += ((__t = (${node.expression})) == null) ? '' : __t;`;
case 'escape':
return `__p += __e(${node.expression});`;
case 'evaluate':
return node.expression;
}
})
.join('\n')}
}
return __p;
};
`;
}
/**
* Templating algorithm with source map support. The map is outputted as //# sourceMapUrl=...
*/ | {
"end_byte": 6449,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/template.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/template.ts_6450_12227 | function templateWithSourceMap(ast: TemplateAst, options?: TemplateOptions): string {
const sourceUrl = ast.fileName;
const module = options && options.module ? 'module.exports.default =' : '';
const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, "\\\\\\'");
const preamble = new SourceNode(1, 0, sourceUrl, '').add(
new SourceNode(1, 0, sourceUrl, [
`return ${module} function(obj) {\n`,
' obj || (obj = {});\n',
' let __t;\n',
' let __p = "";\n',
` const __escapes = ${JSON.stringify(kHtmlEscapes)};\n`,
` const __escapesre = new RegExp('${reHtmlEscape}', 'g');\n`,
`\n`,
` const __e = function(s) { `,
` return s ? s.replace(__escapesre, function(key) { return __escapes[key]; }) : '';`,
` };\n`,
` with (obj) {\n`,
]),
);
const end = ast.children.length
? ast.children[ast.children.length - 1].end
: { line: 0, column: 0 };
const nodes = ast.children
.reduce((chunk, node) => {
let code: string | SourceNode | (SourceNode | string)[] = '';
switch (node.kind) {
case 'content':
code = [
new SourceNode(node.start.line, node.start.column, sourceUrl, '__p = __p'),
...node.content.split('\n').map((line, i, arr) => {
return new SourceNode(
node.start.line + i,
i == 0 ? node.start.column : 0,
sourceUrl,
'\n + ' + JSON.stringify(line + (i == arr.length - 1 ? '' : '\n')),
);
}),
new SourceNode(node.end.line, node.end.column, sourceUrl, ';\n'),
];
break;
case 'interpolate':
code = [
new SourceNode(node.start.line, node.start.column, sourceUrl, '__p += ((__t = '),
...node.expression.split('\n').map((line, i, arr) => {
return new SourceNode(
node.start.line + i,
i == 0 ? node.start.column : 0,
sourceUrl,
line + (i == arr.length - 1 ? '' : '\n'),
);
}),
new SourceNode(node.end.line, node.end.column, sourceUrl, ') == null ? "" : __t);\n'),
];
break;
case 'escape':
code = [
new SourceNode(node.start.line, node.start.column, sourceUrl, '__p += __e('),
...node.expression.split('\n').map((line, i, arr) => {
return new SourceNode(
node.start.line + i,
i == 0 ? node.start.column : 0,
sourceUrl,
line + (i == arr.length - 1 ? '' : '\n'),
);
}),
new SourceNode(node.end.line, node.end.column, sourceUrl, ');\n'),
];
break;
case 'evaluate':
code = [
...node.expression.split('\n').map((line, i, arr) => {
return new SourceNode(
node.start.line + i,
i == 0 ? node.start.column : 0,
sourceUrl,
line + (i == arr.length - 1 ? '' : '\n'),
);
}),
new SourceNode(node.end.line, node.end.column, sourceUrl, '\n'),
];
break;
}
return chunk.add(new SourceNode(node.start.line, node.start.column, sourceUrl, code));
}, preamble)
.add(
new SourceNode(end.line, end.column, sourceUrl, [' };\n', '\n', ' return __p;\n', '}\n']),
);
const code = nodes.toStringWithSourceMap({
file: sourceUrl,
sourceRoot: (options && options.sourceRoot) || '.',
});
// Set the source content in the source map, otherwise the sourceUrl is not enough
// to find the content.
code.map.setSourceContent(sourceUrl, ast.content);
return (
code.code +
'\n//# sourceMappingURL=data:application/json;base64,' +
Buffer.from(code.map.toString()).toString('base64')
);
}
/**
* An equivalent of EJS templates, which is based on John Resig's `tmpl` implementation
* (http://ejohn.org/blog/javascript-micro-templating/) and Laura Doktorova's doT.js
* (https://github.com/olado/doT).
*
* This version differs from lodash by removing support from ES6 quasi-literals, and making the
* code slightly simpler to follow. It also does not depend on any third party, which is nice.
*
* Finally, it supports SourceMap, if you ever need to debug, which is super nice.
*
* @param content The template content.
* @param options Optional Options. See TemplateOptions for more description.
* @return {(input: T) => string} A function that accept an input object and returns the content
* of the template with the input applied.
*/
export function template<T>(content: string, options?: TemplateOptions): (input: T) => string {
const sourceUrl = (options && options.sourceURL) || 'ejs';
const ast = templateParser(content, sourceUrl);
let source: string;
// If there's no need for source map support, we revert back to the fast implementation.
if (options && options.sourceMap) {
source = templateWithSourceMap(ast, options);
} else {
source = templateFast(ast, options);
}
// We pass a dummy module in case the module option is passed. If `module: true` is passed, we
// need to only use the source, not the function itself. Otherwise expect a module object to be
// passed, and we use that one.
const fn = Function('module', source);
const module =
options && options.module ? (options.module === true ? { exports: {} } : options.module) : null;
const result = fn(module);
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
return result;
} | {
"end_byte": 12227,
"start_byte": 6450,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/template.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/partially-ordered-set.ts_0_3839 | /**
* @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 '../exception';
export class DependencyNotFoundException extends BaseException {
constructor() {
super('One of the dependencies is not part of the set.');
}
}
export class CircularDependencyFoundException extends BaseException {
constructor() {
super('Circular dependencies found.');
}
}
export class PartiallyOrderedSet<T> implements Set<T> {
private _items = new Map<T, Set<T>>();
protected _checkCircularDependencies(item: T, deps: Set<T>) {
if (deps.has(item)) {
throw new CircularDependencyFoundException();
}
deps.forEach((dep) => this._checkCircularDependencies(item, this._items.get(dep) || new Set()));
}
clear() {
this._items.clear();
}
has(item: T) {
return this._items.has(item);
}
get size() {
return this._items.size;
}
forEach(
callbackfn: (value: T, value2: T, set: PartiallyOrderedSet<T>) => void,
thisArg?: any, // eslint-disable-line @typescript-eslint/no-explicit-any
): void {
for (const x of this) {
callbackfn.call(thisArg, x, x, this);
}
}
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
*entries(): SetIterator<[T, T]> {
for (const item of this) {
yield [item, item];
}
}
/**
* Despite its name, returns an iterable of the values in the set,
*/
keys(): SetIterator<T> {
return this.values();
}
/**
* Returns an iterable of values in the set.
*/
values(): SetIterator<T> {
return this[Symbol.iterator]();
}
add(item: T, deps: Set<T> | T[] = new Set()) {
if (Array.isArray(deps)) {
deps = new Set(deps);
}
// Verify item is not already in the set.
if (this._items.has(item)) {
const itemDeps = this._items.get(item) || new Set<T>();
// If the dependency list is equal, just return, otherwise remove and keep going.
let equal = true;
for (const dep of deps) {
if (!itemDeps.has(dep)) {
equal = false;
break;
}
}
if (equal) {
for (const dep of itemDeps) {
if (!deps.has(dep)) {
equal = false;
break;
}
}
}
if (equal) {
return this;
} else {
this._items.delete(item);
}
}
// Verify all dependencies are part of the Set.
for (const dep of deps) {
if (!this._items.has(dep)) {
throw new DependencyNotFoundException();
}
}
// Verify there's no dependency cycle.
this._checkCircularDependencies(item, deps);
this._items.set(item, new Set(deps));
return this;
}
delete(item: T) {
if (!this._items.has(item)) {
return false;
}
// Remove it from all dependencies if force == true.
this._items.forEach((value) => value.delete(item));
return this._items.delete(item);
}
*[Symbol.iterator]() {
const copy: Map<T, Set<T>> = new Map(this._items);
for (const [key, value] of copy.entries()) {
copy.set(key, new Set(value));
}
while (copy.size > 0) {
const run: T[] = [];
// Take the first item without dependencies.
for (const [item, deps] of copy.entries()) {
if (deps.size == 0) {
run.push(item);
}
}
for (const item of run) {
copy.forEach((s) => s.delete(item));
copy.delete(item);
yield item;
}
if (run.length == 0) {
// uh oh...
throw new CircularDependencyFoundException();
}
}
return undefined;
}
get [Symbol.toStringTag](): 'Set' {
return 'Set';
}
}
| {
"end_byte": 3839,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/partially-ordered-set.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/priority-queue_spec.ts_0_479 | /**
* @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 { PriorityQueue } from './priority-queue';
describe('PriorityQueue', () => {
it('adds an item', () => {
const queue = new PriorityQueue<number>((x, y) => x - y);
queue.push(99);
expect(queue.size).toBe(1);
expect(queue.peek()).toBe(99);
});
});
| {
"end_byte": 479,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/priority-queue_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/literals.ts_0_2183 | /**
* @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 interface TemplateTag<R = string> {
// Any is the only way here.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(template: TemplateStringsArray, ...substitutions: any[]): R;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function oneLine(strings: TemplateStringsArray, ...values: any[]) {
const endResult = String.raw(strings, ...values);
return endResult.replace(/(?:\r?\n(?:\s*))+/gm, ' ').trim();
}
export function indentBy(indentations: number): TemplateTag {
let i = '';
while (indentations--) {
i += ' ';
}
return (strings, ...values) => {
return i + stripIndent(strings, ...values).replace(/\n/g, '\n' + i);
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function stripIndent(strings: TemplateStringsArray, ...values: any[]) {
const endResult = String.raw(strings, ...values);
// remove the shortest leading indentation from each line
const match = endResult.match(/^[ \t]*(?=\S)/gm);
// return early if there's nothing to strip
if (match === null) {
return endResult;
}
const indent = Math.min(...match.map((el) => el.length));
const regexp = new RegExp('^[ \\t]{' + indent + '}', 'gm');
return (indent > 0 ? endResult.replace(regexp, '') : endResult).trim();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function stripIndents(strings: TemplateStringsArray, ...values: any[]) {
return String.raw(strings, ...values)
.split('\n')
.map((line) => line.trim())
.join('\n')
.trim();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function trimNewlines(strings: TemplateStringsArray, ...values: any[]) {
const endResult = String.raw(strings, ...values);
return (
endResult
// Remove the newline at the start.
.replace(/^(?:\r?\n)+/, '')
// Remove the newline at the end and following whitespace.
.replace(/(?:\r?\n(?:\s*))$/, '')
);
}
| {
"end_byte": 2183,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/literals.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/priority-queue.ts_0_1063 | /**
* @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
*/
/** Naive priority queue; not intended for large datasets */
export class PriorityQueue<T> {
private _items = new Array<T>();
constructor(private _comparator: (x: T, y: T) => number) {}
clear() {
this._items = new Array<T>();
}
push(item: T) {
const index = this._items.findIndex((existing) => this._comparator(item, existing) <= 0);
if (index === -1) {
this._items.push(item);
} else {
this._items.splice(index, 0, item);
}
}
pop(): T | undefined {
if (this._items.length === 0) {
return undefined;
}
return this._items.splice(0, 1)[0];
}
peek(): T | undefined {
if (this._items.length === 0) {
return undefined;
}
return this._items[0];
}
get size(): number {
return this._items.length;
}
toArray(): Array<T> {
return this._items.slice();
}
}
| {
"end_byte": 1063,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/priority-queue.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/partially-ordered-set_spec.ts_0_1014 | /**
* @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 { PartiallyOrderedSet } from './partially-ordered-set';
describe('PartiallyOrderedSet', () => {
it('can add an item', () => {
const set = new PartiallyOrderedSet<string>();
set.add('hello');
expect([...set]).toEqual(['hello']);
});
it('can remove an item', () => {
const set = new PartiallyOrderedSet<string>();
set.add('hello');
set.add('world');
set.delete('world');
expect([...set]).toEqual(['hello']);
});
it('list items in determistic order of dependency', () => {
const set = new PartiallyOrderedSet<string>();
set.add('red');
set.add('yellow', ['red']);
set.add('green', ['red']);
set.add('blue');
set.add('purple', ['red', 'blue']);
expect([...set]).toEqual(['red', 'blue', 'yellow', 'green', 'purple']);
});
});
| {
"end_byte": 1014,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/partially-ordered-set_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/object.ts_0_1178 | /**
* @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
*/
const copySymbol = Symbol();
export function deepCopy<T>(value: T): T {
if (Array.isArray(value)) {
return value.map((o) => deepCopy(o)) as unknown as T;
} else if (value && typeof value === 'object') {
const valueCasted = value as unknown as {
[copySymbol]?: T;
toJSON?: () => string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
};
if (valueCasted[copySymbol]) {
// This is a circular dependency. Just return the cloned value.
return valueCasted[copySymbol] as T;
}
if (valueCasted['toJSON']) {
return JSON.parse(valueCasted['toJSON']()) as T;
}
const copy = Object.create(Object.getPrototypeOf(valueCasted));
valueCasted[copySymbol] = copy;
for (const key of Object.getOwnPropertyNames(valueCasted)) {
copy[key] = deepCopy(valueCasted[key]);
}
delete valueCasted[copySymbol];
return copy;
} else {
return value;
}
}
| {
"end_byte": 1178,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/object.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/index.ts_0_459 | /**
* @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 tags from './literals';
import * as strings from './strings';
export * from './object';
export * from './template';
export * from './partially-ordered-set';
export * from './priority-queue';
export * from './lang';
export { tags, strings };
| {
"end_byte": 459,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/literals_spec.ts_0_1210 | /**
* @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 { oneLine, stripIndent, stripIndents, trimNewlines } from './literals';
describe('literals', () => {
describe('stripIndent', () => {
it('works', () => {
const test = stripIndent`
hello world
how are you?
test
`;
expect(test).toBe('hello world\n how are you?\ntest');
});
});
describe('stripIndents', () => {
it('works', () => {
const test = stripIndents`
hello world
how are you?
test
`;
expect(test).toBe('hello world\nhow are you?\ntest');
});
});
describe('oneLine', () => {
it('works', () => {
const test = oneLine`
hello world
how are you? blue red
test
`;
expect(test).toBe('hello world how are you? blue red test');
});
});
describe('trimNewlines', () => {
it('works', () => {
const test = trimNewlines`
hello world
`;
expect(test).toBe(' hello world');
});
});
});
| {
"end_byte": 1210,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/literals_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/utils/lang.ts_0_590 | /**
* @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
*/
// Borrowed from @angular/core
/**
* Determine if the argument is shaped like a Promise
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isPromise(obj: any): obj is Promise<any> {
// allow any Promise/A+ compliant thenable.
// It's up to the caller to ensure that obj.then conforms to the spec
return !!obj && typeof obj.then === 'function';
}
| {
"end_byte": 590,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/utils/lang.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/utils.ts_0_724 | /**
* @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-next-line @typescript-eslint/no-empty-interface
export interface JsonArray extends Array<JsonValue> {}
export interface JsonObject {
[prop: string]: JsonValue;
}
export type JsonValue = boolean | string | number | JsonArray | JsonObject | null;
export function isJsonObject(value: JsonValue): value is JsonObject {
return value != null && typeof value === 'object' && !Array.isArray(value);
}
export function isJsonArray(value: JsonValue): value is JsonArray {
return Array.isArray(value);
}
| {
"end_byte": 724,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/utils.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/index.ts_0_291 | /**
* @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 schema from './schema/index';
export * from './utils';
export { schema };
| {
"end_byte": 291,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/schema.ts_0_1668 | /**
* @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 '../utils';
/**
* A specialized interface for JsonSchema (to come). JsonSchemas are also JsonObject.
*
* @public
*/
export type JsonSchema = JsonObject | boolean;
export function isJsonSchema(value: unknown): value is JsonSchema {
return isJsonObject(value as JsonValue) || value === false || value === true;
}
/**
* Return a schema that is the merge of all subschemas, ie. it should validate all the schemas
* that were passed in. It is possible to make an invalid schema this way, e.g. by using
* `mergeSchemas({ type: 'number' }, { type: 'string' })`, which will never validate.
* @param schemas All schemas to be merged.
*/
export function mergeSchemas(...schemas: (JsonSchema | undefined)[]): JsonSchema {
return schemas.reduce<JsonSchema>((prev, curr) => {
if (curr === undefined) {
return prev;
}
if (prev === false || curr === false) {
return false;
} else if (prev === true) {
return curr;
} else if (curr === true) {
return prev;
} else if (Array.isArray(prev.allOf)) {
if (Array.isArray(curr.allOf)) {
return { ...prev, allOf: [...prev.allOf, ...curr.allOf] };
} else {
return { ...prev, allOf: [...prev.allOf, curr] };
}
} else if (Array.isArray(curr.allOf)) {
return { ...prev, allOf: [prev, ...curr.allOf] };
} else {
return { ...prev, allOf: [prev, curr] };
}
}, true);
}
| {
"end_byte": 1668,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/schema.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/pointer.ts_0_1003 | /**
* @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 { JsonPointer } from './interface';
export function buildJsonPointer(fragments: string[]): JsonPointer {
return ('/' +
fragments
.map((f) => {
return f.replace(/~/g, '~0').replace(/\//g, '~1');
})
.join('/')) as JsonPointer;
}
export function joinJsonPointer(root: JsonPointer, ...others: string[]): JsonPointer {
if (root == '/') {
return buildJsonPointer(others);
}
return (root + buildJsonPointer(others)) as JsonPointer;
}
export function parseJsonPointer(pointer: JsonPointer): string[] {
if (pointer === '') {
return [];
}
if (pointer.charAt(0) !== '/') {
throw new Error('Relative pointer: ' + pointer);
}
return pointer
.substring(1)
.split(/\//)
.map((str) => str.replace(/~1/g, '/').replace(/~0/g, '~'));
}
| {
"end_byte": 1003,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/pointer.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/visitor.ts_0_7420 | /**
* @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 {
Observable,
concat,
concatMap,
from,
ignoreElements,
isObservable,
mergeMap,
of as observableOf,
tap,
} from 'rxjs';
import { JsonArray, JsonObject, JsonValue } from '../utils';
import { JsonPointer, JsonSchemaVisitor, JsonVisitor } from './interface';
import { buildJsonPointer, joinJsonPointer } from './pointer';
import { JsonSchema } from './schema';
export interface ReferenceResolver<ContextT> {
(ref: string, context?: ContextT): { context?: ContextT; schema?: JsonObject };
}
function _getObjectSubSchema(schema: JsonSchema | undefined, key: string): JsonObject | undefined {
if (typeof schema !== 'object' || schema === null) {
return undefined;
}
// Is it an object schema?
if (typeof schema.properties == 'object' || schema.type == 'object') {
if (
typeof schema.properties == 'object' &&
typeof (schema.properties as JsonObject)[key] == 'object'
) {
return (schema.properties as JsonObject)[key] as JsonObject;
}
if (typeof schema.additionalProperties == 'object') {
return schema.additionalProperties as JsonObject;
}
return undefined;
}
// Is it an array schema?
if (typeof schema.items == 'object' || schema.type == 'array') {
return typeof schema.items == 'object' ? (schema.items as JsonObject) : undefined;
}
return undefined;
}
function _visitJsonRecursive<ContextT>(
json: JsonValue,
visitor: JsonVisitor,
ptr: JsonPointer,
schema?: JsonSchema,
refResolver?: ReferenceResolver<ContextT>,
context?: ContextT,
root?: JsonObject | JsonArray,
): Observable<JsonValue> {
if (schema === true || schema === false) {
// There's no schema definition, so just visit the JSON recursively.
schema = undefined;
}
// eslint-disable-next-line no-prototype-builtins
if (schema && schema.hasOwnProperty('$ref') && typeof schema['$ref'] == 'string') {
if (refResolver) {
const resolved = refResolver(schema['$ref'], context);
schema = resolved.schema;
context = resolved.context;
}
}
const value = visitor(json, ptr, schema as JsonObject, root);
return (isObservable(value) ? value : observableOf(value)).pipe(
concatMap((value) => {
if (Array.isArray(value)) {
return concat(
from(value).pipe(
mergeMap((item, i) => {
return _visitJsonRecursive(
item,
visitor,
joinJsonPointer(ptr, '' + i),
_getObjectSubSchema(schema, '' + i),
refResolver,
context,
root || value,
).pipe(tap<JsonValue>((x) => (value[i] = x)));
}),
ignoreElements(),
),
observableOf<JsonValue>(value),
);
} else if (typeof value == 'object' && value !== null) {
return concat(
from(Object.getOwnPropertyNames(value)).pipe(
mergeMap((key) => {
return _visitJsonRecursive(
value[key],
visitor,
joinJsonPointer(ptr, key),
_getObjectSubSchema(schema, key),
refResolver,
context,
root || value,
).pipe(
tap<JsonValue>((x) => {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (descriptor && descriptor.writable && value[key] !== x) {
value[key] = x;
}
}),
);
}),
ignoreElements(),
),
observableOf(value),
);
} else {
return observableOf(value);
}
}),
);
}
/**
* Visit all the properties in a JSON object, allowing to transform them. It supports calling
* properties synchronously or asynchronously (through Observables).
* The original object can be mutated or replaced entirely. In case where it's replaced, the new
* value is returned. When it's mutated though the original object will be changed.
*
* Please note it is possible to have an infinite loop here (which will result in a stack overflow)
* if you return 2 objects that references each others (or the same object all the time).
*
* @param {JsonValue} json The Json value to visit.
* @param {JsonVisitor} visitor A function that will be called on every items.
* @param {JsonObject} schema A JSON schema to pass through to the visitor (where possible).
* @param refResolver a function to resolve references in the schema.
* @returns {Observable< | undefined>} The observable of the new root, if the root changed.
*/
export function visitJson<ContextT>(
json: JsonValue,
visitor: JsonVisitor,
schema?: JsonSchema,
refResolver?: ReferenceResolver<ContextT>,
context?: ContextT,
): Observable<JsonValue> {
return _visitJsonRecursive(json, visitor, buildJsonPointer([]), schema, refResolver, context);
}
export function visitJsonSchema(schema: JsonSchema, visitor: JsonSchemaVisitor) {
if (schema === false || schema === true) {
// Nothing to visit.
return;
}
const keywords = {
additionalItems: true,
items: true,
contains: true,
additionalProperties: true,
propertyNames: true,
not: true,
};
const arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true,
};
const propsKeywords = {
definitions: true,
properties: true,
patternProperties: true,
additionalProperties: true,
dependencies: true,
items: true,
};
function _traverse(
schema: JsonObject | JsonArray,
jsonPtr: JsonPointer,
rootSchema: JsonObject,
parentSchema?: JsonObject | JsonArray,
keyIndex?: string,
) {
if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
visitor(schema, jsonPtr, parentSchema, keyIndex);
for (const key of Object.keys(schema)) {
const sch = schema[key];
if (key in propsKeywords) {
if (sch && typeof sch == 'object') {
for (const prop of Object.keys(sch)) {
_traverse(
(sch as JsonObject)[prop] as JsonObject,
joinJsonPointer(jsonPtr, key, prop),
rootSchema,
schema,
prop,
);
}
}
} else if (key in keywords) {
_traverse(sch as JsonObject, joinJsonPointer(jsonPtr, key), rootSchema, schema, key);
} else if (key in arrayKeywords) {
if (Array.isArray(sch)) {
for (let i = 0; i < sch.length; i++) {
_traverse(
sch[i] as JsonArray,
joinJsonPointer(jsonPtr, key, '' + i),
rootSchema,
sch,
'' + i,
);
}
}
} else if (Array.isArray(sch)) {
for (let i = 0; i < sch.length; i++) {
_traverse(
sch[i] as JsonArray,
joinJsonPointer(jsonPtr, key, '' + i),
rootSchema,
sch,
'' + i,
);
}
}
}
}
}
_traverse(schema, buildJsonPointer([]), schema);
}
| {
"end_byte": 7420,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/visitor.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/registry_spec.ts_0_432 | /**
* @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 { SchemaFormat } from './interface';
import { CoreSchemaRegistry, SchemaValidationException } from './registry';
import { addUndefinedDefaults } from './transforms'; | {
"end_byte": 432,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/registry_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/registry_spec.ts_434_8926 | describe('CoreSchemaRegistry', () => {
it('works asynchronously', async () => {
const registry = new CoreSchemaRegistry();
registry.addPostTransform(addUndefinedDefaults);
const data: any = {};
const validator = await registry.compile({
properties: {
bool: { type: 'boolean' },
str: { type: 'string', default: 'someString' },
obj: {
properties: {
num: { type: 'number' },
other: { type: 'number', default: 0 },
},
},
tslint: {
$ref: 'https://raw.githubusercontent.com/SchemaStore/schemastore/734c0e5/src/schemas/json/tslint.json#',
},
},
});
const result = await validator(data);
expect(result.success).toBe(true);
expect(data.obj.num).toBeUndefined();
expect(data.tslint).not.toBeUndefined();
});
it('supports pre transforms', async () => {
const registry = new CoreSchemaRegistry();
registry.addPostTransform(addUndefinedDefaults);
const data = {};
registry.addPreTransform((data, ptr) => {
if (ptr == '/') {
return { str: 'string' };
}
return data;
});
const validator = await registry.compile({
properties: {
bool: { type: 'boolean' },
str: { type: 'string', default: 'someString' },
obj: {
properties: {
num: { type: 'number' },
other: { type: 'number', default: 0 },
},
},
},
});
const result = await validator(data);
const resultData = result.data as any;
expect(result.success).toBe(true);
expect(resultData.str).toBe('string');
expect(resultData.obj.num).toBeUndefined();
});
it('supports local references', async () => {
const registry = new CoreSchemaRegistry();
registry.addPostTransform(addUndefinedDefaults);
const data = { numbers: { one: 1 } };
const validator = await registry.compile({
properties: {
numbers: {
type: 'object',
additionalProperties: { '$ref': '#/definitions/myRef' },
},
},
definitions: {
myRef: { type: 'integer' },
},
});
const result = await validator(data);
expect(result.success).toBe(true);
expect(data.numbers.one).not.toBeUndefined();
});
it('fails on invalid additionalProperties', async () => {
const registry = new CoreSchemaRegistry();
registry.addPostTransform(addUndefinedDefaults);
const data = { notNum: 'foo' };
const validator = await registry.compile({
properties: {
num: { type: 'number' },
},
additionalProperties: false,
});
const result = await validator(data);
expect(result.success).toBe(false);
expect(result.errors && result.errors[0].message).toContain(
'must NOT have additional properties',
);
});
it('fails on invalid enum value', async () => {
const registry = new CoreSchemaRegistry();
registry.addPostTransform(addUndefinedDefaults);
const data = { packageManager: 'foo' };
const validator = await registry.compile({
properties: {
packageManager: { type: 'string', enum: ['npm', 'yarn', 'pnpm', 'cnpm'] },
},
additionalProperties: false,
});
const result = await validator(data);
expect(result.success).toBe(false);
expect(new SchemaValidationException(result.errors).message).toContain(
`Data path "/packageManager" must be equal to one of the allowed values. Allowed values are: "npm", "yarn", "pnpm", "cnpm".`,
);
});
it('fails on invalid additionalProperties async', async () => {
const registry = new CoreSchemaRegistry();
registry.addPostTransform(addUndefinedDefaults);
const data = { notNum: 'foo' };
const validator = await registry.compile({
$async: true,
properties: {
num: { type: 'number' },
},
additionalProperties: false,
});
const result = await validator(data);
expect(result.success).toBe(false);
expect(result.errors?.[0].message).toContain('must NOT have additional properties');
expect(result.errors?.[0].keyword).toBe('additionalProperties');
});
it('supports sync format', async () => {
const registry = new CoreSchemaRegistry();
const data = { str: 'hotdog' };
const format = {
name: 'is-hotdog',
formatter: {
validate: (str: string) => str === 'hotdog',
},
};
registry.addFormat(format);
const validator = await registry.compile({
properties: {
str: { type: 'string', format: 'is-hotdog' },
},
});
const result = await validator(data);
expect(result.success).toBe(true);
});
it('supports async format', async () => {
const registry = new CoreSchemaRegistry();
const data = { str: 'hotdog' };
const format: SchemaFormat = {
name: 'is-hotdog',
formatter: {
async: true,
validate: async (str: string) => str === 'hotdog',
},
};
registry.addFormat(format);
const validator = await registry.compile({
$async: true,
properties: {
str: { type: 'string', format: 'is-hotdog' },
},
});
const result = await validator(data);
expect(result.success).toBe(true);
});
it('shows dataPath and message on error', async () => {
const registry = new CoreSchemaRegistry();
const data = { hotdot: 'hotdog', banana: 'banana' };
const format: SchemaFormat = {
name: 'is-hotdog',
formatter: {
async: false,
validate: (str: string) => str === 'hotdog',
},
};
registry.addFormat(format);
const validator = await registry.compile({
properties: {
hotdot: { type: 'string', format: 'is-hotdog' },
banana: { type: 'string', format: 'is-hotdog' },
},
});
const result = await validator(data);
expect(result.success).toBe(false);
expect(result.errors && result.errors[0]).toBeTruthy();
expect(result.errors && result.errors[0].keyword).toBe('format');
expect(result.errors && result.errors[0].instancePath).toBe('/banana');
expect(result.errors && (result.errors[0].params as any).format).toBe('is-hotdog');
});
it('supports smart defaults', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {
arr: [{}],
};
registry.addSmartDefaultProvider('test', (schema) => {
expect(schema).toEqual({
$source: 'test',
});
return true;
});
registry.addSmartDefaultProvider('test2', (schema) => {
expect(schema).toEqual({
$source: 'test2',
blue: 'yep',
});
return schema['blue'];
});
registry.addSmartDefaultProvider('test3', () => {
return [1, 2, 3];
});
const validator = await registry.compile({
properties: {
bool: {
$ref: '#/definitions/example',
},
arr: {
items: {
properties: {
'test': {
$ref: '#/definitions/other',
},
},
},
},
arr2: {
$ref: '#/definitions/test3',
},
obj: {
properties: {
deep: {
properties: {
arr: {
$ref: '#/definitions/test3',
},
},
},
},
},
},
definitions: {
example: {
type: 'boolean',
$default: {
$source: 'test',
},
},
other: {
type: 'string',
$default: {
$source: 'test2',
blue: 'yep',
},
},
test3: {
type: 'array',
$default: {
$source: 'test3',
},
},
},
});
const result = await validator(data);
expect(result.success).toBe(true);
expect(data.bool).toBe(true);
expect(data.arr[0].test).toBe('yep');
expect(data.arr2).toEqual([1, 2, 3]);
expect(data.obj.deep.arr).toEqual([1, 2, 3]);
});
it('works with true as a schema and post-transforms', async () => {
const registry = new CoreSchemaRegistry();
registry.addPostTransform(addUndefinedDefaults);
const data = { a: 1, b: 2 };
const validate = await registry.compile(true);
const result = await validate(data);
expect(result.success).toBe(true);
expect(result.data).toBe(data);
}); | {
"end_byte": 8926,
"start_byte": 434,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/registry_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/registry_spec.ts_8930_9857 | it('adds deprecated options usage', async () => {
const registry = new CoreSchemaRegistry();
const deprecatedMessages: string[] = [];
registry.useXDeprecatedProvider((m) => deprecatedMessages.push(m));
const data = {
foo: true,
bar: true,
bat: true,
};
const validator = await registry.compile({
properties: {
foo: { type: 'boolean', 'x-deprecated': 'Use bar instead.' },
bar: { type: 'boolean', 'x-deprecated': true },
buz: { type: 'boolean', 'x-deprecated': true },
bat: { type: 'boolean', 'x-deprecated': false },
},
});
const result = await validator(data);
expect(deprecatedMessages.length).toBe(2);
expect(deprecatedMessages[0]).toBe('Option "foo" is deprecated: Use bar instead.');
expect(deprecatedMessages[1]).toBe('Option "bar" is deprecated.');
expect(result.success).toBe(true, result.errors);
});
}); | {
"end_byte": 9857,
"start_byte": 8930,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/registry_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/interface.ts_0_3453 | /**
* @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 { ErrorObject, Format } from 'ajv';
import { Observable, ObservableInput } from 'rxjs';
import { JsonArray, JsonObject, JsonValue } from '../utils';
export type JsonPointer = string & {
__PRIVATE_DEVKIT_JSON_POINTER: void;
};
export interface SchemaValidatorResult {
data: JsonValue;
success: boolean;
errors?: SchemaValidatorError[];
}
export type SchemaValidatorError = Partial<ErrorObject>;
export interface SchemaValidatorOptions {
applyPreTransforms?: boolean;
applyPostTransforms?: boolean;
withPrompts?: boolean;
}
export interface SchemaValidator {
(data: JsonValue, options?: SchemaValidatorOptions): Promise<SchemaValidatorResult>;
}
export type SchemaFormatter = Format;
export interface SchemaFormat {
name: string;
formatter: SchemaFormatter;
}
export interface SmartDefaultProvider<T> {
(schema: JsonObject): T | Observable<T>;
}
export interface SchemaKeywordValidator {
(
data: JsonValue,
schema: JsonValue,
parent: JsonObject | JsonArray | undefined,
parentProperty: string | number | undefined,
pointer: JsonPointer,
rootData: JsonValue,
): boolean | Observable<boolean>;
}
export interface PromptDefinition {
id: string;
type: string;
message: string;
default?: string | string[] | number | boolean | null;
validator?: (value: JsonValue) => boolean | string | Promise<boolean | string>;
items?: Array<string | { value: JsonValue; label: string }>;
raw?: string | JsonObject;
multiselect?: boolean;
propertyTypes: Set<string>;
}
export type PromptProvider = (
definitions: Array<PromptDefinition>,
) => ObservableInput<{ [id: string]: JsonValue }>;
export interface SchemaRegistry {
// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types
compile(schema: Object): Promise<SchemaValidator>;
/** @private */
ɵflatten(schema: JsonObject | string): Promise<JsonObject>;
addFormat(format: SchemaFormat): void;
addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>): void;
usePromptProvider(provider: PromptProvider): void;
useXDeprecatedProvider(onUsage: (message: string) => void): void;
/**
* Add a transformation step before the validation of any Json.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
/**
* Add a transformation step after the validation of any Json. The JSON will not be validated
* after the POST, so if transformations are not compatible with the Schema it will not result
* in an error.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
}
export interface JsonSchemaVisitor {
(
current: JsonObject | JsonArray,
pointer: JsonPointer,
parentSchema?: JsonObject | JsonArray,
index?: string,
): void;
}
export interface JsonVisitor {
(
value: JsonValue,
pointer: JsonPointer,
schema?: JsonObject,
root?: JsonObject | JsonArray,
): Observable<JsonValue> | JsonValue;
}
| {
"end_byte": 3453,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/interface.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/utility.ts_0_2568 | /**
* @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, isJsonArray, isJsonObject } from '../utils';
import { JsonSchema } from './schema';
const allTypes = ['string', 'integer', 'number', 'object', 'array', 'boolean', 'null'];
export function getTypesOfSchema(schema: JsonSchema): Set<string> {
if (!schema) {
return new Set();
}
if (schema === true) {
return new Set(allTypes);
}
let potentials: Set<string>;
if (typeof schema.type === 'string') {
potentials = new Set([schema.type]);
} else if (Array.isArray(schema.type)) {
potentials = new Set(schema.type as string[]);
} else if (isJsonArray(schema.enum)) {
potentials = new Set();
// Gather the type of each enum values, and use that as a starter for potential types.
for (const v of schema.enum) {
switch (typeof v) {
case 'string':
case 'number':
case 'boolean':
potentials.add(typeof v);
break;
case 'object':
if (Array.isArray(v)) {
potentials.add('array');
} else if (v === null) {
potentials.add('null');
} else {
potentials.add('object');
}
break;
}
}
} else {
potentials = new Set(allTypes);
}
if (isJsonObject(schema.not)) {
const notTypes = getTypesOfSchema(schema.not);
potentials = new Set([...potentials].filter((p) => !notTypes.has(p)));
}
if (Array.isArray(schema.allOf)) {
for (const sub of schema.allOf) {
const types = getTypesOfSchema(sub as JsonObject);
potentials = new Set([...types].filter((t) => potentials.has(t)));
}
}
if (Array.isArray(schema.oneOf)) {
let options = new Set<string>();
for (const sub of schema.oneOf) {
const types = getTypesOfSchema(sub as JsonObject);
options = new Set([...options, ...types]);
}
potentials = new Set([...options].filter((o) => potentials.has(o)));
}
if (Array.isArray(schema.anyOf)) {
let options = new Set<string>();
for (const sub of schema.anyOf) {
const types = getTypesOfSchema(sub as JsonObject);
options = new Set([...options, ...types]);
}
potentials = new Set([...options].filter((o) => potentials.has(o)));
}
if (schema.properties) {
potentials.add('object');
} else if (schema.items) {
potentials.add('array');
}
return potentials;
}
| {
"end_byte": 2568,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/utility.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/registry.ts_0_8284 | /**
* @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 Ajv, { SchemaObjCxt, ValidateFunction } from 'ajv';
import ajvAddFormats from 'ajv-formats';
import * as http from 'http';
import * as https from 'https';
import { Observable, from, isObservable, lastValueFrom } from 'rxjs';
import * as Url from 'url';
import { BaseException } from '../../exception';
import { PartiallyOrderedSet, deepCopy } from '../../utils';
import { JsonArray, JsonObject, JsonValue, isJsonObject } from '../utils';
import {
JsonPointer,
JsonVisitor,
PromptDefinition,
PromptProvider,
SchemaFormat,
SchemaRegistry,
SchemaValidator,
SchemaValidatorError,
SchemaValidatorOptions,
SchemaValidatorResult,
SmartDefaultProvider,
} from './interface';
import { JsonSchema } from './schema';
import { getTypesOfSchema } from './utility';
import { visitJson, visitJsonSchema } from './visitor';
export type UriHandler = (
uri: string,
) => Observable<JsonObject> | Promise<JsonObject> | null | undefined;
export class SchemaValidationException extends BaseException {
public readonly errors: SchemaValidatorError[];
constructor(
errors?: SchemaValidatorError[],
baseMessage = 'Schema validation failed with the following errors:',
) {
if (!errors || errors.length === 0) {
super('Schema validation failed.');
this.errors = [];
return;
}
const messages = SchemaValidationException.createMessages(errors);
super(`${baseMessage}\n ${messages.join('\n ')}`);
this.errors = errors;
}
public static createMessages(errors?: SchemaValidatorError[]): string[] {
if (!errors || errors.length === 0) {
return [];
}
const messages = errors.map((err) => {
let message = `Data path ${JSON.stringify(err.instancePath)} ${err.message}`;
if (err.params) {
switch (err.keyword) {
case 'additionalProperties':
message += `(${err.params.additionalProperty})`;
break;
case 'enum':
message += `. Allowed values are: ${(err.params.allowedValues as string[] | undefined)
?.map((v) => `"${v}"`)
.join(', ')}`;
break;
}
}
return message + '.';
});
return messages;
}
}
interface SchemaInfo {
smartDefaultRecord: Map<string, JsonObject>;
promptDefinitions: Array<PromptDefinition>;
}
export class CoreSchemaRegistry implements SchemaRegistry {
private _ajv: Ajv;
private _uriCache = new Map<string, JsonObject>();
private _uriHandlers = new Set<UriHandler>();
private _pre = new PartiallyOrderedSet<JsonVisitor>();
private _post = new PartiallyOrderedSet<JsonVisitor>();
private _currentCompilationSchemaInfo?: SchemaInfo;
private _smartDefaultKeyword = false;
private _promptProvider?: PromptProvider;
private _sourceMap = new Map<string, SmartDefaultProvider<{}>>();
constructor(formats: SchemaFormat[] = []) {
this._ajv = new Ajv({
strict: false,
loadSchema: (uri: string) => this._fetch(uri),
passContext: true,
});
ajvAddFormats(this._ajv);
for (const format of formats) {
this.addFormat(format);
}
}
private async _fetch(uri: string): Promise<JsonObject> {
const maybeSchema = this._uriCache.get(uri);
if (maybeSchema) {
return maybeSchema;
}
// Try all handlers, one after the other.
for (const handler of this._uriHandlers) {
let handlerResult = handler(uri);
if (handlerResult === null || handlerResult === undefined) {
continue;
}
if (isObservable(handlerResult)) {
handlerResult = lastValueFrom(handlerResult);
}
const value = await handlerResult;
this._uriCache.set(uri, value);
return value;
}
// If none are found, handle using http client.
return new Promise<JsonObject>((resolve, reject) => {
const url = new Url.URL(uri);
const client = url.protocol === 'https:' ? https : http;
client.get(url, (res) => {
if (!res.statusCode || res.statusCode >= 300) {
// Consume the rest of the data to free memory.
res.resume();
reject(new Error(`Request failed. Status Code: ${res.statusCode}`));
} else {
res.setEncoding('utf8');
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const json = JSON.parse(data) as JsonObject;
this._uriCache.set(uri, json);
resolve(json);
} catch (err) {
reject(err);
}
});
}
});
});
}
/**
* Add a transformation step before the validation of any Json.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]) {
this._pre.add(visitor, deps);
}
/**
* Add a transformation step after the validation of any Json. The JSON will not be validated
* after the POST, so if transformations are not compatible with the Schema it will not result
* in an error.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]) {
this._post.add(visitor, deps);
}
protected _resolver(
ref: string,
validate?: ValidateFunction,
): { context?: ValidateFunction; schema?: JsonObject } {
if (!validate || !ref) {
return {};
}
const schema = validate.schemaEnv.root.schema;
const id = typeof schema === 'object' ? schema.$id : null;
let fullReference = ref;
if (typeof id === 'string') {
fullReference = Url.resolve(id, ref);
if (ref.startsWith('#')) {
fullReference = id + fullReference;
}
}
const resolvedSchema = this._ajv.getSchema(fullReference);
return {
context: resolvedSchema?.schemaEnv.validate,
schema: resolvedSchema?.schema as JsonObject,
};
}
/**
* Flatten the Schema, resolving and replacing all the refs. Makes it into a synchronous schema
* that is also easier to traverse. Does not cache the result.
*
* Producing a flatten schema document does not in all cases produce a schema with identical behavior to the original.
* See: https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.appendix.B.2
*
* @param schema The schema or URI to flatten.
* @returns An Observable of the flattened schema object.
* @private since 11.2 without replacement.
*/
async ɵflatten(schema: JsonObject): Promise<JsonObject> {
this._ajv.removeSchema(schema);
this._currentCompilationSchemaInfo = undefined;
const validate = await this._ajv.compileAsync(schema);
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
function visitor(
current: JsonObject | JsonArray,
pointer: JsonPointer,
parentSchema?: JsonObject | JsonArray,
index?: string,
) {
if (
current &&
parentSchema &&
index &&
isJsonObject(current) &&
Object.prototype.hasOwnProperty.call(current, '$ref') &&
typeof current['$ref'] == 'string'
) {
const resolved = self._resolver(current['$ref'], validate);
if (resolved.schema) {
(parentSchema as JsonObject)[index] = resolved.schema;
}
}
}
const schemaCopy = deepCopy(validate.schema as JsonObject);
visitJsonSchema(schemaCopy, visitor);
return schemaCopy;
}
/**
* Compile and return a validation function for the Schema.
*
* @param schema The schema to validate. If a string, will fetch the schema before compiling it
* (using schema as a URI).
*/
async compile(schema: JsonSchema): Promise<SchemaValidator> {
const validate = await this._compile(schema);
return (value, options) => validate(value, options);
}
| {
"end_byte": 8284,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/registry.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/registry.ts_8288_17423 | rivate async _compile(
schema: JsonSchema,
): Promise<
(data: JsonValue, options?: SchemaValidatorOptions) => Promise<SchemaValidatorResult>
> {
if (typeof schema === 'boolean') {
return async (data) => ({ success: schema, data });
}
const schemaInfo: SchemaInfo = {
smartDefaultRecord: new Map<string, JsonObject>(),
promptDefinitions: [],
};
this._ajv.removeSchema(schema);
let validator: ValidateFunction;
try {
this._currentCompilationSchemaInfo = schemaInfo;
validator = this._ajv.compile(schema);
} catch (e) {
// This should eventually be refactored so that we we handle race condition where the same schema is validated at the same time.
if (!(e instanceof Ajv.MissingRefError)) {
throw e;
}
validator = await this._ajv.compileAsync(schema);
} finally {
this._currentCompilationSchemaInfo = undefined;
}
return async (data: JsonValue, options?: SchemaValidatorOptions) => {
const validationOptions: SchemaValidatorOptions = {
withPrompts: true,
applyPostTransforms: true,
applyPreTransforms: true,
...options,
};
const validationContext = {
promptFieldsWithValue: new Set<string>(),
};
// Apply pre-validation transforms
if (validationOptions.applyPreTransforms) {
for (const visitor of this._pre.values()) {
data = await lastValueFrom(
visitJson(data, visitor, schema, this._resolver.bind(this), validator),
);
}
}
// Apply smart defaults
await this._applySmartDefaults(data, schemaInfo.smartDefaultRecord);
// Apply prompts
if (validationOptions.withPrompts) {
const visitor: JsonVisitor = (value, pointer) => {
if (value !== undefined) {
validationContext.promptFieldsWithValue.add(pointer);
}
return value;
};
if (typeof schema === 'object') {
await lastValueFrom(
visitJson(data, visitor, schema, this._resolver.bind(this), validator),
);
}
const definitions = schemaInfo.promptDefinitions.filter(
(def) => !validationContext.promptFieldsWithValue.has(def.id),
);
if (definitions.length > 0) {
await this._applyPrompts(data, definitions);
}
}
// Validate using ajv
try {
// eslint-disable-next-line @typescript-eslint/await-thenable
const success = await validator.call(validationContext, data);
if (!success) {
return { data, success, errors: validator.errors ?? [] };
}
} catch (error) {
if (error instanceof Ajv.ValidationError) {
return { data, success: false, errors: error.errors };
}
throw error;
}
// Apply post-validation transforms
if (validationOptions.applyPostTransforms) {
for (const visitor of this._post.values()) {
data = await lastValueFrom(
visitJson(data, visitor, schema, this._resolver.bind(this), validator),
);
}
}
return { data, success: true };
};
}
addFormat(format: SchemaFormat): void {
this._ajv.addFormat(format.name, format.formatter);
}
addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>) {
if (this._sourceMap.has(source)) {
throw new Error(source);
}
this._sourceMap.set(source, provider as unknown as SmartDefaultProvider<{}>);
if (!this._smartDefaultKeyword) {
this._smartDefaultKeyword = true;
this._ajv.addKeyword({
keyword: '$default',
errors: false,
valid: true,
compile: (schema, _parentSchema, it) => {
const compilationSchemInfo = this._currentCompilationSchemaInfo;
if (compilationSchemInfo === undefined) {
return () => true;
}
// We cheat, heavily.
const pathArray = this.normalizeDataPathArr(it);
compilationSchemInfo.smartDefaultRecord.set(JSON.stringify(pathArray), schema);
return () => true;
},
metaSchema: {
type: 'object',
properties: {
'$source': { type: 'string' },
},
additionalProperties: true,
required: ['$source'],
},
});
}
}
registerUriHandler(handler: UriHandler) {
this._uriHandlers.add(handler);
}
usePromptProvider(provider: PromptProvider) {
const isSetup = !!this._promptProvider;
this._promptProvider = provider;
if (isSetup) {
return;
}
this._ajv.addKeyword({
keyword: 'x-prompt',
errors: false,
valid: true,
compile: (schema, parentSchema, it) => {
const compilationSchemInfo = this._currentCompilationSchemaInfo;
if (!compilationSchemInfo) {
return () => true;
}
const path = '/' + this.normalizeDataPathArr(it).join('/');
let type: string | undefined;
let items: Array<string | { label: string; value: string | number | boolean }> | undefined;
let message: string;
if (typeof schema == 'string') {
message = schema;
} else {
message = schema.message;
type = schema.type;
items = schema.items;
}
const propertyTypes = getTypesOfSchema(parentSchema as JsonObject);
if (!type) {
if (propertyTypes.size === 1 && propertyTypes.has('boolean')) {
type = 'confirmation';
} else if (Array.isArray((parentSchema as JsonObject).enum)) {
type = 'list';
} else if (
propertyTypes.size === 1 &&
propertyTypes.has('array') &&
(parentSchema as JsonObject).items &&
Array.isArray(((parentSchema as JsonObject).items as JsonObject).enum)
) {
type = 'list';
} else {
type = 'input';
}
}
let multiselect;
if (type === 'list') {
multiselect =
schema.multiselect === undefined
? propertyTypes.size === 1 && propertyTypes.has('array')
: schema.multiselect;
const enumValues = multiselect
? (parentSchema as JsonObject).items &&
((parentSchema as JsonObject).items as JsonObject).enum
: (parentSchema as JsonObject).enum;
if (!items && Array.isArray(enumValues)) {
items = [];
for (const value of enumValues) {
if (typeof value == 'string') {
items.push(value);
} else if (typeof value == 'object') {
// Invalid
} else {
items.push({ label: value.toString(), value });
}
}
}
}
const definition: PromptDefinition = {
id: path,
type,
message,
raw: schema,
items,
multiselect,
propertyTypes,
default:
typeof (parentSchema as JsonObject).default == 'object' &&
(parentSchema as JsonObject).default !== null &&
!Array.isArray((parentSchema as JsonObject).default)
? undefined
: ((parentSchema as JsonObject).default as string[]),
async validator(data: JsonValue): Promise<boolean | string> {
try {
const result = await it.self.validate(parentSchema, data);
// If the schema is sync then false will be returned on validation failure
if (result) {
return result as boolean | string;
} else if (it.self.errors?.length) {
// Validation errors will be present on the Ajv instance when sync
return it.self.errors[0].message as string;
}
} catch (e) {
const validationError = e as { errors?: Error[] };
// If the schema is async then an error will be thrown on validation failure
if (Array.isArray(validationError.errors) && validationError.errors.length) {
return validationError.errors[0].message;
}
}
return false;
},
};
compilationSchemInfo.promptDefinitions.push(definition);
return function (this: { promptFieldsWithValue: Set<string> }) {
// If 'this' is undefined in the call, then it defaults to the global
// 'this'.
if (this && this.promptFieldsWithValue) {
this.promptFieldsWithValue.add(path);
}
return true;
};
},
metaSchema: {
oneOf: [
{ type: 'string' },
{
type: 'object',
properties: {
'type': { type: 'string' },
'message': { type: 'string' },
},
additionalProperties: true,
required: ['message'],
},
],
},
});
}
| {
"end_byte": 17423,
"start_byte": 8288,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/registry.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/registry.ts_17427_20219 | rivate async _applyPrompts(data: JsonValue, prompts: Array<PromptDefinition>): Promise<void> {
const provider = this._promptProvider;
if (!provider) {
return;
}
const answers = await lastValueFrom(from(provider(prompts)));
for (const path in answers) {
const pathFragments = path.split('/').slice(1);
CoreSchemaRegistry._set(data, pathFragments, answers[path], null, undefined, true);
}
}
private static _set(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: any,
fragments: string[],
value: unknown,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
parent: any = null,
parentProperty?: string,
force?: boolean,
): void {
for (let index = 0; index < fragments.length; index++) {
const fragment = fragments[index];
if (/^i\d+$/.test(fragment)) {
if (!Array.isArray(data)) {
return;
}
for (let dataIndex = 0; dataIndex < data.length; dataIndex++) {
CoreSchemaRegistry._set(
data[dataIndex],
fragments.slice(index + 1),
value,
data,
`${dataIndex}`,
);
}
return;
}
if (!data && parent !== null && parentProperty) {
data = parent[parentProperty] = {};
}
parent = data;
parentProperty = fragment;
data = data[fragment];
}
if (parent && parentProperty && (force || parent[parentProperty] === undefined)) {
parent[parentProperty] = value;
}
}
private async _applySmartDefaults<T>(
data: T,
smartDefaults: Map<string, JsonObject>,
): Promise<void> {
for (const [pointer, schema] of smartDefaults.entries()) {
const fragments = JSON.parse(pointer) as string[];
const source = this._sourceMap.get(schema.$source as string);
if (!source) {
continue;
}
let value = source(schema);
if (isObservable(value)) {
value = (await lastValueFrom(value)) as {};
}
CoreSchemaRegistry._set(data, fragments, value);
}
}
useXDeprecatedProvider(onUsage: (message: string) => void): void {
this._ajv.addKeyword({
keyword: 'x-deprecated',
validate: (schema, _data, _parentSchema, dataCxt) => {
if (schema) {
onUsage(
`Option "${dataCxt?.parentDataProperty}" is deprecated${
typeof schema == 'string' ? ': ' + schema : '.'
}`,
);
}
return true;
},
errors: false,
});
}
private normalizeDataPathArr(it: SchemaObjCxt): (number | string)[] {
return it.dataPathArr
.slice(1, it.dataLevel + 1)
.map((p) => (typeof p === 'number' ? p : p.str.replace(/"/g, '')));
}
}
| {
"end_byte": 20219,
"start_byte": 17427,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/registry.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/transforms_spec.ts_0_7132 | /**
* @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 { CoreSchemaRegistry } from './registry';
import { addUndefinedDefaults } from './transforms';
describe('addUndefinedDefaults', () => {
it('should add defaults to undefined properties (1)', async () => {
const registry = new CoreSchemaRegistry();
registry.addPreTransform(addUndefinedDefaults);
const data: any = {}; // eslint-disable-line @typescript-eslint/no-explicit-any
const validator = await registry.compile({
properties: {
bool: { type: 'boolean' },
str: { type: 'string', default: 'someString' },
obj: {
properties: {
num: { type: 'number' },
other: { type: 'number', default: 0 },
},
},
objAllOk: {
allOf: [{ type: 'object' }],
},
objAllBad: {
allOf: [{ type: 'object' }, { type: 'number' }],
},
objOne: {
oneOf: [{ type: 'object' }],
},
objNotOk: {
not: { not: { type: 'object' } },
},
objNotBad: {
type: 'object',
not: { type: 'object' },
},
},
});
const result = await validator(data);
expect(result.success).toBeTrue();
expect(data.bool).toBeUndefined();
expect(data.str).toBe('someString');
expect(data.obj.num).toBeUndefined();
expect(data.obj.other).toBe(0);
expect(data.objAllOk).toEqual({});
expect(data.objOne).toEqual({});
expect(data.objAllBad).toBeUndefined();
expect(data.objNotOk).toEqual({});
expect(data.objNotBad).toBeUndefined();
});
it('should add defaults to undefined properties (2)', async () => {
const registry = new CoreSchemaRegistry();
registry.addPreTransform(addUndefinedDefaults);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = {
bool: undefined,
str: undefined,
obj: {
num: undefined,
},
};
const validator = await registry.compile({
properties: {
bool: { type: 'boolean', default: true },
str: { type: 'string', default: 'someString' },
obj: {
properties: {
num: { type: 'number', default: 0 },
},
},
},
});
const result = await validator(data);
expect(result.success).toBeTrue();
expect(data.bool).toBeTrue();
expect(data.str).toBe('someString');
expect(data.obj.num).toBe(0);
});
it('should add defaults to undefined properties when using oneOf', async () => {
const registry = new CoreSchemaRegistry();
registry.addPreTransform(addUndefinedDefaults);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dataNoObj: any = {
bool: undefined,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dataObj: any = {
bool: undefined,
obj: {
a: false,
},
};
const validator = await registry.compile({
properties: {
bool: { type: 'boolean', default: true },
obj: {
default: true,
oneOf: [
{
type: 'object',
properties: {
a: { type: 'boolean', default: true },
b: { type: 'boolean', default: true },
c: { type: 'boolean', default: false },
},
},
{
type: 'boolean',
},
],
},
noDefaultOneOf: {
oneOf: [
{
type: 'object',
properties: {
a: { type: 'boolean', default: true },
b: { type: 'boolean', default: true },
c: { type: 'boolean', default: false },
},
},
{
type: 'boolean',
},
],
},
},
});
const result1 = await validator(dataNoObj);
expect(result1.success).toBeTrue();
expect(dataNoObj.bool).toBeTrue();
expect(dataNoObj.obj).toBeTrue();
expect(dataNoObj.noDefaultOneOf).toBeUndefined();
const result2 = await validator(dataObj);
expect(result2.success).toBeTrue();
expect(dataObj.bool).toBeTrue();
expect(dataObj.obj.a).toBeFalse();
expect(dataObj.obj.b).toBeTrue();
expect(dataObj.obj.c).toBeFalse();
});
it('should add defaults to undefined properties when using anyOf', async () => {
const registry = new CoreSchemaRegistry();
registry.addPreTransform(addUndefinedDefaults);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dataNoObj: any = {
bool: undefined,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dataObj: any = {
bool: undefined,
obj: {
a: false,
},
};
const validator = await registry.compile({
properties: {
bool: { type: 'boolean', default: true },
obj: {
default: true,
anyOf: [
{
type: 'object',
properties: {
d: { type: 'boolean', default: false },
},
},
{
type: 'object',
properties: {
a: { type: 'boolean', default: true },
b: { type: 'boolean', default: true },
c: { type: 'boolean', default: false },
},
},
{
type: 'boolean',
},
],
},
},
});
const result1 = await validator(dataNoObj);
expect(result1.success).toBeTrue();
expect(dataNoObj.bool).toBeTrue();
expect(dataNoObj.obj).toBeTrue();
const result2 = await validator(dataObj);
expect(result2.success).toBeTrue();
expect(dataObj.bool).toBeTrue();
expect(dataObj.obj.a).toBeFalse();
expect(dataObj.obj.b).toBeTrue();
expect(dataObj.obj.c).toBeFalse();
});
it('should add defaults to undefined properties when using $refs', async () => {
const registry = new CoreSchemaRegistry();
registry.addPreTransform(addUndefinedDefaults);
const dataNoObj: Record<string, boolean> = {};
const dataObj: Record<string, boolean> = {
boolRef: true,
};
const validator = await registry.compile({
definitions: {
boolRef: {
default: false,
type: 'boolean',
},
},
properties: {
bool: {
default: false,
type: 'boolean',
},
boolRef: {
$ref: '#/definitions/boolRef',
},
},
});
const result1 = await validator(dataNoObj);
expect(result1.success).toBeTrue();
expect(dataNoObj['bool']).toBeFalse();
expect(dataNoObj['boolRef']).toBeFalse();
const result2 = await validator(dataObj);
expect(result2.success).toBeTrue();
expect(dataObj['bool']).toBeFalse();
expect(dataObj['boolRef']).toBeTrue();
});
});
| {
"end_byte": 7132,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/transforms_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/index.ts_0_437 | /**
* @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 transforms from './transforms';
export * from './interface';
export * from './pointer';
export * from './registry';
export * from './schema';
export * from './visitor';
export * from './utility';
export { transforms };
| {
"end_byte": 437,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/visitor_spec.ts_0_4095 | /**
* @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 { Observable, from } from 'rxjs';
import { JsonObject, JsonValue } from '..';
import { visitJson } from './visitor';
function syncObs<T>(obs: Observable<T>): T {
let value: T;
let set = false;
obs
.forEach((x) => {
if (set) {
throw new Error('Multiple value.');
}
value = x;
set = true;
})
.catch((err) => fail(err));
if (!set) {
throw new Error('Async observable.');
}
return value!; // eslint-disable-line @typescript-eslint/no-non-null-assertion
}
describe('visitJson', () => {
it('works to replace the root', () => {
const json = { a: 1 };
const newJson = {};
const result = syncObs(visitJson(json, () => newJson));
expect(result).toBe(newJson);
});
it('goes through recursively if replacing root', () => {
const json = { a: 1 };
const newJson = { b: 'hello ' };
const result = syncObs(
visitJson(json, (value) => {
if (typeof value == 'object') {
return newJson;
} else {
return value + 'world';
}
}),
);
expect(result).toEqual({ b: 'hello world' });
expect(newJson).toEqual({ b: 'hello world' });
});
it('goes through all replacements recursively', () => {
const json = { a: 1 };
const newJson = { b: '' };
const newJson2 = { c: [] };
const newJson3 = [1, 2, 3];
const result = syncObs(
visitJson(json, (value, ptr) => {
if (ptr.endsWith('a')) {
return newJson;
} else if (ptr.endsWith('b')) {
return newJson2;
} else if (ptr.endsWith('c')) {
return newJson3;
} else if (typeof value == 'number') {
return '_' + value;
} else if (ptr == '/') {
return value;
} else {
return 'abc';
}
}),
);
expect(result).toEqual({ a: { b: { c: ['_1', '_2', '_3'] } } });
});
it('goes through all replacements recursively (async)', (done) => {
const json = { a: 1 };
const newJson = { b: '' };
const newJson2 = { c: [] };
const newJson3 = [1, 2, 3];
visitJson(json, (value, ptr) => {
if (ptr.endsWith('a')) {
return from(Promise.resolve(newJson));
} else if (ptr.endsWith('b')) {
return from(Promise.resolve(newJson2));
} else if (ptr.endsWith('c')) {
return from(Promise.resolve(newJson3));
} else if (typeof value == 'number') {
return from(Promise.resolve('_' + value));
} else if (ptr == '/') {
return from(Promise.resolve(value));
} else {
return from(Promise.resolve('abc'));
}
})
.toPromise()
.then((result) => {
expect(result).toEqual({ a: { b: { c: ['_1', '_2', '_3'] } } });
done();
}, done.fail);
});
it('works with schema', () => {
const schema = {
properties: {
bool: { type: 'boolean' },
str: { type: 'string', default: 'someString' },
obj: {
properties: {
num: { type: 'number' },
other: { type: 'number', default: 0 },
},
},
},
};
const allPointers: { [ptr: string]: JsonObject | undefined } = {};
function visitor(value: JsonValue, ptr: string, schema?: JsonObject) {
expect(allPointers[ptr]).toBeUndefined();
allPointers[ptr] = schema;
return value;
}
const json = {
bool: true,
str: 'hello',
obj: {
num: 1,
},
};
const result = syncObs(visitJson(json, visitor, schema));
expect(result).toEqual({
bool: true,
str: 'hello',
obj: { num: 1 },
});
expect(allPointers).toEqual({
'/': schema,
'/bool': schema.properties.bool,
'/str': schema.properties.str,
'/obj': schema.properties.obj,
'/obj/num': schema.properties.obj.properties.num,
});
});
});
| {
"end_byte": 4095,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/visitor_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/transforms.ts_0_2988 | /**
* @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, isJsonArray, isJsonObject } from '../utils';
import { JsonPointer } from './interface';
import { JsonSchema } from './schema';
import { getTypesOfSchema } from './utility';
export function addUndefinedDefaults(
value: JsonValue,
_pointer: JsonPointer,
schema?: JsonSchema,
): JsonValue {
if (typeof schema === 'boolean' || schema === undefined) {
return value;
}
value ??= schema.default;
const types = getTypesOfSchema(schema);
if (types.size === 0) {
return value;
}
let type;
if (types.size === 1) {
// only one potential type
type = Array.from(types)[0];
} else if (types.size === 2 && types.has('array') && types.has('object')) {
// need to create one of them and array is simpler
type = 'array';
} else if (schema.properties && types.has('object')) {
// assume object
type = 'object';
} else if (schema.items && types.has('array')) {
// assume array
type = 'array';
} else {
// anything else needs to be checked by the consumer anyway
return value;
}
if (type === 'array') {
return value == undefined ? [] : value;
}
if (type === 'object') {
let newValue;
if (value == undefined) {
newValue = {} as JsonObject;
} else if (isJsonObject(value)) {
newValue = value;
} else {
return value;
}
if (!isJsonObject(schema.properties)) {
return newValue;
}
for (const [propName, schemaObject] of Object.entries(schema.properties)) {
if (propName === '$schema' || !isJsonObject(schemaObject)) {
continue;
}
const value = newValue[propName];
if (value === undefined) {
newValue[propName] = schemaObject.default;
} else if (isJsonObject(value)) {
// Basic support for oneOf and anyOf.
const propertySchemas = schemaObject.oneOf || schemaObject.anyOf;
const allProperties = Object.keys(value);
// Locate a schema which declares all the properties that the object contains.
const adjustedSchema =
isJsonArray(propertySchemas) &&
propertySchemas.find((s) => {
if (!isJsonObject(s)) {
return false;
}
const schemaType = getTypesOfSchema(s);
if (schemaType.size === 1 && schemaType.has('object') && isJsonObject(s.properties)) {
const properties = Object.keys(s.properties);
return allProperties.every((key) => properties.includes(key));
}
return false;
});
if (adjustedSchema && isJsonObject(adjustedSchema)) {
newValue[propName] = addUndefinedDefaults(value, _pointer, adjustedSchema);
}
}
}
return newValue;
}
return value;
}
| {
"end_byte": 2988,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/transforms.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/prompt_spec.ts_0_3989 | /**
* @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 { CoreSchemaRegistry } from './registry';
describe('Prompt Provider', () => {
it('sets properties with answer', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
return { [definitions[0].id]: true };
});
const validator = await registry.compile({
properties: {
test: {
type: 'boolean',
'x-prompt': 'test-message',
},
},
});
await validator(data);
expect(data.test).toBe(true);
});
it('supports mixed schema references', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
return {
'/bool': true,
'/test': 'two',
'/obj/deep/three': 'test3-answer',
};
});
const validator = await registry.compile({
properties: {
bool: {
$ref: '#/definitions/example',
},
test: {
type: 'string',
enum: ['one', 'two', 'three'],
'x-prompt': {
type: 'list',
'message': 'other-message',
},
},
obj: {
properties: {
deep: {
properties: {
three: {
$ref: '#/definitions/test3',
},
},
},
},
},
},
definitions: {
example: {
type: 'boolean',
'x-prompt': 'example-message',
},
test3: {
type: 'string',
'x-prompt': 'test3-message',
},
},
});
const result = await validator(data);
expect(result.success).toBe(true);
expect(data.bool).toBe(true);
expect(data.test).toBe('two');
expect(data.obj.deep.three).toEqual('test3-answer');
});
describe('with shorthand', () => {
it('supports message value', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].message).toBe('test-message');
return {};
});
const validator = await registry.compile({
properties: {
test: {
type: 'string',
'x-prompt': 'test-message',
},
},
});
await validator(data);
});
it('analyzes enums', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('list');
expect(definitions[0].items).toEqual(['one', 'two', 'three']);
return {};
});
const validator = await registry.compile({
properties: {
test: {
type: 'string',
enum: ['one', 'two', 'three'],
'x-prompt': 'test-message',
},
},
});
await validator(data);
});
it('analyzes boolean properties', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('confirmation');
expect(definitions[0].items).toBeUndefined();
return {};
});
const validator = await registry.compile({
properties: {
test: {
type: 'boolean',
'x-prompt': 'test-message',
},
},
});
await validator(data);
});
}); | {
"end_byte": 3989,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/prompt_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/json/schema/prompt_spec.ts_3993_11489 | describe('with longhand', () => {
it('supports message option', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].message).toBe('test-message');
return {};
});
const validator = await registry.compile({
properties: {
test: {
type: 'string',
'x-prompt': {
'message': 'test-message',
},
},
},
});
await validator(data);
});
it('analyzes enums WITH explicit list type', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('list');
expect(definitions[0].items).toEqual(['one', 'two', 'three']);
return { [definitions[0].id]: 'one' };
});
const validator = await registry.compile({
properties: {
test: {
type: 'string',
enum: ['one', 'two', 'three'],
'x-prompt': {
'type': 'list',
'message': 'test-message',
},
},
},
});
await validator(data);
});
it('analyzes list with true multiselect option and object items', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('list');
expect(definitions[0].multiselect).toBe(true);
expect(definitions[0].items).toEqual([
{ 'value': 'one', 'label': 'one' },
{ 'value': 'two', 'label': 'two' },
]);
return { [definitions[0].id]: { 'value': 'one', 'label': 'one' } };
});
const validator = await registry.compile({
properties: {
test: {
type: 'array',
'x-prompt': {
'type': 'list',
'multiselect': true,
'items': [
{ 'value': 'one', 'label': 'one' },
{ 'value': 'two', 'label': 'two' },
],
'message': 'test-message',
},
},
},
});
await validator(data);
});
it('analyzes list with false multiselect option and object items', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('list');
expect(definitions[0].multiselect).toBe(false);
expect(definitions[0].items).toEqual([
{ 'value': 'one', 'label': 'one' },
{ 'value': 'two', 'label': 'two' },
]);
return { [definitions[0].id]: { 'value': 'one', 'label': 'one' } };
});
const validator = await registry.compile({
properties: {
test: {
type: 'array',
'x-prompt': {
'type': 'list',
'multiselect': false,
'items': [
{ 'value': 'one', 'label': 'one' },
{ 'value': 'two', 'label': 'two' },
],
'message': 'test-message',
},
},
},
});
await validator(data);
});
it('analyzes list without multiselect option and object items', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('list');
expect(definitions[0].multiselect).toBe(true);
expect(definitions[0].items).toEqual([
{ 'value': 'one', 'label': 'one' },
{ 'value': 'two', 'label': 'two' },
]);
return { [definitions[0].id]: { 'value': 'two', 'label': 'two' } };
});
const validator = await registry.compile({
properties: {
test: {
type: 'array',
'x-prompt': {
'type': 'list',
'items': [
{ 'value': 'one', 'label': 'one' },
{ 'value': 'two', 'label': 'two' },
],
'message': 'test-message',
},
},
},
});
await validator(data);
});
it('analyzes enums WITHOUT explicit list type', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('list');
expect(definitions[0].multiselect).toBeFalsy();
expect(definitions[0].items).toEqual(['one', 'two', 'three']);
return {};
});
const validator = await registry.compile({
properties: {
test: {
type: 'string',
enum: ['one', 'two', 'three'],
'x-prompt': {
'message': 'test-message',
},
},
},
});
await validator(data);
});
it('analyzes enums WITHOUT explicit list type and multiselect', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('list');
expect(definitions[0].multiselect).toBe(true);
expect(definitions[0].items).toEqual(['one', 'two', 'three']);
return {};
});
const validator = await registry.compile({
properties: {
test: {
type: 'array',
items: {
enum: ['one', 'two', 'three'],
},
'x-prompt': 'test-message',
},
},
});
await validator(data);
});
it('analyzes boolean properties', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('confirmation');
expect(definitions[0].items).toBeUndefined();
return {};
});
const validator = await registry.compile({
properties: {
test: {
type: 'boolean',
'x-prompt': {
'message': 'test-message',
},
},
},
});
await validator(data);
});
it('allows prompt type override', async () => {
const registry = new CoreSchemaRegistry();
const data: any = {};
registry.usePromptProvider(async (definitions) => {
expect(definitions.length).toBe(1);
expect(definitions[0].type).toBe('input');
expect(definitions[0].items).toBeUndefined();
return {};
});
const validator = await registry.compile({
properties: {
test: {
type: 'boolean',
'x-prompt': {
'type': 'input',
'message': 'test-message',
},
},
},
});
await validator(data);
});
});
}); | {
"end_byte": 11489,
"start_byte": 3993,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/json/schema/prompt_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/path.ts_0_7763 | /**
* @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 '../exception';
import { TemplateTag } from '../utils/literals';
export class InvalidPathException extends BaseException {
constructor(path: string) {
super(`Path ${JSON.stringify(path)} is invalid.`);
}
}
export class PathMustBeAbsoluteException extends BaseException {
constructor(path: string) {
super(`Path ${JSON.stringify(path)} must be absolute.`);
}
}
export class PathCannotBeFragmentException extends BaseException {
constructor(path: string) {
super(`Path ${JSON.stringify(path)} cannot be made a fragment.`);
}
}
/**
* A Path recognized by most methods in the DevKit.
*/
export type Path = string & {
__PRIVATE_DEVKIT_PATH: void;
};
/**
* A Path fragment (file or directory name) recognized by most methods in the DevKit.
*/
export type PathFragment = Path & {
__PRIVATE_DEVKIT_PATH_FRAGMENT: void;
};
/**
* The Separator for normalized path.
* @type {Path}
*/
export const NormalizedSep = '/' as Path;
/**
* The root of a normalized path.
* @type {Path}
*/
export const NormalizedRoot = NormalizedSep;
/**
* Split a path into multiple path fragments. Each fragments except the last one will end with
* a path separator.
* @param {Path} path The path to split.
* @returns {Path[]} An array of path fragments.
*/
export function split(path: Path): PathFragment[] {
const fragments = path.split(NormalizedSep).map((x) => fragment(x));
if (fragments[fragments.length - 1].length === 0) {
fragments.pop();
}
return fragments;
}
/**
*
*/
export function extname(path: Path): string {
const base = basename(path);
const i = base.lastIndexOf('.');
if (i < 1) {
return '';
} else {
return base.slice(i);
}
}
/**
* Return the basename of the path, as a Path. See path.basename
*/
export function basename(path: Path): PathFragment {
const i = path.lastIndexOf(NormalizedSep);
if (i == -1) {
return fragment(path);
} else {
return fragment(path.slice(path.lastIndexOf(NormalizedSep) + 1));
}
}
/**
* Return the dirname of the path, as a Path. See path.dirname
*/
export function dirname(path: Path): Path {
const index = path.lastIndexOf(NormalizedSep);
if (index === -1) {
return '' as Path;
}
const endIndex = index === 0 ? 1 : index; // case of file under root: '/file'
return normalize(path.slice(0, endIndex));
}
/**
* Join multiple paths together, and normalize the result. Accepts strings that will be
* normalized as well (but the original must be a path).
*/
export function join(p1: Path, ...others: string[]): Path {
if (others.length > 0) {
return normalize((p1 ? p1 + NormalizedSep : '') + others.join(NormalizedSep));
} else {
return p1;
}
}
/**
* Returns true if a path is absolute.
*/
export function isAbsolute(p: Path) {
return p.startsWith(NormalizedSep);
}
/**
* Returns a path such that `join(from, relative(from, to)) == to`.
* Both paths must be absolute, otherwise it does not make much sense.
*/
export function relative(from: Path, to: Path): Path {
if (!isAbsolute(from)) {
throw new PathMustBeAbsoluteException(from);
}
if (!isAbsolute(to)) {
throw new PathMustBeAbsoluteException(to);
}
let p: string;
if (from == to) {
p = '';
} else {
const splitFrom = split(from);
const splitTo = split(to);
while (splitFrom.length > 0 && splitTo.length > 0 && splitFrom[0] == splitTo[0]) {
splitFrom.shift();
splitTo.shift();
}
if (splitFrom.length == 0) {
p = splitTo.join(NormalizedSep);
} else {
p = splitFrom
.map(() => '..')
.concat(splitTo)
.join(NormalizedSep);
}
}
return normalize(p);
}
/**
* Returns a Path that is the resolution of p2, from p1. If p2 is absolute, it will return p2,
* otherwise will join both p1 and p2.
*/
export function resolve(p1: Path, p2: Path) {
if (isAbsolute(p2)) {
return p2;
} else {
return join(p1, p2);
}
}
export function fragment(path: string): PathFragment {
if (path.indexOf(NormalizedSep) != -1) {
throw new PathCannotBeFragmentException(path);
}
return path as PathFragment;
}
/**
* normalize() cache to reduce computation. For now this grows and we never flush it, but in the
* future we might want to add a few cache flush to prevent this from growing too large.
*/
let normalizedCache = new Map<string, Path>();
/**
* Reset the cache. This is only useful for testing.
* @private
*/
export function resetNormalizeCache() {
normalizedCache = new Map<string, Path>();
}
/**
* Normalize a string into a Path. This is the only mean to get a Path type from a string that
* represents a system path. This method cache the results as real world paths tend to be
* duplicated often.
* Normalization includes:
* - Windows backslashes `\\` are replaced with `/`.
* - Windows drivers are replaced with `/X/`, where X is the drive letter.
* - Absolute paths starts with `/`.
* - Multiple `/` are replaced by a single one.
* - Path segments `.` are removed.
* - Path segments `..` are resolved.
* - If a path is absolute, having a `..` at the start is invalid (and will throw).
* @param path The path to be normalized.
*/
export function normalize(path: string): Path {
let maybePath = normalizedCache.get(path);
if (!maybePath) {
maybePath = noCacheNormalize(path);
normalizedCache.set(path, maybePath);
}
return maybePath;
}
/**
* The no cache version of the normalize() function. Used for benchmarking and testing.
*/
export function noCacheNormalize(path: string): Path {
if (path == '' || path == '.') {
return '' as Path;
} else if (path == NormalizedRoot) {
return NormalizedRoot;
}
// Match absolute windows path.
const original = path;
if (path.match(/^[A-Z]:[/\\]/i)) {
path = '\\' + path[0] + '\\' + path.slice(3);
}
// We convert Windows paths as well here.
const p = path.split(/[/\\]/g);
let relative = false;
let i = 1;
// Special case the first one.
if (p[0] != '') {
p.unshift('.');
relative = true;
}
while (i < p.length) {
if (p[i] == '.') {
p.splice(i, 1);
} else if (p[i] == '..') {
if (i < 2 && !relative) {
throw new InvalidPathException(original);
} else if (i >= 2 && p[i - 1] != '..') {
p.splice(i - 1, 2);
i--;
} else {
i++;
}
} else if (p[i] == '') {
p.splice(i, 1);
} else {
i++;
}
}
if (p.length == 1) {
return p[0] == '' ? NormalizedSep : ('' as Path);
} else {
if (p[0] == '.') {
p.shift();
}
return p.join(NormalizedSep) as Path;
}
}
export const path: TemplateTag<Path> = (strings, ...values) => {
return normalize(String.raw(strings, ...values));
};
// Platform-specific paths.
export type WindowsPath = string & {
__PRIVATE_DEVKIT_WINDOWS_PATH: void;
};
export type PosixPath = string & {
__PRIVATE_DEVKIT_POSIX_PATH: void;
};
export function asWindowsPath(path: Path): WindowsPath {
const drive = path.match(/^\/(\w)(?:\/(.*))?$/);
if (drive) {
const subPath = drive[2] ? drive[2].replace(/\//g, '\\') : '';
return `${drive[1]}:\\${subPath}` as WindowsPath;
}
return path.replace(/\//g, '\\') as WindowsPath;
}
export function asPosixPath(path: Path): PosixPath {
return path as string as PosixPath;
}
export function getSystemPath(path: Path): string {
if (process.platform.startsWith('win32')) {
return asWindowsPath(path);
} else {
return asPosixPath(path);
}
}
| {
"end_byte": 7763,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/path.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/index.ts_0_294 | /**
* @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 virtualFs from './host/index';
export * from './path';
export { virtualFs };
| {
"end_byte": 294,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/path_spec.ts_0_5475 | /**
* @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 {
InvalidPathException,
Path,
PathFragment,
asWindowsPath,
basename,
dirname,
join,
normalize,
relative,
split,
} from './path';
describe('path', () => {
it('normalize', () => {
expect(normalize('////')).toBe('/');
expect(normalize('././././.')).toBe('');
expect(normalize('/./././.')).toBe('/');
// Regular use cases.
expect(normalize('a')).toBe('a');
expect(normalize('a/b/c')).toBe('a/b/c');
expect(normalize('/a/b/c')).toBe('/a/b/c');
expect(normalize('./a/b/c')).toBe('a/b/c');
expect(normalize('/./a/b/c')).toBe('/a/b/c');
expect(normalize('/./a/b/c/')).toBe('/a/b/c');
expect(normalize('/./a/b/./c')).toBe('/a/b/c');
expect(normalize('./a/b/./c')).toBe('a/b/c');
expect(normalize('/./a/b/d/../c')).toBe('/a/b/c');
expect(normalize('/./a/b/./d/../c')).toBe('/a/b/c');
expect(normalize('././a/b/./d/../c')).toBe('a/b/c');
expect(normalize('a/')).toBe('a');
expect(normalize('a/./..')).toBe('');
// Reducing to nothing use cases.
expect(normalize('')).toBe('');
expect(normalize('.')).toBe('');
expect(normalize('/.')).toBe('/');
expect(normalize('/./.')).toBe('/');
expect(normalize('/././.')).toBe('/');
expect(normalize('/c/..')).toBe('/');
// Out of directory.
expect(normalize('..')).toBe('..');
expect(normalize('../..')).toBe('../..');
expect(normalize('../../a')).toBe('../../a');
expect(normalize('b/../../a')).toBe('../a');
expect(normalize('./..')).toBe('..');
expect(normalize('../a/b/c')).toBe('../a/b/c');
expect(normalize('./a/../../a/b/c')).toBe('../a/b/c');
// Invalid use cases.
expect(() => normalize('/./././../././/')).toThrow(new InvalidPathException('/./././../././/'));
expect(() => normalize('/./././../././/../')).toThrow(
new InvalidPathException('/./././../././/../'),
);
expect(() => normalize('/./././../././a/.')).toThrow(
new InvalidPathException('/./././../././a/.'),
);
expect(() => normalize('/c/../../')).toThrow(new InvalidPathException('/c/../../'));
// Windows use cases.
expect(normalize('a\\b\\c')).toBe('a/b/c');
expect(normalize('\\a\\b\\c')).toBe('/a/b/c');
expect(normalize('.\\a\\b\\c')).toBe('a/b/c');
expect(normalize('C:\\a\\b\\c')).toBe('/C/a/b/c');
expect(normalize('c:\\a\\b\\c')).toBe('/c/a/b/c');
expect(normalize('A:\\a\\b\\c')).toBe('/A/a/b/c');
expect(() => normalize('A:\\..\\..')).toThrow(new InvalidPathException('A:\\..\\..'));
expect(normalize('\\.\\a\\b\\c')).toBe('/a/b/c');
expect(normalize('\\.\\a\\b\\.\\c')).toBe('/a/b/c');
expect(normalize('\\.\\a\\b\\d\\..\\c')).toBe('/a/b/c');
expect(normalize('\\.\\a\\b\\.\\d\\..\\c')).toBe('/a/b/c');
expect(normalize('a\\')).toBe('a');
});
describe('split', () => {
const tests: [string, string[]][] = [
['a', ['a']],
['/a/b', ['', 'a', 'b']],
['a/b', ['a', 'b']],
['a/b/', ['a', 'b']],
['', []],
['/', ['']],
];
for (const [input, result] of tests) {
const normalizedInput = normalize(input);
it(`(${JSON.stringify(normalizedInput)}) == "${result}"`, () => {
expect(split(normalizedInput)).toEqual(result as PathFragment[]);
});
}
});
describe('join', () => {
const tests: [string[], string][] = [
[['a'], 'a'],
[['/a', '/b'], '/a/b'],
[['/a', '/b', '/c'], '/a/b/c'],
[['/a', 'b', 'c'], '/a/b/c'],
[['a', 'b', 'c'], 'a/b/c'],
];
for (const [input, result] of tests) {
const args = input.map((x) => normalize(x)) as [Path, ...Path[]];
it(`(${JSON.stringify(args)}) == "${result}"`, () => {
expect(join(...args)).toBe(result);
});
}
});
describe('relative', () => {
const tests = [
['/a/b/c', '/a/b/c', ''],
['/a/b', '/a/b/c', 'c'],
['/a/b', '/a/b/c/d', 'c/d'],
['/a/b/c', '/a/b', '..'],
['/a/b/c', '/a/b/d', '../d'],
['/a/b/c/d/e', '/a/f/g', '../../../../f/g'],
['/src/app/sub1/test1', '/src/app/sub2/test2', '../../sub2/test2'],
['/', '/a/b/c', 'a/b/c'],
['/a/b/c', '/d', '../../../d'],
];
for (const [from, to, result] of tests) {
it(`("${from}", "${to}") == "${result}"`, () => {
const f = normalize(from);
const t = normalize(to);
expect(relative(f, t)).toBe(result);
expect(join(f, relative(f, t))).toBe(t);
});
}
});
it('dirname', () => {
expect(dirname(normalize('a'))).toBe('');
expect(dirname(normalize('/a'))).toBe('/');
expect(dirname(normalize('/a/b/c'))).toBe('/a/b');
expect(dirname(normalize('./c'))).toBe('');
expect(dirname(normalize('./a/b/c'))).toBe('a/b');
});
it('basename', () => {
expect(basename(normalize('a'))).toBe('a');
expect(basename(normalize('/a/b/c'))).toBe('c');
expect(basename(normalize('./c'))).toBe('c');
expect(basename(normalize('.'))).toBe('');
expect(basename(normalize('./a/b/c'))).toBe('c');
});
it('asWindowsPath', () => {
expect(asWindowsPath(normalize('c:/'))).toBe('c:\\');
expect(asWindowsPath(normalize('c:/b/'))).toBe('c:\\b');
expect(asWindowsPath(normalize('c:/b/c'))).toBe('c:\\b\\c');
});
});
| {
"end_byte": 5475,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/path_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/memory_spec.ts_0_5543 | /**
* @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 { fragment, normalize } from '../path';
import { stringToFileBuffer } from './buffer';
import { SimpleMemoryHost } from './memory';
import { SyncDelegateHost } from './sync';
describe('SimpleMemoryHost', () => {
it('can watch', () => {
const host = new SyncDelegateHost(new SimpleMemoryHost());
host.write(normalize('/sub/file1'), stringToFileBuffer(''));
let recursiveCalled = 0;
let noRecursiveCalled = 0;
let noRecursiveFileCalled = 0;
let diffFile = 0;
host.watch(normalize('/sub'), { recursive: true })!.subscribe(() => recursiveCalled++);
host.watch(normalize('/sub'))!.subscribe(() => noRecursiveCalled++);
host.watch(normalize('/sub/file2'))!.subscribe(() => noRecursiveFileCalled++);
host.watch(normalize('/sub/file3'))!.subscribe(() => diffFile++);
host.write(normalize('/sub/file2'), stringToFileBuffer(''));
expect(recursiveCalled).toBe(1);
expect(noRecursiveCalled).toBe(0);
expect(noRecursiveFileCalled).toBe(1);
expect(diffFile).toBe(0);
host.write(normalize('/sub/file3'), stringToFileBuffer(''));
expect(recursiveCalled).toBe(2);
expect(noRecursiveCalled).toBe(0);
expect(noRecursiveFileCalled).toBe(1);
expect(diffFile).toBe(1);
});
it('can read', () => {
const host = new SyncDelegateHost(new SimpleMemoryHost());
const buffer = stringToFileBuffer('hello');
host.write(normalize('/hello'), buffer);
expect(host.read(normalize('/hello'))).toBe(buffer);
});
it('can delete', () => {
const host = new SyncDelegateHost(new SimpleMemoryHost());
const buffer = stringToFileBuffer('hello');
expect(host.exists(normalize('/sub/file1'))).toBe(false);
host.write(normalize('/sub/file1'), buffer);
expect(host.exists(normalize('/sub/file1'))).toBe(true);
host.delete(normalize('/sub/file1'));
expect(host.exists(normalize('/sub/file1'))).toBe(false);
});
it('can delete directory', () => {
const host = new SyncDelegateHost(new SimpleMemoryHost());
const buffer = stringToFileBuffer('hello');
expect(host.exists(normalize('/sub/file1'))).toBe(false);
host.write(normalize('/sub/file1'), buffer);
host.write(normalize('/subfile.2'), buffer);
expect(host.exists(normalize('/sub/file1'))).toBe(true);
expect(host.exists(normalize('/subfile.2'))).toBe(true);
host.delete(normalize('/sub'));
expect(host.exists(normalize('/sub/file1'))).toBe(false);
expect(host.exists(normalize('/sub'))).toBe(false);
expect(host.exists(normalize('/subfile.2'))).toBe(true);
});
it('can rename', () => {
const host = new SyncDelegateHost(new SimpleMemoryHost());
const buffer = stringToFileBuffer('hello');
expect(host.exists(normalize('/sub/file1'))).toBe(false);
host.write(normalize('/sub/file1'), buffer);
expect(host.exists(normalize('/sub/file1'))).toBe(true);
host.rename(normalize('/sub/file1'), normalize('/sub/file2'));
expect(host.exists(normalize('/sub/file1'))).toBe(false);
expect(host.exists(normalize('/sub/file2'))).toBe(true);
expect(host.read(normalize('/sub/file2'))).toBe(buffer);
});
it('can list', () => {
const host = new SyncDelegateHost(new SimpleMemoryHost());
const buffer = stringToFileBuffer('hello');
host.write(normalize('/sub/file1'), buffer);
host.write(normalize('/sub/file2'), buffer);
host.write(normalize('/sub/sub1/file3'), buffer);
host.write(normalize('/file4'), buffer);
expect(host.list(normalize('/sub'))).toEqual([
fragment('file1'),
fragment('file2'),
fragment('sub1'),
]);
expect(host.list(normalize('/'))).toEqual([fragment('sub'), fragment('file4')]);
expect(host.list(normalize('/inexistent'))).toEqual([]);
});
it('supports isFile / isDirectory', () => {
const host = new SyncDelegateHost(new SimpleMemoryHost());
const buffer = stringToFileBuffer('hello');
host.write(normalize('/sub/file1'), buffer);
host.write(normalize('/sub/file2'), buffer);
host.write(normalize('/sub/sub1/file3'), buffer);
host.write(normalize('/file4'), buffer);
expect(host.isFile(normalize('/sub'))).toBe(false);
expect(host.isFile(normalize('/sub1'))).toBe(false);
expect(host.isDirectory(normalize('/'))).toBe(true);
expect(host.isDirectory(normalize('/sub'))).toBe(true);
expect(host.isDirectory(normalize('/sub/sub1'))).toBe(true);
expect(host.isDirectory(normalize('/sub/file1'))).toBe(false);
expect(host.isDirectory(normalize('/sub/sub1/file3'))).toBe(false);
});
it('makes every path absolute', () => {
const host = new SyncDelegateHost(new SimpleMemoryHost());
const buffer = stringToFileBuffer('hello');
const buffer2 = stringToFileBuffer('hello 2');
host.write(normalize('file1'), buffer);
host.write(normalize('/sub/file2'), buffer);
host.write(normalize('sub/file2'), buffer2);
expect(host.isFile(normalize('file1'))).toBe(true);
expect(host.isFile(normalize('/file1'))).toBe(true);
expect(host.isFile(normalize('/sub/file2'))).toBe(true);
expect(host.read(normalize('sub/file2'))).toBe(buffer2);
expect(host.isDirectory(normalize('/sub'))).toBe(true);
expect(host.isDirectory(normalize('sub'))).toBe(true);
});
});
| {
"end_byte": 5543,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/memory_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/record.ts_0_8387 | /**
* @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 {
EMPTY,
Observable,
concat,
concatMap,
map,
from as observableFrom,
of,
reduce,
switchMap,
throwError,
toArray,
} from 'rxjs';
import {
FileAlreadyExistException,
FileDoesNotExistException,
PathIsDirectoryException,
UnknownException,
} from '../../exception';
import { Path, PathFragment } from '../path';
import {
FileBuffer,
Host,
HostCapabilities,
HostWatchOptions,
ReadonlyHost,
Stats,
} from './interface';
import { SimpleMemoryHost } from './memory';
export interface CordHostCreate {
kind: 'create';
path: Path;
content: FileBuffer;
}
export interface CordHostOverwrite {
kind: 'overwrite';
path: Path;
content: FileBuffer;
}
export interface CordHostRename {
kind: 'rename';
from: Path;
to: Path;
}
export interface CordHostDelete {
kind: 'delete';
path: Path;
}
export type CordHostRecord = CordHostCreate | CordHostOverwrite | CordHostRename | CordHostDelete;
/**
* A Host that records changes to the underlying Host, while keeping a record of Create, Overwrite,
* Rename and Delete of files.
*
* This is fully compatible with Host, but will keep a staging of every changes asked. That staging
* follows the principle of the Tree (e.g. can create a file that already exists).
*
* Using `create()` and `overwrite()` will force those operations, but using `write` will add
* the create/overwrite records IIF the files does/doesn't already exist.
*/
export class CordHost extends SimpleMemoryHost {
protected _filesToCreate = new Set<Path>();
protected _filesToRename = new Map<Path, Path>();
protected _filesToRenameRevert = new Map<Path, Path>();
protected _filesToDelete = new Set<Path>();
protected _filesToOverwrite = new Set<Path>();
constructor(protected _back: ReadonlyHost) {
super();
}
get backend(): ReadonlyHost {
return this._back;
}
override get capabilities(): HostCapabilities {
// Our own host is always Synchronous, but the backend might not be.
return {
synchronous: this._back.capabilities.synchronous,
};
}
/**
* Create a copy of this host, including all actions made.
* @returns {CordHost} The carbon copy.
*/
clone(): CordHost {
const dolly = new CordHost(this._back);
dolly._cache = new Map(this._cache);
dolly._filesToCreate = new Set(this._filesToCreate);
dolly._filesToRename = new Map(this._filesToRename);
dolly._filesToRenameRevert = new Map(this._filesToRenameRevert);
dolly._filesToDelete = new Set(this._filesToDelete);
dolly._filesToOverwrite = new Set(this._filesToOverwrite);
return dolly;
}
/**
* Commit the changes recorded to a Host. It is assumed that the host does have the same structure
* as the host that was used for backend (could be the same host).
* @param host The host to create/delete/rename/overwrite files to.
* @param force Whether to skip existence checks when creating/overwriting. This is
* faster but might lead to incorrect states. Because Hosts natively don't support creation
* versus overwriting (it's only writing), we check for existence before completing a request.
* @returns An observable that completes when done, or error if an error occured.
*/
commit(host: Host, force = false): Observable<void> {
// Really commit everything to the actual host.
return observableFrom(this.records()).pipe(
concatMap((record) => {
switch (record.kind) {
case 'delete':
return host.delete(record.path);
case 'rename':
return host.rename(record.from, record.to);
case 'create':
return host.exists(record.path).pipe(
switchMap((exists) => {
if (exists && !force) {
return throwError(new FileAlreadyExistException(record.path));
} else {
return host.write(record.path, record.content);
}
}),
);
case 'overwrite':
return host.exists(record.path).pipe(
switchMap((exists) => {
if (!exists && !force) {
return throwError(new FileDoesNotExistException(record.path));
} else {
return host.write(record.path, record.content);
}
}),
);
}
}),
reduce(() => {}),
);
}
records(): CordHostRecord[] {
return [
...[...this._filesToDelete.values()].map(
(path) =>
({
kind: 'delete',
path,
}) as CordHostRecord,
),
...[...this._filesToRename.entries()].map(
([from, to]) =>
({
kind: 'rename',
from,
to,
}) as CordHostRecord,
),
...[...this._filesToCreate.values()].map(
(path) =>
({
kind: 'create',
path,
content: this._read(path),
}) as CordHostRecord,
),
...[...this._filesToOverwrite.values()].map(
(path) =>
({
kind: 'overwrite',
path,
content: this._read(path),
}) as CordHostRecord,
),
];
}
/**
* Specialized version of {@link CordHost#write} which forces the creation of a file whether it
* exists or not.
* @param {} path
* @param {FileBuffer} content
* @returns {Observable<void>}
*/
create(path: Path, content: FileBuffer): Observable<void> {
if (super._exists(path)) {
throw new FileAlreadyExistException(path);
}
if (this._filesToDelete.has(path)) {
this._filesToDelete.delete(path);
this._filesToOverwrite.add(path);
} else {
this._filesToCreate.add(path);
}
return super.write(path, content);
}
overwrite(path: Path, content: FileBuffer): Observable<void> {
return this.isDirectory(path).pipe(
switchMap((isDir) => {
if (isDir) {
return throwError(new PathIsDirectoryException(path));
}
return this.exists(path);
}),
switchMap((exists) => {
if (!exists) {
return throwError(new FileDoesNotExistException(path));
}
if (!this._filesToCreate.has(path)) {
this._filesToOverwrite.add(path);
}
return super.write(path, content);
}),
);
}
override write(path: Path, content: FileBuffer): Observable<void> {
return this.exists(path).pipe(
switchMap((exists) => {
if (exists) {
// It exists, but might be being renamed or deleted. In that case we want to create it.
if (this.willRename(path) || this.willDelete(path)) {
return this.create(path, content);
} else {
return this.overwrite(path, content);
}
} else {
return this.create(path, content);
}
}),
);
}
override read(path: Path): Observable<FileBuffer> {
if (this._exists(path)) {
return super.read(path);
}
return this._back.read(path);
}
override delete(path: Path): Observable<void> {
if (this._exists(path)) {
if (this._filesToCreate.has(path)) {
this._filesToCreate.delete(path);
} else if (this._filesToOverwrite.has(path)) {
this._filesToOverwrite.delete(path);
this._filesToDelete.add(path);
} else {
const maybeOrigin = this._filesToRenameRevert.get(path);
if (maybeOrigin) {
this._filesToRenameRevert.delete(path);
this._filesToRename.delete(maybeOrigin);
this._filesToDelete.add(maybeOrigin);
} else {
return throwError(
new UnknownException(`This should never happen. Path: ${JSON.stringify(path)}.`),
);
}
}
return super.delete(path);
} else {
return this._back.exists(path).pipe(
switchMap((exists) => {
if (exists) {
this._filesToDelete.add(path);
return of<void>();
} else {
return throwError(new FileDoesNotExistException(path));
}
}),
);
}
} | {
"end_byte": 8387,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/record.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/record.ts_8391_12425 | override rename(from: Path, to: Path): Observable<void> {
return concat(this.exists(to), this.exists(from)).pipe(
toArray(),
switchMap(([existTo, existFrom]) => {
if (!existFrom) {
return throwError(new FileDoesNotExistException(from));
}
if (from === to) {
return EMPTY;
}
if (existTo) {
return throwError(new FileAlreadyExistException(to));
}
// If we're renaming a file that's been created, shortcircuit to creating the `to` path.
if (this._filesToCreate.has(from)) {
this._filesToCreate.delete(from);
this._filesToCreate.add(to);
return super.rename(from, to);
}
if (this._filesToOverwrite.has(from)) {
this._filesToOverwrite.delete(from);
// Recursively call this function. This is so we don't repeat the bottom logic. This
// if will be by-passed because we just deleted the `from` path from files to overwrite.
return concat(
this.rename(from, to),
new Observable<never>((x) => {
this._filesToOverwrite.add(to);
x.complete();
}),
);
}
if (this._filesToDelete.has(to)) {
this._filesToDelete.delete(to);
this._filesToDelete.add(from);
this._filesToOverwrite.add(to);
// We need to delete the original and write the new one.
return this.read(from).pipe(map((content) => this._write(to, content)));
}
const maybeTo1 = this._filesToRenameRevert.get(from);
if (maybeTo1) {
// We already renamed to this file (A => from), let's rename the former to the new
// path (A => to).
this._filesToRename.delete(maybeTo1);
this._filesToRenameRevert.delete(from);
from = maybeTo1;
}
this._filesToRename.set(from, to);
this._filesToRenameRevert.set(to, from);
// If the file is part of our data, just rename it internally.
if (this._exists(from)) {
return super.rename(from, to);
} else {
// Create a file with the same content.
return this._back.read(from).pipe(switchMap((content) => super.write(to, content)));
}
}),
);
}
override list(path: Path): Observable<PathFragment[]> {
return concat(super.list(path), this._back.list(path)).pipe(
reduce((list: Set<PathFragment>, curr: PathFragment[]) => {
curr.forEach((elem) => list.add(elem));
return list;
}, new Set<PathFragment>()),
map((set) => [...set]),
);
}
override exists(path: Path): Observable<boolean> {
return this._exists(path)
? of(true)
: this.willDelete(path) || this.willRename(path)
? of(false)
: this._back.exists(path);
}
override isDirectory(path: Path): Observable<boolean> {
return this._exists(path) ? super.isDirectory(path) : this._back.isDirectory(path);
}
override isFile(path: Path): Observable<boolean> {
return this._exists(path)
? super.isFile(path)
: this.willDelete(path) || this.willRename(path)
? of(false)
: this._back.isFile(path);
}
override stat(path: Path): Observable<Stats | null> | null {
return this._exists(path)
? super.stat(path)
: this.willDelete(path) || this.willRename(path)
? of(null)
: this._back.stat(path);
}
override watch(path: Path, options?: HostWatchOptions) {
// Watching not supported.
return null;
}
willCreate(path: Path): boolean {
return this._filesToCreate.has(path);
}
willOverwrite(path: Path): boolean {
return this._filesToOverwrite.has(path);
}
willDelete(path: Path): boolean {
return this._filesToDelete.has(path);
}
willRename(path: Path): boolean {
return this._filesToRename.has(path);
}
willRenameTo(path: Path, to: Path): boolean {
return this._filesToRename.get(path) === to;
}
} | {
"end_byte": 12425,
"start_byte": 8391,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/record.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/resolver.ts_0_2059 | /**
* @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 { Observable } from 'rxjs';
import { Path, PathFragment } from '../path';
import {
FileBuffer,
Host,
HostCapabilities,
HostWatchEvent,
HostWatchOptions,
Stats,
} from './interface';
/**
* A Host that runs a method before calling its delegate. This is an abstract class and its actual
* behaviour is entirely dependant of the subclass.
*/
export abstract class ResolverHost<T extends object> implements Host<T> {
protected abstract _resolve(path: Path): Path;
constructor(protected _delegate: Host<T>) {}
get capabilities(): HostCapabilities {
return this._delegate.capabilities;
}
write(path: Path, content: FileBuffer): Observable<void> {
return this._delegate.write(this._resolve(path), content);
}
read(path: Path): Observable<FileBuffer> {
return this._delegate.read(this._resolve(path));
}
delete(path: Path): Observable<void> {
return this._delegate.delete(this._resolve(path));
}
rename(from: Path, to: Path): Observable<void> {
return this._delegate.rename(this._resolve(from), this._resolve(to));
}
list(path: Path): Observable<PathFragment[]> {
return this._delegate.list(this._resolve(path));
}
exists(path: Path): Observable<boolean> {
return this._delegate.exists(this._resolve(path));
}
isDirectory(path: Path): Observable<boolean> {
return this._delegate.isDirectory(this._resolve(path));
}
isFile(path: Path): Observable<boolean> {
return this._delegate.isFile(this._resolve(path));
}
// Some hosts may not support stat.
stat(path: Path): Observable<Stats<T> | null> | null {
return this._delegate.stat(this._resolve(path));
}
// Some hosts may not support watching.
watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null {
return this._delegate.watch(this._resolve(path), options);
}
}
| {
"end_byte": 2059,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/resolver.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/buffer.ts_0_671 | /**
* @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 { TextDecoder, TextEncoder } from 'node:util';
import { FileBuffer } from './interface';
export function stringToFileBuffer(str: string): FileBuffer {
return new TextEncoder().encode(str).buffer;
}
export function fileBufferToString(fileBuffer: FileBuffer): string {
if (fileBuffer.toString.length === 1) {
return (fileBuffer.toString as (enc: string) => string)('utf-8');
}
return new TextDecoder('utf-8').decode(new Uint8Array(fileBuffer));
}
| {
"end_byte": 671,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/buffer.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/test.ts_0_4238 | /**
* @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 { Observable } from 'rxjs';
import { Path, PathFragment, join, normalize } from '../path';
import { fileBufferToString, stringToFileBuffer } from './buffer';
import { FileBuffer, HostWatchEvent, HostWatchOptions, Stats } from './interface';
import { SimpleMemoryHost, SimpleMemoryHostStats } from './memory';
import { SyncDelegateHost } from './sync';
export type TestLogRecord =
| {
kind:
| 'write'
| 'read'
| 'delete'
| 'list'
| 'exists'
| 'isDirectory'
| 'isFile'
| 'stat'
| 'watch';
path: Path;
}
| {
kind: 'rename';
from: Path;
to: Path;
};
export class TestHost extends SimpleMemoryHost {
protected _records: TestLogRecord[] = [];
protected _sync: SyncDelegateHost<{}> | null = null;
constructor(map: { [path: string]: string } = {}) {
super();
for (const filePath of Object.getOwnPropertyNames(map)) {
this._write(normalize(filePath), stringToFileBuffer(map[filePath]));
}
}
get records(): TestLogRecord[] {
return [...this._records];
}
clearRecords(): void {
this._records = [];
}
get files(): Path[] {
const sync = this.sync;
function _visit(p: Path): Path[] {
return sync
.list(p)
.map((fragment) => join(p, fragment))
.reduce((files, path) => {
if (sync.isDirectory(path)) {
return files.concat(_visit(path));
} else {
return files.concat(path);
}
}, [] as Path[]);
}
return _visit(normalize('/'));
}
get sync(): SyncDelegateHost<{}> {
if (!this._sync) {
this._sync = new SyncDelegateHost<{}>(this);
}
return this._sync;
}
clone(): TestHost {
const newHost = new TestHost();
newHost._cache = new Map(this._cache);
return newHost;
}
// Override parents functions to keep a record of all operators that were done.
protected override _write(path: Path, content: FileBuffer): void {
this._records.push({ kind: 'write', path });
return super._write(path, content);
}
protected override _read(path: Path): ArrayBuffer {
this._records.push({ kind: 'read', path });
return super._read(path);
}
protected override _delete(path: Path): void {
this._records.push({ kind: 'delete', path });
return super._delete(path);
}
protected override _rename(from: Path, to: Path): void {
this._records.push({ kind: 'rename', from, to });
return super._rename(from, to);
}
protected override _list(path: Path): PathFragment[] {
this._records.push({ kind: 'list', path });
return super._list(path);
}
protected override _exists(path: Path): boolean {
this._records.push({ kind: 'exists', path });
return super._exists(path);
}
protected override _isDirectory(path: Path): boolean {
this._records.push({ kind: 'isDirectory', path });
return super._isDirectory(path);
}
protected override _isFile(path: Path): boolean {
this._records.push({ kind: 'isFile', path });
return super._isFile(path);
}
protected override _stat(path: Path): Stats<SimpleMemoryHostStats> | null {
this._records.push({ kind: 'stat', path });
return super._stat(path);
}
protected override _watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> {
this._records.push({ kind: 'watch', path });
return super._watch(path, options);
}
$write(path: string, content: string): void {
return super._write(normalize(path), stringToFileBuffer(content));
}
$read(path: string): string {
return fileBufferToString(super._read(normalize(path)));
}
$list(path: string): PathFragment[] {
return super._list(normalize(path));
}
$exists(path: string): boolean {
return super._exists(normalize(path));
}
$isDirectory(path: string): boolean {
return super._isDirectory(normalize(path));
}
$isFile(path: string): boolean {
return super._isFile(normalize(path));
}
}
| {
"end_byte": 4238,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/test.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/pattern.ts_0_1065 | /**
* @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 { parse as parseGlob } from 'picomatch';
import { Path } from '../path';
import { ResolverHost } from './resolver';
export type ReplacementFunction = (path: Path) => Path;
/**
*/
export class PatternMatchingHost<StatsT extends object = {}> extends ResolverHost<StatsT> {
protected _patterns = new Map<RegExp, ReplacementFunction>();
addPattern(pattern: string | string[], replacementFn: ReplacementFunction): void {
const patterns = Array.isArray(pattern) ? pattern : [pattern];
for (const glob of patterns) {
const { output } = parseGlob(glob);
this._patterns.set(new RegExp(`^${output}$`), replacementFn);
}
}
protected _resolve(path: Path): Path {
let newPath = path;
this._patterns.forEach((fn, re) => {
if (re.test(path)) {
newPath = fn(newPath);
}
});
return newPath;
}
}
| {
"end_byte": 1065,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/pattern.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/scoped.ts_0_602 | /**
* @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 { NormalizedRoot, Path, join } from '../path';
import { Host } from './interface';
import { ResolverHost } from './resolver';
export class ScopedHost<T extends object> extends ResolverHost<T> {
constructor(
delegate: Host<T>,
protected _root: Path = NormalizedRoot,
) {
super(delegate);
}
protected _resolve(path: Path): Path {
return join(this._root, path);
}
}
| {
"end_byte": 602,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/scoped.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/test_spec.ts_0_581 | /**
* @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 test from './test';
// Yes, we realize the irony of testing a test host.
describe('TestHost', () => {
it('can list files', () => {
const files = {
'/x/y/z': '',
'/a': '',
'/h': '',
'/x/y/b': '',
};
const host = new test.TestHost(files);
expect(host.files.sort() as string[]).toEqual(Object.keys(files).sort());
});
});
| {
"end_byte": 581,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/test_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/empty.ts_0_1086 | /**
* @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 { Observable, of, throwError } from 'rxjs';
import { FileDoesNotExistException } from '../../exception';
import { Path, PathFragment } from '../path';
import { FileBuffer, HostCapabilities, ReadonlyHost, Stats } from './interface';
export class Empty implements ReadonlyHost {
readonly capabilities: HostCapabilities = {
synchronous: true,
};
read(path: Path): Observable<FileBuffer> {
return throwError(new FileDoesNotExistException(path));
}
list(path: Path): Observable<PathFragment[]> {
return of([]);
}
exists(path: Path): Observable<boolean> {
return of(false);
}
isDirectory(path: Path): Observable<boolean> {
return of(false);
}
isFile(path: Path): Observable<boolean> {
return of(false);
}
stat(path: Path): Observable<Stats<{}> | null> {
// We support stat() but have no file.
return of(null);
}
}
| {
"end_byte": 1086,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/empty.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/interface.ts_0_1819 | /**
* @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 { Observable } from 'rxjs';
import { Path, PathFragment } from '../path';
export type FileBuffer = ArrayBuffer;
export type FileBufferLike = ArrayBufferLike;
export interface HostWatchOptions {
readonly persistent?: boolean;
readonly recursive?: boolean;
}
export enum HostWatchEventType {
Changed = 0,
Created = 1,
Deleted = 2,
Renamed = 3, // Applied to the original file path.
}
export type Stats<T extends object = {}> = T & {
isFile(): boolean;
isDirectory(): boolean;
readonly size: number;
readonly atime: Date;
readonly mtime: Date;
readonly ctime: Date;
readonly birthtime: Date;
};
export interface HostWatchEvent {
readonly time: Date;
readonly type: HostWatchEventType;
readonly path: Path;
}
export interface HostCapabilities {
synchronous: boolean;
}
export interface ReadonlyHost<StatsT extends object = {}> {
readonly capabilities: HostCapabilities;
read(path: Path): Observable<FileBuffer>;
list(path: Path): Observable<PathFragment[]>;
exists(path: Path): Observable<boolean>;
isDirectory(path: Path): Observable<boolean>;
isFile(path: Path): Observable<boolean>;
// Some hosts may not support stats.
stat(path: Path): Observable<Stats<StatsT> | null> | null;
}
export interface Host<StatsT extends object = {}> extends ReadonlyHost<StatsT> {
write(path: Path, content: FileBufferLike): Observable<void>;
delete(path: Path): Observable<void>;
rename(from: Path, to: Path): Observable<void>;
// Some hosts may not support watching.
watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null;
}
| {
"end_byte": 1819,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/interface.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/pattern_spec.ts_0_1477 | /**
* @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 { normalize } from '..';
import { stringToFileBuffer } from './buffer';
import { SimpleMemoryHost } from './memory';
import { PatternMatchingHost } from './pattern';
describe('PatternMatchingHost', () => {
it('works for NativeScript', () => {
const content = stringToFileBuffer('hello world');
const content2 = stringToFileBuffer('hello world 2');
const host = new SimpleMemoryHost();
host.write(normalize('/some/file.tns.ts'), content).subscribe();
const pHost = new PatternMatchingHost(host);
pHost.read(normalize('/some/file.tns.ts')).subscribe((x) => expect(x).toBe(content));
pHost.addPattern('**/*.tns.ts', (path) => {
return normalize(path.replace(/\.tns\.ts$/, '.ts'));
});
// This file will not exist because /some/file.ts does not exist.
try {
pHost.read(normalize('/some/file.tns.ts')).subscribe(undefined, (err) => {
expect(err.message).toMatch(/does not exist/);
});
} catch {
// Ignore it. RxJS <6 still throw errors when they happen synchronously.
}
// Create the file, it should exist now.
pHost.write(normalize('/some/file.ts'), content2).subscribe();
pHost.read(normalize('/some/file.tns.ts')).subscribe((x) => expect(x).toBe(content2));
});
});
| {
"end_byte": 1477,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/pattern_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/alias_spec.ts_0_2073 | /**
* @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 { normalize } from '..';
import { AliasHost } from './alias';
import { stringToFileBuffer } from './buffer';
import { SimpleMemoryHost } from './memory';
describe('AliasHost', () => {
it('works as in the example', () => {
const content = stringToFileBuffer('hello world');
const host = new SimpleMemoryHost();
host.write(normalize('/some/file'), content).subscribe();
const aHost = new AliasHost(host);
aHost.read(normalize('/some/file')).subscribe((x) => expect(x).toBe(content));
aHost.aliases.set(normalize('/some/file'), normalize('/other/path'));
// This file will not exist because /other/path does not exist.
try {
aHost.read(normalize('/some/file')).subscribe(undefined, (err) => {
expect(err.message).toMatch(/does not exist/);
});
} catch {
// Ignore it. RxJS <6 still throw errors when they happen synchronously.
}
});
it('works as in the example (2)', () => {
const content = stringToFileBuffer('hello world');
const content2 = stringToFileBuffer('hello world 2');
const host = new SimpleMemoryHost();
host.write(normalize('/some/folder/file'), content).subscribe();
const aHost = new AliasHost(host);
aHost.read(normalize('/some/folder/file')).subscribe((x) => expect(x).toBe(content));
aHost.aliases.set(normalize('/some'), normalize('/other'));
// This file will not exist because /other/path does not exist.
try {
aHost
.read(normalize('/some/folder/file'))
.subscribe(undefined, (err) => expect(err.message).toMatch(/does not exist/));
} catch {}
// Create the file with new content and verify that this has the new content.
aHost.write(normalize('/other/folder/file'), content2).subscribe();
aHost.read(normalize('/some/folder/file')).subscribe((x) => expect(x).toBe(content2));
});
});
| {
"end_byte": 2073,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/alias_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/memory.ts_0_757 | /**
* @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 { Observable, Subject } from 'rxjs';
import {
FileAlreadyExistException,
FileDoesNotExistException,
PathIsDirectoryException,
PathIsFileException,
} from '../../exception';
import {
NormalizedRoot,
NormalizedSep,
Path,
PathFragment,
dirname,
isAbsolute,
join,
normalize,
split,
} from '../path';
import {
FileBuffer,
Host,
HostCapabilities,
HostWatchEvent,
HostWatchEventType,
HostWatchOptions,
Stats,
} from './interface';
export interface SimpleMemoryHostStats {
readonly content: FileBuffer | null;
} | {
"end_byte": 757,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/memory.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/memory.ts_759_9115 | export class SimpleMemoryHost implements Host<{}> {
protected _cache = new Map<Path, Stats<SimpleMemoryHostStats>>();
private _watchers = new Map<Path, [HostWatchOptions, Subject<HostWatchEvent>][]>();
protected _newDirStats() {
return {
inspect() {
return '<Directory>';
},
isFile() {
return false;
},
isDirectory() {
return true;
},
size: 0,
atime: new Date(),
ctime: new Date(),
mtime: new Date(),
birthtime: new Date(),
content: null,
};
}
protected _newFileStats(content: FileBuffer, oldStats?: Stats<SimpleMemoryHostStats>) {
return {
inspect() {
return `<File size(${content.byteLength})>`;
},
isFile() {
return true;
},
isDirectory() {
return false;
},
size: content.byteLength,
atime: oldStats ? oldStats.atime : new Date(),
ctime: new Date(),
mtime: new Date(),
birthtime: oldStats ? oldStats.birthtime : new Date(),
content,
};
}
constructor() {
this._cache.set(normalize('/'), this._newDirStats());
}
protected _toAbsolute(path: Path): Path {
return isAbsolute(path) ? path : normalize('/' + path);
}
protected _updateWatchers(path: Path, type: HostWatchEventType): void {
const time = new Date();
let currentPath = path;
let parent: Path | null = null;
if (this._watchers.size == 0) {
// Nothing to do if there's no watchers.
return;
}
const maybeWatcher = this._watchers.get(currentPath);
if (maybeWatcher) {
maybeWatcher.forEach((watcher) => {
const [options, subject] = watcher;
subject.next({ path, time, type });
if (!options.persistent && type == HostWatchEventType.Deleted) {
subject.complete();
this._watchers.delete(currentPath);
}
});
}
do {
currentPath = parent !== null ? parent : currentPath;
parent = dirname(currentPath);
const maybeWatcher = this._watchers.get(currentPath);
if (maybeWatcher) {
maybeWatcher.forEach((watcher) => {
const [options, subject] = watcher;
if (!options.recursive) {
return;
}
subject.next({ path, time, type });
if (!options.persistent && type == HostWatchEventType.Deleted) {
subject.complete();
this._watchers.delete(currentPath);
}
});
}
} while (parent != currentPath);
}
get capabilities(): HostCapabilities {
return { synchronous: true };
}
/**
* List of protected methods that give direct access outside the observables to the cache
* and internal states.
*/
protected _write(path: Path, content: FileBuffer): void {
path = this._toAbsolute(path);
const old = this._cache.get(path);
if (old && old.isDirectory()) {
throw new PathIsDirectoryException(path);
}
// Update all directories. If we find a file we know it's an invalid write.
const fragments = split(path);
let curr: Path = normalize('/');
for (const fr of fragments) {
curr = join(curr, fr);
const maybeStats = this._cache.get(fr);
if (maybeStats) {
if (maybeStats.isFile()) {
throw new PathIsFileException(curr);
}
} else {
this._cache.set(curr, this._newDirStats());
}
}
// Create the stats.
const stats: Stats<SimpleMemoryHostStats> = this._newFileStats(content, old);
this._cache.set(path, stats);
this._updateWatchers(path, old ? HostWatchEventType.Changed : HostWatchEventType.Created);
}
protected _read(path: Path): FileBuffer {
path = this._toAbsolute(path);
const maybeStats = this._cache.get(path);
if (!maybeStats) {
throw new FileDoesNotExistException(path);
} else if (maybeStats.isDirectory()) {
throw new PathIsDirectoryException(path);
} else if (!maybeStats.content) {
throw new PathIsDirectoryException(path);
} else {
return maybeStats.content;
}
}
protected _delete(path: Path): void {
path = this._toAbsolute(path);
if (this._isDirectory(path)) {
for (const [cachePath] of this._cache.entries()) {
if (cachePath.startsWith(path + NormalizedSep) || cachePath === path) {
this._cache.delete(cachePath);
}
}
} else {
this._cache.delete(path);
}
this._updateWatchers(path, HostWatchEventType.Deleted);
}
protected _rename(from: Path, to: Path): void {
from = this._toAbsolute(from);
to = this._toAbsolute(to);
if (!this._cache.has(from)) {
throw new FileDoesNotExistException(from);
} else if (this._cache.has(to)) {
throw new FileAlreadyExistException(to);
}
if (this._isDirectory(from)) {
for (const path of this._cache.keys()) {
if (path.startsWith(from + NormalizedSep)) {
const content = this._cache.get(path);
if (content) {
// We don't need to clone or extract the content, since we're moving files.
this._cache.set(join(to, NormalizedSep, path.slice(from.length)), content);
}
}
}
} else {
const content = this._cache.get(from);
if (content) {
const fragments = split(to);
const newDirectories: Path[] = [];
let curr: Path = normalize('/');
for (const fr of fragments) {
curr = join(curr, fr);
const maybeStats = this._cache.get(fr);
if (maybeStats) {
if (maybeStats.isFile()) {
throw new PathIsFileException(curr);
}
} else {
newDirectories.push(curr);
}
}
for (const newDirectory of newDirectories) {
this._cache.set(newDirectory, this._newDirStats());
}
this._cache.delete(from);
this._cache.set(to, content);
}
}
this._updateWatchers(from, HostWatchEventType.Renamed);
}
protected _list(path: Path): PathFragment[] {
path = this._toAbsolute(path);
if (this._isFile(path)) {
throw new PathIsFileException(path);
}
const fragments = split(path);
const result = new Set<PathFragment>();
if (path !== NormalizedRoot) {
for (const p of this._cache.keys()) {
if (p.startsWith(path + NormalizedSep)) {
result.add(split(p)[fragments.length]);
}
}
} else {
for (const p of this._cache.keys()) {
if (p.startsWith(NormalizedSep) && p !== NormalizedRoot) {
result.add(split(p)[1]);
}
}
}
return [...result];
}
protected _exists(path: Path): boolean {
return !!this._cache.get(this._toAbsolute(path));
}
protected _isDirectory(path: Path): boolean {
const maybeStats = this._cache.get(this._toAbsolute(path));
return maybeStats ? maybeStats.isDirectory() : false;
}
protected _isFile(path: Path): boolean {
const maybeStats = this._cache.get(this._toAbsolute(path));
return maybeStats ? maybeStats.isFile() : false;
}
protected _stat(path: Path): Stats<SimpleMemoryHostStats> | null {
const maybeStats = this._cache.get(this._toAbsolute(path));
if (!maybeStats) {
return null;
} else {
return maybeStats;
}
}
protected _watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> {
path = this._toAbsolute(path);
const subject = new Subject<HostWatchEvent>();
let maybeWatcherArray = this._watchers.get(path);
if (!maybeWatcherArray) {
maybeWatcherArray = [];
this._watchers.set(path, maybeWatcherArray);
}
maybeWatcherArray.push([options || {}, subject]);
return subject.asObservable();
}
write(path: Path, content: FileBuffer): Observable<void> {
return new Observable<void>((obs) => {
this._write(path, content);
obs.next();
obs.complete();
});
}
read(path: Path): Observable<FileBuffer> {
return new Observable<FileBuffer>((obs) => {
const content = this._read(path);
obs.next(content);
obs.complete();
});
}
delete(path: Path): Observable<void> {
return new Observable<void>((obs) => {
this._delete(path);
obs.next();
obs.complete();
});
} | {
"end_byte": 9115,
"start_byte": 759,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/memory.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/memory.ts_9119_10383 | rename(from: Path, to: Path): Observable<void> {
return new Observable<void>((obs) => {
this._rename(from, to);
obs.next();
obs.complete();
});
}
list(path: Path): Observable<PathFragment[]> {
return new Observable<PathFragment[]>((obs) => {
obs.next(this._list(path));
obs.complete();
});
}
exists(path: Path): Observable<boolean> {
return new Observable<boolean>((obs) => {
obs.next(this._exists(path));
obs.complete();
});
}
isDirectory(path: Path): Observable<boolean> {
return new Observable<boolean>((obs) => {
obs.next(this._isDirectory(path));
obs.complete();
});
}
isFile(path: Path): Observable<boolean> {
return new Observable<boolean>((obs) => {
obs.next(this._isFile(path));
obs.complete();
});
}
// Some hosts may not support stat.
stat(path: Path): Observable<Stats<{}> | null> | null {
return new Observable<Stats<{}> | null>((obs) => {
obs.next(this._stat(path));
obs.complete();
});
}
watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null {
return this._watch(path, options);
}
reset(): void {
this._cache.clear();
this._watchers.clear();
}
} | {
"end_byte": 10383,
"start_byte": 9119,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/memory.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/index.ts_0_566 | /**
* @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 test from './test';
export * from './alias';
export * from './buffer';
export * from './create';
export * from './empty';
export * from './interface';
export * from './memory';
export * from './pattern';
export * from './record';
export * from './safe';
export * from './scoped';
export * from './sync';
export * from './resolver';
export { test };
| {
"end_byte": 566,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/index.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/create.ts_0_2225 | /**
* @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 { Observable } from 'rxjs';
import { Path, PathFragment } from '../path';
import { FileBuffer, FileBufferLike, Host, HostCapabilities, Stats } from './interface';
export interface SyncHostHandler<StatsT extends object = {}> {
read(path: Path): FileBuffer;
list(path: Path): PathFragment[];
exists(path: Path): boolean;
isDirectory(path: Path): boolean;
isFile(path: Path): boolean;
stat(path: Path): Stats<StatsT> | null;
write(path: Path, content: FileBufferLike): void;
delete(path: Path): void;
rename(from: Path, to: Path): void;
}
function wrapAction<T>(action: () => T): Observable<T> {
return new Observable((subscriber) => {
subscriber.next(action());
subscriber.complete();
});
}
export function createSyncHost<StatsT extends object = {}>(
handler: SyncHostHandler<StatsT>,
): Host<StatsT> {
return new (class {
get capabilities(): HostCapabilities {
return { synchronous: true };
}
read(path: Path): Observable<FileBuffer> {
return wrapAction(() => handler.read(path));
}
list(path: Path): Observable<PathFragment[]> {
return wrapAction(() => handler.list(path));
}
exists(path: Path): Observable<boolean> {
return wrapAction(() => handler.exists(path));
}
isDirectory(path: Path): Observable<boolean> {
return wrapAction(() => handler.isDirectory(path));
}
isFile(path: Path): Observable<boolean> {
return wrapAction(() => handler.isFile(path));
}
stat(path: Path): Observable<Stats<StatsT> | null> {
return wrapAction(() => handler.stat(path));
}
write(path: Path, content: FileBufferLike): Observable<void> {
return wrapAction(() => handler.write(path, content));
}
delete(path: Path): Observable<void> {
return wrapAction(() => handler.delete(path));
}
rename(from: Path, to: Path): Observable<void> {
return wrapAction(() => handler.rename(from, to));
}
watch(): null {
return null;
}
})();
}
| {
"end_byte": 2225,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/create.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/safe.ts_0_1593 | /**
* @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 { Observable, catchError, of } from 'rxjs';
import { Path, PathFragment } from '../path';
import { FileBuffer, HostCapabilities, ReadonlyHost, Stats } from './interface';
/**
* A Host that filters out errors. The only exception is `read()` which will still error out if
* the delegate returned an error (e.g. NodeJS will error out if the file doesn't exist).
*/
export class SafeReadonlyHost<StatsT extends object = {}> implements ReadonlyHost<StatsT> {
constructor(private _delegate: ReadonlyHost<StatsT>) {}
get capabilities(): HostCapabilities {
return this._delegate.capabilities;
}
read(path: Path): Observable<FileBuffer> {
return this._delegate.read(path);
}
list(path: Path): Observable<PathFragment[]> {
return this._delegate.list(path).pipe(catchError(() => of([])));
}
exists(path: Path): Observable<boolean> {
return this._delegate.exists(path);
}
isDirectory(path: Path): Observable<boolean> {
return this._delegate.isDirectory(path).pipe(catchError(() => of(false)));
}
isFile(path: Path): Observable<boolean> {
return this._delegate.isFile(path).pipe(catchError(() => of(false)));
}
// Some hosts may not support stats.
stat(path: Path): Observable<Stats<StatsT> | null> | null {
const maybeStat = this._delegate.stat(path);
return maybeStat && maybeStat.pipe(catchError(() => of(null)));
}
}
| {
"end_byte": 1593,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/safe.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/alias.ts_0_3264 | /**
* @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 { NormalizedRoot, Path, PathFragment, join, split } from '../path';
import { ResolverHost } from './resolver';
/**
* A Virtual Host that allow to alias some paths to other paths.
*
* This does not verify, when setting an alias, that the target or source exist. Neither does it
* check whether it's a file or a directory. Please not that directories are also renamed/replaced.
*
* No recursion is done on the resolution, which means the following is perfectly valid then:
*
* ```
* host.aliases.set(normalize('/file/a'), normalize('/file/b'));
* host.aliases.set(normalize('/file/b'), normalize('/file/a'));
* ```
*
* This will result in a proper swap of two files for each others.
*
* @example
* const host = new SimpleMemoryHost();
* host.write(normalize('/some/file'), content).subscribe();
*
* const aHost = new AliasHost(host);
* aHost.read(normalize('/some/file'))
* .subscribe(x => expect(x).toBe(content));
* aHost.aliases.set(normalize('/some/file'), normalize('/other/path');
*
* // This file will not exist because /other/path does not exist.
* aHost.read(normalize('/some/file'))
* .subscribe(undefined, err => expect(err.message).toMatch(/does not exist/));
*
* @example
* const host = new SimpleMemoryHost();
* host.write(normalize('/some/folder/file'), content).subscribe();
*
* const aHost = new AliasHost(host);
* aHost.read(normalize('/some/folder/file'))
* .subscribe(x => expect(x).toBe(content));
* aHost.aliases.set(normalize('/some'), normalize('/other');
*
* // This file will not exist because /other/path does not exist.
* aHost.read(normalize('/some/folder/file'))
* .subscribe(undefined, err => expect(err.message).toMatch(/does not exist/));
*
* // Create the file with new content and verify that this has the new content.
* aHost.write(normalize('/other/folder/file'), content2).subscribe();
* aHost.read(normalize('/some/folder/file'))
* .subscribe(x => expect(x).toBe(content2));
*/
export class AliasHost<StatsT extends object = {}> extends ResolverHost<StatsT> {
protected _aliases = new Map<Path, Path>();
protected _resolve(path: Path): Path {
let maybeAlias = this._aliases.get(path);
const sp = split(path);
const remaining: PathFragment[] = [];
// Also resolve all parents of the requested files, only picking the first one that matches.
// This can have surprising behaviour when aliases are inside another alias. It will always
// use the closest one to the file.
while (!maybeAlias && sp.length > 0) {
const p = join(NormalizedRoot, ...sp);
maybeAlias = this._aliases.get(p);
if (maybeAlias) {
maybeAlias = join(maybeAlias, ...remaining);
}
// Allow non-null-operator because we know sp.length > 0 (condition on while).
remaining.unshift(sp.pop()!); // eslint-disable-line @typescript-eslint/no-non-null-assertion
}
return maybeAlias || path;
}
get aliases(): Map<Path, Path> {
return this._aliases;
}
}
| {
"end_byte": 3264,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/alias.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts_0_407 | /**
* @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 { path } from '../path';
import { stringToFileBuffer } from './buffer';
import { CordHost } from './record';
import * as test from './test'; | {
"end_byte": 407,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts_409_8375 | describe('CordHost', () => {
const TestHost = test.TestHost;
const mutatingTestRecord = ['write', 'delete', 'rename'];
it('works (create)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/blue`, stringToFileBuffer(`hi`)).subscribe(undefined, done.fail);
const target = new TestHost();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'write', path: path`/blue` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(true);
done();
});
it('works (create -> create)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/blue`, stringToFileBuffer(`hi`)).subscribe(undefined, done.fail);
host.write(path`/blue`, stringToFileBuffer(`hi again`)).subscribe(undefined, done.fail);
const target = new TestHost();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'write', path: path`/blue` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(true);
expect(target.$read('/blue')).toBe('hi again');
done();
});
it('works (create -> delete)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/blue`, stringToFileBuffer(`hi`)).subscribe(undefined, done.fail);
host.delete(path`/blue`).subscribe(undefined, done.fail);
const target = new TestHost();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(false);
done();
});
it('works (create -> rename)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/blue`, stringToFileBuffer(`hi`)).subscribe(undefined, done.fail);
host.rename(path`/blue`, path`/red`).subscribe(undefined, done.fail);
const target = new TestHost();
host.commit(target).subscribe(undefined, done.fail);
// Check that there's only 1 write done.
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'write', path: path`/red` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(false);
expect(target.$exists('/red')).toBe(true);
done();
});
it('works (create -> rename (identity))', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/blue`, stringToFileBuffer(`hi`)).subscribe(undefined, done.fail);
host.rename(path`/blue`, path`/blue`).subscribe(undefined, done.fail);
const target = new TestHost();
host.commit(target).subscribe(undefined, done.fail);
// Check that there's only 1 write done.
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'write', path: path`/blue` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(true);
done();
});
it('works (create -> rename -> rename)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/blue`, stringToFileBuffer(`hi`)).subscribe(undefined, done.fail);
host.rename(path`/blue`, path`/red`).subscribe(undefined, done.fail);
host.rename(path`/red`, path`/yellow`).subscribe(undefined, done.fail);
const target = new TestHost();
host.commit(target).subscribe(undefined, done.fail);
// Check that there's only 1 write done.
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'write', path: path`/yellow` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(false);
expect(target.$exists('/red')).toBe(false);
expect(target.$exists('/yellow')).toBe(true);
done();
});
it('works (rename)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
// Check that there's only 1 write done.
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'rename', from: path`/hello`, to: path`/blue` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(true);
done();
});
it('works (rename -> rename)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail);
host.rename(path`/blue`, path`/red`).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
// Check that there's only 1 write done.
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'rename', from: path`/hello`, to: path`/red` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(false);
expect(target.$exists('/red')).toBe(true);
done();
});
it('works (rename -> create)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail);
host.write(path`/hello`, stringToFileBuffer(`beautiful world`)).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
// Check that there's only 1 write done.
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'rename', from: path`/hello`, to: path`/blue` },
{ kind: 'write', path: path`/hello` },
]);
expect(target.$exists('/hello')).toBe(true);
expect(target.$exists('/blue')).toBe(true);
done();
});
it('works (overwrite)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/hello`, stringToFileBuffer(`beautiful world`)).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
// Check that there's only 1 write done.
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'write', path: path`/hello` },
]);
expect(target.$exists('/hello')).toBe(true);
expect(target.$read('/hello')).toBe('beautiful world');
done();
});
it('works (overwrite -> overwrite)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/hello`, stringToFileBuffer(`beautiful world`)).subscribe(undefined, done.fail);
host.write(path`/hello`, stringToFileBuffer(`again`)).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
// Check that there's only 1 write done.
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'write', path: path`/hello` },
]);
expect(target.$exists('/hello')).toBe(true);
expect(target.$read('/hello')).toBe('again');
done();
}); | {
"end_byte": 8375,
"start_byte": 409,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts_8379_16185 | it('works (overwrite -> rename)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/hello`, stringToFileBuffer(`beautiful world`)).subscribe(undefined, done.fail);
host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'rename', from: path`/hello`, to: path`/blue` },
{ kind: 'write', path: path`/blue` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(true);
expect(target.$read('/blue')).toBe('beautiful world');
done();
});
it('works (overwrite -> delete)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/hello`, stringToFileBuffer(`beautiful world`)).subscribe(undefined, done.fail);
host.delete(path`/hello`).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'delete', path: path`/hello` },
]);
expect(target.$exists('/hello')).toBe(false);
done();
});
it('works (rename -> overwrite)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail);
host.write(path`/blue`, stringToFileBuffer(`beautiful world`)).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'rename', from: path`/hello`, to: path`/blue` },
{ kind: 'write', path: path`/blue` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(true);
expect(target.$read('/blue')).toBe('beautiful world');
done();
});
it('works (delete)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.delete(path`/hello`).subscribe(undefined, done.fail);
const target = new TestHost();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'delete', path: path`/hello` },
]);
expect(target.$exists('/hello')).toBe(false);
done();
});
it('works (delete -> create)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.delete(path`/hello`).subscribe(undefined, done.fail);
host.write(path`/hello`, stringToFileBuffer(`beautiful world`)).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'write', path: path`/hello` },
]);
expect(target.$exists('/hello')).toBe(true);
expect(target.$read('/hello')).toBe('beautiful world');
done();
});
it('works (rename -> delete)', (done) => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail);
host.delete(path`/blue`).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'delete', path: path`/hello` },
]);
expect(target.$exists('/hello')).toBe(false);
done();
});
it('works (delete -> rename)', (done) => {
const base = new TestHost({
'/hello': 'world',
'/blue': 'foo',
});
const host = new CordHost(base);
host.delete(path`/blue`).subscribe(undefined, done.fail);
host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail);
const target = base.clone();
host.commit(target).subscribe(undefined, done.fail);
expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([
{ kind: 'delete', path: path`/hello` },
{ kind: 'write', path: path`/blue` },
]);
expect(target.$exists('/hello')).toBe(false);
expect(target.$exists('/blue')).toBe(true);
done();
});
it('errors: commit (create: exists)', () => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/blue`, stringToFileBuffer(`hi`)).subscribe();
const target = new TestHost({
'/blue': 'test',
});
let error = false;
host.commit(target).subscribe(
undefined,
() => (error = true),
() => (error = false),
);
expect(error).toBe(true);
});
it('errors: commit (overwrite: not exist)', () => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.write(path`/hello`, stringToFileBuffer(`hi`)).subscribe();
const target = new TestHost({});
let error = false;
host.commit(target).subscribe(
undefined,
() => (error = true),
() => (error = false),
);
expect(error).toBe(true);
});
it('errors: commit (rename: not exist)', () => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.rename(path`/hello`, path`/blue`).subscribe();
const target = new TestHost({});
let error = false;
host.commit(target).subscribe(
undefined,
() => (error = true),
() => (error = false),
);
expect(error).toBe(true);
});
it('errors: commit (rename: exist)', () => {
const base = new TestHost({
'/hello': 'world',
});
const host = new CordHost(base);
host.rename(path`/hello`, path`/blue`).subscribe();
const target = new TestHost({
'/blue': 'foo',
});
let error = false;
host.commit(target).subscribe(
undefined,
() => (error = true),
() => (error = false),
);
expect(error).toBe(true);
});
it('errors (write directory)', () => {
const base = new TestHost({
'/dir/hello': 'world',
});
const host = new CordHost(base);
let error = false;
host.write(path`/dir`, stringToFileBuffer(`beautiful world`)).subscribe(
undefined,
() => (error = true),
() => (error = false),
);
expect(error).toBe(true);
});
it('errors (delete: not exist)', () => {
const base = new TestHost({});
const host = new CordHost(base);
let error = false;
host.delete(path`/hello`).subscribe(
undefined,
() => (error = true),
() => (error = false),
);
expect(error).toBe(true);
});
it('errors (rename: exist)', () => {
const base = new TestHost({
'/hello': 'world',
'/blue': 'foo',
});
const host = new CordHost(base);
let error = false;
host.rename(path`/hello`, path`/blue`).subscribe(
undefined,
() => (error = true),
() => (error = false),
);
expect(error).toBe(true);
});
it('errors (rename: not exist)', () => {
const base = new TestHost({});
const host = new CordHost(base);
let error = false;
host.rename(path`/hello`, path`/blue`).subscribe(
undefined,
() => (error = true),
() => (error = false),
);
expect(error).toBe(true);
});
}); | {
"end_byte": 16185,
"start_byte": 8379,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts"
} |
angular-cli/packages/angular_devkit/core/src/virtual-fs/host/sync.ts_0_3268 | /**
* @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 { Observable } from 'rxjs';
import { BaseException } from '../../exception';
import { Path, PathFragment } from '../path';
import {
FileBuffer,
FileBufferLike,
Host,
HostCapabilities,
HostWatchEvent,
HostWatchOptions,
Stats,
} from './interface';
export class SynchronousDelegateExpectedException extends BaseException {
constructor() {
super(`Expected a synchronous delegate but got an asynchronous one.`);
}
}
/**
* Implement a synchronous-only host interface (remove the Observable parts).
*/
export class SyncDelegateHost<T extends object = {}> {
constructor(protected _delegate: Host<T>) {
if (!_delegate.capabilities.synchronous) {
throw new SynchronousDelegateExpectedException();
}
}
protected _doSyncCall<ResultT>(observable: Observable<ResultT>): ResultT {
let completed = false;
let result: ResultT | undefined = undefined;
let errorResult: Error | undefined = undefined;
// Perf note: this is not using an observer object to avoid a performance penalty in RxJS.
// See https://github.com/ReactiveX/rxjs/pull/5646 for details.
observable.subscribe(
(x: ResultT) => (result = x),
(err: Error) => (errorResult = err),
() => (completed = true),
);
if (errorResult !== undefined) {
throw errorResult;
}
if (!completed) {
throw new SynchronousDelegateExpectedException();
}
// The non-null operation is to work around `void` type. We don't allow to return undefined
// but ResultT could be void, which is undefined in JavaScript, so this doesn't change the
// behaviour.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return result!;
}
get capabilities(): HostCapabilities {
return this._delegate.capabilities;
}
get delegate(): Host<T> {
return this._delegate;
}
write(path: Path, content: FileBufferLike): void {
return this._doSyncCall(this._delegate.write(path, content));
}
read(path: Path): FileBuffer {
return this._doSyncCall(this._delegate.read(path));
}
delete(path: Path): void {
return this._doSyncCall(this._delegate.delete(path));
}
rename(from: Path, to: Path): void {
return this._doSyncCall(this._delegate.rename(from, to));
}
list(path: Path): PathFragment[] {
return this._doSyncCall(this._delegate.list(path));
}
exists(path: Path): boolean {
return this._doSyncCall(this._delegate.exists(path));
}
isDirectory(path: Path): boolean {
return this._doSyncCall(this._delegate.isDirectory(path));
}
isFile(path: Path): boolean {
return this._doSyncCall(this._delegate.isFile(path));
}
// Some hosts may not support stat.
stat(path: Path): Stats<T> | null {
const result: Observable<Stats<T> | null> | null = this._delegate.stat(path);
if (result) {
return this._doSyncCall(result);
} else {
return null;
}
}
watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null {
return this._delegate.watch(path, options);
}
}
| {
"end_byte": 3268,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/src/virtual-fs/host/sync.ts"
} |
angular-cli/packages/angular_devkit/build_angular/README.md_0_3551 | # @angular-devkit/build-angular
This package contains [Architect builders](/packages/angular_devkit/architect/README.md) used to build and test Angular applications and libraries.
## Builders
| Name | Description |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| application | Build an Angular application targeting a browser and server environment using [esbuild](https://esbuild.github.io). |
| app-shell | Build an Angular [App shell](https://angular.dev/ecosystem/service-workers/app-shell). |
| browser | Build an Angular application targeting a browser environment using [Webpack](https://webpack.js.org). |
| browser-esbuild | Build an Angular application targeting a browser environment using [esbuild](https://esbuild.github.io). |
| dev-server | A development server that provides live reloading. |
| extract-i18n | Extract i18n messages from an Angular application. |
| karma | Execute unit tests using [Karma](https://github.com/karma-runner/karma) test runner. |
| ng-packagr | Build and package an Angular library in [Angular Package Format (APF)](https://angular.dev/tools/libraries/angular-package-format) format using [ng-packagr](https://github.com/ng-packagr/ng-packagr). |
| prerender | [Prerender](https://angular.dev/guide/prerendering) pages of your application. Prerendering is the process where a dynamic page is processed at build time generating static HTML. |
| server | Build an Angular application targeting a [Node.js](https://nodejs.org) environment. |
| ssr-dev-server | A development server which offers live reload during development, but uses server-side rendering. |
| protractor | **Deprecated** - Run end-to-end tests using [Protractor](https://www.protractortest.org/) framework. |
## Disclaimer
While the builders when executed via the Angular CLI and their associated options are considered stable, the programmatic APIs are not considered officially supported and are not subject to the breaking change guarantees of SemVer.
| {
"end_byte": 3551,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/README.md"
} |
angular-cli/packages/angular_devkit/build_angular/BUILD.bazel_0_7920 | # 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 = "app_shell_schema",
src = "src/builders/app-shell/schema.json",
)
ts_json_schema(
name = "browser_schema",
src = "src/builders/browser/schema.json",
)
ts_json_schema(
name = "browser_esbuild_schema",
src = "src/builders/browser-esbuild/schema.json",
)
ts_json_schema(
name = "dev_server_schema",
src = "src/builders/dev-server/schema.json",
)
ts_json_schema(
name = "extract_i18n_schema",
src = "src/builders/extract-i18n/schema.json",
)
ts_json_schema(
name = "jest_schema",
src = "src/builders/jest/schema.json",
)
ts_json_schema(
name = "karma_schema",
src = "src/builders/karma/schema.json",
)
ts_json_schema(
name = "protractor_schema",
src = "src/builders/protractor/schema.json",
)
ts_json_schema(
name = "server_schema",
src = "src/builders/server/schema.json",
)
ts_json_schema(
name = "ng_packagr_schema",
src = "src/builders/ng-packagr/schema.json",
)
ts_json_schema(
name = "ssr_dev_server_schema",
src = "src/builders/ssr-dev-server/schema.json",
)
ts_json_schema(
name = "prerender_schema",
src = "src/builders/prerender/schema.json",
)
ts_json_schema(
name = "web_test_runner_schema",
src = "src/builders/web-test-runner/schema.json",
)
ts_library(
name = "build_angular",
package_name = "@angular-devkit/build-angular",
srcs = glob(
include = [
"src/**/*.ts",
"plugins/**/*.ts",
],
exclude = [
"src/test-utils.ts",
"src/**/*_spec.ts",
"src/**/tests/**/*.ts",
"plugins/**/*_spec.ts",
"src/testing/**/*.ts",
],
) + [
"//packages/angular_devkit/build_angular:src/builders/app-shell/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/browser-esbuild/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/browser/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/dev-server/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/extract-i18n/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/jest/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/karma/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/ng-packagr/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/prerender/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/protractor/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/server/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/ssr-dev-server/schema.ts",
"//packages/angular_devkit/build_angular:src/builders/web-test-runner/schema.ts",
],
data = glob(
include = [
"src/**/schema.json",
"src/**/*.js",
"src/**/*.mjs",
"src/**/*.html",
],
) + [
"builders.json",
"package.json",
],
module_name = "@angular-devkit/build-angular",
module_root = "src/index.d.ts",
deps = [
"//packages/angular/build",
"//packages/angular/build:private",
"//packages/angular/ssr",
"//packages/angular_devkit/architect",
"//packages/angular_devkit/build_webpack",
"//packages/angular_devkit/core",
"//packages/angular_devkit/core/node",
"//packages/ngtools/webpack",
"@npm//@ampproject/remapping",
"@npm//@angular/common",
"@npm//@angular/compiler-cli",
"@npm//@angular/core",
"@npm//@angular/localize",
"@npm//@angular/platform-server",
"@npm//@angular/service-worker",
"@npm//@babel/core",
"@npm//@babel/generator",
"@npm//@babel/helper-annotate-as-pure",
"@npm//@babel/helper-split-export-declaration",
"@npm//@babel/plugin-transform-async-generator-functions",
"@npm//@babel/plugin-transform-async-to-generator",
"@npm//@babel/plugin-transform-runtime",
"@npm//@babel/preset-env",
"@npm//@babel/runtime",
"@npm//@discoveryjs/json-ext",
"@npm//@types/babel__core",
"@npm//@types/browser-sync",
"@npm//@types/karma",
"@npm//@types/less",
"@npm//@types/loader-utils",
"@npm//@types/node",
"@npm//@types/picomatch",
"@npm//@types/semver",
"@npm//@types/watchpack",
"@npm//@vitejs/plugin-basic-ssl",
"@npm//@web/test-runner",
"@npm//ajv",
"@npm//ansi-colors",
"@npm//autoprefixer",
"@npm//babel-loader",
"@npm//browserslist",
"@npm//copy-webpack-plugin",
"@npm//css-loader",
"@npm//esbuild",
"@npm//esbuild-wasm",
"@npm//fast-glob",
"@npm//http-proxy-middleware",
"@npm//istanbul-lib-instrument",
"@npm//jsonc-parser",
"@npm//karma",
"@npm//karma-source-map-support",
"@npm//less",
"@npm//less-loader",
"@npm//license-webpack-plugin",
"@npm//loader-utils",
"@npm//mini-css-extract-plugin",
"@npm//ng-packagr",
"@npm//open",
"@npm//ora",
"@npm//piscina",
"@npm//postcss",
"@npm//postcss-loader",
"@npm//resolve-url-loader",
"@npm//rxjs",
"@npm//sass",
"@npm//sass-loader",
"@npm//semver",
"@npm//source-map-loader",
"@npm//source-map-support",
"@npm//terser",
"@npm//tree-kill",
"@npm//tslib",
"@npm//typescript",
"@npm//webpack",
"@npm//webpack-dev-middleware",
"@npm//webpack-dev-server",
"@npm//webpack-merge",
"@npm//webpack-subresource-integrity",
],
)
ts_library(
name = "build_angular_test_lib",
testonly = True,
srcs = glob(
include = [
"src/**/*_spec.ts",
],
exclude = [
"src/builders/**/*_spec.ts",
],
),
data = glob(["test/**/*"]),
deps = [
":build_angular",
":build_angular_test_utils",
"//packages/angular_devkit/architect/testing",
"//packages/angular_devkit/core",
"@npm//fast-glob",
"@npm//prettier",
"@npm//typescript",
"@npm//webpack",
],
)
jasmine_node_test(
name = "build_angular_test",
srcs = [":build_angular_test_lib"],
)
genrule(
name = "license",
srcs = ["//:LICENSE"],
outs = ["LICENSE"],
cmd = "cp $(execpath //:LICENSE) $@",
)
pkg_npm(
name = "npm_package",
pkg_deps = [
"//packages/angular/build:package.json",
"//packages/angular_devkit/architect:package.json",
"//packages/angular_devkit/build_webpack:package.json",
"//packages/angular_devkit/core:package.json",
"//packages/ngtools/webpack:package.json",
],
tags = ["release-package"],
deps = [
":README.md",
":build_angular",
":license",
],
)
api_golden_test_npm_package(
name = "build_angular_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular_cli/goldens/public-api/angular_devkit/build_angular",
npm_package = "angular_cli/packages/angular_devkit/build_angular/npm_package",
)
# Large build_angular specs | {
"end_byte": 7920,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/BUILD.bazel"
} |
angular-cli/packages/angular_devkit/build_angular/BUILD.bazel_7922_12548 | ts_library(
name = "build_angular_test_utils",
testonly = True,
srcs = glob(
include = [
"src/testing/**/*.ts",
"src/**/tests/*.ts",
],
exclude = [
"src/**/*_spec.ts",
],
),
data = glob(["test/**/*"]),
tsconfig = "//:tsconfig-test.json",
deps = [
":build_angular",
"//modules/testing/builder",
"//packages/angular/build",
"//packages/angular/build:private",
"//packages/angular_devkit/architect",
"//packages/angular_devkit/architect/node",
"//packages/angular_devkit/architect/testing",
"//packages/angular_devkit/core",
"//packages/angular_devkit/core/node",
"@npm//rxjs",
],
)
LARGE_SPECS = {
"app-shell": {},
"dev-server": {
"shards": 10,
"size": "large",
"flaky": True,
"extra_deps": [
"//packages/angular_devkit/build_webpack",
"@npm//@types/http-proxy",
"@npm//http-proxy",
"@npm//puppeteer",
"@npm//undici",
],
},
"extract-i18n": {},
"karma": {
"shards": 6,
"size": "large",
"flaky": True,
"extra_deps": [
"@npm//karma",
"@npm//karma-chrome-launcher",
"@npm//karma-coverage",
"@npm//karma-jasmine",
"@npm//karma-jasmine-html-reporter",
"@npm//puppeteer",
],
},
"protractor": {
"extra_deps": [
"@npm//jasmine-spec-reporter",
"@npm//protractor",
"@npm//puppeteer",
"@npm//ts-node",
],
# NB: does not run on rbe because webdriver manager uses an absolute path to chromedriver
"tags": ["no-remote-exec"],
# NB: multiple shards will compete for port 4200 so limiting to 1
"shards": 1,
},
"server": {
"size": "large",
"extra_deps": [
"@npm//@angular/animations",
],
},
"ng-packagr": {},
"browser": {
"shards": 10,
"size": "large",
"flaky": True,
"extra_deps": [
"@npm//@angular/animations",
"@npm//@angular/material",
],
},
"prerender": {},
"browser-esbuild": {},
"ssr-dev-server": {
"extra_deps": [
"@npm//@types/browser-sync",
"@npm//browser-sync",
"@npm//express",
"@npm//undici",
"//packages/angular/ssr/node",
],
},
}
[
ts_library(
name = "build_angular_" + spec + "_test_lib",
testonly = True,
srcs = glob(["src/builders/" + spec + "/**/*_spec.ts"]),
tsconfig = "//:tsconfig-test.json",
deps = [
# Dependencies needed to compile and run the specs themselves.
":build_angular",
":build_angular_test_utils",
"//modules/testing/builder",
"//packages/angular/build",
"//packages/angular/build:private",
"//packages/angular_devkit/architect",
"//packages/angular_devkit/architect/node",
"//packages/angular_devkit/architect/testing",
"//packages/angular_devkit/core",
"//packages/angular_devkit/core/node",
# Base dependencies for the application in hello-world-app.
# Some tests also require extra dependencies.
"@npm//@angular/common",
"@npm//@angular/compiler",
"@npm//@angular/compiler-cli",
"@npm//@angular/core",
"@npm//@angular/platform-browser",
"@npm//@angular/platform-browser-dynamic",
"@npm//@angular/router",
"@npm//rxjs",
"@npm//tslib",
"@npm//typescript",
"@npm//zone.js",
] + LARGE_SPECS[spec].get("extra_deps", []),
)
for spec in LARGE_SPECS
]
[
jasmine_node_test(
name = "build_angular_" + spec + "_test",
size = LARGE_SPECS[spec].get("size", "medium"),
flaky = LARGE_SPECS[spec].get("flaky", False),
shard_count = LARGE_SPECS[spec].get("shards", 2),
# These tests are resource intensive and should not be over-parallized as they will
# compete for the resources of other parallel tests slowing everything down.
# Ask Bazel to allocate multiple CPUs for these tests with "cpu:n" tag.
tags = [
"cpu:2",
] + LARGE_SPECS[spec].get("tags", []),
deps = [":build_angular_" + spec + "_test_lib"],
)
for spec in LARGE_SPECS
] | {
"end_byte": 12548,
"start_byte": 7922,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/BUILD.bazel"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.