Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/angular_devkit/core/src/exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,13 @@ export class PathIsFileException extends BaseException {
super(`Path "${path}" is a file.`);
}
}
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.');
}
}
53 changes: 45 additions & 8 deletions packages/angular_devkit/core/src/json/schema/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ import * as http from 'node:http';
import * as https from 'node:https';
import * as Url from 'node:url';
import { Observable, from, isObservable, lastValueFrom } from 'rxjs';
import { BaseException } from '../../exception';
import { PartiallyOrderedSet } from '../../utils';
import {
BaseException,
CircularDependencyFoundException,
DependencyNotFoundException,
} from '../../exception';
import { JsonArray, JsonObject, JsonValue, isJsonObject } from '../utils';
import {
JsonPointer,
Expand Down Expand Up @@ -93,12 +96,46 @@ interface SchemaInfo {
promptDefinitions: Array<PromptDefinition>;
}

/**
* Adds a transform to an ordered list of transforms.
*
* Transforms run in insertion order and each transform is only present once. Dependencies
* must already be in the list, which guarantees that they run before the added transform.
*/
function addTransform(
transforms: JsonVisitor[],
visitor: JsonVisitor,
deps: JsonVisitor[] = [],
): void {
const existingIndex = transforms.indexOf(visitor);
const position = existingIndex === -1 ? transforms.length : existingIndex;

for (const dep of deps) {
const depIndex = transforms.indexOf(dep);
if (depIndex === -1) {
throw new DependencyNotFoundException();
}
if (depIndex === position) {
throw new CircularDependencyFoundException();
}
if (depIndex > position) {
throw new Error(
'The transform is already registered and runs before one of the provided dependencies.',
);
}
}

if (existingIndex === -1) {
transforms.push(visitor);
}
}

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 _pre: JsonVisitor[] = [];
private _post: JsonVisitor[] = [];

private _currentCompilationSchemaInfo?: SchemaInfo;

Expand Down Expand Up @@ -181,7 +218,7 @@ export class CoreSchemaRegistry implements SchemaRegistry {
* @param {JsonVisitor[]} deps [Deprecated] A list of other visitors to run before. Add transforms in the desired execution order instead.
*/
addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void {
this._pre.add(visitor, deps);
addTransform(this._pre, visitor, deps);
}

/**
Expand All @@ -192,7 +229,7 @@ export class CoreSchemaRegistry implements SchemaRegistry {
* @param {JsonVisitor[]} deps [Deprecated] A list of other visitors to run before. Add transforms in the desired execution order instead.
*/
addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void {
this._post.add(visitor, deps);
addTransform(this._post, visitor, deps);
}

protected _resolver(
Expand Down Expand Up @@ -326,7 +363,7 @@ export class CoreSchemaRegistry implements SchemaRegistry {

// Apply pre-validation transforms
if (validationOptions.applyPreTransforms) {
for (const visitor of this._pre.values()) {
for (const visitor of this._pre) {
data = await lastValueFrom(
visitJson(data, visitor, schema, this._resolver.bind(this), validator),
);
Expand Down Expand Up @@ -378,7 +415,7 @@ export class CoreSchemaRegistry implements SchemaRegistry {

// Apply post-validation transforms
if (validationOptions.applyPostTransforms) {
for (const visitor of this._post.values()) {
for (const visitor of this._post) {
data = await lastValueFrom(
visitJson(data, visitor, schema, this._resolver.bind(this), validator),
);
Expand Down
91 changes: 90 additions & 1 deletion packages/angular_devkit/core/src/json/schema/registry_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
*/

/* eslint-disable @typescript-eslint/no-explicit-any */
import { CircularDependencyFoundException, DependencyNotFoundException } from '../../exception';
import { JsonValue } from '../utils';
import { SchemaFormat } from './interface';
import { JsonVisitor, SchemaFormat } from './interface';
import { CoreSchemaRegistry, SchemaValidationException } from './registry';
import { JsonSchema } from './schema';
import { addUndefinedDefaults } from './transforms';
Expand Down Expand Up @@ -454,4 +455,92 @@ describe('CoreSchemaRegistry', () => {
expect(messages).toEqual(['Data path "/outputPath" must be string.']);
});
});

describe('transform ordering', () => {
function createVisitor(name: string, calls: string[]): JsonVisitor {
return (value) => {
calls.push(name);

return value;
};
}

async function run(registry: CoreSchemaRegistry): Promise<void> {
const validator = await registry.compile({ type: 'string' });
const result = await validator('value');
expect(result.success).toBe(true);
}

it('runs transforms in the order they were added', async () => {
const calls: string[] = [];
const registry = new CoreSchemaRegistry();
registry.addPreTransform(createVisitor('pre1', calls));
registry.addPreTransform(createVisitor('pre2', calls));
registry.addPostTransform(createVisitor('post1', calls));
registry.addPostTransform(createVisitor('post2', calls));

await run(registry);

expect(calls).toEqual(['pre1', 'pre2', 'post1', 'post2']);
});

it('only runs a transform once when it is added multiple times', async () => {
const calls: string[] = [];
const registry = new CoreSchemaRegistry();
const first = createVisitor('first', calls);
registry.addPostTransform(first);
registry.addPostTransform(createVisitor('second', calls));
registry.addPostTransform(first);

await run(registry);

expect(calls).toEqual(['first', 'second']);
});

it('runs a transform after its dependencies', async () => {
const calls: string[] = [];
const registry = new CoreSchemaRegistry();
const first = createVisitor('first', calls);
const second = createVisitor('second', calls);
registry.addPostTransform(first);
registry.addPostTransform(second, [first]);
// Adding again with dependencies that already run earlier is a no-op.
registry.addPostTransform(second, [first]);

await run(registry);

expect(calls).toEqual(['first', 'second']);
});

it('throws when a dependency has not been added', () => {
const registry = new CoreSchemaRegistry();
const missing = createVisitor('missing', []);

expect(() => registry.addPreTransform(createVisitor('visitor', []), [missing])).toThrowError(
DependencyNotFoundException,
);
});

it('throws when a transform depends on itself', () => {
const registry = new CoreSchemaRegistry();
const visitor = createVisitor('visitor', []);
registry.addPreTransform(visitor);

expect(() => registry.addPreTransform(visitor, [visitor])).toThrowError(
CircularDependencyFoundException,
);
});

it('throws when an existing transform is given a dependency that runs after it', () => {
const registry = new CoreSchemaRegistry();
const first = createVisitor('first', []);
const second = createVisitor('second', []);
registry.addPreTransform(first);
registry.addPreTransform(second);

expect(() => registry.addPreTransform(first, [second])).toThrowError(
/already registered and runs before/,
);
});
});
});
13 changes: 1 addition & 12 deletions packages/angular_devkit/core/src/utils/partially-ordered-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,7 @@
* 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.');
}
}
import { CircularDependencyFoundException, DependencyNotFoundException } from '../exception';

/**
* @deprecated Use standard arrays and ensure correct insertion order instead.
Expand Down
Loading