Dataset Preview
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed because of a cast error
Error code: DatasetGenerationCastError Exception: DatasetGenerationCastError Message: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 672 new columns ({'000104', '000425', '000120', '000010', '000459', '000123', '000356', '000233', '000593', '000162', '000661', '000617', '000087', '000600', '000610', '000259', '000034', '000479', '000514', '000375', '000463', '000271', '000039', '000561', '000132', '000116', '000047', '000229', '000635', '000252', '000124', '000456', '000464', '000307', '000646', '000538', '000167', '000306', '000444', '000284', '000466', '000398', '000018', '000212', '000634', '000134', '000209', '000329', '000469', '000519', '000022', '000040', '000276', '000509', '000230', '000521', '000075', '000536', '000402', '000186', '000115', '000210', '000143', '000312', '000535', '000599', '000108', '000044', '000563', '000222', '000288', '000361', '000397', '000586', '000658', '000248', '000139', '000299', '000343', '000196', '000136', '000302', '000547', '000110', '000006', '000219', '000408', '000079', '000383', '000642', '000117', '000534', '000138', '000429', '000494', '000300', '000272', '000322', '000107', '000511', '000226', '000103', '000327', '000360', '000621', '000001', '000517', '000620', '000265', '000651', '000473', '000169', '000527', '000481', '000255', '000207', '000387', '000458', '000523', '000153', '000262', '000310', '000163', '000215', '000172', '000454', '000430', '000344', '000221', '000619', '000326', '000597', '000341', '000246', '000330', '000436', '000067', '000544', '000065', '000301', '000338', '000267', '000036', '000373', '000214', '000283', '000184', '000002', '000231', '000396', ... '000560', '000211', '000386', '000178', '000632', '000238', '000426', '000471', '000569', '000366', '000046', '000382', '000203', '000354', '000604', '000287', '000149', '000559', '000666', '000490', '000029', '000099', '000171', '000636', '000063', '000097', '000188', '000487', '000292', '000144', '000415', '000324', '000220', '000253', '000496', '000058', '000374', '000500', '000083', '000076', '000085', '000637', '000190', '000393', '000630', '000665', '000168', '000546', '000247', '000503', '000224', '000321', '000461', '000495', '000260', '000066', '000389', '000074', '000422', '000468', '000263', '000355', '000217', '000261', '000176', '000395', '000365', '000112', '000372', '000282', '000164', '000571', '000200', '000320', '000250', '000198', '000309', '000611', '000369', '000216', '000392', '000440', '000007', '000441', '000131', '000417', '000060', '000554', '000628', '000648', '000504', '000363', '000347', '000093', '000421', '000121', '000609', '000249', '000340', '000437', '000151', '000579', '000498', '000285', '000595', '000194', '000235', '000113', '000304', '000035', '000328', '000305', '000520', '000380', '000024', '000011', '000505', '000154', '000240', '000313', '000413', '000166', '000416', '000140', '000385', '000613', '000342', '000428', '000650', '000056', '000550', '000541', '000202', '000081', '000411', '000174', '000427', '000150', '000668', '000197', '000662', '000502', '000647', '000125', '000551', '000119', '000652', '000057', '000406', '000175'}) and 2 missing columns ({'text', 'id'}). This happened while the json dataset builder was generating data using hf://datasets/embedding-benchmark/FreshStack_mteb/relevance.jsonl (at revision 53ce890bda820516ab90b575d738bbc1922dadb9) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations) Traceback: Traceback (most recent call last): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1831, in _prepare_split_single writer.write_table(table) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 644, in write_table pa_table = table_cast(pa_table, self._schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2272, in table_cast return cast_table_to_schema(table, schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2218, in cast_table_to_schema raise CastError( datasets.table.CastError: Couldn't cast 000000: struct<014212: int64, 014259: int64, 014132: int64, 014273: int64> child 0, 014212: int64 child 1, 014259: int64 child 2, 014132: int64 child 3, 014273: int64 000001: struct<006217: int64, 014325: int64, 006211: int64, 011904: int64, 004532: int64, 011134: int64, 009729: int64> child 0, 006217: int64 child 1, 014325: int64 child 2, 006211: int64 child 3, 011904: int64 child 4, 004532: int64 child 5, 011134: int64 child 6, 009729: int64 000002: struct<004594: int64, 011486: int64, 010533: int64, 010648: int64, 010649: int64, 004592: int64, 004646: int64, 004645: int64, 010647: int64, 014359: int64, 004625: int64> child 0, 004594: int64 child 1, 011486: int64 child 2, 010533: int64 child 3, 010648: int64 child 4, 010649: int64 child 5, 004592: int64 child 6, 004646: int64 child 7, 004645: int64 child 8, 010647: int64 child 9, 014359: int64 child 10, 004625: int64 000003: struct<014070: int64, 010501: int64, 014023: int64, 014080: int64, 004554: int64, 004550: int64, 004552: int64, 014005: int64, 012067: int64, 012374: int64, 014020: int64, 003814: int64, 006471: int64, 115418: int64, 014073: int64, 001880: int64> child 0, 014070: int64 child 1, 010501: int64 child 2, 014023: int64 child 3, 014080: int64 child 4, 004554: int64 child 5, 004550: int64 child 6, 004552: int64 child 7, 014005: int64 child 8, 012067: int64 child 9, 012374: int64 child 10, 014020: int64 child 11, 003814: int64 child 12, 00647 ... nt64 child 2, 271803: int64 child 3, 271344: int64 child 4, 271350: int64 child 5, 245881: int64 child 6, 244725: int64 000666: struct<271040: int64, 244815: int64, 271643: int64, 271048: int64, 271150: int64, 271307: int64, 271647: int64, 271648: int64, 270768: int64, 270763: int64, 271005: int64> child 0, 271040: int64 child 1, 244815: int64 child 2, 271643: int64 child 3, 271048: int64 child 4, 271150: int64 child 5, 271307: int64 child 6, 271647: int64 child 7, 271648: int64 child 8, 270768: int64 child 9, 270763: int64 child 10, 271005: int64 000667: struct<253193: int64, 253194: int64, 270752: int64, 244758: int64, 270751: int64> child 0, 253193: int64 child 1, 253194: int64 child 2, 270752: int64 child 3, 244758: int64 child 4, 270751: int64 000668: struct<271025: int64, 271041: int64, 271127: int64, 271126: int64, 271308: int64, 244657: int64, 271004: int64, 271007: int64, 271149: int64, 270951: int64> child 0, 271025: int64 child 1, 271041: int64 child 2, 271127: int64 child 3, 271126: int64 child 4, 271308: int64 child 5, 244657: int64 child 6, 271004: int64 child 7, 271007: int64 child 8, 271149: int64 child 9, 270951: int64 000669: struct<246535: int64, 271698: int64, 271347: int64> child 0, 246535: int64 child 1, 271698: int64 child 2, 271347: int64 000670: struct<270786: int64> child 0, 270786: int64 000671: struct<271051: int64, 271150: int64> child 0, 271051: int64 child 1, 271150: int64 to {'id': Value('string'), 'text': Value('string')} because column names don't match During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1456, in compute_config_parquet_and_info_response parquet_operations = convert_to_parquet(builder) File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1055, in convert_to_parquet builder.download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 894, in download_and_prepare self._download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 970, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1702, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1833, in _prepare_split_single raise DatasetGenerationCastError.from_cast_error( datasets.exceptions.DatasetGenerationCastError: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 672 new columns ({'000104', '000425', '000120', '000010', '000459', '000123', '000356', '000233', '000593', '000162', '000661', '000617', '000087', '000600', '000610', '000259', '000034', '000479', '000514', '000375', '000463', '000271', '000039', '000561', '000132', '000116', '000047', '000229', '000635', '000252', '000124', '000456', '000464', '000307', '000646', '000538', '000167', '000306', '000444', '000284', '000466', '000398', '000018', '000212', '000634', '000134', '000209', '000329', '000469', '000519', '000022', '000040', '000276', '000509', '000230', '000521', '000075', '000536', '000402', '000186', '000115', '000210', '000143', '000312', '000535', '000599', '000108', '000044', '000563', '000222', '000288', '000361', '000397', '000586', '000658', '000248', '000139', '000299', '000343', '000196', '000136', '000302', '000547', '000110', '000006', '000219', '000408', '000079', '000383', '000642', '000117', '000534', '000138', '000429', '000494', '000300', '000272', '000322', '000107', '000511', '000226', '000103', '000327', '000360', '000621', '000001', '000517', '000620', '000265', '000651', '000473', '000169', '000527', '000481', '000255', '000207', '000387', '000458', '000523', '000153', '000262', '000310', '000163', '000215', '000172', '000454', '000430', '000344', '000221', '000619', '000326', '000597', '000341', '000246', '000330', '000436', '000067', '000544', '000065', '000301', '000338', '000267', '000036', '000373', '000214', '000283', '000184', '000002', '000231', '000396', ... '000560', '000211', '000386', '000178', '000632', '000238', '000426', '000471', '000569', '000366', '000046', '000382', '000203', '000354', '000604', '000287', '000149', '000559', '000666', '000490', '000029', '000099', '000171', '000636', '000063', '000097', '000188', '000487', '000292', '000144', '000415', '000324', '000220', '000253', '000496', '000058', '000374', '000500', '000083', '000076', '000085', '000637', '000190', '000393', '000630', '000665', '000168', '000546', '000247', '000503', '000224', '000321', '000461', '000495', '000260', '000066', '000389', '000074', '000422', '000468', '000263', '000355', '000217', '000261', '000176', '000395', '000365', '000112', '000372', '000282', '000164', '000571', '000200', '000320', '000250', '000198', '000309', '000611', '000369', '000216', '000392', '000440', '000007', '000441', '000131', '000417', '000060', '000554', '000628', '000648', '000504', '000363', '000347', '000093', '000421', '000121', '000609', '000249', '000340', '000437', '000151', '000579', '000498', '000285', '000595', '000194', '000235', '000113', '000304', '000035', '000328', '000305', '000520', '000380', '000024', '000011', '000505', '000154', '000240', '000313', '000413', '000166', '000416', '000140', '000385', '000613', '000342', '000428', '000650', '000056', '000550', '000541', '000202', '000081', '000411', '000174', '000427', '000150', '000668', '000197', '000662', '000502', '000647', '000125', '000551', '000119', '000652', '000057', '000406', '000175'}) and 2 missing columns ({'text', 'id'}). This happened while the json dataset builder was generating data using hf://datasets/embedding-benchmark/FreshStack_mteb/relevance.jsonl (at revision 53ce890bda820516ab90b575d738bbc1922dadb9) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
id
string | text
string |
---|---|
000077
|
import { match } from 'node:assert';
import { createProjectFromAsset } from '../../utils/assets';
import {
expectFileMatchToExist,
expectFileNotToExist,
expectFileToExist,
expectFileToMatch,
} from '../../utils/fs';
import { execAndWaitForOutputToMatch, ng, noSilentNg } from '../../utils/process';
import { findFreePort } from '../../utils/network';
export default async function () {
await createProjectFromAsset('19-ssr-project-webpack', false, false);
await ng('update', `@angular/cli`, '--name=use-application-builder');
await Promise.all([
expectFileNotToExist('tsconfig.server.json'),
expectFileToMatch('tsconfig.json', 'esModuleInterop'),
expectFileToMatch('src/server.ts', 'import.meta.url'),
]);
// Verify project now creates bundles
await noSilentNg('build', '--configuration=production');
await Promise.all([
expectFileToExist('dist/18-ssr-project-webpack/server/server.mjs'),
expectFileMatchToExist('dist/18-ssr-project-webpack/browser', /main-[a-zA-Z0-9]{8}\.js/),
]);
// Verify that the app runs
const port = await findFreePort();
await execAndWaitForOutputToMatch('ng', ['serve', '--port', String(port)], /complete\./);
const response = await fetch(`http://localhost:${port}/`);
const text = await response.text();
match(text, /app is running!/);
}
|
000090
|
import assert from 'node:assert';
import { setTimeout } from 'node:timers/promises';
import { replaceInFile, writeMultipleFiles } from '../../utils/fs';
import { ng, silentNg, waitForAnyProcessOutputToMatch } from '../../utils/process';
import { installWorkspacePackages, uninstallPackage } from '../../utils/packages';
import { ngServe, updateJsonFile, useSha } from '../../utils/project';
import { getGlobalVariable } from '../../utils/env';
export default async function () {
assert(
getGlobalVariable('argv')['esbuild'],
'This test should not be called in the Webpack suite.',
);
// Forcibly remove in case another test doesn't clean itself up.
await uninstallPackage('@angular/ssr');
await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install');
await useSha();
await installWorkspacePackages();
// Update angular.json
await updateJsonFile('angular.json', (workspaceJson) => {
const appArchitect = workspaceJson.projects['test-project'].architect;
const options = appArchitect.build.options;
options.outputMode = 'server';
});
await writeMultipleFiles({
// Replace the template of app.component.html as it makes it harder to debug
'src/app/app.component.html': '<router-outlet />',
'src/app/app.routes.ts': `
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent }
];
`,
'src/app/app.routes.server.ts': `
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{ path: '**', renderMode: RenderMode.Server }
];
`,
'src/server.ts': `
import { AngularNodeAppEngine, writeResponseToNodeResponse, isMainModule, createNodeRequestHandler } from '@angular/ssr/node';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
export function app(): express.Express {
const server = express();
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const angularNodeAppEngine = new AngularNodeAppEngine();
server.use('/api/**', (req, res) => res.json({ hello: 'foo' }));
server.get('**', express.static(browserDistFolder, {
maxAge: '1y',
index: 'index.html'
}));
server.get('**', (req, res, next) => {
angularNodeAppEngine.render(req)
.then((response) => response ? writeResponseToNodeResponse(response, res) : next())
.catch(next);
});
return server;
}
const server = app();
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
server.listen(port, () => {
console.log(\`Node Express server listening on http://localhost:\${port}\`);
});
}
export const reqHandler = createNodeRequestHandler(server);
`,
});
await silentNg('generate', 'component', 'home');
const port = await ngServe();
// Verify the server is running and the API response is correct.
await validateResponse('/main.js', /bootstrapApplication/);
await validateResponse('/api/test', /foo/);
await validateResponse('/home', /home works/);
// Modify the home component and validate the change.
await modifyFileAndWaitUntilUpdated(
'src/app/home/home.component.html',
'home works',
'yay home works!!!',
);
await validateResponse('/api/test', /foo/);
await validateResponse('/home', /yay home works/);
// Modify the API response and validate the change.
await modifyFileAndWaitUntilUpdated('src/server.ts', `{ hello: 'foo' }`, `{ hello: 'bar' }`);
await validateResponse('/api/test', /bar/);
await validateResponse('/home', /yay home works/);
async function validateResponse(pathname: string, match: RegExp): Promise<void> {
const response = await fetch(new URL(pathname, `http://localhost:${port}`));
const text = await response.text();
assert.match(text, match);
assert.equal(response.status, 200);
}
}
async function modifyFileAndWaitUntilUpdated(
filePath: string,
searchValue: string,
replaceValue: string,
): Promise<void> {
await Promise.all([
waitForAnyProcessOutputToMatch(/Page reload sent to client/),
setTimeout(100).then(() => replaceInFile(filePath, searchValue, replaceValue)),
]);
}
|
000095
|
import assert from 'node:assert';
import { setTimeout } from 'node:timers/promises';
import { replaceInFile, writeMultipleFiles } from '../../utils/fs';
import { ng, silentNg, waitForAnyProcessOutputToMatch } from '../../utils/process';
import { installPackage, installWorkspacePackages, uninstallPackage } from '../../utils/packages';
import { ngServe, updateJsonFile, useSha } from '../../utils/project';
import { getGlobalVariable } from '../../utils/env';
export default async function () {
assert(
getGlobalVariable('argv')['esbuild'],
'This test should not be called in the Webpack suite.',
);
// Forcibly remove in case another test doesn't clean itself up.
await uninstallPackage('@angular/ssr');
await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install');
await useSha();
await installWorkspacePackages();
await installPackage('fastify@5');
// Update angular.json
await updateJsonFile('angular.json', (workspaceJson) => {
const appArchitect = workspaceJson.projects['test-project'].architect;
const options = appArchitect.build.options;
options.outputMode = 'server';
});
await writeMultipleFiles({
// Replace the template of app.component.html as it makes it harder to debug
'src/app/app.component.html': '<router-outlet />',
'src/app/app.routes.ts': `
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent }
];
`,
'src/app/app.routes.server.ts': `
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{ path: '**', renderMode: RenderMode.Server }
];
`,
'src/server.ts': `
import { AngularNodeAppEngine, writeResponseToNodeResponse, isMainModule, createNodeRequestHandler } from '@angular/ssr/node';
import fastify from 'fastify';
export function app() {
const server = fastify();
const angularNodeAppEngine = new AngularNodeAppEngine();
server.get('/api/*', (req, reply) => reply.send({ hello: 'foo' }));
server.get('*', async (req, reply) => {
try {
const response = await angularNodeAppEngine.render(req.raw);
if (response) {
await writeResponseToNodeResponse(response, reply.raw);
} else {
reply.callNotFound();
}
} catch (error) {
reply.send(error);
}
});
return server;
}
const server = app();
if (isMainModule(import.meta.url)) {
const port = +(process.env['PORT'] || 4000);
server.listen({ port }, () => {
console.log(\`Fastify server listening on http://localhost:\${port}\`);
});
}
export const reqHandler = createNodeRequestHandler(async (req, res) => {
await server.ready();
server.server.emit('request', req, res);
});
`,
});
await silentNg('generate', 'component', 'home');
const port = await ngServe();
// Verify the server is running and the API response is correct.
await validateResponse('/main.js', /bootstrapApplication/);
await validateResponse('/api/test', /foo/);
await validateResponse('/home', /home works/);
// Modify the home component and validate the change.
await modifyFileAndWaitUntilUpdated(
'src/app/home/home.component.html',
'home works',
'yay home works!!!',
);
await validateResponse('/api/test', /foo/);
await validateResponse('/home', /yay home works/);
// Modify the API response and validate the change.
await modifyFileAndWaitUntilUpdated('src/server.ts', `{ hello: 'foo' }`, `{ hello: 'bar' }`);
await validateResponse('/api/test', /bar/);
await validateResponse('/home', /yay home works/);
async function validateResponse(pathname: string, match: RegExp): Promise<void> {
const response = await fetch(new URL(pathname, `http://localhost:${port}`));
const text = await response.text();
assert.match(text, match);
assert.equal(response.status, 200);
}
}
async function modifyFileAndWaitUntilUpdated(
filePath: string,
searchValue: string,
replaceValue: string,
): Promise<void> {
await Promise.all([
waitForAnyProcessOutputToMatch(/Page reload sent to client/),
setTimeout(100).then(() => replaceInFile(filePath, searchValue, replaceValue)),
]);
}
|
000124
|
import { ng } from '../../../utils/process';
import { useCIChrome } from '../../../utils/project';
export default async function () {
await ng('generate', 'app', 'standalone', '--experimental-zoneless', '--standalone');
await useCIChrome('standalone', 'projects/standalone');
await ng('test', 'standalone', '--watch=false');
await ng('build', 'standalone');
await ng(
'generate',
'app',
'ngmodules',
'--experimental-zoneless',
'--no-standalone',
'--skip-install',
);
await useCIChrome('ngmodules', 'projects/ngmodules');
await ng('test', 'ngmodules', '--watch=false');
await ng('build', 'ngmodules');
}
|
000171
|
import assert from 'node:assert';
import { killAllProcesses, ng } from '../../../utils/process';
import { rimraf, writeMultipleFiles } from '../../../utils/fs';
import { installWorkspacePackages } from '../../../utils/packages';
import { ngServe, useSha } from '../../../utils/project';
export default async function () {
// Forcibly remove in case another test doesn't clean itself up.
await rimraf('node_modules/@angular/ssr');
await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation');
await useSha();
await installWorkspacePackages();
await writeMultipleFiles({
// Add http client and route
'src/app/app.config.ts': `
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter([{
path: '',
component: HomeComponent,
}]),
provideClientHydration(),
provideHttpClient(withFetch()),
],
};
`,
// Add asset
'public/media.json': JSON.stringify({ dataFromAssets: true }),
// Update component to do an HTTP call to asset.
'src/app/app.component.ts': `
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
template: \`
<p>{{ data | json }}</p>
<router-outlet></router-outlet>
\`,
})
export class AppComponent {
data: any;
constructor() {
const http = inject(HttpClient);
http.get('/media.json').toPromise().then((d) => {
this.data = d;
});
}
}
`,
});
await ng('generate', 'component', 'home');
const match = /<p>{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/;
const port = await ngServe('--no-ssl');
assert.match(await (await fetch(`http://localhost:${port}/`)).text(), match);
await killAllProcesses();
try {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const sslPort = await ngServe('--ssl');
assert.match(await (await fetch(`https://localhost:${sslPort}/`)).text(), match);
} finally {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1';
}
}
|
000223
|
import { writeMultipleFiles } from '../../../utils/fs';
import { silentNg } from '../../../utils/process';
export async function libraryConsumptionSetup(): Promise<void> {
await silentNg('generate', 'library', 'my-lib');
// Force an external template
await writeMultipleFiles({
'projects/my-lib/src/lib/my-lib.component.html': `<p>my-lib works!</p>`,
'projects/my-lib/src/lib/my-lib.component.ts': `import { Component } from '@angular/core';
@Component({
standalone: true,
selector: 'lib-my-lib',
templateUrl: './my-lib.component.html',
})
export class MyLibComponent {}`,
'./src/app/app.component.ts': `
import { Component } from '@angular/core';
import { MyLibService, MyLibComponent } from 'my-lib';
@Component({
standalone: true,
selector: 'app-root',
template: '<lib-my-lib></lib-my-lib>',
imports: [MyLibComponent],
})
export class AppComponent {
title = 'test-project';
constructor(myLibService: MyLibService) {
console.log(myLibService);
}
}
`,
'e2e/src/app.e2e-spec.ts': `
import { browser, logging, element, by } from 'protractor';
import { AppPage } from './app.po';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display text from library component', async () => {
await page.navigateTo();
expect(await element(by.css('lib-my-lib p')).getText()).toEqual('my-lib works!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
}));
});
});
`,
});
}
|
000240
|
import assert, { match } from 'node:assert';
import { readFile, writeMultipleFiles } from '../../../utils/fs';
import { ng, noSilentNg, silentNg } from '../../../utils/process';
import { getGlobalVariable } from '../../../utils/env';
import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages';
import { useSha } from '../../../utils/project';
export default async function () {
assert(
getGlobalVariable('argv')['esbuild'],
'This test should not be called in the Webpack suite.',
);
// Forcibly remove in case another test doesn't clean itself up.
await uninstallPackage('@angular/ssr');
await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install');
await useSha();
await installWorkspacePackages();
await writeMultipleFiles({
// Add asset
'public/media.json': JSON.stringify({ dataFromAssets: true }),
// Update component to do an HTTP call to asset and API.
'src/app/app.component.ts': `
import { Component, inject } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [JsonPipe, RouterOutlet],
template: \`
<p>{{ assetsData | json }}</p>
<p>{{ apiData | json }}</p>
<router-outlet></router-outlet>
\`,
})
export class AppComponent {
assetsData: any;
apiData: any;
constructor() {
const http = inject(HttpClient);
http.get('/media.json').toPromise().then((d) => {
this.assetsData = d;
});
http.get('/api').toPromise().then((d) => {
this.apiData = d;
});
}
}
`,
// Add http client and route
'src/app/app.config.ts': `
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter([{
path: 'home',
component: HomeComponent,
}]),
provideClientHydration(),
provideHttpClient(withFetch()),
],
};
`,
'src/server.ts': `
import { AngularNodeAppEngine, writeResponseToNodeResponse, isMainModule, createNodeRequestHandler } from '@angular/ssr/node';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
export function app(): express.Express {
const server = express();
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const angularNodeAppEngine = new AngularNodeAppEngine();
server.get('/api', (req, res) => res.json({ dataFromAPI: true }));
server.get('**', express.static(browserDistFolder, {
maxAge: '1y',
index: 'index.html'
}));
server.get('**', (req, res, next) => {
angularNodeAppEngine.render(req)
.then((response) => response ? writeResponseToNodeResponse(response, res) : next())
.catch(next);
});
return server;
}
const server = app();
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
server.listen(port, () => {
console.log(\`Node Express server listening on http://localhost:\${port}\`);
});
}
export const reqHandler = createNodeRequestHandler(server);
`,
});
await silentNg('generate', 'component', 'home');
await noSilentNg('build', '--output-mode=static');
const contents = await readFile('dist/test-project/browser/home/index.html');
match(contents, /<p>{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/);
match(contents, /<p>{[\S\s]*"dataFromAPI":[\s\S]*true[\S\s]*}<\/p>/);
match(contents, /home works!/);
}
|
000242
|
import { join } from 'node:path';
import { existsSync } from 'node:fs';
import assert from 'node:assert';
import { expectFileToMatch, writeFile } from '../../../utils/fs';
import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process';
import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages';
import { useSha } from '../../../utils/project';
import { getGlobalVariable } from '../../../utils/env';
import { findFreePort } from '../../../utils/network';
export default async function () {
assert(
getGlobalVariable('argv')['esbuild'],
'This test should not be called in the Webpack suite.',
);
// Forcibly remove in case another test doesn't clean itself up.
await uninstallPackage('@angular/ssr');
await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install');
await useSha();
await installWorkspacePackages();
// Add routes
await writeFile(
'src/app/app.routes.ts',
`
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { CsrComponent } from './csr/csr.component';
import { SsrComponent } from './ssr/ssr.component';
import { SsgComponent } from './ssg/ssg.component';
import { AppShellComponent } from './app-shell/app-shell.component';
import { SsgWithParamsComponent } from './ssg-with-params/ssg-with-params.component';
export const routes: Routes = [
{
path: 'app-shell',
component: AppShellComponent
},
{
path: '',
component: HomeComponent,
},
{
path: 'ssg',
component: SsgComponent,
},
{
path: 'ssr',
component: SsrComponent,
},
{
path: 'csr',
component: CsrComponent,
},
{
path: 'redirect',
redirectTo: 'ssg'
},
{
path: 'ssg/:id',
component: SsgWithParamsComponent,
},
];
`,
);
// Add server routing
await writeFile(
'src/app/app.routes.server.ts',
`
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
path: 'ssg/:id',
renderMode: RenderMode.Prerender,
headers: { 'x-custom': 'ssg-with-params' },
getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}],
},
{
path: 'ssr',
renderMode: RenderMode.Server,
headers: { 'x-custom': 'ssr' },
},
{
path: 'csr',
renderMode: RenderMode.Client,
headers: { 'x-custom': 'csr' },
},
{
path: 'app-shell',
renderMode: RenderMode.AppShell,
},
{
path: '**',
renderMode: RenderMode.Prerender,
headers: { 'x-custom': 'ssg' },
},
];
`,
);
// Generate components for the above routes
const componentNames: string[] = ['home', 'ssg', 'ssg-with-params', 'csr', 'ssr', 'app-shell'];
for (const componentName of componentNames) {
await silentNg('generate', 'component', componentName);
}
await noSilentNg('build', '--output-mode=server');
const expects: Record<string, string> = {
'index.html': 'home works!',
'ssg/index.html': 'ssg works!',
'ssg/one/index.html': 'ssg-with-params works!',
'ssg/two/index.html': 'ssg-with-params works!',
};
for (const [filePath, fileMatch] of Object.entries(expects)) {
await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch);
}
const filesDoNotExist: string[] = ['csr/index.html', 'ssr/index.html', 'redirect/index.html'];
for (const filePath of filesDoNotExist) {
const file = join('dist/test-project/browser', filePath);
assert.equal(existsSync(file), false, `Expected '${file}' to not exist.`);
}
// Tests responses
const responseExpects: Record<
string,
{ headers: Record<string, string>; content: string; serverContext: string }
> = {
'/': {
content: 'home works',
serverContext: 'ng-server-context="ssg"',
headers: {
'x-custom': 'ssg',
},
},
'/ssg': {
content: 'ssg works!',
serverContext: 'ng-server-context="ssg"',
headers: {
'x-custom': 'ssg',
},
},
'/ssr': {
content: 'ssr works!',
serverContext: 'ng-server-context="ssr"',
headers: {
'x-custom': 'ssr',
},
},
'/csr': {
content: 'app-shell works',
serverContext: 'ng-server-context="app-shell"',
headers: {
'x-custom': 'csr',
},
},
};
const port = await spawnServer();
for (const [pathname, { content, headers, serverContext }] of Object.entries(responseExpects)) {
const res = await fetch(`http://localhost:${port}${pathname}`);
const text = await res.text();
assert.match(
text,
new RegExp(content),
`Response for '${pathname}': ${content} was not matched in content.`,
);
assert.match(
text,
new RegExp(serverContext),
`Response for '${pathname}': ${serverContext} was not matched in content.`,
);
for (const [name, value] of Object.entries(headers)) {
assert.equal(
res.headers.get(name),
value,
`Response for '${pathname}': ${name} header value did not match expected.`,
);
}
}
}
async function spawnServer(): Promise<number> {
const port = await findFreePort();
await execAndWaitForOutputToMatch(
'npm',
['run', 'serve:ssr:test-project'],
/Node Express server listening on/,
{
'PORT': String(port),
},
);
return port;
}
|
000250
|
import { ng } from '../../../utils/process';
import { getGlobalVariable } from '../../../utils/env';
import { expectFileToMatch, rimraf, writeMultipleFiles } from '../../../utils/fs';
import { installWorkspacePackages } from '../../../utils/packages';
import { useSha } from '../../../utils/project';
export default async function () {
const useWebpackBuilder = !getGlobalVariable('argv')['esbuild'];
if (useWebpackBuilder) {
// Not supported by the webpack based builder.
return;
}
// Forcibly remove in case another test doesn't clean itself up.
await rimraf('node_modules/@angular/ssr');
await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation');
await useSha();
await installWorkspacePackages();
await writeMultipleFiles({
// Add http client and route
'src/app/app.config.ts': `
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import {HomeComponent} from './home/home.component';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter([{
path: '',
component: HomeComponent,
}]),
provideClientHydration(),
provideHttpClient(withFetch()),
],
};
`,
// Add asset
'public/media.json': JSON.stringify({ dataFromAssets: true }),
'public/media with-space.json': JSON.stringify({ dataFromAssetsWithSpace: true }),
// Update component to do an HTTP call to asset.
'src/app/app.component.ts': `
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
template: \`
<p>{{ data | json }}</p>
<p>{{ dataWithSpace | json }}</p>
<router-outlet></router-outlet>
\`,
})
export class AppComponent {
data: any;
dataWithSpace: any;
constructor() {
const http = inject(HttpClient);
http.get('/media.json').subscribe((d) => {
this.data = d;
});
http.get('/media%20with-space.json').subscribe((d) => {
this.dataWithSpace = d;
});
}
}
`,
});
await ng('generate', 'component', 'home');
await ng('build', '--configuration=production', '--prerender');
await expectFileToMatch(
'dist/test-project/browser/index.html',
/<p>{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/,
);
await expectFileToMatch(
'dist/test-project/browser/index.html',
/<p>{[\S\s]*"dataFromAssetsWithSpace":[\s\S]*true[\S\s]*}<\/p>/,
);
}
|
000251
|
import { ng } from '../../../utils/process';
import { getGlobalVariable } from '../../../utils/env';
import { rimraf, writeMultipleFiles } from '../../../utils/fs';
import { match } from 'node:assert';
import { expectToFail } from '../../../utils/utils';
import { useSha } from '../../../utils/project';
import { installWorkspacePackages } from '../../../utils/packages';
export default async function () {
const useWebpackBuilder = !getGlobalVariable('argv')['esbuild'];
if (useWebpackBuilder) {
return;
}
// Forcibly remove in case another test doesn't clean itself up.
await rimraf('node_modules/@angular/ssr');
await ng('add', '@angular/ssr', '--skip-confirmation');
await useSha();
await installWorkspacePackages();
await writeMultipleFiles({
'src/app/app.component.ts': `
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'test-ssr';
constructor() {
console.log(window)
}
}
`,
});
const { message } = await expectToFail(() =>
ng('build', '--configuration', 'development', '--prerender'),
);
match(
message,
// When babel is used it will add names to the sourcemap and `constructor` will be used in the stack trace.
// This will currently only happen if AOT and script optimizations are set which enables advanced optimizations.
/window is not defined[.\s\S]*(?:constructor|_AppComponent) \(.*app\.component\.ts\:\d+:\d+\)/,
);
}
|
000264
|
import express from 'express';
import { dirname, resolve } from 'path';
import { getGlobalVariable } from '../../utils/env';
import { appendToFile, copyFile, createDir, replaceInFile, writeFile } from '../../utils/fs';
import { installPackage } from '../../utils/packages';
import { updateJsonFile } from '../../utils/project';
import { readNgVersion } from '../../utils/version';
import { Server } from 'http';
import { AddressInfo } from 'net';
// Configurations for each locale.
const translationFile = 'src/locale/messages.xlf';
export const baseDir = 'dist/test-project/browser';
export const langTranslations = [
{
lang: 'en-US',
outputPath: `${baseDir}/en-US`,
translation: {
helloPartial: 'Hello',
hello: 'Hello i18n!',
plural: 'Updated 3 minutes ago',
date: 'January',
},
},
{
lang: 'fr',
outputPath: `${baseDir}/fr`,
translation: {
helloPartial: 'Bonjour',
hello: 'Bonjour i18n!',
plural: 'Mis à jour il y a 3 minutes',
date: 'janvier',
},
translationReplacements: [
['Hello', 'Bonjour'],
['Updated', 'Mis à jour'],
['just now', 'juste maintenant'],
['one minute ago', 'il y a une minute'],
[/other {/g, 'other {il y a '],
['minutes ago', 'minutes'],
],
},
{
lang: 'de',
outputPath: `${baseDir}/de`,
translation: {
helloPartial: 'Hallo',
hello: 'Hallo i18n!',
plural: 'Aktualisiert vor 3 Minuten',
date: 'Januar',
},
translationReplacements: [
['Hello', 'Hallo'],
['Updated', 'Aktualisiert'],
['just now', 'gerade jetzt'],
['one minute ago', 'vor einer Minute'],
[/other {/g, 'other {vor '],
['minutes ago', 'Minuten'],
],
},
];
export const sourceLocale = langTranslations[0].lang;
export interface ExternalServer {
readonly server: Server;
readonly port: number;
readonly url: string;
}
/**
* Create an `express` `http.Server` listening on a random port.
*
* Call .close() on the server return value to close the server.
*/
export async function externalServer(outputPath: string, baseUrl = '/'): Promise<ExternalServer> {
const app = express();
app.use(baseUrl, express.static(resolve(outputPath)));
return new Promise((resolve) => {
const server = app.listen(0, 'localhost', () => {
const { port } = server.address() as AddressInfo;
resolve({
server,
port,
url: `http://localhost:${port}${baseUrl}`,
});
});
});
}
export const baseHrefs: { [l: string]: string } = {
'en-US': '/en/',
fr: '/fr-FR/',
de: '',
};
|
000274
|
export function updateServerFileForWebpack(filepath: string): Promise<void> {
return writeFile(
filepath,
`
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr/node';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import bootstrap from './main.server';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const indexHtml = join(serverDistFolder, 'index.server.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', browserDistFolder);
server.get('**', express.static(browserDistFolder, {
maxAge: '1y',
index: 'index.html',
}));
// All regular routes use the Angular engine
server.get('**', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: \`\${protocol}://\${headers.host}\${originalUrl}\`,
publicPath: browserDistFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
function run(): void {
const port = process.env['PORT'] || 4000;
const server = app();
server.listen(port, () => {
console.log(\`Node Express server listening on http://localhost:\${port}\`);
});
}
run();
`,
);
}
|
000318
|
import 'zone.js/node';
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import * as express from 'express';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import AppServerModule from './src/main.server';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), 'dist/18-ssr-project-webpack/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html'))
? join(distFolder, 'index.original.html')
: join(distFolder, 'index.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', distFolder);
// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
// All regular routes use the Angular engine
server.get('*', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
bootstrap: AppServerModule,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: distFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
function run(): void {
const port = process.env['PORT'] || 4000;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export default AppServerModule;
|
000337
|
import 'zone.js/node';
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr/node';
import * as express from 'express';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import AppServerModule from './src/main.server';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), 'dist/18-ssr-project-webpack/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html'))
? join(distFolder, 'index.original.html')
: join(distFolder, 'index.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', distFolder);
// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
// All regular routes use the Angular engine
server.get('*', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
bootstrap: AppServerModule,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: distFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
function run(): void {
const port = process.env['PORT'] || 4000;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export default AppServerModule;
|
000366
|
# Building and Testing Angular CLI
## Installation
To get started locally, follow these instructions:
1. If you haven't done it already, [make a fork of this repo](https://github.com/angular/angular-cli/fork).
1. Clone to your local computer using `git`.
1. Make sure that you have Node `v18.19` or higher installed. See instructions [here](https://nodejs.org/en/download/).
1. Make sure that you have `yarn` installed; see instructions [here](https://yarnpkg.com/lang/en/docs/install/).
1. Run `yarn` (no arguments) from the root of your clone of this project to install dependencies.
## Building and Installing the CLI
To make a local build:
```shell
yarn build --local
```
This generates a number of tarballs in the `dist/` directory. To actually use
the locally built tools, switch to another repository reproducing the specific
issue you want to fix (or just generate a local repo with `ng new`). Then
install the locally built packages:
```shell
cd "${EXAMPLE_ANGULAR_PROJECT_REPO}"
npm install -D ${CLI_REPO}/dist/*.tgz
```
Builds of this example project will use tooling created from the previous local
build and include any local changes. When using the CLI, it will automatically
check for a local install and use that if present. This means you can just run:
```shell
npm install -g @angular/cli
```
to get a global install of the latest CLI release. Then running any `ng` command
in the example project will automatically find and use the local build of the
CLI.
Note: If you are testing `ng update`, be aware that installing all the tarballs
will also update the framework (`@angular/core`) to the latest version. In this
case, simply install the CLI alone with
`npm install -D ${CLI_REPO}/dist/_angular_cli.tgz`, that way the rest of the
project remains to be upgraded with `ng update`.
## Debugging
To debug an invocation of the CLI, [build and install the CLI for an example
project](#building-and-installing-the-cli), then run the desired `ng` command
as:
```shell
node --inspect-brk node_modules/.bin/ng ...
```
This will trigger a breakpoint as the CLI starts up. You can connect to this
using the supported mechanisms for your IDE, but the simplest option is to open
Chrome to [chrome://inspect](chrome://inspect) and then click on the `inspect`
link for the `node_modules/.bin/ng` Node target.
Unfortunately, the CLI dynamically `require()`'s other files mid-execution, so
the debugger is not aware of all the source code files before hand. As a result,
it is tough to put breakpoints on files before the CLI loads them. The easiest
workaround is to use the `debugger;` statement to stop execution in the file you
are interested in, and then you should be able to step around and set breakpoints
as expected.
## Testing
There are two different test suites which can be run locally:
### Unit tests
- Run all tests: `yarn bazel test //packages/...`
- Run a subset of the tests, use the full Bazel target example: `yarn bazel test //packages/schematics/angular:angular_test`
- For a complete list of test targets use the following Bazel query: `yarn bazel query "tests(//packages/...)"`
When debugging a specific test, change `describe()` or `it()` to `fdescribe()`
and `fit()` to focus execution to just that one test. This will keep the output clean and speed up execution by not running irrelevant tests.
You can find more info about debugging [tests with Bazel in the docs.](https://github.com/angular/angular-cli/blob/main/docs/process/bazel.md#debugging-jasmine_node_test)
### End to end tests
- For a complete list of test targets use the following Bazel query: `yarn bazel query "tests(//tests/...)"`
- Run a subset of the tests: `yarn bazel test //tests/legacy-cli:e2e_node18 --config=e2e --test_filter="tests/i18n/ivy-localize-*"`
- Use `bazel run` to debug failing tests debugging: `yarn bazel run //tests/legacy-cli:e2e_node18 --config=e2e --test_arg="--glob=tests/basic/aot.ts"`
- Provide additional `e2e_runner` options using `--test_arg`: `--test_arg="--package-manager=yarn"`
When running the debug commands, Node will stop and wait for a debugger to attach.
You can attach your IDE to the debugger to stop on breakpoints and step through the code. Also, see [IDE Specific Usage](#ide-specific-usage) for a
simpler debug story.
## IDE Specific Usage
Some additional tips for developing in specific IDEs.
### Intellij IDEA / WebStorm
To load the project in Intellij products, simply `Open` the repository folder.
Do **not** `Import Project`, because that will overwrite the existing
configuration.
Once opened, the editor should automatically detect run configurations in the
workspace. Use the drop down to choose which one to run and then click the `Run`
button to start it. When executing a debug target, make sure to click the
`Debug` icon to automatically attach the debugger (if you click `Run`, Node will
wait forever for a debugger to attach).

### VS Code
In order to debug some Angular CLI behaviour using Visual Studio Code, you can run `npm run build`, and then use a launch configuration like the following:
```json
{
"type": "node",
"request": "launch",
"name": "ng serve",
"cwd": "<path to an Angular project generated with Angular-CLI>",
"program": "${workspaceFolder}/dist/@angular/cli/bin/ng",
"args": [
"<ng command>",
...other arguments
],
"console": "integratedTerminal"
}
```
Then you can add breakpoints in `dist/@angular` files.
For more information about Node.js debugging in VS Code, see the related [VS Code Documentation](https://code.visualstudio.com/docs/nodejs/nodejs-debugging).
## CPU Profiling
In order to investigate performance issues, CPU profiling is often useful.
### Creating a profile
Node.js 16+ users can use the Node.js command line argument `--cpu-prof` to create a CPU profile.
```bash
node --cpu-prof node_modules/.bin/ng build
```
In addition to this one, another, more elaborated way to capture a CPU profile using the Chrome Devtools is detailed in https://github.com/angular/angular-cli/issues/8259#issue-269908550.
#### Opening a profile
You can use the Chrome Devtools to process it. To do so:
1. open `chrome://inspect` in Chrome
1. click on "Open dedicated DevTools for Node"
1. go to the "profiler" tab
1. click on the "Load" button and select the generated `.cpuprofile` file
1. on the left panel, select the associated file
## Creating New Packages
Adding a package to this repository means running two separate commands:
1. `schematics devkit:package PACKAGE_NAME`. This will update the `.monorepo` file, and create the
base files for the new package (package.json, src/index, etc).
1. `devkit-admin templates`. This will update the README and all other template files that might
have changed when adding a new package.
For private packages, you will need to add a `"private": true` key to your package.json manually.
This will require re-running the template admin script.
|
000372
|
| | Deploy URL | Base HREF |
| ------------------------------------------- | :--------: | :-------: |
| Initial scripts (index.html) | ✅ 👍 | ✅ 👍 |
| Initial stylesheets (index.html) | ✅ 👍 | ✅ 👍 |
| Lazy scripts (routes/import()/etc.) | ✅ 👍 | ✅ 👍 |
| Processed CSS resources (images/fonts/etc.) | ✅ 👍 | ✅ 👍 |
| Relative template (HTML) assets | ❌ 👎 | ✅ 👍 |
| Angular Router Default Base (APP_BASE_HREF) | ❌ | ✅ \*1 |
| Single reference in deployed Application | ❌ 👎 | ✅ 👍 |
| Special resource logic within CLI | ✅ 👎 | ❌ 👍 |
| Relative fetch/XMLHttpRequest | ❌ | ✅ |
✅ - has/affects the item/trait
❌ - does not have/affect the item/trait
👍 - favorable behavior
👎 - unfavorable behavior
\*1 -- Users with more complicated setups may need to manually configure the `APP_BASE_HREF` token within the application. (e.g., application routing base is `/` but assets/scripts/etc. are at `/assets/`)
|
000377
|
# Important Considerations when Using Angular Universal
## Introduction
Although the goal of the Universal project is the ability to seamlessly render an Angular
application on the server, there are some inconsistencies that you should consider. First,
there is the obvious discrepancy between the server and browser environments. When rendering
on the server, your application is in an ephemeral or "snapshot" state. The application is
fully rendered once, with the resulting HTML returned, and the remaining application state
destroyed until the next render. Next, the server environment inherently does not have the
same capabilities as the browser (and has some that likewise the browser does not). For
instance, the server does not have any concept of cookies. You can polyfill this and other
functionality, but there is no perfect solution for this. In later sections, we'll walk
through potential mitigations to reduce the scope of errors when rendering on the server.
Please also note the goal of SSR: improved initial render time for your application. This
means that anything that has the potential to reduce the speed of your application in this
initial render should be avoided or sufficiently guarded against. Again, we'll review how
to accomplish this in later sections.
## "window is not defined"
One of the most common issues when using Angular Universal is the lack of browser global
variables in the server environment. This is because the Universal project uses
[domino](https://github.com/fgnass/domino) as the server DOM rendering engine. As a result,
there is certain functionality that won't be present or supported on the server. This
includes the `window` and `document` global objects, cookies, certain HTML elements (like canvas),
and several others. There is no exhaustive list, so please be aware of the fact that if you
see an error like this, where a previously-accessible global is not defined, it's likely because
that global is not available through domino.
> Fun fact: Domino stands for "DOM in Node"
### How to fix?
#### Strategy 1: Injection
Frequently, the needed global is available through the Angular platform via Dependency Injection (DI).
For instance, the global `document` is available through the `DOCUMENT` token. Additionally, a _very_
primitive version of both `window` and `location` exist through the `DOCUMENT` object. For example:
```ts
// example.service.ts
import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Injectable()
export class ExampleService {
constructor(@Inject(DOCUMENT) private _doc: Document) {}
getWindow(): Window | null {
return this._doc.defaultView;
}
getLocation(): Location {
return this._doc.location;
}
createElement(tag: string): HTMLElement {
return this._doc.createElement(tag);
}
}
```
Please be judicious about using these references, and lower your expectations about their capabilities. `localStorage`
is one frequently-requested API that won't work how you want it to out of the box. If you need to write your own library
components, please consider using this method to provide similar functionality on the server (this is what Angular CDK
and Material do).
#### Strategy 2: Guards
If you can't inject the proper global value you need from the Angular platform, you can "guard" against
invocation of browser code, so long as you don't need to access that code on the server. For instance,
often invocations of the global `window` element are to get window size, or some other visual aspect.
However, on the server, there is no concept of "screen", and so this functionality is rarely needed.
You may read online and elsewhere that the recommended approach is to use `isPlatformBrowser` or
`isPlatformServer`. This guidance is **incorrect**. This is because you wind up creating platform-specific
code branches in your application code. This not only increases the size of your application unnecessarily,
but it also adds complexity that then has to be maintained. By separating code into separate platform-specific
modules and implementations, your base code can remain about business logic, and platform-specific exceptions
are handled as they should be: on a case-by-case abstraction basis. This can be accomplished using Angular's Dependency
Injection (DI) in order to remove the offending code and drop in a replacement at runtime. Here's an example:
```ts
// window-service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class WindowService {
getWidth(): number {
return window.innerWidth;
}
}
```
```ts
// server-window.service.ts
import { Injectable } from '@angular/core';
import { WindowService } from './window.service';
@Injectable()
export class ServerWindowService extends WindowService {
getWidth(): number {
return 0;
}
}
```
```ts
// app-server.module.ts
import {NgModule} from '@angular/core';
import {WindowService} from './window.service';
import {ServerWindowService} from './server-window.service';
@NgModule({
providers: [{
provide: WindowService,
useClass: ServerWindowService,
}]
})
```
If you have a component provided by a third-party that is not Universal-compatible out of the box,
you can create two separate modules for browser and server (the server module you should already have),
in addition to your base app module. The base app module will contain all of your platform-agnostic code,
the browser module will contain all of your browser-specific/server-incompatible code, and vice-versa for
your server module. In order to avoid editing too much template code, you can create a no-op component
to drop in for the library component. Here's an example:
```ts
// example.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'example-component',
template: `<library-component></library-component>`, // this is provided by a third-party lib
// that causes issues rendering on Universal
})
export class ExampleComponent {}
```
```ts
// app.module.ts
import {NgModule} from '@angular/core';
import {ExampleComponent} from './example.component';
@NgModule({
declarations: [ExampleComponent],
})
```
```ts
// browser-app.module.ts
import {NgModule} from '@angular/core';
import {LibraryModule} from 'some-lib';
import {AppModule} from './app.module';
@NgModule({
imports: [AppModule, LibraryModule],
})
```
```ts
// library-shim.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'library-component',
template: '',
})
export class LibraryShimComponent {}
```
```ts
// server.app.module.ts
import { NgModule } from '@angular/core';
import { LibraryShimComponent } from './library-shim.component';
import { AppModule } from './app.module';
@NgModule({
imports: [AppModule],
declarations: [LibraryShimComponent],
})
export class ServerAppModule {}
```
#### Strategy 3: Shims
If all else fails, and you simply must have access to some sort of browser functionality, you can patch
the global scope of the server environment to include the globals you need. For instance:
```ts
// server.ts
global['window'] = {
// properties you need implemented here...
};
```
This can be applied to any undefined element. Please be careful when you do this, as playing with the global
scope is generally considered an anti-pattern.
> Fun fact: a shim is a patch for functionality that will never be supported on a given platform. A
> polyfill is a patch for functionality that is planned to be supported, or is supported on newer versions
## Application is slow, or worse, won't render
The Angular Universal rendering process is straightforward, but just as simply can be blocked or slowed down
by well-meaning or innocent-looking code. First, some background on the rendering process. When a render
request is made for platform-server (the Angular Universal platform), a single route navigation is executed.
When that navigation completes, meaning that all Zone.js macrotasks are completed, the DOM in whatever state
it's in at that time is returned to the user.
> A Zone.js macrotask is just a JavaScript macrotask that executes in/is patched by Zone.js
This means that if there is a process, like a microtask, that takes up ticks to complete, or a long-standing
HTTP request, the rendering process will not complete, or will take longer. Macrotasks include calls to globals
like `setTimeout` and `setInterval`, and `Observables`. Calling these without cancelling them, or letting them run
longer than needed on the server could result in suboptimal rendering.
> It may be worth brushing up on the JavaScript event loop and learning the difference between microtasks
> and macrotasks, if you don't know it already. [Here's](https://javascript.info/event-loop) a good reference.
## My HTTP, Firebase, WebSocket, etc. won't finish before render!
Similarly to the above section on waiting for macrotasks to complete, the flip-side is that the platform will
not wait for microtasks to complete before finishing the render. In Angular Universal, we have patched the
Angular HTTP client to turn it into a macrotask, to ensure that any needed HTTP requests complete for a given
render. However, this type of patch may not be appropriate for all microtasks, and so it is recommended you use
your best judgment on how to proceed. You can look at the code reference for how Universal wraps a task to turn
it into a macrotask, or you can simply opt to change the server behavior of the given tasks.
|
000380
|
# Setting Up Local Repository
1. Clone the Angular-CLI repo. A local copy works just fine.
1. Create an upstream remote:
```bash
$ git remote add upstream https://github.com/angular/angular-cli.git
```
# Caretaker
The caretaker should triage issues, merge PR, and sheppard the release.
Caretaker rotation can be found
[here](https://rotations.corp.google.com/rotation/5117919353110528) and individual shifts can
be modified as necessary to accommodate caretaker's schedules. This automatically syncs to a
Google Calendar
[here](https://calendar.google.com/calendar/u/0/[email protected]).
Click the "+" button in the bottom right to add it to your calendar to see shifts alongside the
rest of your schedule.
The primary caretaker is responsible for both merging PRs and performing the weekly release.
The secondary caretaker does not have any _direct_ responsibilities, but they may need to take
over the primary's responsibilities if the primary is unavailable for an extended time (a day
or more) or in the event of an emergency.
At the end of each caretaker's rotation, the primary should perform a handoff in which they
provide information to the next caretaker about the current state of the repository and update
the access group to now include the next caretakers. To perform this update to the access group,
the caretaker can run:
```bash
$ yarn ng-dev caretaker handoff
```
## Merging PRs
The list of PRs which are currently ready to merge (approved with passing status checks) can
be found with [this search](https://github.com/angular/angular-cli/pulls?q=is%3Apr+is%3Aopen+label%3A%22action%3A+merge%22+-is%3Adraft).
This list should be checked daily and any ready PRs should be merged. For each PR, check the
`target` label to understand where it should be merged to. You can find which branches a specific
PR will be merged into with the `yarn ng-dev pr check-target-branches <pr>` command.
When ready to merge a PR, run the following command:
```
yarn ng-dev pr merge <pr>
```
### Maintaining LTS branches
Releases that are under Long Term Support (LTS) are listed on [angular.dev](https://angular.dev/reference/releases#support-policy-and-schedule).
Since there could be more than one LTS branch at any one time, PR authors who want to
merge commits into LTS branches must open a pull request against the specific base branch they'd like to target.
In general, cherry picks for LTS should only be done if it meets one of the criteria below:
1. It addresses a critical security vulnerability.
2. It fixes a breaking change in the external environment.
For example, this could happen if one of the dependencies is deleted from NPM.
3. It fixes a legitimate failure on CI for a particular LTS branch.
# Release
Releasing is performed using Angular's unified release tooling. Each week, two releases are expected, `latest` and `next` on npm. For major
and minor releases, some dependencies need to be manually bumped. The following files contain all the version numbers which need to be
manually updated:
- [`latest-versions.ts`](/packages/schematics/angular/utility/latest-versions.ts#L=18)
- [`latest-versions/package.json`](/packages/schematics/angular/utility/latest-versions/package.json)
- [`@angular/pwa`](/packages/angular/pwa/package.json)
- [`@angular-devkit/build-angular`](/packages/angular_devkit/build_angular/package.json)
- [`@ngtools/webpack`](/packages/ngtools/webpack/package.json)
**DURING a minor OR major CLI release:**
Once FW releases the actual minor/major release (for example: `13.0.0` or `13.1.0`), the above versions should be updated to match (remove
`-rc.0` and `-next.0`). This **must** be done as a separate PR which lands _after_ FW releases (or else CI will fail) but _before_ the CLI
release PR. Releases are built before the PR is sent for review, so any changes after that point won't be included in the release.
**AFTER a major CLI release:**
Once a major release is complete, peer dependencies in the above files will need to be updated to "undo" the above change and add the
prerelease version segment on `main`. For example, `"@angular/compiler-cli": "^13.0.0-next.0"` should become
`"@angular/compiler-cli": "^13.0.0 || ^13.1.0-next.0"`. This should be done for all the peer deps in the above files.
**AFTER a minor OR major CLI release:**
`latest-versions.ts` also needs to be updated to use `-next.0` after a major or minor release. However this needs to happen _after_ FW
publishes the initial `-next.0` release, which will happen 1 week after the major or minor release.
## Releasing the CLI
Typical patch and next releases do not require FW to release in advance, as CLI does not pin the FW
dependency.
After confirming that the above steps have been done or are not necessary, run the following and
navigate the prompts:
```sh
yarn ng-dev release publish
```
Releases should be done in "reverse semver order", meaning they should follow:
Oldest LTS -> Newest LTS -> Patch -> RC -> Next
This can skip any versions which don't need releases, so most weeks are just "Patch -> Next".
## Releasing a new package
Wombat has some special access requirements which need to be configured to publish a new NPM package.
See [this Wombat doc](http://g3doc/company/teams/cloud-client-libraries/team/automation/docs/npm-publish-service#existing-package)
and [this postmortem](http://docs/document/d/1emx2mhvF5xMzNUlDrVRYKI_u4iUOnVrg3rV6c5jk2is?resourcekey=0-qpsFbBfwioYT4f6kyUm8ZA&tab=t.0)
for more info.
Angular is _not_ an organization on NPM, therefore each package is published
independently and Wombat access needs to be managed individually. This also means
we can't rely on Wombat already having access to a new package.
In order to configure a brand new NPM package, it first needs to be published
manually so we can add Wombat access to it. Note that this step can and should be
done prior to weekly releases. The sooner this can be done, the less likely it
will block the next weekly release.
1. Check out the `main` branch, which should always have a `-next` version.
- This avoids having the initial publish actually be used in production.
1. Trigger a release build locally.
```shell
nvm install
yarn --frozen-lockfile
yarn -s ng-dev release build
```
1. Log in to NPM as `angular`.
```shell
npm login
```
- See these two Valentine entries for authentication details:
- https://valentine.corp.google.com/#/show/1460636514618735
- https://valentine.corp.google.com/#/show/1531867371192103
1. Publish the release.
```shell
(cd dist/releases/my-scope/my-pkg/ && npm publish --access public)
```
1. Add Wombat to the package.
```shell
npm owner add google-wombot @my-scope/my-pkg
```
1. Don't forget to logout.
```shell
npm logout
```
1. File a bug like [b/336626936](http://b/336626936) to ask Wombat maintainers to
accept the invite for the new package.
Once Wombat accepts the invite, regular automated releases should work as expected.
|
000408
|
#!/usr/bin/env node
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* eslint-disable no-console */
/* eslint-disable import/no-unassigned-import */
'use strict';
const path = require('path');
// Error if the external CLI appears to be used inside a google3 context.
if (process.cwd().split(path.sep).includes('google3')) {
console.error(
'This is the external Angular CLI, but you appear to be running in google3. There is a separate, internal version of the CLI which should be used instead. See http://go/angular/cli.',
);
process.exit();
}
// Provide a title to the process in `ps`.
// Due to an obscure Mac bug, do not start this title with any symbol.
try {
process.title = 'ng ' + Array.from(process.argv).slice(2).join(' ');
} catch (_) {
// If an error happened above, use the most basic title.
process.title = 'ng';
}
const rawCommandName = process.argv[2];
if (rawCommandName === '--get-yargs-completions' || rawCommandName === 'completion') {
// Skip Node.js supported checks when running ng completion.
// A warning at this stage could cause a broken source action (`source <(ng completion script)`) when in the shell init script.
require('./bootstrap');
return;
}
// This node version check ensures that extremely old versions of node are not used.
// These may not support ES2015 features such as const/let/async/await/etc.
// These would then crash with a hard to diagnose error message.
var version = process.versions.node.split('.').map((part) => Number(part));
if (version[0] % 2 === 1) {
// Allow new odd numbered releases with a warning (currently v17+)
console.warn(
'Node.js version ' +
process.version +
' detected.\n' +
'Odd numbered Node.js versions will not enter LTS status and should not be used for production.' +
' For more information, please see https://nodejs.org/en/about/previous-releases/.',
);
require('./bootstrap');
} else if (version[0] < 18 || (version[0] === 18 && version[1] < 19)) {
// Error and exit if less than 18.19
console.error(
'Node.js version ' +
process.version +
' detected.\n' +
'The Angular CLI requires a minimum Node.js version of v18.19.\n\n' +
'Please update your Node.js version or visit https://nodejs.org/ for additional instructions.\n',
);
process.exitCode = 3;
} else {
require('./bootstrap');
}
|
000496
|
The command can be used to build a project of type "application" or "library".
When used to build a library, a different builder is invoked, and only the `ts-config`, `configuration`, `poll` and `watch` options are applied.
All other options apply only to building applications.
The application builder uses the [esbuild](https://esbuild.github.io/) build tool, with default configuration options specified in the workspace configuration file (`angular.json`) or with a named alternative configuration.
A "development" configuration is created by default when you use the CLI to create the project, and you can use that configuration by specifying the `--configuration development`.
The configuration options generally correspond to the command options.
You can override individual configuration defaults by specifying the corresponding options on the command line.
The command can accept option names given in dash-case.
Note that in the configuration file, you must specify names in camelCase.
Some additional options can only be set through the configuration file,
either by direct editing or with the `ng config` command.
These include `assets`, `styles`, and `scripts` objects that provide runtime-global resources to include in the project.
Resources in CSS, such as images and fonts, are automatically written and fingerprinted at the root of the output folder.
For further details, see [Workspace Configuration](reference/configs/workspace-config).
|
000510
|
# Angular SSR
Read the dev guide [here](https://angular.dev/guide/ssr).
|
000517
|
/**
* @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 { getPotentialLocaleIdFromUrl } from '../src/i18n';
describe('getPotentialLocaleIdFromUrl', () => {
it('should extract locale ID correctly when basePath is present', () => {
const url = new URL('https://example.com/base/en/page');
const basePath = '/base';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should extract locale ID correctly when basePath has trailing slash', () => {
const url = new URL('https://example.com/base/en/page');
const basePath = '/base/';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should extract locale ID correctly when url has no trailing slash', () => {
const url = new URL('https://example.com/base/en');
const basePath = '/base/';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should extract locale ID correctly when url no trailing slash', () => {
const url = new URL('https://example.com/base/en/');
const basePath = '/base/';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should handle URL with no pathname after basePath', () => {
const url = new URL('https://example.com/base/');
const basePath = '/base';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('');
});
it('should handle URL where basePath is the entire pathname', () => {
const url = new URL('https://example.com/base');
const basePath = '/base';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('');
});
it('should handle complex basePath correctly', () => {
const url = new URL('https://example.com/base/path/en/page');
const basePath = '/base/path';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should handle URL with query parameters and hash', () => {
const url = new URL('https://example.com/base/en?query=param#hash');
const basePath = '/base';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
});
|
000648
|
/**
* @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 { RootDatabase, open } from 'lmdb';
import { Cache, CacheStore } from './cache';
export class LmbdCacheStore implements CacheStore<unknown> {
readonly #cacheFileUrl;
#db: RootDatabase | undefined;
constructor(readonly cachePath: string) {
this.#cacheFileUrl = cachePath;
}
#ensureCacheFile(): RootDatabase {
this.#db ??= open({
path: this.#cacheFileUrl,
compression: true,
});
return this.#db;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async get(key: string): Promise<any> {
const db = this.#ensureCacheFile();
const value = db.get(key);
return value;
}
has(key: string): boolean {
return this.#ensureCacheFile().doesExist(key);
}
async set(key: string, value: unknown): Promise<this> {
const db = this.#ensureCacheFile();
await db.put(key, value);
return this;
}
createCache<V = unknown>(namespace: string): Cache<V> {
return new Cache(this, namespace);
}
async close() {
try {
await this.#db?.close();
} catch {
// Failure to close should not be fatal
}
}
}
|
000657
|
/**
* @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
*/
/**
* @fileoverview
* Provides infrastructure for common caching functionality within the build system.
*/
/**
* A backing data store for one or more Cache instances.
* The interface is intentionally designed to support using a JavaScript
* Map instance as a potential cache store.
*/
export interface CacheStore<V> {
/**
* Returns the specified value from the cache store or `undefined` if not found.
* @param key The key to retrieve from the store.
*/
get(key: string): V | undefined | Promise<V | undefined>;
/**
* Returns whether the provided key is present in the cache store.
* @param key The key to check from the store.
*/
has(key: string): boolean | Promise<boolean>;
/**
* Adds a new value to the cache store if the key is not present.
* Updates the value for the key if already present.
* @param key The key to associate with the value in the cache store.
* @param value The value to add to the cache store.
*/
set(key: string, value: V): this | Promise<this>;
}
/**
* A cache object that allows accessing and storing key/value pairs in
* an underlying CacheStore. This class is the primary method for consumers
* to use a cache.
*/
export class Cache<V, S extends CacheStore<V> = CacheStore<V>> {
constructor(
protected readonly store: S,
readonly namespace?: string,
) {}
/**
* Prefixes a key with the cache namespace if present.
* @param key A key string to prefix.
* @returns A prefixed key if a namespace is present. Otherwise the provided key.
*/
protected withNamespace(key: string): string {
if (this.namespace) {
return `${this.namespace}:${key}`;
}
return key;
}
/**
* Gets the value associated with a provided key if available.
* Otherwise, creates a value using the factory creator function, puts the value
* in the cache, and returns the new value.
* @param key A key associated with the value.
* @param creator A factory function for the value if no value is present.
* @returns A value associated with the provided key.
*/
async getOrCreate(key: string, creator: () => V | Promise<V>): Promise<V> {
const namespacedKey = this.withNamespace(key);
let value = await this.store.get(namespacedKey);
if (value === undefined) {
value = await creator();
await this.store.set(namespacedKey, value);
}
return value;
}
/**
* Gets the value associated with a provided key if available.
* @param key A key associated with the value.
* @returns A value associated with the provided key if present. Otherwise, `undefined`.
*/
async get(key: string): Promise<V | undefined> {
const value = await this.store.get(this.withNamespace(key));
return value;
}
/**
* Puts a value in the cache and associates it with the provided key.
* If the key is already present, the value is updated instead.
* @param key A key associated with the value.
* @param value A value to put in the cache.
*/
async put(key: string, value: V): Promise<void> {
await this.store.set(this.withNamespace(key), value);
}
}
/**
* A lightweight in-memory cache implementation based on a JavaScript Map object.
*/
export class MemoryCache<V> extends Cache<V, Map<string, V>> {
constructor() {
super(new Map());
}
/**
* Removes all entries from the cache instance.
*/
clear() {
this.store.clear();
}
/**
* Provides all the values currently present in the cache instance.
* @returns An iterable of all values in the cache.
*/
values() {
return this.store.values();
}
/**
* Provides all the keys/values currently present in the cache instance.
* @returns An iterable of all key/value pairs in the cache.
*/
entries() {
return this.store.entries();
}
}
|
000663
|
/**
* @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 type { Metafile, PartialMessage } from 'esbuild';
/**
* Checks the input files of a build to determine if any of the files included
* in the build are not ESM. ESM files can be tree-shaken and otherwise optimized
* in ways that CommonJS and other module formats cannot. The esbuild metafile
* information is used as the basis for the analysis as it contains information
* for each input file including its respective format.
*
* If any allowed dependencies are provided via the `allowedCommonJsDependencies`
* parameter, both the direct import and any deep imports will be ignored and no
* diagnostic will be generated. Use `'*'` as entry to skip the check.
*
* If a module has been issued a diagnostic message, then all descendant modules
* will not be checked. This prevents a potential massive amount of inactionable
* messages since the initial module import is the cause of the problem.
*
* @param metafile An esbuild metafile object to check.
* @param allowedCommonJsDependencies An optional list of allowed dependencies.
* @returns Zero or more diagnostic messages for any non-ESM modules.
*/
export function checkCommonJSModules(
metafile: Metafile,
allowedCommonJsDependencies?: string[],
): PartialMessage[] {
const messages: PartialMessage[] = [];
const allowedRequests = new Set(allowedCommonJsDependencies);
if (allowedRequests.has('*')) {
return messages;
}
// Ignore Angular locale definitions which are currently UMD
allowedRequests.add('@angular/common/locales');
// Ignore zone.js due to it currently being built with a UMD like structure.
// Once the build output is updated to be fully ESM, this can be removed.
allowedRequests.add('zone.js');
// Used by '@angular/platform-server' and is in a seperate chunk that is unused when
// using `provideHttpClient(withFetch())`.
allowedRequests.add('xhr2');
// Packages used by @angular/ssr.
// While beasties is ESM it has a number of direct and transtive CJS deps.
allowedRequests.add('express');
allowedRequests.add('beasties');
// Find all entry points that contain code (JS/TS)
const files: string[] = [];
for (const { entryPoint } of Object.values(metafile.outputs)) {
if (!entryPoint) {
continue;
}
if (!isPathCode(entryPoint)) {
continue;
}
files.push(entryPoint);
}
// Track seen files so they are only analyzed once.
// Bundler runtime code is also ignored since it cannot be actionable.
const seenFiles = new Set<string>(['<runtime>']);
// Analyze the files present by walking the import graph
let currentFile: string | undefined;
while ((currentFile = files.shift())) {
const input = metafile.inputs[currentFile];
for (const imported of input.imports) {
// Ignore imports that were already seen or not originally in the code (bundler injected)
if (!imported.original || seenFiles.has(imported.path)) {
continue;
}
seenFiles.add(imported.path);
// If the dependency is allowed ignore all other checks
if (allowedRequests.has(imported.original)) {
continue;
}
// Only check actual code files
if (!isPathCode(imported.path)) {
continue;
}
// Check if non-relative import is ESM format and issue a diagnostic if the file is not allowed
if (
!isPotentialRelative(imported.original) &&
metafile.inputs[imported.path].format !== 'esm'
) {
const request = imported.original;
let notAllowed = true;
if (allowedRequests.has(request)) {
notAllowed = false;
} else {
// Check for deep imports of allowed requests
for (const allowed of allowedRequests) {
if (request.startsWith(allowed + '/')) {
notAllowed = false;
break;
}
}
}
if (notAllowed) {
// Issue a diagnostic message for CommonJS module
messages.push(createCommonJSModuleError(request, currentFile));
}
// Skip all descendants since they are also most likely not ESM but solved by addressing this import
continue;
}
// Add the path so that its imports can be checked
files.push(imported.path);
}
}
return messages;
}
/**
* Determines if a file path has an extension that is a JavaScript or TypeScript
* code file.
*
* @param name A path to check for code file extensions.
* @returns True, if a code file path; false, otherwise.
*/
function isPathCode(name: string): boolean {
return /\.[cm]?[jt]sx?$/.test(name);
}
/**
* Test an import module specifier to determine if the string potentially references a relative file.
* npm packages should not start with a period so if the first character is a period than it is not a
* package. While this is sufficient for the use case in the CommmonJS checker, only checking the
* first character does not definitely indicate the specifier is a relative path.
*
* @param specifier An import module specifier.
* @returns True, if specifier is potentially relative; false, otherwise.
*/
function isPotentialRelative(specifier: string): boolean {
return specifier[0] === '.';
}
/**
* Creates an esbuild diagnostic message for a given non-ESM module request.
*
* @param request The requested non-ESM module name.
* @param importer The path of the file containing the import.
* @returns A message representing the diagnostic.
*/
function createCommonJSModuleError(request: string, importer: string): PartialMessage {
const error = {
text: `Module '${request}' used by '${importer}' is not ESM`,
notes: [
{
text:
'CommonJS or AMD dependencies can cause optimization bailouts.\n' +
'For more information see: https://angular.dev/tools/cli/build#configuring-commonjs-dependencies',
},
],
};
return error;
}
|
000747
|
export function getLocaleBaseHref(
baseHref: string | undefined,
i18n: NormalizedApplicationBuildOptions['i18nOptions'],
locale: string,
): string | undefined {
if (i18n.flatOutput) {
return undefined;
}
if (i18n.locales[locale] && i18n.locales[locale].baseHref !== '') {
return urlJoin(baseHref || '', i18n.locales[locale].baseHref ?? `/${locale}/`);
}
return undefined;
}
|
000786
|
/**
* @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 { buildApplication } from '../../index';
import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup';
describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {
describe('Option: "baseHref"', () => {
beforeEach(async () => {
// Application code is not needed for asset tests
await harness.writeFile('src/main.ts', 'console.log("TEST");');
});
it('should update the base element href attribute when option is set', async () => {
harness.useTarget('build', {
...BASE_OPTIONS,
baseHref: '/abc',
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness.expectFile('dist/browser/index.html').content.toContain('<base href="/abc">');
});
it('should update the base element with no href attribute when option is set', async () => {
await harness.writeFile(
'src/index.html',
`
<html>
<head><base></head>
<body></body>
</html>
`,
);
harness.useTarget('build', {
...BASE_OPTIONS,
baseHref: '/abc',
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness.expectFile('dist/browser/index.html').content.toContain('<base href="/abc">');
});
it('should add the base element href attribute when option is set', async () => {
await harness.writeFile(
'src/index.html',
`
<html>
<head></head>
<body></body>
</html>
`,
);
harness.useTarget('build', {
...BASE_OPTIONS,
baseHref: '/abc',
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness.expectFile('dist/browser/index.html').content.toContain('<base href="/abc">');
});
it('should update the base element href attribute when option is set to an empty string', async () => {
harness.useTarget('build', {
...BASE_OPTIONS,
baseHref: '',
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness.expectFile('dist/browser/index.html').content.toContain('<base href="">');
});
it('should not update the base element href attribute when option is not present', async () => {
harness.useTarget('build', {
...BASE_OPTIONS,
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness.expectFile('dist/browser/index.html').content.toContain('<base href="/">');
});
it('should not change the base element href attribute when option is not present', async () => {
await harness.writeFile(
'src/index.html',
`
<html>
<head><base href="."></head>
<body></body>
</html>
`,
);
harness.useTarget('build', {
...BASE_OPTIONS,
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness.expectFile('dist/browser/index.html').content.toContain('<base href=".">');
});
});
});
|
000811
|
/**
* @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 { buildApplication } from '../../index';
import { CrossOrigin } from '../../schema';
import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup';
describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {
describe('Option: "crossOrigin"', () => {
beforeEach(async () => {
// Application code is not needed for asset tests
await harness.writeFile('src/main.ts', 'console.log("TEST");');
// Add a global stylesheet to test link elements
await harness.writeFile('src/styles.css', '/* Global styles */');
// Reduce the input index HTML to a single line to simplify comparing
await harness.writeFile(
'src/index.html',
'<html><head><base href="/"></head><body><app-root></app-root></body></html>',
);
});
it('should add the use-credentials crossorigin attribute when option is set to use-credentials', async () => {
harness.useTarget('build', {
...BASE_OPTIONS,
styles: ['src/styles.css'],
crossOrigin: CrossOrigin.UseCredentials,
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness
.expectFile('dist/browser/index.html')
.content.toEqual(
`<html><head><base href="/"><link rel="stylesheet" href="styles.css" crossorigin="use-credentials"></head>` +
`<body><app-root></app-root>` +
`<script src="main.js" type="module" crossorigin="use-credentials"></script></body></html>`,
);
});
it('should add the anonymous crossorigin attribute when option is set to anonymous', async () => {
harness.useTarget('build', {
...BASE_OPTIONS,
styles: ['src/styles.css'],
crossOrigin: CrossOrigin.Anonymous,
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness
.expectFile('dist/browser/index.html')
.content.toEqual(
`<html><head><base href="/">` +
`<link rel="stylesheet" href="styles.css" crossorigin="anonymous"></head>` +
`<body><app-root></app-root>` +
`<script src="main.js" type="module" crossorigin="anonymous"></script></body></html>`,
);
});
it('should not add a crossorigin attribute when option is set to none', async () => {
harness.useTarget('build', {
...BASE_OPTIONS,
styles: ['src/styles.css'],
crossOrigin: CrossOrigin.None,
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness
.expectFile('dist/browser/index.html')
.content.toEqual(
`<html><head><base href="/">` +
`<link rel="stylesheet" href="styles.css"></head>` +
`<body><app-root></app-root>` +
`<script src="main.js" type="module"></script></body></html>`,
);
});
it('should not add a crossorigin attribute when option is not present', async () => {
harness.useTarget('build', {
...BASE_OPTIONS,
styles: ['src/styles.css'],
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
harness
.expectFile('dist/browser/index.html')
.content.toEqual(
`<html><head><base href="/">` +
`<link rel="stylesheet" href="styles.css"></head>` +
`<body><app-root></app-root>` +
`<script src="main.js" type="module"></script></body></html>`,
);
});
});
});
|
000826
|
/**
* @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 browserslist from 'browserslist';
export function getSupportedBrowsers(
projectRoot: string,
logger: { warn(message: string): void },
): string[] {
browserslist.defaults = [
'last 2 Chrome versions',
'last 1 Firefox version',
'last 2 Edge major versions',
'last 2 Safari major versions',
'last 2 iOS major versions',
'last 2 Android major versions',
'Firefox ESR',
];
// Get browsers from config or default.
const browsersFromConfigOrDefault = new Set(browserslist(undefined, { path: projectRoot }));
// Get browsers that support ES6 modules.
const browsersThatSupportEs6 = new Set(browserslist('supports es6-module'));
const unsupportedBrowsers: string[] = [];
for (const browser of browsersFromConfigOrDefault) {
if (!browsersThatSupportEs6.has(browser)) {
browsersFromConfigOrDefault.delete(browser);
unsupportedBrowsers.push(browser);
}
}
if (unsupportedBrowsers.length) {
logger.warn(
`One or more browsers which are configured in the project's Browserslist configuration ` +
'will be ignored as ES5 output is not supported by the Angular CLI.\n' +
`Ignored browsers: ${unsupportedBrowsers.join(', ')}`,
);
}
return Array.from(browsersFromConfigOrDefault);
}
|
000953
|
describe('lazy route generator', () => {
const options = {
...defaultOptions,
route: '/new-route',
module: 'app',
};
it('should generate a lazy loaded module with a routing module', async () => {
const tree = await schematicRunner.runSchematic('module', options, appTree);
const files = tree.files;
expect(files).toEqual(
jasmine.arrayContaining([
'/projects/bar/src/app/foo/foo.module.ts',
'/projects/bar/src/app/foo/foo-routing.module.ts',
'/projects/bar/src/app/foo/foo.component.ts',
'/projects/bar/src/app/foo/foo.component.html',
'/projects/bar/src/app/foo/foo.component.css',
]),
);
const appRoutingModuleContent = tree.readContent(
'/projects/bar/src/app/app-routing.module.ts',
);
expect(appRoutingModuleContent).toMatch(
/path: '\/new-route', loadChildren: \(\) => import\('.\/foo\/foo.module'\).then\(m => m.FooModule\)/,
);
const fooRoutingModuleContent = tree.readContent(
'/projects/bar/src/app/foo/foo-routing.module.ts',
);
expect(fooRoutingModuleContent).toMatch(/RouterModule.forChild\(routes\)/);
expect(fooRoutingModuleContent).toMatch(
/const routes: Routes = \[\r?\n?\s*{ path: '', component: FooComponent }\r?\n?\s*\];/,
);
});
it('should generate a lazy loaded module with embedded route declarations', async () => {
appTree.overwrite(
'/projects/bar/src/app/app.module.ts',
`
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
RouterModule.forRoot([])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
`,
);
appTree.delete('/projects/bar/src/app/app-routing.module.ts');
const tree = await schematicRunner.runSchematic('module', options, appTree);
const files = tree.files;
expect(files).toContain('/projects/bar/src/app/foo/foo.module.ts');
expect(files).not.toContain('/projects/bar/src/app/foo/foo-routing.module.ts');
expect(files).toContain('/projects/bar/src/app/foo/foo.component.ts');
expect(files).toContain('/projects/bar/src/app/foo/foo.component.html');
expect(files).toContain('/projects/bar/src/app/foo/foo.component.css');
const appModuleContent = tree.readContent('/projects/bar/src/app/app.module.ts');
expect(appModuleContent).toMatch(
/path: '\/new-route', loadChildren: \(\) => import\('.\/foo\/foo.module'\).then\(m => m.FooModule\)/,
);
const fooModuleContent = tree.readContent('/projects/bar/src/app/foo/foo.module.ts');
expect(fooModuleContent).toMatch(/RouterModule.forChild\(routes\)/);
expect(fooModuleContent).toMatch(
/const routes: Routes = \[\r?\n?\s*{ path: '', component: FooComponent }\r?\n?\s*\];/,
);
});
it('should generate a lazy loaded module when "flat" flag is true', async () => {
const tree = await schematicRunner.runSchematic(
'module',
{ ...options, flat: true },
appTree,
);
const files = tree.files;
expect(files).toEqual(
jasmine.arrayContaining([
'/projects/bar/src/app/foo.module.ts',
'/projects/bar/src/app/foo-routing.module.ts',
'/projects/bar/src/app/foo.component.ts',
'/projects/bar/src/app/foo.component.html',
'/projects/bar/src/app/foo.component.css',
]),
);
const appRoutingModuleContent = tree.readContent(
'/projects/bar/src/app/app-routing.module.ts',
);
expect(appRoutingModuleContent).toMatch(
/path: '\/new-route', loadChildren: \(\) => import\('.\/foo.module'\).then\(m => m.FooModule\)/,
);
});
it('should generate a lazy loaded module and add route in another parallel routing module', async () => {
await schematicRunner.runSchematic(
'module',
{
...defaultOptions,
name: 'foo',
routing: true,
},
appTree,
);
const tree = await schematicRunner.runSchematic(
'module',
{
...defaultOptions,
name: 'bar',
module: 'foo',
route: 'new-route',
},
appTree,
);
expect(tree.files).toEqual(
jasmine.arrayContaining([
'/projects/bar/src/app/foo/foo-routing.module.ts',
'/projects/bar/src/app/foo/foo.module.ts',
'/projects/bar/src/app/bar/bar-routing.module.ts',
'/projects/bar/src/app/bar/bar.module.ts',
'/projects/bar/src/app/bar/bar.component.ts',
]),
);
const barRoutingModuleContent = tree.readContent(
'/projects/bar/src/app/bar/bar-routing.module.ts',
);
expect(barRoutingModuleContent).toContain(`path: '', component: BarComponent `);
const fooRoutingModuleContent = tree.readContent(
'/projects/bar/src/app/foo/foo-routing.module.ts',
);
expect(fooRoutingModuleContent).toContain(
`loadChildren: () => import('../bar/bar.module').then(m => m.BarModule)`,
);
});
it('should not add reference to RouterModule when referencing lazy routing module', async () => {
// Delete routing module
appTree.delete('/projects/bar/src/app/app-routing.module.ts');
// Update app.module to contain the route config.
appTree.overwrite(
'projects/bar/src/app/app.module.ts',
`
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, RouterModule.forRoot([])],
declarations: [AppComponent],
})
export class AppModule {}
`,
);
const tree = await schematicRunner.runSchematic(
'module',
{
...defaultOptions,
name: 'bar',
route: 'bar',
routing: true,
module: 'app.module.ts',
},
appTree,
);
const content = tree.readContent('/projects/bar/src/app/bar/bar.module.ts');
expect(content).toContain('RouterModule.forChild(routes)');
expect(content).not.toContain('BarRoutingModule');
});
});
});
|
000976
|
import { <% if(changeDetection !== 'Default') { %>ChangeDetectionStrategy, <% }%>Component<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%> } from '@angular/core';
@Component({<% if(!skipSelector) {%>
selector: '<%= selector %>',<%}%><% if(standalone) {%>
imports: [],<%} else { %>
standalone: false,
<% }%><% if(inlineTemplate) { %>
template: `
<p>
<%= dasherize(name) %> works!
</p>
`<% } else { %>
templateUrl: './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>.html'<% } if(inlineStyle) { %>,
styles: `<% if(displayBlock){ %>
:host {
display: block;
}
<% } %>`<% } else if (style !== 'none') { %>,
styleUrl: './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>.<%= style %>'<% } %><% if(!!viewEncapsulation) { %>,
encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>,
changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %>
})
export <% if(exportDefault) {%>default <%}%>class <%= classify(name) %><%= classify(type) %> {
}
|
000985
|
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering()
]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
|
000991
|
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';<% if(serverRouting) { %>
import { provideServerRoutesConfig } from '@angular/ssr';<% } %>
import { appConfig } from './app.config';<% if(serverRouting) { %>
import { serverRoutes } from './app.routes.server';<% } %>
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering(),<% if(serverRouting) { %>
provideServerRoutesConfig(serverRoutes)<% } %>
]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
|
000998
|
# <%= classify(name) %>
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version <%= angularLatestVersion %>.
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
```bash
ng generate component component-name
```
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
```bash
ng generate --help
```
## Building
To build the library, run:
```bash
ng build <%= name %>
```
This command will compile your project, and the build artifacts will be placed in the `dist/` directory.
### Publishing the Library
Once the project is built, you can publish your library by following these steps:
1. Navigate to the `dist` directory:
```bash
cd dist/<%= dasherize(name) %>
```
2. Run the `npm publish` command to publish your library to the npm registry:
```bash
npm publish
```
## Running unit tests
To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command:
```bash
ng test
```
## Running end-to-end tests
For end-to-end (e2e) testing, run:
```bash
ng e2e
```
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
001005
|
/**
* @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import { join } from 'node:path';
import { Schema as ServerOptions } from './schema';
describe('SSR Schematic', () => {
const defaultOptions: ServerOptions = {
project: 'test-app',
};
const schematicRunner = new SchematicTestRunner(
'@schematics/angular',
require.resolve(join(__dirname, '../collection.json')),
);
let appTree: UnitTestTree;
const workspaceOptions = {
name: 'workspace',
newProjectRoot: 'projects',
version: '6.0.0',
};
beforeEach(async () => {
appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'workspace',
workspaceOptions,
);
});
describe('non standalone application', () => {
beforeEach(async () => {
appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'application',
{
name: 'test-app',
inlineStyle: false,
inlineTemplate: false,
routing: false,
style: 'css',
skipTests: false,
standalone: false,
},
appTree,
);
});
it('should add dependency: express', async () => {
const tree = await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
const filePath = '/package.json';
const contents = tree.readContent(filePath);
expect(contents).toContain('express');
});
it('should install npm dependencies', async () => {
await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
expect(schematicRunner.tasks.length).toBe(1);
expect(schematicRunner.tasks[0].name).toBe('node-package');
expect((schematicRunner.tasks[0].options as { command: string }).command).toBe('install');
});
it(`should update 'tsconfig.app.json' files with Express main file`, async () => {
const tree = await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
const { files } = tree.readJson('/projects/test-app/tsconfig.app.json') as {
files: string[];
};
expect(files).toEqual(['src/main.ts', 'src/main.server.ts', 'src/server.ts']);
});
});
describe('standalone application', () => {
beforeEach(async () => {
appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'application',
{
name: 'test-app',
inlineStyle: false,
inlineTemplate: false,
routing: false,
style: 'css',
skipTests: false,
standalone: true,
},
appTree,
);
});
it('should add script section in package.json', async () => {
const tree = await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
const { scripts } = tree.readJson('/package.json') as { scripts: Record<string, string> };
expect(scripts['serve:ssr:test-app']).toBe(`node dist/test-app/server/server.mjs`);
});
it('works when using a custom "outputPath.browser" and "outputPath.server" values', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const config = appTree.readJson('/angular.json') as any;
const build = config.projects['test-app'].architect.build;
build.options.outputPath = {
base: build.options.outputPath,
browser: 'public',
server: 'node-server',
};
appTree.overwrite('/angular.json', JSON.stringify(config, undefined, 2));
const tree = await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
const { scripts } = tree.readJson('/package.json') as { scripts: Record<string, string> };
expect(scripts['serve:ssr:test-app']).toBe(`node dist/test-app/node-server/server.mjs`);
const serverFileContent = tree.readContent('/projects/test-app/src/server.ts');
expect(serverFileContent).toContain(`resolve(serverDistFolder, '../public')`);
});
it(`removes "outputPath.browser" when it's an empty string`, async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const config = appTree.readJson('/angular.json') as any;
const build = config.projects['test-app'].architect.build;
build.options.outputPath = {
base: build.options.outputPath,
browser: '',
server: 'node-server',
};
appTree.overwrite('/angular.json', JSON.stringify(config, undefined, 2));
const tree = await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
const { scripts } = tree.readJson('/package.json') as { scripts: Record<string, string> };
expect(scripts['serve:ssr:test-app']).toBe(`node dist/test-app/node-server/server.mjs`);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updatedConfig = tree.readJson('/angular.json') as any;
expect(updatedConfig.projects['test-app'].architect.build.options.outputPath).toEqual({
base: 'dist/test-app',
server: 'node-server',
});
});
});
describe('Legacy browser builder', () => {
function convertBuilderToLegacyBrowser(): void {
const config = JSON.parse(appTree.readContent('/angular.json'));
const build = config.projects['test-app'].architect.build;
build.builder = '@angular-devkit/build-angular:browser';
build.options = {
...build.options,
main: build.options.browser,
browser: undefined,
};
build.configurations.development = {
...build.configurations.development,
vendorChunk: true,
namedChunks: true,
buildOptimizer: false,
};
appTree.overwrite('/angular.json', JSON.stringify(config, undefined, 2));
}
beforeEach(async () => {
appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'application',
{
name: 'test-app',
inlineStyle: false,
inlineTemplate: false,
routing: false,
style: 'css',
skipTests: false,
standalone: false,
},
appTree,
);
convertBuilderToLegacyBrowser();
});
it(`should update 'tsconfig.server.json' files with Express main file`, async () => {
const tree = await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
const { files } = tree.readJson('/projects/test-app/tsconfig.server.json') as {
files: string[];
};
expect(files).toEqual(['src/main.server.ts', 'src/server.ts']);
});
it(`should add export to main file in 'server.ts'`, async () => {
const tree = await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
const content = tree.readContent('/projects/test-app/src/server.ts');
expect(content).toContain(`export default AppServerModule`);
});
it(`should add correct value to 'distFolder'`, async () => {
const tree = await schematicRunner.runSchematic('ssr', defaultOptions, appTree);
const content = tree.readContent('/projects/test-app/src/server.ts');
expect(content).toContain(`const distFolder = join(process.cwd(), 'dist/test-app/browser');`);
});
});
});
|
001006
|
import 'zone.js/node';
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr/node';
import * as express from 'express';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %> from './main.server';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), '<%= browserDistDirectory %>');
const indexHtml = existsSync(join(distFolder, 'index.original.html'))
? join(distFolder, 'index.original.html')
: join(distFolder, 'index.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', distFolder);
// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
// All regular routes use the Angular engine
server.get('*', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
<% if (isStandalone) { %>bootstrap<% } else { %>bootstrap: AppServerModule<% } %>,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: distFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
function run(): void {
const port = process.env['PORT'] || 4000;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export default <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %>;
|
001007
|
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine, isMainModule } from '@angular/ssr/node';
import express from 'express';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %> from './main.server';
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../<%= browserDistDirectory %>');
const indexHtml = join(serverDistFolder, 'index.server.html');
const app = express();
const commonEngine = new CommonEngine();
/**
* Example Express Rest API endpoints can be defined here.
* Uncomment and define endpoints as necessary.
*
* Example:
* ```ts
* app.get('/api/**', (req, res) => {
* // Handle API request
* });
* ```
*/
/**
* Serve static files from /<%= browserDistDirectory %>
*/
app.get(
'**',
express.static(browserDistFolder, {
maxAge: '1y',
index: 'index.html'
}),
);
/**
* Handle all other requests by rendering the Angular application.
*/
app.get('**', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
<% if (isStandalone) { %>bootstrap<% } else { %>bootstrap: AppServerModule<% } %>,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
/**
* Start the server if this module is the main entry point.
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
*/
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
app.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
|
001008
|
import {
AngularNodeAppEngine,
createNodeRequestHandler,
isMainModule,
writeResponseToNodeResponse,
} from '@angular/ssr/node';
import express from 'express';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../<%= browserDistDirectory %>');
const app = express();
const angularApp = new AngularNodeAppEngine();
/**
* Example Express Rest API endpoints can be defined here.
* Uncomment and define endpoints as necessary.
*
* Example:
* ```ts
* app.get('/api/**', (req, res) => {
* // Handle API request
* });
* ```
*/
/**
* Serve static files from /<%= browserDistDirectory %>
*/
app.get(
'**',
express.static(browserDistFolder, {
maxAge: '1y',
index: 'index.html',
setHeaders: (res) => {
const headers = angularApp.getPrerenderHeaders(res.req);
for (const [key, value] of headers) {
res.setHeader(key, value);
}
},
}),
);
/**
* Handle all other requests by rendering the Angular application.
*/
app.get('**', (req, res, next) => {
angularApp
.render(req)
.then((response) =>
response ? writeResponseToNodeResponse(response, res) : next(),
)
.catch(next);
});
/**
* Start the server if this module is the main entry point.
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
*/
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
app.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
/**
* The request handler used by the Angular CLI (dev-server and during build).
*/
export const reqHandler = createNodeRequestHandler(app);
|
001089
|
/**
* @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import { parse as parseJson } from 'jsonc-parser';
import { latestVersions } from '../utility/latest-versions';
import { Schema as WorkspaceOptions } from '../workspace/schema';
import { Schema as ApplicationOptions, Style, ViewEncapsulation } from './schema';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function readJsonFile(tree: UnitTestTree, path: string): any {
return parseJson(tree.readContent(path).toString());
}
describe('Application Schematic', () => {
const schematicRunner = new SchematicTestRunner(
'@schematics/angular',
require.resolve('../collection.json'),
);
const workspaceOptions: WorkspaceOptions = {
name: 'workspace',
newProjectRoot: 'projects',
version: '6.0.0',
};
const defaultOptions: ApplicationOptions = {
name: 'foo',
skipPackageJson: false,
};
let workspaceTree: UnitTestTree;
beforeEach(async () => {
workspaceTree = await schematicRunner.runSchematic('workspace', workspaceOptions);
});
it('should create all files of an application', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{ ...defaultOptions, standalone: false },
workspaceTree,
);
expect(tree.files).toEqual(
jasmine.arrayContaining([
'/projects/foo/tsconfig.app.json',
'/projects/foo/tsconfig.spec.json',
'/projects/foo/public/favicon.ico',
'/projects/foo/src/index.html',
'/projects/foo/src/main.ts',
'/projects/foo/src/styles.css',
'/projects/foo/src/app/app.module.ts',
'/projects/foo/src/app/app.component.css',
'/projects/foo/src/app/app.component.html',
'/projects/foo/src/app/app.component.spec.ts',
'/projects/foo/src/app/app.component.ts',
]),
);
});
it('should add the application to the workspace', async () => {
const options = { ...defaultOptions };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const workspace = JSON.parse(tree.readContent('/angular.json'));
expect(workspace.projects.foo).toBeDefined();
});
it('should set the prefix to app if none is set', async () => {
const options = { ...defaultOptions };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const workspace = JSON.parse(tree.readContent('/angular.json'));
expect(workspace.projects.foo.prefix).toEqual('app');
});
it('should set the prefix correctly', async () => {
const options = { ...defaultOptions, prefix: 'pre' };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const workspace = JSON.parse(tree.readContent('/angular.json'));
expect(workspace.projects.foo.prefix).toEqual('pre');
});
it('should set the right paths in the tsconfig.app.json', async () => {
const tree = await schematicRunner.runSchematic('application', defaultOptions, workspaceTree);
const { files, extends: _extends } = readJsonFile(tree, '/projects/foo/tsconfig.app.json');
expect(files).toEqual(['src/main.ts']);
expect(_extends).toBe('../../tsconfig.json');
});
it('should set the right paths in the tsconfig.spec.json', async () => {
const tree = await schematicRunner.runSchematic('application', defaultOptions, workspaceTree);
const { extends: _extends } = readJsonFile(tree, '/projects/foo/tsconfig.spec.json');
expect(_extends).toBe('../../tsconfig.json');
});
it('should install npm dependencies when `skipInstall` is false', async () => {
await schematicRunner.runSchematic(
'application',
{ ...defaultOptions, ssr: true, skipInstall: false },
workspaceTree,
);
expect(schematicRunner.tasks.length).toBe(1);
expect(schematicRunner.tasks[0].name).toBe('node-package');
expect((schematicRunner.tasks[0].options as { command: string }).command).toBe('install');
});
it('should not install npm dependencies when `skipInstall` is true', async () => {
await schematicRunner.runSchematic(
'application',
{ ...defaultOptions, ssr: true, skipInstall: true },
workspaceTree,
);
expect(schematicRunner.tasks.length).toBe(0);
});
it('should set the skipTests flag for other schematics when using --skipTests=true', async () => {
const options: ApplicationOptions = { ...defaultOptions, skipTests: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const config = JSON.parse(tree.readContent('/angular.json'));
const schematics = config.projects.foo.schematics;
expect(schematics['@schematics/angular:class']).toEqual({ skipTests: true });
expect(schematics['@schematics/angular:component']).toEqual({ skipTests: true });
expect(schematics['@schematics/angular:directive']).toEqual({ skipTests: true });
expect(schematics['@schematics/angular:guard']).toEqual({ skipTests: true });
expect(schematics['@schematics/angular:interceptor']).toEqual({ skipTests: true });
expect(schematics['@schematics/angular:pipe']).toEqual({ skipTests: true });
expect(schematics['@schematics/angular:resolver']).toEqual({ skipTests: true });
expect(schematics['@schematics/angular:service']).toEqual({ skipTests: true });
});
it('minimal=true should not create e2e and test targets', async () => {
const options = { ...defaultOptions, minimal: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const config = JSON.parse(tree.readContent('/angular.json'));
const architect = config.projects.foo.architect;
expect(architect.test).not.toBeDefined();
expect(architect.e2e).not.toBeDefined();
});
it('minimal=true should configure the schematics options for components', async () => {
const options = { ...defaultOptions, minimal: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const config = JSON.parse(tree.readContent('/angular.json'));
const schematics = config.projects.foo.schematics;
expect(schematics['@schematics/angular:component']).toEqual({
inlineTemplate: true,
inlineStyle: true,
skipTests: true,
});
});
it('minimal=true allows inlineStyle=false when configuring the schematics options for components', async () => {
const options = { ...defaultOptions, minimal: true, inlineStyle: false };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const config = JSON.parse(tree.readContent('/angular.json'));
const schematics = config.projects.foo.schematics;
expect(schematics['@schematics/angular:component']).toEqual({
inlineTemplate: true,
skipTests: true,
});
});
it('minimal=true allows inlineTemplate=false when configuring the schematics options for components', async () => {
const options = { ...defaultOptions, minimal: true, inlineTemplate: false };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const config = JSON.parse(tree.readContent('/angular.json'));
const schematics = config.projects.foo.schematics;
expect(schematics['@schematics/angular:component']).toEqual({
inlineStyle: true,
skipTests: true,
});
});
it(`should create an application with SSR features when 'ssr=true'`, async () => {
const options = { ...defaultOptions, ssr: true };
const filePath = '/projects/foo/src/server.ts';
expect(workspaceTree.exists(filePath)).toBeFalse();
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
expect(tree.exists(filePath)).toBeTrue();
});
it(`should not create an application with SSR features when 'ssr=false'`, async () => {
const options = { ...defaultOptions, ssr: false };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
expect(tree.exists('/projects/foo/src/server.ts')).toBeFalse();
});
|
001091
|
it(`should create kebab-case project folder names with PascalCase project name`, async () => {
const options: ApplicationOptions = { ...defaultOptions, name: 'MyCool' };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const exists = tree.exists('/projects/my-cool/tsconfig.app.json');
expect(exists).toBeTrue();
});
it(`should create scoped kebab-case project folder names with PascalCase project name`, async () => {
const options: ApplicationOptions = { ...defaultOptions, name: '@foo/MyCool' };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const exists = tree.exists('/projects/foo/my-cool/tsconfig.app.json');
expect(exists).toBeTrue();
});
it('should support creating applications with `_` and `.` in name', async () => {
const options = { ...defaultOptions, name: 'foo.bar_buz' };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
expect(tree.exists('/projects/foo.bar_buz/tsconfig.app.json')).toBeTrue();
});
it('should support creating scoped application', async () => {
const scopedName = '@myscope/myapp';
const options = { ...defaultOptions, name: scopedName };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const cfg = JSON.parse(tree.readContent('/angular.json'));
expect(cfg.projects['@myscope/myapp']).toBeDefined();
});
it('should create correct files when using minimal', async () => {
const options = { ...defaultOptions, minimal: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const files = tree.files;
[
'/projects/foo/tsconfig.spec.json',
'/projects/foo/src/app/app.component.css',
'/projects/foo/src/app/app.component.html',
'/projects/foo/src/app/app.component.spec.ts',
].forEach((x) => expect(files).not.toContain(x));
expect(files).toEqual(
jasmine.arrayContaining([
'/projects/foo/tsconfig.app.json',
'/projects/foo/public/favicon.ico',
'/projects/foo/src/index.html',
'/projects/foo/src/main.ts',
'/projects/foo/src/styles.css',
'/projects/foo/src/app/app.component.ts',
]),
);
});
it('should create correct files when using minimal and inlineStyle=false', async () => {
const options = { ...defaultOptions, minimal: true, inlineStyle: false };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const files = tree.files;
[
'/projects/foo/tsconfig.spec.json',
'/projects/foo/karma.conf.js',
'/projects/foo/src/test.ts',
'/projects/foo/src/app/app.component.html',
'/projects/foo/src/app/app.component.spec.ts',
].forEach((x) => expect(files).not.toContain(x));
expect(files).toEqual(
jasmine.arrayContaining([
'/projects/foo/tsconfig.app.json',
'/projects/foo/public/favicon.ico',
'/projects/foo/src/index.html',
'/projects/foo/src/main.ts',
'/projects/foo/src/styles.css',
'/projects/foo/src/app/app.component.css',
'/projects/foo/src/app/app.component.ts',
]),
);
});
it('should create correct files when using minimal and inlineTemplate=false', async () => {
const options = { ...defaultOptions, minimal: true, inlineTemplate: false };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const files = tree.files;
[
'/projects/foo/tsconfig.spec.json',
'/projects/foo/karma.conf.js',
'/projects/foo/src/test.ts',
'/projects/foo/src/app/app.component.css',
'/projects/foo/src/app/app.component.spec.ts',
].forEach((x) => expect(files).not.toContain(x));
expect(files).toEqual(
jasmine.arrayContaining([
'/projects/foo/tsconfig.app.json',
'/projects/foo/public/favicon.ico',
'/projects/foo/src/index.html',
'/projects/foo/src/main.ts',
'/projects/foo/src/styles.css',
'/projects/foo/src/app/app.component.html',
'/projects/foo/src/app/app.component.ts',
]),
);
});
it('should create all files of a standalone application', async () => {
const options = { ...defaultOptions, standalone: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const files = tree.files;
expect(files).toEqual(
jasmine.arrayContaining([
'/projects/foo/tsconfig.app.json',
'/projects/foo/tsconfig.spec.json',
'/projects/foo/public/favicon.ico',
'/projects/foo/src/index.html',
'/projects/foo/src/main.ts',
'/projects/foo/src/styles.css',
'/projects/foo/src/app/app.config.ts',
'/projects/foo/src/app/app.component.css',
'/projects/foo/src/app/app.component.html',
'/projects/foo/src/app/app.component.spec.ts',
'/projects/foo/src/app/app.component.ts',
]),
);
});
it('should not create any module files', async () => {
const options = { ...defaultOptions, standalone: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const moduleFiles = tree.files.filter((file) => file.endsWith('.module.ts'));
expect(moduleFiles.length).toEqual(0);
});
it('should enable zone event coalescing by default', async () => {
const options = { ...defaultOptions, standalone: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const appConfig = tree.readContent('/projects/foo/src/app/app.config.ts');
expect(appConfig).toContain('provideZoneChangeDetection({ eventCoalescing: true })');
});
it('should create a standalone component', async () => {
const options = { ...defaultOptions, standalone: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const component = tree.readContent('/projects/foo/src/app/app.component.ts');
expect(component).not.toContain('standalone');
});
it('should create routing information by default', async () => {
const options = { ...defaultOptions, standalone: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
expect(tree.files).toContain('/projects/foo/src/app/app.routes.ts');
const component = tree.readContent('/projects/foo/src/app/app.component.ts');
expect(component).toContain(`import { RouterOutlet } from '@angular/router';`);
expect(component).toContain(`imports: [RouterOutlet]`);
const config = tree.readContent('/projects/foo/src/app/app.config.ts');
expect(config).toContain(`import { provideRouter } from '@angular/router';`);
expect(config).toContain(`import { routes } from './app.routes';`);
expect(config).toContain('provideRouter(routes)');
});
it('should create a main.ts', async () => {
const options = { ...defaultOptions, standalone: true };
const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const main = tree.readContent('/projects/foo/src/main.ts');
expect(main).toContain('bootstrapApplication');
});
|
001099
|
import { Routes } from '@angular/router';
export const routes: Routes = [];
|
001121
|
/**
* @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import { Schema as ApplicationOptions } from '../application/schema';
import { Schema as WorkspaceOptions } from '../workspace/schema';
import { Schema as GuardOptions } from './schema';
describe('Guard Schematic', () => {
const schematicRunner = new SchematicTestRunner(
'@schematics/angular',
require.resolve('../collection.json'),
);
const defaultOptions: GuardOptions = {
name: 'foo',
flat: true,
project: 'bar',
};
const workspaceOptions: WorkspaceOptions = {
name: 'workspace',
newProjectRoot: 'projects',
version: '6.0.0',
};
const appOptions: ApplicationOptions = {
name: 'bar',
inlineStyle: false,
inlineTemplate: false,
routing: false,
skipTests: false,
skipPackageJson: false,
};
let appTree: UnitTestTree;
beforeEach(async () => {
appTree = await schematicRunner.runSchematic('workspace', workspaceOptions);
appTree = await schematicRunner.runSchematic('application', appOptions, appTree);
});
it('should create a (deprecated) class-based guard with --no-functional', async () => {
const tree = await schematicRunner.runSchematic(
'guard',
{ ...defaultOptions, functional: false },
appTree,
);
const files = tree.files;
expect(files).toContain('/projects/bar/src/app/foo.guard.spec.ts');
expect(files).toContain('/projects/bar/src/app/foo.guard.ts');
});
it('should respect the skipTests flag', async () => {
const options = { ...defaultOptions, skipTests: true };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const files = tree.files;
expect(files).not.toContain('/projects/bar/src/app/foo.guard.spec.ts');
expect(files).toContain('/projects/bar/src/app/foo.guard.ts');
});
it('should respect the flat flag', async () => {
const options = { ...defaultOptions, flat: false };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const files = tree.files;
expect(files).toContain('/projects/bar/src/app/foo/foo.guard.spec.ts');
expect(files).toContain('/projects/bar/src/app/foo/foo.guard.ts');
});
it('should respect the sourceRoot value', async () => {
const config = JSON.parse(appTree.readContent('/angular.json'));
config.projects.bar.sourceRoot = 'projects/bar/custom';
appTree.overwrite('/angular.json', JSON.stringify(config, null, 2));
appTree = await schematicRunner.runSchematic('guard', defaultOptions, appTree);
expect(appTree.files).toContain('/projects/bar/custom/app/foo.guard.ts');
});
it('should respect the implements value', async () => {
const options = { ...defaultOptions, implements: ['CanActivate'], functional: false };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts');
expect(fileString).toContain('CanActivate');
expect(fileString).toContain('canActivate');
expect(fileString).not.toContain('CanActivateChild');
expect(fileString).not.toContain('canActivateChild');
expect(fileString).not.toContain('CanMatch');
expect(fileString).not.toContain('canMatch');
});
it('should generate a functional guard by default', async () => {
const options = { ...defaultOptions, implements: ['CanActivate'] };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts');
expect(fileString).toContain('export const fooGuard: CanActivateFn = (route, state) => {');
expect(fileString).not.toContain('CanActivateChild');
expect(fileString).not.toContain('canActivateChild');
expect(fileString).not.toContain('CanMatch');
expect(fileString).not.toContain('canMatch');
});
it('should generate a helper function to execute the guard in a test', async () => {
const options = { ...defaultOptions, implements: ['CanActivate'] };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.spec.ts');
expect(fileString).toContain('const executeGuard: CanActivateFn = (...guardParameters) => ');
expect(fileString).toContain(
'TestBed.runInInjectionContext(() => fooGuard(...guardParameters));',
);
});
it('should generate CanDeactivateFn with unknown functional guard', async () => {
const options = { ...defaultOptions, implements: ['CanDeactivate'] };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts');
expect(fileString).toContain(
'export const fooGuard: CanDeactivateFn<unknown> = ' +
'(component, currentRoute, currentState, nextState) => {',
);
});
it('should respect the implements values in (deprecated) class-based guards', async () => {
const implementationOptions = ['CanActivate', 'CanDeactivate', 'CanActivateChild'];
const options = { ...defaultOptions, implements: implementationOptions, functional: false };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts');
// Should contain all implementations
implementationOptions.forEach((implementation: string) => {
expect(fileString).toContain(implementation);
const functionName = `${implementation.charAt(0).toLowerCase()}${implementation.slice(1)}`;
expect(fileString).toContain(functionName);
});
});
it('should add correct imports based on CanMatch implementation in (deprecated) class-based guards', async () => {
const implementationOptions = ['CanMatch'];
const options = { ...defaultOptions, implements: implementationOptions, functional: false };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts');
const expectedImports = `import { CanMatch, GuardResult, MaybeAsync, Route, UrlSegment } from '@angular/router';`;
expect(fileString).toContain(expectedImports);
});
it('should add correct imports based on CanActivate implementation in (deprecated) class-based guards', async () => {
const implementationOptions = ['CanActivate'];
const options = { ...defaultOptions, implements: implementationOptions, functional: false };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts');
const expectedImports =
`import { ActivatedRouteSnapshot, CanActivate, GuardResult, ` +
`MaybeAsync, RouterStateSnapshot } from '@angular/router';`;
expect(fileString).toContain(expectedImports);
});
it('should add correct imports based on canActivate functional guard', async () => {
const options = { ...defaultOptions, implements: ['CanActivate'] };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts');
const expectedImports = `import { CanActivateFn } from '@angular/router';`;
expect(fileString).toContain(expectedImports);
});
it('should add correct imports if multiple implementations was selected in (deprecated) class-based guards', async () => {
const implementationOptions = ['CanActivate', 'CanMatch', 'CanActivateChild'];
const options = { ...defaultOptions, implements: implementationOptions, functional: false };
const tree = await schematicRunner.runSchematic('guard', options, appTree);
const fileString = tree.readContent('/projects/bar/src/app/foo.guard.ts');
const expectedImports =
`import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, CanMatch, GuardResult, ` +
`MaybeAsync, Route, RouterStateSnapshot, UrlSegment } from '@angular/router';`;
expect(fileString).toContain(expectedImports);
});
});
|
001123
|
import { TestBed } from '@angular/core/testing';
import { <%= classify(name) %>Guard } from './<%= dasherize(name) %>.guard';
describe('<%= classify(name) %>Guard', () => {
let guard: <%= classify(name) %>Guard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(<%= classify(name) %>Guard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});
|
001125
|
import { TestBed } from '@angular/core/testing';
import { <%= guardType %> } from '@angular/router';
import { <%= camelize(name) %>Guard } from './<%= dasherize(name) %>.guard';
describe('<%= camelize(name) %>Guard', () => {
const executeGuard: <%= guardType %> = (...guardParameters) =>
TestBed.runInInjectionContext(() => <%= camelize(name) %>Guard(...guardParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(executeGuard).toBeTruthy();
});
});
|
001133
|
/**
* @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 { SchematicTestRunner } from '@angular-devkit/schematics/testing';
import { Schema as NgNewOptions } from './schema';
describe('Ng New Schematic', () => {
const schematicRunner = new SchematicTestRunner(
'@schematics/angular',
require.resolve('../collection.json'),
);
const defaultOptions: NgNewOptions = {
name: 'foo',
directory: 'bar',
version: '6.0.0',
};
it('should create files of a workspace', async () => {
const options = { ...defaultOptions };
const tree = await schematicRunner.runSchematic('ng-new', options);
const files = tree.files;
expect(files).toContain('/bar/angular.json');
});
it('should create files of an application', async () => {
const options = { ...defaultOptions };
const tree = await schematicRunner.runSchematic('ng-new', options);
const files = tree.files;
expect(files).toEqual(
jasmine.arrayContaining([
'/bar/tsconfig.app.json',
'/bar/src/main.ts',
'/bar/src/app/app.config.ts',
]),
);
expect(files).not.toEqual(jasmine.arrayContaining(['/bar/src/app/app.module.ts']));
});
it('should create module files of a standalone=false application', async () => {
const options = { ...defaultOptions, standalone: false };
const tree = await schematicRunner.runSchematic('ng-new', options);
const files = tree.files;
expect(files).toEqual(
jasmine.arrayContaining([
'/bar/tsconfig.app.json',
'/bar/src/main.ts',
'/bar/src/app/app.module.ts',
]),
);
});
it('should should set the prefix in angular.json and in app.component.ts', async () => {
const options = { ...defaultOptions, prefix: 'pre' };
const tree = await schematicRunner.runSchematic('ng-new', options);
const content = tree.readContent('/bar/angular.json');
expect(content).toMatch(/"prefix": "pre"/);
});
it('should set up the app module when standalone=false', async () => {
const options: NgNewOptions = {
name: 'foo',
version: '6.0.0',
standalone: false,
};
const tree = await schematicRunner.runSchematic('ng-new', options);
const moduleContent = tree.readContent('/foo/src/app/app.module.ts');
expect(moduleContent).toMatch(/declarations:\s*\[\s*AppComponent\s*\]/m);
});
it('createApplication=false should create an empty workspace', async () => {
const options = { ...defaultOptions, createApplication: false };
const tree = await schematicRunner.runSchematic('ng-new', options);
const files = tree.files;
expect(files).toContain('/bar/angular.json');
expect(files).not.toContain('/bar/src');
});
it('minimal=true should not create an e2e target', async () => {
const options = { ...defaultOptions, minimal: true };
const tree = await schematicRunner.runSchematic('ng-new', options);
const confContent = JSON.parse(tree.readContent('/bar/angular.json'));
expect(confContent.projects.foo.e2e).toBeUndefined();
});
it('should add packageManager option in angular.json', async () => {
const tree = await schematicRunner.runSchematic('ng-new', {
...defaultOptions,
packageManager: 'npm',
});
const { cli } = JSON.parse(tree.readContent('/bar/angular.json'));
expect(cli.packageManager).toBe('npm');
});
});
|
001196
|
describe('addRootImport', () => {
it('should add a root import to an NgModule-based app', async () => {
await setupProject();
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}.forRoot([])`,
),
host,
);
const content = readFile('app/app.module.ts');
assertContains(content, `import { MyModule } from '@my/module';`);
assertContains(content, `imports: [BrowserModule, MyModule.forRoot([])]`);
});
it('should add a root import to a standalone app', async () => {
await setupProject(true);
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
const content = readFile('app/app.config.ts');
assertContains(content, `importProvidersFrom`);
assertContains(content, `import { MyModule } from '@my/module';`);
assertContains(content, `importProvidersFrom(MyModule)`);
});
it('should add a root import to a standalone app whose app config does not have a providers array', async () => {
await setupProject(true);
host.overwrite(
getPathWithinProject('app/app.config.ts'),
`
import { ApplicationConfig } from '@angular/core';
export const appConfig: ApplicationConfig = {};
`,
);
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
const content = readFile('app/app.config.ts');
assertContains(
content,
`import { ApplicationConfig, importProvidersFrom } from '@angular/core';`,
);
assertContains(content, `import { MyModule } from '@my/module';`);
assertContains(content, `providers: [importProvidersFrom(MyModule)]`);
});
it('should add a root import to a standalone app with a config with providers', async () => {
await setupProject(true);
host.overwrite(
getPathWithinProject('app/app.config.ts'),
`
import { ApplicationConfig } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
{provide: 'foo', useValue: 123}
]
};
`,
);
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
const content = readFile('app/app.config.ts');
assertContains(
content,
`import { ApplicationConfig, importProvidersFrom } from '@angular/core';`,
);
assertContains(content, `import { MyModule } from '@my/module';`);
assertContains(
content,
`providers: [
{provide: 'foo', useValue: 123},
importProvidersFrom(MyModule)
]`,
);
});
it(
'should add a root import to a standalone app whose app config does not have have ' +
'a providers array, but has another property',
async () => {
await setupProject(true);
host.overwrite(
getPathWithinProject('app/app.config.ts'),
`
import { ApplicationConfig } from '@angular/core';
export const appConfig: ApplicationConfig = {
otherProp: {},
};
`,
);
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
const content = readFile('app/app.config.ts');
assertContains(
content,
`import { ApplicationConfig, importProvidersFrom } from '@angular/core';`,
);
assertContains(content, `import { MyModule } from '@my/module';`);
assertContains(
content,
`
export const appConfig: ApplicationConfig = {
otherProp: {},
providers: [importProvidersFrom(MyModule)]
};
`,
);
},
);
it('should add a root import to a standalone app with an inline app config', async () => {
await setupProject(true);
host.overwrite(
getPathWithinProject('main.ts'),
`
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {});
`,
);
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
const content = readFile('main.ts');
assertContains(content, `import { importProvidersFrom } from '@angular/core';`);
assertContains(content, `import { MyModule } from '@my/module';`);
assertContains(
content,
`bootstrapApplication(AppComponent, {
providers: [importProvidersFrom(MyModule)]
});`,
);
});
it('should add a root import to a standalone app without an app config', async () => {
await setupProject(true);
host.overwrite(
getPathWithinProject('main.ts'),
`
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent);
`,
);
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
const content = readFile('main.ts');
assertContains(content, `import { importProvidersFrom } from '@angular/core';`);
assertContains(content, `import { MyModule } from '@my/module';`);
assertContains(
content,
`bootstrapApplication(AppComponent, {
providers: [importProvidersFrom(MyModule)]
});`,
);
});
it('should add a root import to a standalone app with a merged app config', async () => {
await setupProject(true);
host.overwrite(
getPathWithinProject('main.ts'),
`
import { mergeApplicationConfig } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
bootstrapApplication(AppComponent, mergeApplicationConfig(a, b));
`,
);
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
const content = readFile('main.ts');
assertContains(
content,
`import { mergeApplicationConfig, importProvidersFrom } from '@angular/core';`,
);
assertContains(content, `import { MyModule } from '@my/module';`);
assertContains(
content,
`bootstrapApplication(AppComponent, mergeApplicationConfig(a, b, {
providers: [importProvidersFrom(MyModule)]
}));`,
);
});
it('should alias symbols that conflict with existing code', async () => {
await setupProject();
await testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('BrowserModule', '@my/module')}.forRoot([])`,
),
host,
);
const content = readFile('app/app.module.ts');
assertContains(content, `import { BrowserModule as BrowserModule_alias } from '@my/module';`);
assertContains(content, `imports: [BrowserModule, BrowserModule_alias.forRoot([])]`);
});
it('should throw an error if the bootstrapApplication code has no arguments', async () => {
await setupProject(true);
const mainPath = getPathWithinProject('main.ts');
host.overwrite(
mainPath,
`
import { bootstrapApplication } from '@angular/platform-browser';
bootstrapApplication();
`,
);
const promise = testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
await expectAsync(promise).toBeRejectedWithError(
`Cannot add provider to invalid bootstrapApplication call in ${mainPath}`,
);
});
it('should throw an error if the bootstrapApplication call cannot be analyzed', async () => {
await setupProject(true);
const mainPath = getPathWithinProject('main.ts');
host.overwrite(
mainPath,
`
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from '@external/app-config';
bootstrapApplication(AppComponent, appConfig);
`,
);
const promise = testRule(
addRootImport(
projectName,
({ code, external }) => code`${external('MyModule', '@my/module')}`,
),
host,
);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
await expectAsync(promise).toBeRejectedWithError(
`Cannot statically analyze bootstrapApplication call in ${mainPath}`,
);
});
|
001297
|
# @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.
|
001348
|
export async function getCommonConfig(wco: WebpackConfigOptions): Promise<Configuration> {
const { root, projectRoot, buildOptions, tsConfig, projectName, sourceRoot, tsConfigPath } = wco;
const {
cache,
codeCoverage,
crossOrigin = 'none',
platform = 'browser',
aot = true,
codeCoverageExclude = [],
main,
sourceMap: {
styles: stylesSourceMap,
scripts: scriptsSourceMap,
vendor: vendorSourceMap,
hidden: hiddenSourceMap,
},
optimization: { styles: stylesOptimization, scripts: scriptsOptimization },
commonChunk,
vendorChunk,
subresourceIntegrity,
verbose,
poll,
webWorkerTsConfig,
externalDependencies = [],
allowedCommonJsDependencies,
} = buildOptions;
const isPlatformServer = buildOptions.platform === 'server';
const extraPlugins: { apply(compiler: Compiler): void }[] = [];
const extraRules: RuleSetRule[] = [];
const entryPoints: Configuration['entry'] = {};
// Load ESM `@angular/compiler-cli` using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
const { VERSION: NG_VERSION } =
await loadEsmModule<typeof import('@angular/compiler-cli')>('@angular/compiler-cli');
const { GLOBAL_DEFS_FOR_TERSER, GLOBAL_DEFS_FOR_TERSER_WITH_AOT } = await loadEsmModule<
typeof import('@angular/compiler-cli/private/tooling')
>('@angular/compiler-cli/private/tooling');
// determine hashing format
const hashFormat = getOutputHashFormat(buildOptions.outputHashing);
if (buildOptions.progress) {
extraPlugins.push(new ProgressPlugin(platform));
}
const localizePackageInitEntryPoint = '@angular/localize/init';
const hasLocalizeType = tsConfig.options.types?.some(
(t) => t === '@angular/localize' || t === localizePackageInitEntryPoint,
);
if (hasLocalizeType) {
entryPoints['main'] = [localizePackageInitEntryPoint];
}
if (buildOptions.main) {
const mainPath = path.resolve(root, buildOptions.main);
if (Array.isArray(entryPoints['main'])) {
entryPoints['main'].push(mainPath);
} else {
entryPoints['main'] = [mainPath];
}
}
if (isPlatformServer) {
// Fixes Critical dependency: the request of a dependency is an expression
extraPlugins.push(new ContextReplacementPlugin(/@?hapi|express[\\/]/));
if (
isPackageInstalled(wco.root, '@angular/platform-server') &&
Array.isArray(entryPoints['main'])
) {
// This import must come before any imports (direct or transitive) that rely on DOM built-ins being
// available, such as `@angular/elements`.
entryPoints['main'].unshift('@angular/platform-server/init');
}
}
const polyfills = [...buildOptions.polyfills];
if (!aot) {
polyfills.push('@angular/compiler');
}
if (polyfills.length) {
// `zone.js/testing` is a **special** polyfill because when not imported in the main it fails with the below errors:
// `Error: Expected to be running in 'ProxyZone', but it was not found.`
// This was also the reason why previously it was imported in `test.ts` as the first module.
// From Jia li:
// This is because the jasmine functions such as beforeEach/it will not be patched by zone.js since
// jasmine will not be loaded yet, so the ProxyZone will not be there. We have to load zone-testing.js after
// jasmine is ready.
// We could force loading 'zone.js/testing' prior to jasmine by changing the order of scripts in 'karma-context.html'.
// But this has it's own problems as zone.js needs to be loaded prior to jasmine due to patching of timing functions
// See: https://github.com/jasmine/jasmine/issues/1944
// Thus the correct order is zone.js -> jasmine -> zone.js/testing.
const zoneTestingEntryPoint = 'zone.js/testing';
const polyfillsExludingZoneTesting = polyfills.filter((p) => p !== zoneTestingEntryPoint);
if (Array.isArray(entryPoints['polyfills'])) {
entryPoints['polyfills'].push(...polyfillsExludingZoneTesting);
} else {
entryPoints['polyfills'] = polyfillsExludingZoneTesting;
}
if (polyfillsExludingZoneTesting.length !== polyfills.length) {
if (Array.isArray(entryPoints['main'])) {
entryPoints['main'].unshift(zoneTestingEntryPoint);
} else {
entryPoints['main'] = [zoneTestingEntryPoint];
}
}
}
if (allowedCommonJsDependencies) {
// When this is not defined it means the builder doesn't support showing common js usages.
// When it does it will be an array.
extraPlugins.push(
new CommonJsUsageWarnPlugin({
allowedDependencies: allowedCommonJsDependencies,
}),
);
}
// process global scripts
// Add a new asset for each entry.
for (const { bundleName, inject, paths } of globalScriptsByBundleName(buildOptions.scripts)) {
// Lazy scripts don't get a hash, otherwise they can't be loaded by name.
const hash = inject ? hashFormat.script : '';
extraPlugins.push(
new ScriptsWebpackPlugin({
name: bundleName,
sourceMap: scriptsSourceMap,
scripts: paths,
filename: `${path.basename(bundleName)}${hash}.js`,
basePath: root,
}),
);
}
// process asset entries
if (buildOptions.assets.length) {
extraPlugins.push(
new CopyWebpackPlugin({
patterns: assetPatterns(root, buildOptions.assets),
}),
);
}
if (buildOptions.extractLicenses) {
const LicenseWebpackPlugin = require('license-webpack-plugin').LicenseWebpackPlugin;
extraPlugins.push(
new LicenseWebpackPlugin({
stats: {
warnings: false,
errors: false,
},
perChunkOutput: false,
outputFilename: '3rdpartylicenses.txt',
skipChildCompilers: true,
}),
);
}
if (scriptsSourceMap || stylesSourceMap) {
const include = [];
if (scriptsSourceMap) {
include.push(/js$/);
}
if (stylesSourceMap) {
include.push(/css$/);
}
extraPlugins.push(new DevToolsIgnorePlugin());
extraPlugins.push(
new SourceMapDevToolPlugin({
filename: '[file].map',
include,
// We want to set sourceRoot to `webpack:///` for non
// inline sourcemaps as otherwise paths to sourcemaps will be broken in browser
// `webpack:///` is needed for Visual Studio breakpoints to work properly as currently
// there is no way to set the 'webRoot'
sourceRoot: 'webpack:///',
moduleFilenameTemplate: '[resource-path]',
append: hiddenSourceMap ? false : undefined,
}),
);
}
if (verbose) {
extraPlugins.push(new WatchFilesLogsPlugin());
}
if (buildOptions.statsJson) {
extraPlugins.push(
new JsonStatsPlugin(path.resolve(root, buildOptions.outputPath, 'stats.json')),
);
}
if (subresourceIntegrity) {
extraPlugins.push(
new SubresourceIntegrityPlugin({
hashFuncNames: ['sha384'],
}),
);
}
if (scriptsSourceMap || stylesSourceMap) {
extraRules.push({
test: /\.[cm]?jsx?$/,
enforce: 'pre',
loader: require.resolve('source-map-loader'),
options: {
filterSourceMappingUrl: (_mapUri: string, resourcePath: string) => {
if (vendorSourceMap) {
// Consume all sourcemaps when vendor option is enabled.
return true;
}
// Don't consume sourcemaps in node_modules when vendor is disabled.
// But, do consume local libraries sourcemaps.
return !resourcePath.includes('node_modules');
},
},
});
}
if (main || polyfills) {
extraRules.push({
test: tsConfig.options.allowJs ? /\.[cm]?[tj]sx?$/ : /\.[cm]?tsx?$/,
loader: AngularWebpackLoaderPath,
// The below are known paths that are not part of the TypeScript compilation even when allowJs is enabled.
exclude: [
/[\\/]node_modules[/\\](?:css-loader|mini-css-extract-plugin|webpack-dev-server|webpack)[/\\]/,
],
});
extraPlugins.push(createIvyPlugin(wco, aot, tsConfigPath));
}
if (webWorkerTsConfig) {
extraPlugins.push(createIvyPlugin(wco, false, path.resolve(wco.root, webWorkerTsConfig)));
}
const extraMinimizers = [];
|
001618
|
# Overview
Jobs is a high-order API that adds inputs, runtime type checking, sequencing, and other
functionality on top of RxJS' `Observable`s.
# Background
An `Observable` (at a higher level) is a function that receives a `Subscriber`, and outputs
multiple values, and finishes once it calls the `Subscriber.prototype.complete()` method (in
JavaScript):
```javascript
const output1To10EverySecond = function (subscriber) {
let t = 0;
const i = setInterval(() => {
t++;
subscriber.next(t);
if (t === 10) {
subscriber.complete(t);
}
}, 1000);
return () => clearInterval(i);
};
const stream$ = new Observable(output1To10EverySecond);
// Start the function, and output 1 to 100, once per line.
stream$.subscribe((x) => console.log(x));
```
This, of course, can be typed in TypeScript, but those types are not enforced at runtime.
# Glossary
- `job handler`. The function that implements the job's logic.
- `raw input`. The input observable sending messages to the job. These messages are of type
`JobInboundMessage`.
- `raw output`. The output observer returned from the `job handler`. Messages on this observable
are of type `JobOutboundMessage`.
# Description
A `JobHandler`, similar to observables, is a function that receives an argument and a context, and
returns an `Observable` of messages, which can include outputs that are typed at runtime (using a
Json Schema):
```javascript
const output1ToXEverySecond = function (x, context) {
return new Observable((subscriber) => {
let t = 0;
// Notify our users that the actual work is started.
subscriber.next({ kind: JobOutboundMessageKind.Start });
const i = setInterval(() => {
t++;
subscriber.next({ kind: JobOutboundMessageKind.Output, value: t });
if (t === x) {
subscriber.next({ kind: JobOutboundMessageKind.End });
subscriber.complete();
}
}, 1000);
return () => {
clearInterval(i);
};
});
};
// For now, jobs can not be called without a registry and scheduler.
const registry = new SimpleJobRegistry();
registry.register('output-from-1-to-x', output1ToXEverySecond, {
argument: { type: 'number' },
output: { type: 'number' },
});
const scheduler = new SimpleScheduler(registry);
// Need to keep the same name that the registry would understand.
// Count from 1 to 10.
const job = scheduler.schedule('output-from-1-to-x', 10);
// A Job<> instance has more members, but we only want the output values here.
job.output.subscribe((x) => console.log(x));
```
This seems like a lot of boilerplate in comparison, but there are a few advantages;
1. lifecycle. Jobs can tell when they start doing work and when work is done.
1. everything is typed, even at runtime.
1. the context also contains an input Observable that receives typed input messages, including
input values, and stop requests.
1. jobs can also schedule other jobs and wait for them, even if they don't know if a job is
implemented in the system.
## Diagram
A simpler way to think about jobs in contrast to observables is that job are closer to a Unix
process. It has an argument (command line flags), receive inputs (STDIN and interrupt signals),
and output values (STDOUT) as well as diagnostic (STDERR). They can be plugged one into another
(piping), and can be transformed, synchronized and scheduled (fork, exec, cron).
```plain
- given A the type of the argument
- given I the type of the input
- given O the type of the output
,______________________
JobInboundMessage<I> --> | handler(argument: A) | --> JobOutboundMessage<O>
- JobOutboundMessageKind.Output
- ...
```
`JobInboundMessage` includes:
1. `JobInboundMessageKind.Ping`. A simple message that should be answered with
`JobOutboundMessageKind.Pong` when the job is responsive. The `id` field of the message should
be used when returning `Pong`.
1. `JobInboundMessageKind.Stop`. The job should be stopped. This is used when
cancelling/unsubscribing from the `output` (or by calling `stop()`). Any inputs or outputs
after this message will be ignored.
1. `JobInboundMessageKind.Input` is used when sending inputs to a job. These correspond to the
`next` methods of an `Observer` and are reported to the job through its `context.input`
Observable. There is no way to communicate an error to the job.
`JobOutboundMessage` includes:
1. `JobOutboundMessageKind.Ready`. The `Job<>` was created, its dependencies are done, and the
library is validating Argument and calling the internal job code.
1. `JobOutboundMessageKind.Start`. The job code itself should send that message when started.
`createJobHandler()` will do it automatically.
1. `JobOutboundMessageKind.End`. The job has ended. This is done by the job itself and should
always be sent when completed. The scheduler will listen to this message to set the state and
unblock dependent jobs. `createJobHandler()` automatically send this message.
1. `JobOutboundMessageKind.Pong`. The job should answer a `JobInboundMessageKind.Ping` message with
this. Automatically done by `createJobHandler()`.
1. `JobOutboundMessageKind.Output`. An `Output` has been generated by the job.
1. `JobOutboundMessageKind.ChannelMessage`, `JobOutboundMessageKind.ChannelError` and
`JobOutboundMessageKind.ChannelComplete` are used for output channels. These correspond to
the `next`, `error` and `complete` methods of an `Observer` and are available to the callee
through the `job.channels` map of Observable.
Utilities should have some filtering and dispatching to separate observables, as a convenience for
the user. An example of this would be the `Job.prototype.output` observable which only contains
the value contained by messages of type `JobOutboundMessageKind.Output`.
|
001630
|
# Creating Jobs
A job is at its core a function with a description object attached to it. The description object
stores the JSON schemas used to validate the types of the argument passed in, the input and
output values. By default, a job accepts and can output any JSON object.
```typescript
import { Observable } from 'rxjs';
import { jobs } from '@angular-devkit/core';
const argument = {
type: 'array',
items: { type: 'number' },
};
const output = {
type: 'number',
};
export function add(argument: number[]): Observable<jobs.JobOutboundMessage<number>> {
return new Observable((o) => {
o.next({ kind: jobs.JobOutboundMessageKind.Start });
o.next({
kind: jobs.JobOutboundMessageKind.Output,
output: argument.reduce((total, curr) => total + curr, 0),
});
o.next({ kind: jobs.JobOutboundMessageKind.End });
o.complete();
});
}
// Add a property to `add` to make it officially a JobHandler. The Job system does not recognize
// any function as a JobHandler.
add.jobDescription = {
argument: argument,
output: output,
};
// Call the job with an array as argument, and log its output.
declare const scheduler: jobs.Scheduler;
scheduler.schedule('add', [1, 2, 3, 4]).output.subscribe((x) => console.log(x)); // Will output 10.
```
This is a lot of boilerplate, so we made some helpers to improve readability and manage argument,
input and output automatically:
```typescript
// Add is a JobHandler function, like the above.
export const add = jobs.createJobHandler<number[], number>((argument) =>
argument.reduce((total, curr) => total + curr, 0),
);
// Schedule like above.
```
You can also return a Promise or an Observable, as jobs are asynchronous. This helper will set
start and end messages appropriately. It will also manage channels automatically (see below).
A more complex job can be declared like this:
```typescript
import { Observable } from 'rxjs';
import { jobs } from '@angular-devkit/core';
// Show progress with each count in a separate output channel. Output "more" in a channel.
export const count = jobs.createJobHandler<number, number>(
// Receive a context that contains additional methods to create channels.
(argument: number, { createChannel }) =>
new Observable<number>((o) => {
const side = createChannel('side', { type: 'string', const: 'more' });
const progress = createChannel('progress', { type: 'number' });
let i = 0;
function doCount() {
o.next(i++);
progress.next(i / argument);
side.next('more');
if (i < argument) {
setTimeout(doCount, 100);
} else {
o.complete();
}
}
setTimeout(doCount, 100);
}),
{
argument: { type: 'number' },
output: { type: 'number' },
},
);
// Get a hold of a scheduler that refers to the job above.
declare const scheduler: jobs.Scheduler;
const job = scheduler.schedule('count', 0);
job.getChannel('side').subscribe((x) => console.log(x));
// You can type a channel too. Messages will be filtered out.
job.getChannel<number>('progress', { type: 'number' }).subscribe((x) => console.log(x));
```
## <a name="Communicating"></a>Communicating With Jobs
Jobs can be started and updated in a separate process or thread, and as such communication with a
job should avoid using global objects (which might not be shared). The jobs API and schedulers
provide 2 communication streams (one for input and the other for output), named `inboundBus` and
`outboundBus`.
### Raw Input Stream
The `schedule()` function returns a `Job<>` interface that contains a `inboundBus` member of type
`Observer<JobInboundMessage>`. All messages sent _to_ the job goes through this stream. The `kind`
member of the `JobInboundMessage` interface dictates what kind of message it is sending:
1. `JobInboundMessageKind.Ping`. A simple message that should be answered with
`JobOutboundMessageKind.Pong` when the job is responsive. The `id` field of the message should
be used when returning `Pong`.
1. `JobInboundMessageKind.Stop`. The job should be stopped. This is used when
cancelling/unsubscribing from the `output` (or by calling `stop()`). Any inputs or outputs
after this message will be ignored.
1. `JobInboundMessageKind.Input` is used when sending inputs to a job. These correspond to the
`next` methods of an `Observer` and are reported to the job through its `context.input`
Observable. There is no way to communicate an error to the job.
Using the `createJobHandler()` helper, all those messages are automatically handled by the
boilerplate code. If you need direct access to raw inputs, you should subscribe to the
`context.inboundBus` Observable.
### Raw Output Stream
The `Job<>` interface also contains a `outboundBus` member (of type
`Observable<JobOutboundMessage<O>>` where `O` is the typed output of the job) which is the output
complement of `inboundBus`. All messages sent _from_ the job goes through this stream. The `kind`
member of the `JobOutboundMessage<O>` interface dictates what kind of message it is sending:
1. `JobOutboundMessageKind.Create`. The `Job<>` was created, its dependencies are done, and the
library is validating Argument and calling the internal job code.
1. `JobOutboundMessageKind.Start`. The job code itself should send that message when started.
`createJobHandler()` will do it automatically.
1. `JobOutboundMessageKind.End`. The job has ended. This is done by the job itself and should always
be sent when completed. The scheduler will listen to this message to set the state and unblock
dependent jobs. `createJobHandler()` automatically send this message.
1. `JobOutboundMessageKind.Pong`. The job should answer a `JobInboundMessageKind.Ping` message with
this. Automatically done by `createJobHandler()`.
1. `JobOutboundMessageKind.Output`. An `Output` has been generated by the job.
1. `JobOutboundMessageKind.ChannelMessage`, `JobOutboundMessageKind.ChannelError` and
`JobOutboundMessageKind.ChannelComplete` are used for output channels. These correspond to the
`next`, `error` and `complete` methods of an `Observer` and are available to the callee through
the `job.channels` map of Observable.
Those messages can be accessed directly through the `job.outboundBus` member. The job itself should
return an `Observable<JobOutboundMessage<O>>`. The `createJobHandler()` helper handles most of use
cases of this and makes it easier for jobs to handle this.
## Job Dispatchers
Dispatchers are a helper that redirect to different jobs given conditions. To create a job
dispatcher, use the `createDispatcher()` function:
```typescript
import { jobs } from '@angular-devkit/core';
// A dispatcher that installs node modules given a user's preference.
const dispatcher = jobs.createDispatcher({
name: 'node-install',
argument: { properties: { moduleName: { type: 'string' } } },
output: { type: 'boolean' },
});
const npmInstall = jobs.createJobHandler(/* ... */, { name: 'npm-install' });
const yarnInstall = jobs.createJobHandler(/* ... */, { name: 'yarn-install' });
const pnpmInstall = jobs.createJobHandler(/* ... */, { name: 'pnpm-install' });
declare const registry: jobs.SimpleJobRegistry;
registry.register(dispatcher);
registry.register(npmInstall);
registry.register(yarnInstall);
registry.register(pnpmInstall);
// Default to npm.
dispatcher.setDefaultDelegate(npmInstall.name);
// If the user is asking for yarn over npm, uses it.
dispatcher.addConditionalDelegate(() => userWantsYarn, yarnInstall.name);
```
|
001649
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.dev/reference/versions#browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/**
* Required to support Web Animations `@angular/platform-browser/animations`.
* Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
**/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/
|
001654
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { existsSync } from 'fs';
import * as path from 'path';
import { URL, pathToFileURL } from 'url';
import { Compilation, Configuration } from 'webpack';
export interface EmittedFiles {
id?: string;
name?: string;
file: string;
initial: boolean;
asset?: boolean;
extension: string;
}
export function getEmittedFiles(compilation: Compilation): EmittedFiles[] {
const files: EmittedFiles[] = [];
const chunkFileNames = new Set<string>();
// adds all chunks to the list of emitted files such as lazy loaded modules
for (const chunk of compilation.chunks) {
for (const file of chunk.files) {
if (chunkFileNames.has(file)) {
continue;
}
chunkFileNames.add(file);
files.push({
id: chunk.id?.toString(),
name: chunk.name,
file,
extension: path.extname(file),
initial: chunk.isOnlyInitial(),
});
}
}
// add all other files
for (const file of Object.keys(compilation.assets)) {
// Chunk files have already been added to the files list above
if (chunkFileNames.has(file)) {
continue;
}
files.push({ file, extension: path.extname(file), initial: false, asset: true });
}
return files;
}
/**
* This uses a dynamic import to load a module which may be ESM.
* CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript
* will currently, unconditionally downlevel dynamic import into a require call.
* require calls cannot load ESM code and will result in a runtime error. To workaround
* this, a Function constructor is used to prevent TypeScript from changing the dynamic import.
* Once TypeScript provides support for keeping the dynamic import this workaround can
* be dropped.
*
* @param modulePath The path of the module to load.
* @returns A Promise that resolves to the dynamically imported module.
*/
function loadEsmModule<T>(modulePath: string | URL): Promise<T> {
return new Function('modulePath', `return import(modulePath);`)(modulePath) as Promise<T>;
}
export async function getWebpackConfig(configPath: string): Promise<Configuration> {
if (!existsSync(configPath)) {
throw new Error(`Webpack configuration file ${configPath} does not exist.`);
}
switch (path.extname(configPath)) {
case '.mjs':
// Load the ESM configuration file using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
return (await loadEsmModule<{ default: Configuration }>(pathToFileURL(configPath))).default;
case '.cjs':
return require(configPath);
default:
// The file could be either CommonJS or ESM.
// CommonJS is tried first then ESM if loading fails.
try {
return require(configPath);
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ERR_REQUIRE_ESM') {
// Load the ESM configuration file using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
return (await loadEsmModule<{ default: Configuration }>(pathToFileURL(configPath)))
.default;
}
throw e;
}
}
}
|
001815
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.dev/reference/versions#browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags.ts';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/
|
End of preview.
No dataset card yet
- Downloads last month
- 12