initial commit

This commit is contained in:
dahyeon committed 2026-04-11 11:27:53 -07:00
commit 6215e0fb7d
31158 files changed
+4069656

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
+4
View File
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}
+98
View File
@@ -0,0 +1,98 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ pnpm install
```
## Compile and run the project
```bash
# development
$ pnpm run start
# watch mode
$ pnpm run start:dev
# production mode
$ pnpm run start:prod
```
## Run tests
```bash
# unit tests
$ pnpm run test
# e2e tests
$ pnpm run test:e2e
# test coverage
$ pnpm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ pnpm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
+35
View File
@@ -0,0 +1,35 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }],
},
},
);
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
+79
View File
@@ -0,0 +1,79 @@
{
"name": "api",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./start.ps1\"\"",
"start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./start.ps1\"\"",
"start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./start.ps1\"\"",
"pm2:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); ./start.ps1 -UsePm2\"",
"pm2:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); ./start.ps1 -UsePm2\"",
"pm2:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); ./start.ps1 -UsePm2\"",
"start:debug": "nest start --debug --watch",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.7",
"mongoose": "^9.4.1",
"nats": "^2.29.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"temporal-polyfill": "^0.3.2"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^24.0.0",
"@types/supertest": "^7.0.0",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^17.0.0",
"jest": "^30.0.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
+22
View File
@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
+12
View File
@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+8
View File
@@ -0,0 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
@@ -0,0 +1,94 @@
import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose';
import { SecretService } from '../secret/secret.service';
import { moeumModelDefinitions, MoeumModelTypes } from './schema';
@Injectable({ scope: Scope.DEFAULT })
export class ConnectionService implements OnModuleInit {
private connection: mongoose.Connection | null = null;
constructor(private readonly secretService: SecretService) {}
private moeumModels: Map<string, mongoose.Model<any>> | null = null;
public async getConnection(): Promise<mongoose.Connection> {
if (this.connection !== null && this.connection.readyState === 1) {
return this.connection;
}
const connectionString = await this.secretService.get(
'MONGODB_CONNECTION_STRING',
);
const defaultConnection = await mongoose
.createConnection(connectionString, {
dbName: 'moeum',
minPoolSize: 10,
maxPoolSize: 20,
})
.asPromise();
this.connection = defaultConnection;
console.log('Default Connection이 새로 생성됨.');
return this.connection;
}
public async getMoeumModels<K extends keyof MoeumModelTypes>(
modelKey: K,
): Promise<mongoose.Model<MoeumModelTypes[K]>> {
if (this.moeumModels)
return this.moeumModels.get(modelKey) as mongoose.Model<
MoeumModelTypes[K]
>;
const moeumModels = new Map<K, mongoose.Model<MoeumModelTypes[K]>>();
// const connection = await this.getTenantConnection(tenantId);
const connection = await this.getConnection();
moeumModelDefinitions.forEach((modelDefinition) => {
// 이미 생성된 경우 컴파일 스킵.
if (
Object.prototype.hasOwnProperty.call(
connection.models,
modelDefinition.name,
)
) {
moeumModels.set(
modelDefinition.name as K,
connection.models[modelDefinition.name],
);
return;
} else {
moeumModels.set(
modelDefinition.name as K,
connection.model<MoeumModelTypes[K]>(
modelDefinition.name,
modelDefinition.schema,
modelDefinition.schemaName,
),
);
}
});
this.moeumModels = moeumModels;
return moeumModels.get(modelKey) as mongoose.Model<MoeumModelTypes[K]>;
}
public async createSession(
options?: mongoose.ClientSessionOptions,
): Promise<mongoose.ClientSession | undefined> {
try {
const connection = await this.getConnection();
const session = await connection.startSession(options);
return session as unknown as mongoose.ClientSession;
} catch (error) {
console.log(error);
}
}
public async onModuleInit() {
await this.getConnection().catch(console.error);
}
public async onModuleDestroy() {
this.connection?.close();
}
}
@@ -0,0 +1,9 @@
import { DynamicModule, Module } from '@nestjs/common';
import { ConnectionService } from './connection.service';
@Module({
imports: [],
providers: [ConnectionService],
exports: [ConnectionService],
})
export class DatabaseModule {}
@@ -0,0 +1,248 @@
import mongoose, { Schema, HydratedDocument } from 'mongoose';
import { ModelDefinition } from './types';
export type MetadataDataType =
| 'string'
| 'number'
| 'boolean'
| 'array'
| 'json';
export type MetadataValue =
| string
| number
| boolean
| unknown[]
| Record<string, unknown>
| null;
export interface MongooseTimestamps {
createdAt: Date;
updatedAt: Date;
}
export interface Metadata {
key: string;
value: MetadataValue;
dataType: MetadataDataType;
isReserved: boolean;
}
export interface TaxonomyChildItem {
title: string;
order: number;
articleId?: mongoose.Types.ObjectId;
slug?: string; //article document의 slug 참조 (임베딩)
children?: TaxonomyChildItem[];
}
export interface Taxonomy extends MongooseTimestamps {
label: string;
items: TaxonomyChildItem[];
metadatas: Metadata[];
}
export type TaxonomyDocument = HydratedDocument<Taxonomy>;
export interface ContentSection {
headline: string;
taxonomies: ContentSectionEmbeddedTaxonomy[];
}
export interface ContentSectionEmbeddedTaxonomy {
taxonomyId: mongoose.Types.ObjectId;
label: string; // 성능 최적화를 위해 임베딩된 label
}
export interface Content extends MongooseTimestamps {
key: string;
label: string;
sections: ContentSection[];
}
export type ContentDocument = HydratedDocument<Content>;
export interface Article extends MongooseTimestamps {
title: string;
slug: string;
content: string;
status: 'draft' | 'published' | 'archived';
metadatas: Metadata[];
}
export type ArticleDocument = HydratedDocument<Article>;
const metadataValueDefinition =
{
type: mongoose.SchemaTypes.Mixed,
required: false, // required: true로 하면 value가 null인 경우 에러 발생
default: null,
validate: {
validator: function (this: Metadata, v: MetadataValue) {
if (v === null) {
return true;
}
switch (this.dataType) {
case 'string':
return typeof v === 'string';
case 'number':
return typeof v === 'number';
case 'boolean':
return typeof v === 'boolean';
case 'array':
return Array.isArray(v);
case 'json':
return typeof v === 'object' && !Array.isArray(v);
default:
return false;
}
},
message: function (this: Metadata, props: { value: MetadataValue }) {
return `Value "${props.value}" does not match the expected data type "${this.dataType}" for key "${this.key}".`;
},
},
} as mongoose.SchemaDefinitionProperty<MetadataValue>;
export const MetadataSubSchema = new mongoose.Schema<Metadata>(
{
key: { type: String, required: true },
value: metadataValueDefinition,
dataType: {
type: String,
required: false,
default: 'string',
enum: ['string', 'number', 'boolean', 'array', 'json'],
},
isReserved: { type: Boolean, required: false, default: false },
},
{
_id: false,
},
);
export const TaxonomyChildItemSubSchema = new Schema<TaxonomyChildItem>(
{
title: { type: String, required: true },
order: { type: Number, required: true, default: 100 },
slug: { type: String }, // slug는 없을 수도 있으므로 required 제외
articleId: { type: Schema.Types.ObjectId, ref: 'article' },
},
{
_id: false, // 하위 아이템마다 _id가 생성되는 것을 방지 (선택 사항)
},
);
// **중요: 재귀 참조 설정**
// 스키마 정의 후 .add()를 통해 자기 자신을 children 배열로 추가합니다.
TaxonomyChildItemSubSchema.add({
children: { type: [TaxonomyChildItemSubSchema], default: [] },
});
// 2. 메인 도큐먼트 스키마 (Root)
export const TaxonomySchema = new Schema<Taxonomy>(
{
// items 배열은 위에서 정의한 재귀 스키마를 따름
label: { type: String, required: true },
items: {
type: [TaxonomyChildItemSubSchema],
default: [],
},
// metadata는 구조가 가변적이므로 Mixed 타입 사용
metadatas: {
type: [MetadataSubSchema],
required: true,
default: [],
},
},
{
timestamps: true, // createAt, updatedAt 자동 생성
collection: 'taxonomy', // 컬렉션 이름 지정
},
);
TaxonomySchema.index({ label: 1 }, { unique: true });
export const ContentSectionEmbeddedTaxonomySubSchema =
new Schema<ContentSectionEmbeddedTaxonomy>(
{
taxonomyId: {
type: Schema.Types.ObjectId,
ref: 'taxonomy',
required: true,
},
label: { type: String, required: true },
},
{ _id: false },
);
export const ContentSectionSubSchema = new Schema<ContentSection>(
{
headline: { type: String, required: true },
taxonomies: {
type: [ContentSectionEmbeddedTaxonomySubSchema],
required: true,
default: [],
},
},
{ _id: false },
);
export const ContentSchema = new Schema<Content>(
{
key: { type: String, required: true, unique: true },
label: { type: String, required: true },
sections: {
type: [ContentSectionSubSchema],
default: [],
},
},
{
timestamps: true,
collection: 'content',
},
);
export const ArticleSchema = new Schema<Article>(
{
title: { type: String, required: true },
content: { type: String, required: true },
slug: { type: String, required: true, unique: true },
status: {
type: String,
enum: ['draft', 'published', 'archived'],
default: 'draft',
},
metadatas: {
type: [MetadataSubSchema],
required: true,
default: [],
validate: {
validator: function (metas: Metadata[]) {
const keys = metas.map((m) => m.key);
return keys.length === new Set(keys).size;
},
message: 'Duplicate metadata keys are not allowed.',
},
},
},
{
timestamps: true,
collection: 'article',
},
);
ArticleSchema.index({ title: 'text', content: 'text' });
export const moeumModelDefinitions: ModelDefinition[] = [
{ name: 'taxonomy', schema: TaxonomySchema, schemaName: 'taxonomy' },
{ name: 'content', schema: ContentSchema, schemaName: 'content' },
{ name: 'article', schema: ArticleSchema, schemaName: 'article' },
];
export interface MoeumModelTypes {
taxonomy: Taxonomy;
content: Content;
article: Article;
}
+5
View File
@@ -0,0 +1,5 @@
export interface ModelDefinition {
name: string;
schema: mongoose.Schema<any>;
schemaName?: string;
}
@@ -0,0 +1,14 @@
import { Module, Global } from '@nestjs/common';
import { SecretModule } from './secret/secret.module';
// import { DatabaseModule } from './database/database.module';
import { NatsModule } from './nats/nats.module';
import { DatabaseModule } from './database/database.module';
// import { DatabaseModule } from './database/database.module';
@Global()
@Module({
imports: [SecretModule, NatsModule, DatabaseModule],
providers: [],
exports: [SecretModule, NatsModule, DatabaseModule],
})
export class GlobalModule {}
@@ -0,0 +1 @@
export const NATS_CLIENT = Symbol('NATS_CLIENT');
@@ -0,0 +1,50 @@
import { Module } from '@nestjs/common';
import fs from 'fs/promises';
import { connect } from 'nats';
import type { NatsConnection } from 'nats';
import { SecretModule } from '../secret/secret.module';
import { SecretService } from '../secret/secret.service';
import { NATS_CLIENT } from './nats.constants';
import { NatsService } from './nats.service';
@Module({
imports: [SecretModule],
providers: [
{
provide: NATS_CLIENT,
inject: [SecretService],
useFactory: async (
secretService: SecretService,
): Promise<NatsConnection> => {
await secretService.ready();
const [endpoint, user, password, serviceName, cacert] =
await Promise.all([
secretService.get<string>('NATS_ENDPOINT'),
secretService.get<string>('NATS_USER'),
secretService.get<string>('NATS_PASS'),
secretService.get<string>('SERVICE_NAME'),
fs.readFile('internal-service-ca.pem', 'utf8'),
]);
return connect({
name: serviceName,
servers: [endpoint],
tls: {
ca: cacert,
},
maxReconnectAttempts: -1,
reconnectTimeWait: 500,
reconnect: true,
pingInterval: 20000,
timeout: 5000,
user,
pass: password,
});
},
},
NatsService,
],
exports: [NatsService, NATS_CLIENT],
})
export class NatsModule {}
@@ -0,0 +1,36 @@
import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
import { StringCodec } from 'nats';
import type { NatsConnection } from 'nats';
import { NATS_CLIENT } from './nats.constants';
@Injectable()
export class NatsService implements OnModuleDestroy {
private readonly stringCodec = StringCodec();
constructor(
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
) {}
async onModuleDestroy() {
try {
// 안전 종료: drain -> closed 대기
const closed = this.natsClient.closed();
await this.natsClient.drain();
const err = await closed;
if (err) console.error('NATS closed with error:', err);
} catch (e) {
// drain 실패 시 강제 close
try {
await this.natsClient.close();
} catch {}
}
}
public async publish<T = unknown>(subject: string, data: T): Promise<void> {
this.natsClient.publish(
subject,
this.stringCodec.encode(JSON.stringify(data)),
);
await this.natsClient.flush();
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { SecretService } from './secret.service';
@Module({
imports: [],
providers: [SecretService],
exports: [SecretService],
})
export class SecretModule {}
@@ -0,0 +1,134 @@
import { Injectable, Logger } from '@nestjs/common';
import { InfisicalSDK } from '@infisical/sdk';
import { ConfigService } from '@nestjs/config';
type SecretMap = Record<string, string | boolean | undefined>;
@Injectable()
export class SecretService {
private logger = new Logger(SecretService.name);
private secrets: SecretMap | null = null; // null = 아직 로드 전
private loading?: Promise<void>; // 진행 중인 로드(중복 호출 방지)
private infisicalClient: InfisicalSDK;
private readonly siteUrl: string;
private readonly clientSecret: string;
private readonly clientId: string;
private readonly projectId: string;
private readonly PROCESS_ENVS = [
'COSMOSDB_ENDPOINT',
'COSMOSDB_KEY',
'NATS_ENDPOINT',
'NATS_TOKEN',
'NATS_URL',
// 필요시 추가
] as const;
constructor(private readonly config: ConfigService) {
this.siteUrl =
this.config.get<string>('INFISICAL_SITE_URL') ??
'https://secret-manager.dahyeon.us/';
this.clientSecret = this.config.get<string>(
'INFISICAL_CLIENT_SECRET',
) as string;
this.clientId = this.config.get<string>('INFISICAL_CLIENT_ID') as string;
this.projectId = this.config.get<string>('INFISICAL_PROJECT_ID') as string;
// console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId)
if (!this.siteUrl || !this.clientSecret || !this.clientId) {
throw new Error('Missing required Infisical configuration');
}
this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl });
}
/** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */
private async fetchSecrets(): Promise<void> {
if (this.secrets) return; // 이미 로드됨
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
this.loading = (async () => {
await this.infisicalClient.auth().universalAuth.login({
clientId: this.clientId,
clientSecret: this.clientSecret,
});
// console.log(this.infisicalClient)
const res = await this.infisicalClient.secrets().listSecrets({
environment:
process.env.NODE_ENV === 'prod'
? 'prod'
: process.env.NODE_ENV === 'test'
? 'staging'
: 'dev',
projectId: this.projectId,
});
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
const map: SecretMap = {};
for (const s of res.secrets) {
map[s.secretKey] = s.secretValue;
}
// 필요한 값은 process.env에 반영
for (const k of this.PROCESS_ENVS) {
const v = map[k as string];
if (typeof v === 'string' && v.length > 0) {
process.env[k as string] = v;
}
}
this.secrets = map;
this.logger.log(
`Fetched ${Object.keys(map).length} secrets from Infisical`,
);
})();
try {
await this.loading;
} finally {
this.loading = undefined; // 실패/성공 모두 끝나면 해제(실패 시 재시도 가능)
}
}
/** lazy get: 필요할 때 처음 한번만 로드 */
public async get<T = string>(key: string, fallback?: T): Promise<T> {
if (!this.secrets) {
await this.fetchSecrets();
}
// console.log('Secrets loaded:', this.secrets);
const val = this.secrets![key];
if (val === undefined) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`Secret not found for key="${key}"`);
}
return val as T;
}
/** 필요 시: 동기 접근(초기화 안됐으면 에러). constructor 등에서 강제 사용 금지 */
public getSync<T = string>(key: string, fallback?: T): T {
if (!this.secrets) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`SecretService not initialized yet (key="${key}")`);
}
const val = this.secrets[key];
if (val === undefined) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`Secret not found for key="${key}"`);
}
return val as T;
}
/** 선택: 사전에 강제로 로드하고 싶을 때 호출 */
public async ready(): Promise<void> {
await this.fetchSecrets();
}
}
+63
View File
@@ -0,0 +1,63 @@
param(
[switch]$UsePm2,
[string]$Pm2Name = "lolympus-tournament-support"
)
if (-not $env:NODE_ENV) {
$env:NODE_ENV = "dev"
}
$MainScript = Join-Path $PSScriptRoot "dist/main.js"
if ($isMacOS -or $isLinux) {
$env:MachineEnvFile = "$env:HOME/source/global-env-vars.txt"
} elseif ($isWindows) {
$env:MachineEnvFile = "$env:USERPROFILE/source/global-env-vars.txt"
}
function Set-EnvFromFile {
param([string]$Path)
if (-not (Test-Path $Path)) {
throw "File not found: $Path"
}
foreach ($line in Get-Content $Path) {
if ([string]::IsNullOrWhiteSpace($line)) { continue }
if ($line -match '^\s*#') { continue }
if ($line -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$') {
$key = $matches[1]
$value = $matches[2].Trim()
if (
($value.StartsWith('"') -and $value.EndsWith('"')) -or
($value.StartsWith("'") -and $value.EndsWith("'"))
) {
$value = $value.Substring(1, $value.Length - 2)
}
[System.Environment]::SetEnvironmentVariable($key, $value)
}
}
}
if (Test-Path $env:MachineEnvFile) {
Set-EnvFromFile $env:MachineEnvFile
}
if (-not $env:INFISICAL_CLIENT_ID) {
Write-Error "INFISICAL_CLIENT_ID is not set."
exit 1
}
if (-not $env:INFISICAL_CLIENT_SECRET) {
Write-Error "INFISICAL_CLIENT_SECRET is not set."
exit 1
}
if ($UsePm2) {
pm2 start $MainScript --name $Pm2Name --update-env
} else {
node $MainScript
}
+29
View File
@@ -0,0 +1,29 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
afterEach(async () => {
await app.close();
});
});
+9
View File
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}
+4
View File
@@ -0,0 +1,4 @@
INFISICAL_PROJECT_ID=26a80d59-a424-4e33-adfc-2b6e84d6e25f
SERVICE_NAME=lolympus-tournament-support
VERSION=0.1
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+30
View File
@@ -0,0 +1,30 @@
{
"name": "web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.4",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.4"
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+184
View File
@@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}
+121
View File
@@ -0,0 +1,121 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from './assets/vite.svg'
import heroImg from './assets/hero.png'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<>
<section id="center">
<div className="hero">
<img src={heroImg} className="base" width="170" height="179" alt="" />
<img src={reactLogo} className="framework" alt="React logo" />
<img src={viteLogo} className="vite" alt="Vite logo" />
</div>
<div>
<h1>Get started</h1>
<p>
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
</p>
</div>
<button
className="counter"
onClick={() => setCount((count) => count + 1)}
>
Count is {count}
</button>
</section>
<div className="ticks"></div>
<section id="next-steps">
<div id="docs">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#documentation-icon"></use>
</svg>
<h2>Documentation</h2>
<p>Your questions, answered</p>
<ul>
<li>
<a href="https://vite.dev/" target="_blank">
<img className="logo" src={viteLogo} alt="" />
Explore Vite
</a>
</li>
<li>
<a href="https://react.dev/" target="_blank">
<img className="button-icon" src={reactLogo} alt="" />
Learn more
</a>
</li>
</ul>
</div>
<div id="social">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#social-icon"></use>
</svg>
<h2>Connect with us</h2>
<p>Join the Vite community</p>
<ul>
<li>
<a href="https://github.com/vitejs/vite" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#github-icon"></use>
</svg>
GitHub
</a>
</li>
<li>
<a href="https://chat.vite.dev/" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#discord-icon"></use>
</svg>
Discord
</a>
</li>
<li>
<a href="https://x.com/vite_js" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#x-icon"></use>
</svg>
X.com
</a>
</li>
<li>
<a href="https://bsky.app/profile/vite.dev" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#bluesky-icon"></use>
</svg>
Bluesky
</a>
</li>
</ul>
</div>
</section>
<div className="ticks"></div>
<section id="spacer"></section>
</>
)
}
export default App
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="usLine truncated

After

Width:  |  Height:  |  Size: 8.5 KiB

+111
View File
@@ -0,0 +1,111 @@
:root {
--text: #6b6375;
--text-h: #08060d;
--bg: #fff;
--border: #e5e4e7;
--code-bg: #f4f3ec;
--accent: #aa3bff;
--accent-bg: rgba(170, 59, 255, 0.1);
--accent-border: rgba(170, 59, 255, 0.5);
--social-bg: rgba(244, 243, 236, 0.5);
--shadow:
rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;
--sans: system-ui, 'Segoe UI', Roboto, sans-serif;
--heading: system-ui, 'Segoe UI', Roboto, sans-serif;
--mono: ui-monospace, Consolas, monospace;
font: 18px/145% var(--sans);
letter-spacing: 0.18px;
color-scheme: light dark;
color: var(--text);
background: var(--bg);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@media (max-width: 1024px) {
font-size: 16px;
}
}
@media (prefers-color-scheme: dark) {
:root {
--text: #9ca3af;
--text-h: #f3f4f6;
--bg: #16171d;
--border: #2e303a;
--code-bg: #1f2028;
--accent: #c084fc;
--accent-bg: rgba(192, 132, 252, 0.15);
--accent-border: rgba(192, 132, 252, 0.5);
--social-bg: rgba(47, 48, 58, 0.5);
--shadow:
rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;
}
#social .button-icon {
filter: invert(1) brightness(2);
}
}
#root {
width: 1126px;
max-width: 100%;
margin: 0 auto;
text-align: center;
border-inline: 1px solid var(--border);
min-height: 100svh;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
body {
margin: 0;
}
h1,
h2 {
font-family: var(--heading);
font-weight: 500;
color: var(--text-h);
}
h1 {
font-size: 56px;
letter-spacing: -1.68px;
margin: 32px 0;
@media (max-width: 1024px) {
font-size: 36px;
margin: 20px 0;
}
}
h2 {
font-size: 24px;
line-height: 118%;
letter-spacing: -0.24px;
margin: 0 0 8px;
@media (max-width: 1024px) {
font-size: 20px;
}
}
p {
margin: 0;
}
code,
.counter {
font-family: var(--mono);
display: inline-flex;
border-radius: 4px;
color: var(--text-h);
}
code {
font-size: 15px;
line-height: 135%;
padding: 4px 8px;
background: var(--code-bg);
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})
Generated Vendored
+1496
View File
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
{
"lastValidatedTimestamp": 1775899049458,
"projects": {
"/Users/dahyeon/source/lolympus-tournament-support": {
"name": "lolympus-tournament-support",
"version": "1.0.0"
},
"/Users/dahyeon/source/lolympus-tournament-support/apps/api": {
"name": "api",
"version": "0.0.1"
},
"/Users/dahyeon/source/lolympus-tournament-support/apps/web": {
"name": "web",
"version": "0.0.0"
}
},
"pnpmfileExists": false,
"settings": {
"autoInstallPeers": true,
"catalogs": {},
"dedupeDirectDeps": false,
"dedupeInjectedDeps": true,
"dedupePeerDependents": true,
"dev": true,
"excludeLinksFromLockfile": false,
"hoistPattern": [
"*"
],
"hoistWorkspacePackages": true,
"injectWorkspacePackages": false,
"linkWorkspacePackages": false,
"nodeLinker": "isolated",
"optional": true,
"preferWorkspacePackages": false,
"production": true,
"publicHoistPattern": [],
"workspacePackagePatterns": [
"apps/*",
"packages/*"
]
},
"filteredInstall": true
}
@@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2010-2025 Google LLC. https://angular.dev/license
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,167 @@
# Core
> Shared utilities for Angular DevKit.
# Exception
# Json
## Schema
### SchemaValidatorResult
```
export interface SchemaValidatorResult {
success: boolean;
errors?: string[];
}
```
### SchemaValidator
```
export interface SchemaValidator {
(data: any): Observable<SchemaValidatorResult>;
}
```
### SchemaFormatter
```
export interface SchemaFormatter {
readonly async: boolean;
validate(data: any): boolean | Observable<boolean>;
}
```
### SchemaRegistry
```
export interface SchemaRegistry {
compile(schema: Object): Observable<SchemaValidator>;
addFormat(name: string, formatter: SchemaFormatter): void;
}
```
### CoreSchemaRegistry
`SchemaRegistry` implementation using https://github.com/epoberezkin/ajv.
Constructor accepts object containing `SchemaFormatter` that will be added automatically.
```
export class CoreSchemaRegistry implements SchemaRegistry {
constructor(formats: { [name: string]: SchemaFormatter} = {}) {}
}
```
# Logger
# Utils
# Virtual FS
# Workspaces
The `workspaces` namespace provides an API for interacting with the workspace file formats.
It provides an abstraction of the underlying storage format of the workspace and provides
support for both reading and writing. Currently, the only supported format is the JSON-based
format used by the Angular CLI. For this format, the API provides internal change tracking of values which
enables fine-grained updates to the underlying storage of the workspace. This allows for the
retention of existing formatting and comments.
A workspace is defined via the following object model. Definition collection objects are specialized
Javascript `Map` objects with an additional `add` method to simplify addition and provide more localized
error checking of the newly added values.
```ts
export interface WorkspaceDefinition {
readonly extensions: Record<string, JsonValue | undefined>;
readonly projects: ProjectDefinitionCollection;
}
export interface ProjectDefinition {
readonly extensions: Record<string, JsonValue | undefined>;
readonly targets: TargetDefinitionCollection;
root: string;
prefix?: string;
sourceRoot?: string;
}
export interface TargetDefinition {
options?: Record<string, JsonValue | undefined>;
configurations?: Record<string, Record<string, JsonValue | undefined> | undefined>;
builder: string;
}
```
The API is asynchronous and has two main functions to facilitate reading, creation, and modifying
a workspace: `readWorkspace` and `writeWorkspace`.
```ts
export enum WorkspaceFormat {
JSON,
}
```
```ts
export function readWorkspace(
path: string,
host: WorkspaceHost,
format?: WorkspaceFormat,
): Promise<{ workspace: WorkspaceDefinition }>;
```
```ts
export function writeWorkspace(
workspace: WorkspaceDefinition,
host: WorkspaceHost,
path?: string,
format?: WorkspaceFormat,
): Promise<void>;
```
A `WorkspaceHost` abstracts the underlying data access methods from the functions. It provides
methods to read, write, and analyze paths. A utility function is provided to create
an instance of a `WorkspaceHost` from the Angular DevKit's virtual filesystem host abstraction.
```ts
export interface WorkspaceHost {
readFile(path: string): Promise<string>;
writeFile(path: string, data: string): Promise<void>;
isDirectory(path: string): Promise<boolean>;
isFile(path: string): Promise<boolean>;
}
export function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost;
```
## Usage Example
To demonstrate the usage of the API, the following code will show how to add a option property
to a build target for an application.
```ts
import { NodeJsSyncHost } from '@angular-devkit/core/node';
import { workspaces } from '@angular-devkit/core';
async function demonstrate() {
const host = workspaces.createWorkspaceHost(new NodeJsSyncHost());
const { workspace } = await workspaces.readWorkspace('path/to/workspace/directory/', host);
const project = workspace.projects.get('my-app');
if (!project) {
throw new Error('my-app does not exist');
}
const buildTarget = project.targets.get('build');
if (!buildTarget) {
throw new Error('build target does not exist');
}
buildTarget.options.optimization = true;
await workspaces.writeWorkspace(workspace, host);
}
demonstrate();
```
@@ -0,0 +1,8 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/index';
@@ -0,0 +1,24 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./src/index"), exports);
@@ -0,0 +1,15 @@
/**
* @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 { logging } from '../src';
export interface ProcessOutput {
write(buffer: string | Buffer): boolean;
}
/**
* A Logger that sends information to STDOUT and STDERR.
*/
export declare function createConsoleLogger(verbose?: boolean, stdout?: ProcessOutput, stderr?: ProcessOutput, colors?: Partial<Record<logging.LogLevel, (s: string) => string>>): logging.Logger;
@@ -0,0 +1,57 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConsoleLogger = createConsoleLogger;
const rxjs_1 = require("rxjs");
const src_1 = require("../src");
/**
* A Logger that sends information to STDOUT and STDERR.
*/
function createConsoleLogger(verbose = false, stdout = process.stdout, stderr = process.stderr, colors) {
const logger = new src_1.logging.IndentLogger('cling');
logger.pipe((0, rxjs_1.filter)((entry) => entry.level !== 'debug' || verbose)).subscribe((entry) => {
const color = colors && colors[entry.level];
let output = stdout;
switch (entry.level) {
case 'warn':
case 'fatal':
case 'error':
output = stderr;
break;
}
// If we do console.log(message) or process.stdout.write(message + '\n'), the process might
// stop before the whole message is written and the stream is flushed. This happens when
// streams are asynchronous.
//
// NodeJS IO streams are different depending on platform and usage. In POSIX environment,
// for example, they're asynchronous when writing to a pipe, but synchronous when writing
// to a TTY. In windows, it's the other way around. You can verify which is which with
// stream.isTTY and platform, but this is not good enough.
// In the async case, one should wait for the callback before sending more data or
// continuing the process. In our case it would be rather hard to do (but not impossible).
//
// Instead we take the easy way out and simply chunk the message and call the write
// function while the buffer drain itself asynchronously. With a smaller chunk size than
// the buffer, we are mostly certain that it works. In this case, the chunk has been picked
// as half a page size (4096/2 = 2048), minus some bytes for the color formatting.
// On POSIX it seems the buffer is 2 pages (8192), but just to be sure (could be different
// by platform).
//
// For more details, see https://nodejs.org/api/process.html#process_a_note_on_process_i_o
const chunkSize = 2000; // Small chunk.
let message = entry.message;
while (message) {
const chunk = message.slice(0, chunkSize);
message = message.slice(chunkSize);
output.write(color ? color(chunk) : chunk);
}
output.write('\n');
});
return logger;
}
@@ -0,0 +1,43 @@
/**
* @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 { Stats } from 'node:fs';
import { Observable } from 'rxjs';
import { Path, PathFragment, virtualFs } from '../src';
/**
* An implementation of the Virtual FS using Node as the background. There are two versions; one
* synchronous and one asynchronous.
*/
export declare class NodeJsAsyncHost implements virtualFs.Host<Stats> {
get capabilities(): virtualFs.HostCapabilities;
write(path: Path, content: virtualFs.FileBuffer): Observable<void>;
read(path: Path): Observable<virtualFs.FileBuffer>;
delete(path: Path): Observable<void>;
rename(from: Path, to: Path): Observable<void>;
list(path: Path): Observable<PathFragment[]>;
exists(path: Path): Observable<boolean>;
isDirectory(path: Path): Observable<boolean>;
isFile(path: Path): Observable<boolean>;
stat(path: Path): Observable<virtualFs.Stats<Stats>>;
watch(path: Path, _options?: virtualFs.HostWatchOptions): Observable<virtualFs.HostWatchEvent> | null;
}
/**
* An implementation of the Virtual FS using Node as the backend, synchronously.
*/
export declare class NodeJsSyncHost implements virtualFs.Host<Stats> {
get capabilities(): virtualFs.HostCapabilities;
write(path: Path, content: virtualFs.FileBuffer): Observable<void>;
read(path: Path): Observable<virtualFs.FileBuffer>;
delete(path: Path): Observable<void>;
rename(from: Path, to: Path): Observable<void>;
list(path: Path): Observable<PathFragment[]>;
exists(path: Path): Observable<boolean>;
isDirectory(path: Path): Observable<boolean>;
isFile(path: Path): Observable<boolean>;
stat(path: Path): Observable<virtualFs.Stats<Stats>>;
watch(path: Path, _options?: virtualFs.HostWatchOptions): Observable<virtualFs.HostWatchEvent> | null;
}
@@ -0,0 +1,210 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeJsSyncHost = exports.NodeJsAsyncHost = void 0;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const rxjs_1 = require("rxjs");
const src_1 = require("../src");
async function exists(path) {
try {
await node_fs_1.promises.access(path, node_fs_1.constants.F_OK);
return true;
}
catch {
return false;
}
}
// This will only be initialized if the watch() method is called.
// Otherwise chokidar appears only in type positions, and shouldn't be referenced
// in the JavaScript output.
let FSWatcher;
function loadFSWatcher() {
if (!FSWatcher) {
try {
FSWatcher = require('chokidar').FSWatcher;
}
catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw new Error('As of angular-devkit version 8.0, the "chokidar" package ' +
'must be installed in order to use watch() features.');
}
throw e;
}
}
}
/**
* An implementation of the Virtual FS using Node as the background. There are two versions; one
* synchronous and one asynchronous.
*/
class NodeJsAsyncHost {
get capabilities() {
return { synchronous: false };
}
write(path, content) {
return (0, rxjs_1.from)(node_fs_1.promises.mkdir((0, src_1.getSystemPath)((0, src_1.dirname)(path)), { recursive: true })).pipe((0, rxjs_1.mergeMap)(() => node_fs_1.promises.writeFile((0, src_1.getSystemPath)(path), new Uint8Array(content))));
}
read(path) {
return (0, rxjs_1.from)(node_fs_1.promises.readFile((0, src_1.getSystemPath)(path))).pipe((0, rxjs_1.map)((buffer) => new Uint8Array(buffer).buffer));
}
delete(path) {
return (0, rxjs_1.from)(node_fs_1.promises.rm((0, src_1.getSystemPath)(path), { force: true, recursive: true, maxRetries: 3 }));
}
rename(from, to) {
return (0, rxjs_1.from)(node_fs_1.promises.rename((0, src_1.getSystemPath)(from), (0, src_1.getSystemPath)(to)));
}
list(path) {
return (0, rxjs_1.from)(node_fs_1.promises.readdir((0, src_1.getSystemPath)(path))).pipe((0, rxjs_1.map)((names) => names.map((name) => (0, src_1.fragment)(name))));
}
exists(path) {
return (0, rxjs_1.from)(exists((0, src_1.getSystemPath)(path)));
}
isDirectory(path) {
return this.stat(path).pipe((0, rxjs_1.map)((stat) => stat.isDirectory()));
}
isFile(path) {
return this.stat(path).pipe((0, rxjs_1.map)((stat) => stat.isFile()));
}
// Some hosts may not support stat.
stat(path) {
return (0, rxjs_1.from)(node_fs_1.promises.stat((0, src_1.getSystemPath)(path)));
}
// Some hosts may not support watching.
watch(path, _options) {
return new rxjs_1.Observable((obs) => {
loadFSWatcher();
const watcher = new FSWatcher({ persistent: true });
watcher.add((0, src_1.getSystemPath)(path));
watcher
.on('change', (path) => {
obs.next({
path: (0, src_1.normalize)(path),
time: new Date(),
type: src_1.virtualFs.HostWatchEventType.Changed,
});
})
.on('add', (path) => {
obs.next({
path: (0, src_1.normalize)(path),
time: new Date(),
type: src_1.virtualFs.HostWatchEventType.Created,
});
})
.on('unlink', (path) => {
obs.next({
path: (0, src_1.normalize)(path),
time: new Date(),
type: src_1.virtualFs.HostWatchEventType.Deleted,
});
});
return () => {
void watcher.close();
};
}).pipe((0, rxjs_1.publish)(), (0, rxjs_1.refCount)());
}
}
exports.NodeJsAsyncHost = NodeJsAsyncHost;
/**
* An implementation of the Virtual FS using Node as the backend, synchronously.
*/
class NodeJsSyncHost {
get capabilities() {
return { synchronous: true };
}
write(path, content) {
return new rxjs_1.Observable((obs) => {
(0, node_fs_1.mkdirSync)((0, src_1.getSystemPath)((0, src_1.dirname)(path)), { recursive: true });
(0, node_fs_1.writeFileSync)((0, src_1.getSystemPath)(path), new Uint8Array(content));
obs.next();
obs.complete();
});
}
read(path) {
return new rxjs_1.Observable((obs) => {
const buffer = (0, node_fs_1.readFileSync)((0, src_1.getSystemPath)(path));
obs.next(new Uint8Array(buffer).buffer);
obs.complete();
});
}
delete(path) {
return new rxjs_1.Observable((obs) => {
(0, node_fs_1.rmSync)((0, src_1.getSystemPath)(path), { force: true, recursive: true, maxRetries: 3 });
obs.complete();
});
}
rename(from, to) {
return new rxjs_1.Observable((obs) => {
const toSystemPath = (0, src_1.getSystemPath)(to);
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(toSystemPath), { recursive: true });
(0, node_fs_1.renameSync)((0, src_1.getSystemPath)(from), toSystemPath);
obs.next();
obs.complete();
});
}
list(path) {
return new rxjs_1.Observable((obs) => {
const names = (0, node_fs_1.readdirSync)((0, src_1.getSystemPath)(path));
obs.next(names.map((name) => (0, src_1.fragment)(name)));
obs.complete();
});
}
exists(path) {
return new rxjs_1.Observable((obs) => {
obs.next((0, node_fs_1.existsSync)((0, src_1.getSystemPath)(path)));
obs.complete();
});
}
isDirectory(path) {
return this.stat(path).pipe((0, rxjs_1.map)((stat) => stat.isDirectory()));
}
isFile(path) {
return this.stat(path).pipe((0, rxjs_1.map)((stat) => stat.isFile()));
}
// Some hosts may not support stat.
stat(path) {
return new rxjs_1.Observable((obs) => {
obs.next((0, node_fs_1.statSync)((0, src_1.getSystemPath)(path)));
obs.complete();
});
}
// Some hosts may not support watching.
watch(path, _options) {
return new rxjs_1.Observable((obs) => {
loadFSWatcher();
const watcher = new FSWatcher({ persistent: false });
watcher.add((0, src_1.getSystemPath)(path));
watcher
.on('change', (path) => {
obs.next({
path: (0, src_1.normalize)(path),
time: new Date(),
type: src_1.virtualFs.HostWatchEventType.Changed,
});
})
.on('add', (path) => {
obs.next({
path: (0, src_1.normalize)(path),
time: new Date(),
type: src_1.virtualFs.HostWatchEventType.Created,
});
})
.on('unlink', (path) => {
obs.next({
path: (0, src_1.normalize)(path),
time: new Date(),
type: src_1.virtualFs.HostWatchEventType.Deleted,
});
});
return () => {
void watcher.close();
};
}).pipe((0, rxjs_1.publish)(), (0, rxjs_1.refCount)());
}
}
exports.NodeJsSyncHost = NodeJsSyncHost;
@@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './cli-logger';
export * from './host';
@@ -0,0 +1,25 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./cli-logger"), exports);
__exportStar(require("./host"), exports);
@@ -0,0 +1,20 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as fs from 'node:fs';
import { Path, virtualFs } from '../../src';
/**
* A Sync Scoped Host that creates a temporary directory and scope to it.
*/
export declare class TempScopedNodeJsSyncHost extends virtualFs.ScopedHost<fs.Stats> {
protected _sync?: virtualFs.SyncDelegateHost<fs.Stats>;
protected _root: Path;
constructor();
get files(): Path[];
get root(): Path;
get sync(): virtualFs.SyncDelegateHost<fs.Stats>;
}
@@ -0,0 +1,88 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TempScopedNodeJsSyncHost = void 0;
const fs = __importStar(require("node:fs"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const src_1 = require("../../src");
const host_1 = require("../host");
/**
* A Sync Scoped Host that creates a temporary directory and scope to it.
*/
class TempScopedNodeJsSyncHost extends src_1.virtualFs.ScopedHost {
_sync;
_root;
constructor() {
const root = (0, src_1.normalize)(path.join(os.tmpdir(), `devkit-host-${+Date.now()}-${process.pid}`));
fs.mkdirSync((0, src_1.getSystemPath)(root));
super(new host_1.NodeJsSyncHost(), root);
this._root = root;
}
get files() {
const sync = this.sync;
function _visit(p) {
return sync
.list(p)
.map((fragment) => (0, src_1.join)(p, fragment))
.reduce((files, path) => {
if (sync.isDirectory(path)) {
return files.concat(_visit(path));
}
else {
return files.concat(path);
}
}, []);
}
return _visit((0, src_1.normalize)('/'));
}
get root() {
return this._root;
}
get sync() {
if (!this._sync) {
this._sync = new src_1.virtualFs.SyncDelegateHost(this);
}
return this._sync;
}
}
exports.TempScopedNodeJsSyncHost = TempScopedNodeJsSyncHost;
@@ -0,0 +1,64 @@
{
"name": "@angular-devkit/core",
"version": "19.2.23",
"description": "Angular DevKit - Core Utility Library",
"main": "src/index.js",
"typings": "src/index.d.ts",
"keywords": [
"Angular CLI",
"Angular DevKit",
"angular",
"core",
"devkit",
"sdk"
],
"exports": {
".": {
"types": "./src/index.d.ts",
"default": "./src/index.js"
},
"./node": {
"types": "./node/index.d.ts",
"default": "./node/index.js"
},
"./node/testing": {
"types": "./node/testing/index.d.ts",
"default": "./node/testing/index.js"
},
"./package.json": "./package.json",
"./*": "./*.js",
"./*.js": "./*.js"
},
"dependencies": {
"ajv": "8.18.0",
"ajv-formats": "3.0.1",
"jsonc-parser": "3.3.1",
"picomatch": "4.0.4",
"rxjs": "7.8.1",
"source-map": "0.7.4"
},
"peerDependencies": {
"chokidar": "^4.0.0"
},
"peerDependenciesMeta": {
"chokidar": {
"optional": true
}
},
"repository": {
"type": "git",
"url": "https://github.com/angular/angular-cli.git"
},
"packageManager": "pnpm@10.15.0",
"engines": {
"node": "^18.19.1 || ^20.11.1 || >=22.0.0",
"npm": "^6.11.0 || ^7.5.6 || >=8.0.0",
"yarn": ">= 1.13.0"
},
"author": "Angular Authors",
"license": "MIT",
"bugs": {
"url": "https://github.com/angular/angular-cli/issues"
},
"homepage": "https://github.com/angular/angular-cli"
}
@@ -0,0 +1,25 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export declare class BaseException extends Error {
constructor(message?: string);
}
export declare class UnknownException extends BaseException {
constructor(message: string);
}
export declare class FileDoesNotExistException extends BaseException {
constructor(path: string);
}
export declare class FileAlreadyExistException extends BaseException {
constructor(path: string);
}
export declare class PathIsDirectoryException extends BaseException {
constructor(path: string);
}
export declare class PathIsFileException extends BaseException {
constructor(path: string);
}
@@ -0,0 +1,47 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PathIsFileException = exports.PathIsDirectoryException = exports.FileAlreadyExistException = exports.FileDoesNotExistException = exports.UnknownException = exports.BaseException = void 0;
class BaseException extends Error {
constructor(message = '') {
super(message);
}
}
exports.BaseException = BaseException;
class UnknownException extends BaseException {
constructor(message) {
super(message);
}
}
exports.UnknownException = UnknownException;
// Exceptions
class FileDoesNotExistException extends BaseException {
constructor(path) {
super(`Path "${path}" does not exist.`);
}
}
exports.FileDoesNotExistException = FileDoesNotExistException;
class FileAlreadyExistException extends BaseException {
constructor(path) {
super(`Path "${path}" already exist.`);
}
}
exports.FileAlreadyExistException = FileAlreadyExistException;
class PathIsDirectoryException extends BaseException {
constructor(path) {
super(`Path "${path}" is a directory.`);
}
}
exports.PathIsDirectoryException = PathIsDirectoryException;
class PathIsFileException extends BaseException {
constructor(path) {
super(`Path "${path}" is a file.`);
}
}
exports.PathIsFileException = PathIsFileException;
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as json from './json/index';
import * as logging from './logger/index';
import * as workspaces from './workspace';
export * from './exception';
export * from './json/index';
export * from './utils/index';
export * from './virtual-fs/index';
export { json, logging, workspaces };
@@ -0,0 +1,56 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.workspaces = exports.logging = exports.json = void 0;
const json = __importStar(require("./json/index"));
exports.json = json;
const logging = __importStar(require("./logger/index"));
exports.logging = logging;
const workspaces = __importStar(require("./workspace"));
exports.workspaces = workspaces;
__exportStar(require("./exception"), exports);
__exportStar(require("./json/index"), exports);
__exportStar(require("./utils/index"), exports);
__exportStar(require("./virtual-fs/index"), exports);
@@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as schema from './schema/index';
export * from './utils';
export { schema };
@@ -0,0 +1,49 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.schema = void 0;
const schema = __importStar(require("./schema/index"));
exports.schema = schema;
__exportStar(require("./utils"), exports);
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as transforms from './transforms';
export * from './interface';
export * from './pointer';
export * from './registry';
export * from './schema';
export * from './visitor';
export * from './utility';
export { transforms };
@@ -0,0 +1,54 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transforms = void 0;
const transforms = __importStar(require("./transforms"));
exports.transforms = transforms;
__exportStar(require("./interface"), exports);
__exportStar(require("./pointer"), exports);
__exportStar(require("./registry"), exports);
__exportStar(require("./schema"), exports);
__exportStar(require("./visitor"), exports);
__exportStar(require("./utility"), exports);
@@ -0,0 +1,84 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { ErrorObject, Format } from 'ajv';
import { Observable, ObservableInput } from 'rxjs';
import { JsonArray, JsonObject, JsonValue } from '../utils';
export type JsonPointer = string & {
__PRIVATE_DEVKIT_JSON_POINTER: void;
};
export interface SchemaValidatorResult {
data: JsonValue;
success: boolean;
errors?: SchemaValidatorError[];
}
export type SchemaValidatorError = Partial<ErrorObject>;
export interface SchemaValidatorOptions {
applyPreTransforms?: boolean;
applyPostTransforms?: boolean;
withPrompts?: boolean;
}
export interface SchemaValidator {
(data: JsonValue, options?: SchemaValidatorOptions): Promise<SchemaValidatorResult>;
}
export type SchemaFormatter = Format;
export interface SchemaFormat {
name: string;
formatter: SchemaFormatter;
}
export interface SmartDefaultProvider<T> {
(schema: JsonObject): T | Observable<T>;
}
export interface SchemaKeywordValidator {
(data: JsonValue, schema: JsonValue, parent: JsonObject | JsonArray | undefined, parentProperty: string | number | undefined, pointer: JsonPointer, rootData: JsonValue): boolean | Observable<boolean>;
}
export interface PromptDefinition {
id: string;
type: string;
message: string;
default?: string | string[] | number | boolean | null;
validator?: (value: JsonValue) => boolean | string | Promise<boolean | string>;
items?: Array<string | {
value: JsonValue;
label: string;
}>;
raw?: string | JsonObject;
multiselect?: boolean;
propertyTypes: Set<string>;
}
export type PromptProvider = (definitions: Array<PromptDefinition>) => ObservableInput<{
[id: string]: JsonValue;
}>;
export interface SchemaRegistry {
compile(schema: Object): Promise<SchemaValidator>;
/** @private */
ɵflatten(schema: JsonObject | string): Promise<JsonObject>;
addFormat(format: SchemaFormat): void;
addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>): void;
usePromptProvider(provider: PromptProvider): void;
useXDeprecatedProvider(onUsage: (message: string) => void): void;
/**
* Add a transformation step before the validation of any Json.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
/**
* Add a transformation step after the validation of any Json. The JSON will not be validated
* after the POST, so if transformations are not compatible with the Schema it will not result
* in an error.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
}
export interface JsonSchemaVisitor {
(current: JsonObject | JsonArray, pointer: JsonPointer, parentSchema?: JsonObject | JsonArray, index?: string): void;
}
export interface JsonVisitor {
(value: JsonValue, pointer: JsonPointer, schema?: JsonObject, root?: JsonObject | JsonArray): Observable<JsonValue> | JsonValue;
}
@@ -0,0 +1,9 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,11 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonPointer } from './interface';
export declare function buildJsonPointer(fragments: string[]): JsonPointer;
export declare function joinJsonPointer(root: JsonPointer, ...others: string[]): JsonPointer;
export declare function parseJsonPointer(pointer: JsonPointer): string[];
@@ -0,0 +1,38 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildJsonPointer = buildJsonPointer;
exports.joinJsonPointer = joinJsonPointer;
exports.parseJsonPointer = parseJsonPointer;
function buildJsonPointer(fragments) {
return ('/' +
fragments
.map((f) => {
return f.replace(/~/g, '~0').replace(/\//g, '~1');
})
.join('/'));
}
function joinJsonPointer(root, ...others) {
if (root == '/') {
return buildJsonPointer(others);
}
return (root + buildJsonPointer(others));
}
function parseJsonPointer(pointer) {
if (pointer === '') {
return [];
}
if (pointer.charAt(0) !== '/') {
throw new Error('Relative pointer: ' + pointer);
}
return pointer
.substring(1)
.split(/\//)
.map((str) => str.replace(/~1/g, '/').replace(/~0/g, '~'));
}
@@ -0,0 +1,79 @@
/**
* @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 { ValidateFunction } from 'ajv';
import { Observable } from 'rxjs';
import { BaseException } from '../../exception';
import { JsonObject } from '../utils';
import { JsonVisitor, PromptProvider, SchemaFormat, SchemaRegistry, SchemaValidator, SchemaValidatorError, SmartDefaultProvider } from './interface';
import { JsonSchema } from './schema';
export type UriHandler = (uri: string) => Observable<JsonObject> | Promise<JsonObject> | null | undefined;
export declare class SchemaValidationException extends BaseException {
readonly errors: SchemaValidatorError[];
constructor(errors?: SchemaValidatorError[], baseMessage?: string);
static createMessages(errors?: SchemaValidatorError[]): string[];
}
export declare class CoreSchemaRegistry implements SchemaRegistry {
private _ajv;
private _uriCache;
private _uriHandlers;
private _pre;
private _post;
private _currentCompilationSchemaInfo?;
private _smartDefaultKeyword;
private _promptProvider?;
private _sourceMap;
constructor(formats?: SchemaFormat[]);
private _fetch;
/**
* Add a transformation step before the validation of any Json.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
/**
* Add a transformation step after the validation of any Json. The JSON will not be validated
* after the POST, so if transformations are not compatible with the Schema it will not result
* in an error.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
protected _resolver(ref: string, validate?: ValidateFunction): {
context?: ValidateFunction;
schema?: JsonObject;
};
/**
* Flatten the Schema, resolving and replacing all the refs. Makes it into a synchronous schema
* that is also easier to traverse. Does not cache the result.
*
* Producing a flatten schema document does not in all cases produce a schema with identical behavior to the original.
* See: https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.appendix.B.2
*
* @param schema The schema or URI to flatten.
* @returns An Observable of the flattened schema object.
* @private since 11.2 without replacement.
*/
ɵflatten(schema: JsonObject): Promise<JsonObject>;
/**
* Compile and return a validation function for the Schema.
*
* @param schema The schema to validate. If a string, will fetch the schema before compiling it
* (using schema as a URI).
*/
compile(schema: JsonSchema): Promise<SchemaValidator>;
private _compile;
addFormat(format: SchemaFormat): void;
addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>): void;
registerUriHandler(handler: UriHandler): void;
usePromptProvider(provider: PromptProvider): void;
private _applyPrompts;
private static _set;
private _applySmartDefaults;
useXDeprecatedProvider(onUsage: (message: string) => void): void;
private normalizeDataPathArr;
}
@@ -0,0 +1,564 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoreSchemaRegistry = exports.SchemaValidationException = void 0;
const ajv_1 = __importDefault(require("ajv"));
const ajv_formats_1 = __importDefault(require("ajv-formats"));
const http = __importStar(require("node:http"));
const https = __importStar(require("node:https"));
const Url = __importStar(require("node:url"));
const rxjs_1 = require("rxjs");
const exception_1 = require("../../exception");
const utils_1 = require("../../utils");
const utils_2 = require("../utils");
const utility_1 = require("./utility");
const visitor_1 = require("./visitor");
class SchemaValidationException extends exception_1.BaseException {
errors;
constructor(errors, baseMessage = 'Schema validation failed with the following errors:') {
if (!errors || errors.length === 0) {
super('Schema validation failed.');
this.errors = [];
return;
}
const messages = SchemaValidationException.createMessages(errors);
super(`${baseMessage}\n ${messages.join('\n ')}`);
this.errors = errors;
}
static createMessages(errors) {
if (!errors || errors.length === 0) {
return [];
}
const messages = errors.map((err) => {
let message = `Data path ${JSON.stringify(err.instancePath)} ${err.message}`;
if (err.params) {
switch (err.keyword) {
case 'additionalProperties':
message += `(${err.params.additionalProperty})`;
break;
case 'enum':
message += `. Allowed values are: ${err.params.allowedValues
?.map((v) => `"${v}"`)
.join(', ')}`;
break;
}
}
return message + '.';
});
return messages;
}
}
exports.SchemaValidationException = SchemaValidationException;
class CoreSchemaRegistry {
_ajv;
_uriCache = new Map();
_uriHandlers = new Set();
_pre = new utils_1.PartiallyOrderedSet();
_post = new utils_1.PartiallyOrderedSet();
_currentCompilationSchemaInfo;
_smartDefaultKeyword = false;
_promptProvider;
_sourceMap = new Map();
constructor(formats = []) {
this._ajv = new ajv_1.default({
strict: false,
loadSchema: (uri) => this._fetch(uri),
passContext: true,
});
(0, ajv_formats_1.default)(this._ajv);
for (const format of formats) {
this.addFormat(format);
}
}
async _fetch(uri) {
const maybeSchema = this._uriCache.get(uri);
if (maybeSchema) {
return maybeSchema;
}
// Try all handlers, one after the other.
for (const handler of this._uriHandlers) {
let handlerResult = handler(uri);
if (handlerResult === null || handlerResult === undefined) {
continue;
}
if ((0, rxjs_1.isObservable)(handlerResult)) {
handlerResult = (0, rxjs_1.lastValueFrom)(handlerResult);
}
const value = await handlerResult;
this._uriCache.set(uri, value);
return value;
}
// If none are found, handle using http client.
return new Promise((resolve, reject) => {
const url = new Url.URL(uri);
const client = url.protocol === 'https:' ? https : http;
client.get(url, (res) => {
if (!res.statusCode || res.statusCode >= 300) {
// Consume the rest of the data to free memory.
res.resume();
reject(new Error(`Request failed. Status Code: ${res.statusCode}`));
}
else {
res.setEncoding('utf8');
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const json = JSON.parse(data);
this._uriCache.set(uri, json);
resolve(json);
}
catch (err) {
reject(err);
}
});
}
});
});
}
/**
* Add a transformation step before the validation of any Json.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPreTransform(visitor, deps) {
this._pre.add(visitor, deps);
}
/**
* Add a transformation step after the validation of any Json. The JSON will not be validated
* after the POST, so if transformations are not compatible with the Schema it will not result
* in an error.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPostTransform(visitor, deps) {
this._post.add(visitor, deps);
}
_resolver(ref, validate) {
if (!validate || !ref) {
return {};
}
const schema = validate.schemaEnv.root.schema;
const id = typeof schema === 'object' ? schema.$id : null;
let fullReference = ref;
if (typeof id === 'string') {
fullReference = Url.resolve(id, ref);
if (ref.startsWith('#')) {
fullReference = id + fullReference;
}
}
const resolvedSchema = this._ajv.getSchema(fullReference);
return {
context: resolvedSchema?.schemaEnv.validate,
schema: resolvedSchema?.schema,
};
}
/**
* Flatten the Schema, resolving and replacing all the refs. Makes it into a synchronous schema
* that is also easier to traverse. Does not cache the result.
*
* Producing a flatten schema document does not in all cases produce a schema with identical behavior to the original.
* See: https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.appendix.B.2
*
* @param schema The schema or URI to flatten.
* @returns An Observable of the flattened schema object.
* @private since 11.2 without replacement.
*/
async ɵflatten(schema) {
this._ajv.removeSchema(schema);
this._currentCompilationSchemaInfo = undefined;
const validate = await this._ajv.compileAsync(schema);
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
function visitor(current, pointer, parentSchema, index) {
if (current &&
parentSchema &&
index &&
(0, utils_2.isJsonObject)(current) &&
Object.prototype.hasOwnProperty.call(current, '$ref') &&
typeof current['$ref'] == 'string') {
const resolved = self._resolver(current['$ref'], validate);
if (resolved.schema) {
parentSchema[index] = resolved.schema;
}
}
}
const schemaCopy = (0, utils_1.deepCopy)(validate.schema);
(0, visitor_1.visitJsonSchema)(schemaCopy, visitor);
return schemaCopy;
}
/**
* Compile and return a validation function for the Schema.
*
* @param schema The schema to validate. If a string, will fetch the schema before compiling it
* (using schema as a URI).
*/
async compile(schema) {
const validate = await this._compile(schema);
return (value, options) => validate(value, options);
}
async _compile(schema) {
if (typeof schema === 'boolean') {
return async (data) => ({ success: schema, data });
}
const schemaInfo = {
smartDefaultRecord: new Map(),
promptDefinitions: [],
};
this._ajv.removeSchema(schema);
let validator;
try {
this._currentCompilationSchemaInfo = schemaInfo;
validator = this._ajv.compile(schema);
}
catch (e) {
// This should eventually be refactored so that we we handle race condition where the same schema is validated at the same time.
if (!(e instanceof ajv_1.default.MissingRefError)) {
throw e;
}
validator = await this._ajv.compileAsync(schema);
}
finally {
this._currentCompilationSchemaInfo = undefined;
}
return async (data, options) => {
const validationOptions = {
withPrompts: true,
applyPostTransforms: true,
applyPreTransforms: true,
...options,
};
const validationContext = {
promptFieldsWithValue: new Set(),
};
// Apply pre-validation transforms
if (validationOptions.applyPreTransforms) {
for (const visitor of this._pre.values()) {
data = await (0, rxjs_1.lastValueFrom)((0, visitor_1.visitJson)(data, visitor, schema, this._resolver.bind(this), validator));
}
}
// Apply smart defaults
await this._applySmartDefaults(data, schemaInfo.smartDefaultRecord);
// Apply prompts
if (validationOptions.withPrompts) {
const visitor = (value, pointer) => {
if (value !== undefined) {
validationContext.promptFieldsWithValue.add(pointer);
}
return value;
};
if (typeof schema === 'object') {
await (0, rxjs_1.lastValueFrom)((0, visitor_1.visitJson)(data, visitor, schema, this._resolver.bind(this), validator));
}
const definitions = schemaInfo.promptDefinitions.filter((def) => !validationContext.promptFieldsWithValue.has(def.id));
if (definitions.length > 0) {
await this._applyPrompts(data, definitions);
}
}
// Validate using ajv
try {
// eslint-disable-next-line @typescript-eslint/await-thenable
const success = await validator.call(validationContext, data);
if (!success) {
return { data, success, errors: validator.errors ?? [] };
}
}
catch (error) {
if (error instanceof ajv_1.default.ValidationError) {
return { data, success: false, errors: error.errors };
}
throw error;
}
// Apply post-validation transforms
if (validationOptions.applyPostTransforms) {
for (const visitor of this._post.values()) {
data = await (0, rxjs_1.lastValueFrom)((0, visitor_1.visitJson)(data, visitor, schema, this._resolver.bind(this), validator));
}
}
return { data, success: true };
};
}
addFormat(format) {
this._ajv.addFormat(format.name, format.formatter);
}
addSmartDefaultProvider(source, provider) {
if (this._sourceMap.has(source)) {
throw new Error(source);
}
this._sourceMap.set(source, provider);
if (!this._smartDefaultKeyword) {
this._smartDefaultKeyword = true;
this._ajv.addKeyword({
keyword: '$default',
errors: false,
valid: true,
compile: (schema, _parentSchema, it) => {
const compilationSchemInfo = this._currentCompilationSchemaInfo;
if (compilationSchemInfo === undefined) {
return () => true;
}
// We cheat, heavily.
const pathArray = this.normalizeDataPathArr(it);
compilationSchemInfo.smartDefaultRecord.set(JSON.stringify(pathArray), schema);
return () => true;
},
metaSchema: {
type: 'object',
properties: {
'$source': { type: 'string' },
},
additionalProperties: true,
required: ['$source'],
},
});
}
}
registerUriHandler(handler) {
this._uriHandlers.add(handler);
}
usePromptProvider(provider) {
const isSetup = !!this._promptProvider;
this._promptProvider = provider;
if (isSetup) {
return;
}
this._ajv.addKeyword({
keyword: 'x-prompt',
errors: false,
valid: true,
compile: (schema, parentSchema, it) => {
const compilationSchemInfo = this._currentCompilationSchemaInfo;
if (!compilationSchemInfo) {
return () => true;
}
const path = '/' + this.normalizeDataPathArr(it).join('/');
let type;
let items;
let message;
if (typeof schema == 'string') {
message = schema;
}
else {
message = schema.message;
type = schema.type;
items = schema.items;
}
const propertyTypes = (0, utility_1.getTypesOfSchema)(parentSchema);
if (!type) {
if (propertyTypes.size === 1 && propertyTypes.has('boolean')) {
type = 'confirmation';
}
else if (Array.isArray(parentSchema.enum)) {
type = 'list';
}
else if (propertyTypes.size === 1 &&
propertyTypes.has('array') &&
parentSchema.items &&
Array.isArray(parentSchema.items.enum)) {
type = 'list';
}
else {
type = 'input';
}
}
let multiselect;
if (type === 'list') {
multiselect =
schema.multiselect === undefined
? propertyTypes.size === 1 && propertyTypes.has('array')
: schema.multiselect;
const enumValues = multiselect
? parentSchema.items &&
parentSchema.items.enum
: parentSchema.enum;
if (!items && Array.isArray(enumValues)) {
items = [];
for (const value of enumValues) {
if (typeof value == 'string') {
items.push(value);
}
else if (typeof value == 'object') {
// Invalid
}
else {
items.push({ label: value.toString(), value });
}
}
}
}
const definition = {
id: path,
type,
message,
raw: schema,
items,
multiselect,
propertyTypes,
default: typeof parentSchema.default == 'object' &&
parentSchema.default !== null &&
!Array.isArray(parentSchema.default)
? undefined
: parentSchema.default,
async validator(data) {
try {
const result = await it.self.validate(parentSchema, data);
// If the schema is sync then false will be returned on validation failure
if (result) {
return result;
}
else if (it.self.errors?.length) {
// Validation errors will be present on the Ajv instance when sync
return it.self.errors[0].message;
}
}
catch (e) {
const validationError = e;
// If the schema is async then an error will be thrown on validation failure
if (Array.isArray(validationError.errors) && validationError.errors.length) {
return validationError.errors[0].message;
}
}
return false;
},
};
compilationSchemInfo.promptDefinitions.push(definition);
return function () {
// If 'this' is undefined in the call, then it defaults to the global
// 'this'.
if (this && this.promptFieldsWithValue) {
this.promptFieldsWithValue.add(path);
}
return true;
};
},
metaSchema: {
oneOf: [
{ type: 'string' },
{
type: 'object',
properties: {
'type': { type: 'string' },
'message': { type: 'string' },
},
additionalProperties: true,
required: ['message'],
},
],
},
});
}
async _applyPrompts(data, prompts) {
const provider = this._promptProvider;
if (!provider) {
return;
}
const answers = await (0, rxjs_1.lastValueFrom)((0, rxjs_1.from)(provider(prompts)));
for (const path in answers) {
const pathFragments = path.split('/').slice(1);
CoreSchemaRegistry._set(data, pathFragments, answers[path], null, undefined, true);
}
}
static _set(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data, fragments, value,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
parent = null, parentProperty, force) {
for (let index = 0; index < fragments.length; index++) {
const fragment = fragments[index];
if (/^i\d+$/.test(fragment)) {
if (!Array.isArray(data)) {
return;
}
for (let dataIndex = 0; dataIndex < data.length; dataIndex++) {
CoreSchemaRegistry._set(data[dataIndex], fragments.slice(index + 1), value, data, `${dataIndex}`);
}
return;
}
if (!data && parent !== null && parentProperty) {
data = parent[parentProperty] = {};
}
parent = data;
parentProperty = fragment;
data = data[fragment];
}
if (parent && parentProperty && (force || parent[parentProperty] === undefined)) {
parent[parentProperty] = value;
}
}
async _applySmartDefaults(data, smartDefaults) {
for (const [pointer, schema] of smartDefaults.entries()) {
const fragments = JSON.parse(pointer);
const source = this._sourceMap.get(schema.$source);
if (!source) {
continue;
}
let value = source(schema);
if ((0, rxjs_1.isObservable)(value)) {
value = (await (0, rxjs_1.lastValueFrom)(value));
}
CoreSchemaRegistry._set(data, fragments, value);
}
}
useXDeprecatedProvider(onUsage) {
this._ajv.addKeyword({
keyword: 'x-deprecated',
validate: (schema, _data, _parentSchema, dataCxt) => {
if (schema) {
onUsage(`Option "${dataCxt?.parentDataProperty}" is deprecated${typeof schema == 'string' ? ': ' + schema : '.'}`);
}
return true;
},
errors: false,
});
}
normalizeDataPathArr(it) {
return it.dataPathArr
.slice(1, it.dataLevel + 1)
.map((p) => (typeof p === 'number' ? p : p.str.replace(/"/g, '')));
}
}
exports.CoreSchemaRegistry = CoreSchemaRegistry;
@@ -0,0 +1,22 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonObject } from '../utils';
/**
* A specialized interface for JsonSchema (to come). JsonSchemas are also JsonObject.
*
* @public
*/
export type JsonSchema = JsonObject | boolean;
export declare function isJsonSchema(value: unknown): value is JsonSchema;
/**
* Return a schema that is the merge of all subschemas, ie. it should validate all the schemas
* that were passed in. It is possible to make an invalid schema this way, e.g. by using
* `mergeSchemas({ type: 'number' }, { type: 'string' })`, which will never validate.
* @param schemas All schemas to be merged.
*/
export declare function mergeSchemas(...schemas: (JsonSchema | undefined)[]): JsonSchema;
@@ -0,0 +1,51 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isJsonSchema = isJsonSchema;
exports.mergeSchemas = mergeSchemas;
const utils_1 = require("../utils");
function isJsonSchema(value) {
return (0, utils_1.isJsonObject)(value) || value === false || value === true;
}
/**
* Return a schema that is the merge of all subschemas, ie. it should validate all the schemas
* that were passed in. It is possible to make an invalid schema this way, e.g. by using
* `mergeSchemas({ type: 'number' }, { type: 'string' })`, which will never validate.
* @param schemas All schemas to be merged.
*/
function mergeSchemas(...schemas) {
return schemas.reduce((prev, curr) => {
if (curr === undefined) {
return prev;
}
if (prev === false || curr === false) {
return false;
}
else if (prev === true) {
return curr;
}
else if (curr === true) {
return prev;
}
else if (Array.isArray(prev.allOf)) {
if (Array.isArray(curr.allOf)) {
return { ...prev, allOf: [...prev.allOf, ...curr.allOf] };
}
else {
return { ...prev, allOf: [...prev.allOf, curr] };
}
}
else if (Array.isArray(curr.allOf)) {
return { ...prev, allOf: [prev, ...curr.allOf] };
}
else {
return { ...prev, allOf: [prev, curr] };
}
}, true);
}
@@ -0,0 +1,11 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonValue } from '../utils';
import { JsonPointer } from './interface';
import { JsonSchema } from './schema';
export declare function addUndefinedDefaults(value: JsonValue, _pointer: JsonPointer, schema?: JsonSchema): JsonValue;
@@ -0,0 +1,93 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.addUndefinedDefaults = addUndefinedDefaults;
const utils_1 = require("../utils");
const utility_1 = require("./utility");
function addUndefinedDefaults(value, _pointer, schema) {
if (typeof schema === 'boolean' || schema === undefined) {
return value;
}
value ??= schema.default;
const types = (0, utility_1.getTypesOfSchema)(schema);
if (types.size === 0) {
return value;
}
let type;
if (types.size === 1) {
// only one potential type
type = Array.from(types)[0];
}
else if (types.size === 2 && types.has('array') && types.has('object')) {
// need to create one of them and array is simpler
type = 'array';
}
else if (schema.properties && types.has('object')) {
// assume object
type = 'object';
}
else if (schema.items && types.has('array')) {
// assume array
type = 'array';
}
else {
// anything else needs to be checked by the consumer anyway
return value;
}
if (type === 'array') {
return value == undefined ? [] : value;
}
if (type === 'object') {
let newValue;
if (value == undefined) {
newValue = {};
}
else if ((0, utils_1.isJsonObject)(value)) {
newValue = value;
}
else {
return value;
}
if (!(0, utils_1.isJsonObject)(schema.properties)) {
return newValue;
}
for (const [propName, schemaObject] of Object.entries(schema.properties)) {
if (propName === '$schema' || !(0, utils_1.isJsonObject)(schemaObject)) {
continue;
}
const value = newValue[propName];
if (value === undefined) {
newValue[propName] = schemaObject.default;
}
else if ((0, utils_1.isJsonObject)(value)) {
// Basic support for oneOf and anyOf.
const propertySchemas = schemaObject.oneOf || schemaObject.anyOf;
const allProperties = Object.keys(value);
// Locate a schema which declares all the properties that the object contains.
const adjustedSchema = (0, utils_1.isJsonArray)(propertySchemas) &&
propertySchemas.find((s) => {
if (!(0, utils_1.isJsonObject)(s)) {
return false;
}
const schemaType = (0, utility_1.getTypesOfSchema)(s);
if (schemaType.size === 1 && schemaType.has('object') && (0, utils_1.isJsonObject)(s.properties)) {
const properties = Object.keys(s.properties);
return allProperties.every((key) => properties.includes(key));
}
return false;
});
if (adjustedSchema && (0, utils_1.isJsonObject)(adjustedSchema)) {
newValue[propName] = addUndefinedDefaults(value, _pointer, adjustedSchema);
}
}
}
return newValue;
}
return value;
}
@@ -0,0 +1,9 @@
/**
* @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 { JsonSchema } from './schema';
export declare function getTypesOfSchema(schema: JsonSchema): Set<string>;
@@ -0,0 +1,87 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTypesOfSchema = getTypesOfSchema;
const utils_1 = require("../utils");
const allTypes = ['string', 'integer', 'number', 'object', 'array', 'boolean', 'null'];
function getTypesOfSchema(schema) {
if (!schema) {
return new Set();
}
if (schema === true) {
return new Set(allTypes);
}
let potentials;
if (typeof schema.type === 'string') {
potentials = new Set([schema.type]);
}
else if (Array.isArray(schema.type)) {
potentials = new Set(schema.type);
}
else if ((0, utils_1.isJsonArray)(schema.enum)) {
potentials = new Set();
// Gather the type of each enum values, and use that as a starter for potential types.
for (const v of schema.enum) {
switch (typeof v) {
case 'string':
case 'number':
case 'boolean':
potentials.add(typeof v);
break;
case 'object':
if (Array.isArray(v)) {
potentials.add('array');
}
else if (v === null) {
potentials.add('null');
}
else {
potentials.add('object');
}
break;
}
}
}
else {
potentials = new Set(allTypes);
}
if ((0, utils_1.isJsonObject)(schema.not)) {
const notTypes = getTypesOfSchema(schema.not);
potentials = new Set([...potentials].filter((p) => !notTypes.has(p)));
}
if (Array.isArray(schema.allOf)) {
for (const sub of schema.allOf) {
const types = getTypesOfSchema(sub);
potentials = new Set([...types].filter((t) => potentials.has(t)));
}
}
if (Array.isArray(schema.oneOf)) {
let options = new Set();
for (const sub of schema.oneOf) {
const types = getTypesOfSchema(sub);
options = new Set([...options, ...types]);
}
potentials = new Set([...options].filter((o) => potentials.has(o)));
}
if (Array.isArray(schema.anyOf)) {
let options = new Set();
for (const sub of schema.anyOf) {
const types = getTypesOfSchema(sub);
options = new Set([...options, ...types]);
}
potentials = new Set([...options].filter((o) => potentials.has(o)));
}
if (schema.properties) {
potentials.add('object');
}
else if (schema.items) {
potentials.add('array');
}
return potentials;
}
@@ -0,0 +1,34 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable } from 'rxjs';
import { JsonObject, JsonValue } from '../utils';
import { JsonSchemaVisitor, JsonVisitor } from './interface';
import { JsonSchema } from './schema';
export interface ReferenceResolver<ContextT> {
(ref: string, context?: ContextT): {
context?: ContextT;
schema?: JsonObject;
};
}
/**
* Visit all the properties in a JSON object, allowing to transform them. It supports calling
* properties synchronously or asynchronously (through Observables).
* The original object can be mutated or replaced entirely. In case where it's replaced, the new
* value is returned. When it's mutated though the original object will be changed.
*
* Please note it is possible to have an infinite loop here (which will result in a stack overflow)
* if you return 2 objects that references each others (or the same object all the time).
*
* @param {JsonValue} json The Json value to visit.
* @param {JsonVisitor} visitor A function that will be called on every items.
* @param {JsonObject} schema A JSON schema to pass through to the visitor (where possible).
* @param refResolver a function to resolve references in the schema.
* @returns {Observable< | undefined>} The observable of the new root, if the root changed.
*/
export declare function visitJson<ContextT>(json: JsonValue, visitor: JsonVisitor, schema?: JsonSchema, refResolver?: ReferenceResolver<ContextT>, context?: ContextT): Observable<JsonValue>;
export declare function visitJsonSchema(schema: JsonSchema, visitor: JsonSchemaVisitor): void;
@@ -0,0 +1,146 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.visitJson = visitJson;
exports.visitJsonSchema = visitJsonSchema;
const rxjs_1 = require("rxjs");
const pointer_1 = require("./pointer");
function _getObjectSubSchema(schema, key) {
if (typeof schema !== 'object' || schema === null) {
return undefined;
}
// Is it an object schema?
if (typeof schema.properties == 'object' || schema.type == 'object') {
if (typeof schema.properties == 'object' &&
typeof schema.properties[key] == 'object') {
return schema.properties[key];
}
if (typeof schema.additionalProperties == 'object') {
return schema.additionalProperties;
}
return undefined;
}
// Is it an array schema?
if (typeof schema.items == 'object' || schema.type == 'array') {
return typeof schema.items == 'object' ? schema.items : undefined;
}
return undefined;
}
function _visitJsonRecursive(json, visitor, ptr, schema, refResolver, context, root) {
if (schema === true || schema === false) {
// There's no schema definition, so just visit the JSON recursively.
schema = undefined;
}
// eslint-disable-next-line no-prototype-builtins
if (schema && schema.hasOwnProperty('$ref') && typeof schema['$ref'] == 'string') {
if (refResolver) {
const resolved = refResolver(schema['$ref'], context);
schema = resolved.schema;
context = resolved.context;
}
}
const value = visitor(json, ptr, schema, root);
return ((0, rxjs_1.isObservable)(value) ? value : (0, rxjs_1.of)(value)).pipe((0, rxjs_1.concatMap)((value) => {
if (Array.isArray(value)) {
return (0, rxjs_1.concat)((0, rxjs_1.from)(value).pipe((0, rxjs_1.mergeMap)((item, i) => {
return _visitJsonRecursive(item, visitor, (0, pointer_1.joinJsonPointer)(ptr, '' + i), _getObjectSubSchema(schema, '' + i), refResolver, context, root || value).pipe((0, rxjs_1.tap)((x) => (value[i] = x)));
}), (0, rxjs_1.ignoreElements)()), (0, rxjs_1.of)(value));
}
else if (typeof value == 'object' && value !== null) {
return (0, rxjs_1.concat)((0, rxjs_1.from)(Object.getOwnPropertyNames(value)).pipe((0, rxjs_1.mergeMap)((key) => {
return _visitJsonRecursive(value[key], visitor, (0, pointer_1.joinJsonPointer)(ptr, key), _getObjectSubSchema(schema, key), refResolver, context, root || value).pipe((0, rxjs_1.tap)((x) => {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (descriptor && descriptor.writable && value[key] !== x) {
value[key] = x;
}
}));
}), (0, rxjs_1.ignoreElements)()), (0, rxjs_1.of)(value));
}
else {
return (0, rxjs_1.of)(value);
}
}));
}
/**
* Visit all the properties in a JSON object, allowing to transform them. It supports calling
* properties synchronously or asynchronously (through Observables).
* The original object can be mutated or replaced entirely. In case where it's replaced, the new
* value is returned. When it's mutated though the original object will be changed.
*
* Please note it is possible to have an infinite loop here (which will result in a stack overflow)
* if you return 2 objects that references each others (or the same object all the time).
*
* @param {JsonValue} json The Json value to visit.
* @param {JsonVisitor} visitor A function that will be called on every items.
* @param {JsonObject} schema A JSON schema to pass through to the visitor (where possible).
* @param refResolver a function to resolve references in the schema.
* @returns {Observable< | undefined>} The observable of the new root, if the root changed.
*/
function visitJson(json, visitor, schema, refResolver, context) {
return _visitJsonRecursive(json, visitor, (0, pointer_1.buildJsonPointer)([]), schema, refResolver, context);
}
function visitJsonSchema(schema, visitor) {
if (schema === false || schema === true) {
// Nothing to visit.
return;
}
const keywords = {
additionalItems: true,
items: true,
contains: true,
additionalProperties: true,
propertyNames: true,
not: true,
};
const arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true,
};
const propsKeywords = {
definitions: true,
properties: true,
patternProperties: true,
additionalProperties: true,
dependencies: true,
items: true,
};
function _traverse(schema, jsonPtr, rootSchema, parentSchema, keyIndex) {
if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
visitor(schema, jsonPtr, parentSchema, keyIndex);
for (const key of Object.keys(schema)) {
const sch = schema[key];
if (key in propsKeywords) {
if (sch && typeof sch == 'object') {
for (const prop of Object.keys(sch)) {
_traverse(sch[prop], (0, pointer_1.joinJsonPointer)(jsonPtr, key, prop), rootSchema, schema, prop);
}
}
}
else if (key in keywords) {
_traverse(sch, (0, pointer_1.joinJsonPointer)(jsonPtr, key), rootSchema, schema, key);
}
else if (key in arrayKeywords) {
if (Array.isArray(sch)) {
for (let i = 0; i < sch.length; i++) {
_traverse(sch[i], (0, pointer_1.joinJsonPointer)(jsonPtr, key, '' + i), rootSchema, sch, '' + i);
}
}
}
else if (Array.isArray(sch)) {
for (let i = 0; i < sch.length; i++) {
_traverse(sch[i], (0, pointer_1.joinJsonPointer)(jsonPtr, key, '' + i), rootSchema, sch, '' + i);
}
}
}
}
}
_traverse(schema, (0, pointer_1.buildJsonPointer)([]), schema);
}
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export interface JsonArray extends Array<JsonValue> {
}
export interface JsonObject {
[prop: string]: JsonValue;
}
export type JsonValue = boolean | string | number | JsonArray | JsonObject | null;
export declare function isJsonObject(value: JsonValue): value is JsonObject;
export declare function isJsonArray(value: JsonValue): value is JsonArray;
@@ -0,0 +1,17 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isJsonObject = isJsonObject;
exports.isJsonArray = isJsonArray;
function isJsonObject(value) {
return value != null && typeof value === 'object' && !Array.isArray(value);
}
function isJsonArray(value) {
return Array.isArray(value);
}
@@ -0,0 +1,11 @@
/**
* @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 { Logger } from './logger';
export declare class IndentLogger extends Logger {
constructor(name: string, parent?: Logger | null, indentation?: string);
}
@@ -0,0 +1,40 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndentLogger = void 0;
const rxjs_1 = require("rxjs");
const logger_1 = require("./logger");
/**
* Keep an map of indentation => array of indentations based on the level.
* This is to optimize calculating the prefix based on the indentation itself. Since most logs
* come from similar levels, and with similar indentation strings, this will be shared by all
* loggers. Also, string concatenation is expensive so performing concats for every log entries
* is expensive; this alleviates it.
*/
const indentationMap = {};
class IndentLogger extends logger_1.Logger {
constructor(name, parent = null, indentation = ' ') {
super(name, parent);
indentationMap[indentation] = indentationMap[indentation] || [''];
const indentMap = indentationMap[indentation];
this._observable = this._observable.pipe((0, rxjs_1.map)((entry) => {
const l = entry.path.filter((x) => !!x).length;
if (l >= indentMap.length) {
let current = indentMap[indentMap.length - 1];
while (l >= indentMap.length) {
current += indentation;
indentMap.push(current);
}
}
entry.message = indentMap[l] + entry.message.split(/\n/).join('\n' + indentMap[l]);
return entry;
}));
}
}
exports.IndentLogger = IndentLogger;
@@ -0,0 +1,12 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './indent';
export * from './level';
export * from './logger';
export * from './null-logger';
export * from './transform-logger';
@@ -0,0 +1,28 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./indent"), exports);
__exportStar(require("./level"), exports);
__exportStar(require("./logger"), exports);
__exportStar(require("./null-logger"), exports);
__exportStar(require("./transform-logger"), exports);
@@ -0,0 +1,28 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonObject } from '../json/utils';
import { LogLevel, Logger } from './logger';
export declare class LevelTransformLogger extends Logger {
readonly name: string;
readonly parent: Logger | null;
readonly levelTransform: (level: LogLevel) => LogLevel;
constructor(name: string, parent: (Logger | null) | undefined, levelTransform: (level: LogLevel) => LogLevel);
log(level: LogLevel, message: string, metadata?: JsonObject): void;
createChild(name: string): Logger;
}
export declare class LevelCapLogger extends LevelTransformLogger {
readonly name: string;
readonly parent: Logger | null;
readonly levelCap: LogLevel;
static levelMap: {
[cap: string]: {
[level: string]: string;
};
};
constructor(name: string, parent: (Logger | null) | undefined, levelCap: LogLevel);
}
@@ -0,0 +1,50 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.LevelCapLogger = exports.LevelTransformLogger = void 0;
const logger_1 = require("./logger");
class LevelTransformLogger extends logger_1.Logger {
name;
parent;
levelTransform;
constructor(name, parent = null, levelTransform) {
super(name, parent);
this.name = name;
this.parent = parent;
this.levelTransform = levelTransform;
}
log(level, message, metadata = {}) {
return super.log(this.levelTransform(level), message, metadata);
}
createChild(name) {
return new LevelTransformLogger(name, this, this.levelTransform);
}
}
exports.LevelTransformLogger = LevelTransformLogger;
class LevelCapLogger extends LevelTransformLogger {
name;
parent;
levelCap;
static levelMap = {
debug: { debug: 'debug', info: 'debug', warn: 'debug', error: 'debug', fatal: 'debug' },
info: { debug: 'debug', info: 'info', warn: 'info', error: 'info', fatal: 'info' },
warn: { debug: 'debug', info: 'info', warn: 'warn', error: 'warn', fatal: 'warn' },
error: { debug: 'debug', info: 'info', warn: 'warn', error: 'error', fatal: 'error' },
fatal: { debug: 'debug', info: 'info', warn: 'warn', error: 'error', fatal: 'fatal' },
};
constructor(name, parent = null, levelCap) {
super(name, parent, (level) => {
return (LevelCapLogger.levelMap[levelCap][level] || level);
});
this.name = name;
this.parent = parent;
this.levelCap = levelCap;
}
}
exports.LevelCapLogger = LevelCapLogger;
@@ -0,0 +1,55 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable, Operator, PartialObserver, Subject, Subscription } from 'rxjs';
import { JsonObject } from '../json/utils';
export interface LoggerMetadata extends JsonObject {
name: string;
path: string[];
}
export interface LogEntry extends LoggerMetadata {
level: LogLevel;
message: string;
timestamp: number;
}
export interface LoggerApi {
createChild(name: string): Logger;
log(level: LogLevel, message: string, metadata?: JsonObject): void;
debug(message: string, metadata?: JsonObject): void;
info(message: string, metadata?: JsonObject): void;
warn(message: string, metadata?: JsonObject): void;
error(message: string, metadata?: JsonObject): void;
fatal(message: string, metadata?: JsonObject): void;
}
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
export declare class Logger extends Observable<LogEntry> implements LoggerApi {
readonly name: string;
readonly parent: Logger | null;
protected readonly _subject: Subject<LogEntry>;
protected _metadata: LoggerMetadata;
private _obs;
private _subscription;
protected get _observable(): Observable<LogEntry>;
protected set _observable(v: Observable<LogEntry>);
constructor(name: string, parent?: Logger | null);
asApi(): LoggerApi;
createChild(name: string): Logger;
complete(): void;
log(level: LogLevel, message: string, metadata?: JsonObject): void;
next(entry: LogEntry): void;
debug(message: string, metadata?: JsonObject): void;
info(message: string, metadata?: JsonObject): void;
warn(message: string, metadata?: JsonObject): void;
error(message: string, metadata?: JsonObject): void;
fatal(message: string, metadata?: JsonObject): void;
toString(): string;
lift<R>(operator: Operator<LogEntry, R>): Observable<R>;
subscribe(): Subscription;
subscribe(observer: PartialObserver<LogEntry>): Subscription;
subscribe(next?: (value: LogEntry) => void, error?: (error: Error) => void, complete?: () => void): Subscription;
forEach(next: (value: LogEntry) => void, promiseCtor?: PromiseConstructorLike): Promise<void>;
}
@@ -0,0 +1,122 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
const rxjs_1 = require("rxjs");
class Logger extends rxjs_1.Observable {
name;
parent;
_subject = new rxjs_1.Subject();
_metadata;
_obs = rxjs_1.EMPTY;
_subscription = null;
get _observable() {
return this._obs;
}
set _observable(v) {
if (this._subscription) {
this._subscription.unsubscribe();
}
this._obs = v;
if (this.parent) {
this._subscription = this.subscribe((value) => {
if (this.parent) {
this.parent._subject.next(value);
}
}, (error) => {
if (this.parent) {
this.parent._subject.error(error);
}
}, () => {
if (this._subscription) {
this._subscription.unsubscribe();
}
this._subscription = null;
});
}
}
constructor(name, parent = null) {
super();
this.name = name;
this.parent = parent;
const path = [];
let p = parent;
while (p) {
path.push(p.name);
p = p.parent;
}
this._metadata = { name, path };
this._observable = this._subject.asObservable();
if (this.parent && this.parent._subject) {
// When the parent completes, complete us as well.
this.parent._subject.subscribe(undefined, undefined, () => this.complete());
}
}
asApi() {
return {
createChild: (name) => this.createChild(name),
log: (level, message, metadata) => {
return this.log(level, message, metadata);
},
debug: (message, metadata) => this.debug(message, metadata),
info: (message, metadata) => this.info(message, metadata),
warn: (message, metadata) => this.warn(message, metadata),
error: (message, metadata) => this.error(message, metadata),
fatal: (message, metadata) => this.fatal(message, metadata),
};
}
createChild(name) {
return new this.constructor(name, this);
}
complete() {
this._subject.complete();
}
log(level, message, metadata = {}) {
const entry = Object.assign({}, metadata, this._metadata, {
level,
message,
timestamp: +Date.now(),
});
this._subject.next(entry);
}
next(entry) {
this._subject.next(entry);
}
debug(message, metadata = {}) {
this.log('debug', message, metadata);
}
info(message, metadata = {}) {
this.log('info', message, metadata);
}
warn(message, metadata = {}) {
this.log('warn', message, metadata);
}
error(message, metadata = {}) {
this.log('error', message, metadata);
}
fatal(message, metadata = {}) {
this.log('fatal', message, metadata);
}
toString() {
return `<Logger(${this.name})>`;
}
lift(operator) {
return this._observable.lift(operator);
}
subscribe(_observerOrNext, _error, _complete) {
// eslint-disable-next-line prefer-spread
return this._observable.subscribe.apply(this._observable,
// eslint-disable-next-line prefer-rest-params
arguments);
}
forEach(next, promiseCtor = Promise) {
return this._observable.forEach(next, promiseCtor);
}
}
exports.Logger = Logger;
@@ -0,0 +1,12 @@
/**
* @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 { Logger, LoggerApi } from './logger';
export declare class NullLogger extends Logger {
constructor(parent?: Logger | null);
asApi(): LoggerApi;
}
@@ -0,0 +1,30 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NullLogger = void 0;
const rxjs_1 = require("rxjs");
const logger_1 = require("./logger");
class NullLogger extends logger_1.Logger {
constructor(parent = null) {
super('', parent);
this._observable = rxjs_1.EMPTY;
}
asApi() {
return {
createChild: () => new NullLogger(this),
log() { },
debug() { },
info() { },
warn() { },
error() { },
fatal() { },
};
}
}
exports.NullLogger = NullLogger;
@@ -0,0 +1,12 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable } from 'rxjs';
import { LogEntry, Logger } from './logger';
export declare class TransformLogger extends Logger {
constructor(name: string, transform: (stream: Observable<LogEntry>) => Observable<LogEntry>, parent?: Logger | null);
}
@@ -0,0 +1,18 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransformLogger = void 0;
const logger_1 = require("./logger");
class TransformLogger extends logger_1.Logger {
constructor(name, transform, parent = null) {
super(name, parent);
this._observable = transform(this._observable);
}
}
exports.TransformLogger = TransformLogger;
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as tags from './literals';
import * as strings from './strings';
export * from './object';
export * from './template';
export * from './partially-ordered-set';
export * from './priority-queue';
export * from './lang';
export { tags, strings };
@@ -0,0 +1,55 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.strings = exports.tags = void 0;
const tags = __importStar(require("./literals"));
exports.tags = tags;
const strings = __importStar(require("./strings"));
exports.strings = strings;
__exportStar(require("./object"), exports);
__exportStar(require("./template"), exports);
__exportStar(require("./partially-ordered-set"), exports);
__exportStar(require("./priority-queue"), exports);
__exportStar(require("./lang"), exports);
@@ -0,0 +1,11 @@
/**
* @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
*/
/**
* Determine if the argument is shaped like a Promise
*/
export declare function isPromise(obj: any): obj is Promise<any>;
@@ -0,0 +1,20 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPromise = isPromise;
// Borrowed from @angular/core
/**
* Determine if the argument is shaped like a Promise
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isPromise(obj) {
// allow any Promise/A+ compliant thenable.
// It's up to the caller to ensure that obj.then conforms to the spec
return !!obj && typeof obj.then === 'function';
}
Loaded 100 of 31158 files, more files were not shown because too many files have changed in this diff. Show more