ddd-express 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/LICENSE +21 -0
- package/README.ar.md +117 -0
- package/README.md +314 -2
- package/dist/analyze/check.d.ts +74 -0
- package/dist/analyze/check.js +503 -0
- package/dist/analyze/document.d.ts +26 -0
- package/dist/analyze/document.js +126 -0
- package/dist/analyze/map.d.ts +19 -0
- package/dist/analyze/map.js +283 -0
- package/dist/analyze/openapi.d.ts +7 -0
- package/dist/analyze/openapi.js +236 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +12 -0
- package/dist/core/errors.d.ts +5 -0
- package/dist/core/errors.js +13 -0
- package/dist/core/fields.d.ts +38 -0
- package/dist/core/fields.js +233 -0
- package/dist/core/markers.d.ts +25 -0
- package/dist/core/markers.js +60 -0
- package/dist/core/names.d.ts +30 -0
- package/dist/core/names.js +168 -0
- package/dist/core/output.d.ts +21 -0
- package/dist/core/output.js +29 -0
- package/dist/core/project.d.ts +135 -0
- package/dist/core/project.js +287 -0
- package/dist/core/writer.d.ts +39 -0
- package/dist/core/writer.js +138 -0
- package/dist/generators/analyze.d.ts +16 -0
- package/dist/generators/analyze.js +174 -0
- package/dist/generators/apply.d.ts +28 -0
- package/dist/generators/apply.js +234 -0
- package/dist/generators/common.d.ts +49 -0
- package/dist/generators/common.js +173 -0
- package/dist/generators/domain.d.ts +30 -0
- package/dist/generators/domain.js +198 -0
- package/dist/generators/engine.d.ts +71 -0
- package/dist/generators/engine.js +552 -0
- package/dist/generators/project.d.ts +10 -0
- package/dist/generators/project.js +214 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +14 -0
- package/dist/model/commands.d.ts +28 -0
- package/dist/model/commands.js +228 -0
- package/dist/model/examples.d.ts +6 -0
- package/dist/model/examples.js +152 -0
- package/dist/model/parser.d.ts +28 -0
- package/dist/model/parser.js +222 -0
- package/dist/model/types.d.ts +98 -0
- package/dist/model/types.js +2 -0
- package/dist/model/validate.d.ts +30 -0
- package/dist/model/validate.js +215 -0
- package/dist/run.d.ts +4 -0
- package/dist/run.js +506 -0
- package/dist/scan/project-scan.d.ts +77 -0
- package/dist/scan/project-scan.js +226 -0
- package/dist/scan/source.d.ts +60 -0
- package/dist/scan/source.js +274 -0
- package/dist/templates/aggregate.d.ts +51 -0
- package/dist/templates/aggregate.js +407 -0
- package/dist/templates/building-blocks.d.ts +30 -0
- package/dist/templates/building-blocks.js +155 -0
- package/dist/templates/code.d.ts +14 -0
- package/dist/templates/code.js +51 -0
- package/dist/templates/command.d.ts +47 -0
- package/dist/templates/command.js +376 -0
- package/dist/templates/context.d.ts +16 -0
- package/dist/templates/context.js +43 -0
- package/dist/templates/field-code.d.ts +47 -0
- package/dist/templates/field-code.js +227 -0
- package/dist/templates/postgres.d.ts +25 -0
- package/dist/templates/postgres.js +113 -0
- package/dist/templates/project.d.ts +20 -0
- package/dist/templates/project.js +153 -0
- package/dist/templates/shared-kernel.d.ts +6 -0
- package/dist/templates/shared-kernel.js +44 -0
- package/package.json +58 -4
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sharedKernelFiles = sharedKernelFiles;
|
|
4
|
+
const project_1 = require("../core/project");
|
|
5
|
+
const code_1 = require("./code");
|
|
6
|
+
/**
|
|
7
|
+
* The shared kernel: the small building blocks every bounded context uses.
|
|
8
|
+
* Returns { absolute file path → content }.
|
|
9
|
+
*/
|
|
10
|
+
function sharedKernelFiles(project) {
|
|
11
|
+
const s = (0, project_1.sharedPaths)(project);
|
|
12
|
+
const files = new Map();
|
|
13
|
+
const add = (target, render) => {
|
|
14
|
+
files.set((0, project_1.ts)(target), render((0, code_1.importer)(project, (0, project_1.ts)(target))));
|
|
15
|
+
};
|
|
16
|
+
// ------------------------------------------------------------------------------- domain
|
|
17
|
+
add(s.entity, () => (0, code_1.lines)('/**', ' * An Entity has an identity that stays the same while its attributes change.', ' * Two entities are equal when they are of the same type and have the same id.', ' */', 'export abstract class Entity<Id = string> {', ' readonly id: Id;', '', ' protected constructor(id: Id) {', ' this.id = id;', ' }', '', ' equals(other?: Entity<Id>): boolean {', ' return !!other && other.constructor === this.constructor && other.id === this.id;', ' }', '}'));
|
|
18
|
+
add(s.aggregateRoot, (imp) => (0, code_1.lines)(`import { Entity } from ${imp(s.entity)};`, `import type { DomainEvent } from ${imp(s.domainEvent)};`, '', '/**', ' * An Aggregate Root is the single entry point to a group of objects that change together.', ' * It records the Domain Events it produces. The application layer saves the aggregate,', ' * THEN publishes the events — so nobody hears about a change that was not saved.', ' */', 'export abstract class AggregateRoot<Id = string> extends Entity<Id> {', ' private readonly pendingEvents: DomainEvent[] = [];', '', ' protected record(event: DomainEvent): void {', ' this.pendingEvents.push(event);', ' }', '', ' /** The events recorded so far, without clearing them. */', ' peekEvents(): readonly DomainEvent[] {', ' return [...this.pendingEvents];', ' }', '', ' /** Returns and clears the pending events. Call it once, after a successful save. */', ' pullEvents(): DomainEvent[] {', ' return this.pendingEvents.splice(0, this.pendingEvents.length);', ' }', '}'));
|
|
19
|
+
add(s.valueObject, () => (0, code_1.lines)('/**', ' * Base class for Value Objects. A Value Object:', ' * 1. has no id — its identity IS its values', ' * 2. is immutable — "change" it by creating a new one', ' * 3. protects itself — it cannot exist in an invalid state', ' */', 'export abstract class ValueObject<T extends object> {', ' protected readonly props: Readonly<T>;', '', ' protected constructor(props: T) {', ' this.props = Object.freeze({ ...props });', ' }', '', ' equals(other?: ValueObject<T>): boolean {', ' if (!other || other.constructor !== this.constructor) return false;', ' return JSON.stringify(this.props) === JSON.stringify(other.props);', ' }', '}'));
|
|
20
|
+
add(s.domainEvent, () => (0, code_1.lines)('/**', ' * A Domain Event is something that HAPPENED in the domain, named in the past tense', ' * (VisitCompleted, InvoicePaid). It carries what listeners need — and nothing more.', ' */', 'export abstract class DomainEvent {', ' readonly occurredAt: Date = new Date();', ' abstract readonly aggregateId: string;', '', ' /** The event name, e.g. "VisitCompleted". */', ' get eventName(): string {', ' return this.constructor.name;', ' }', '}'));
|
|
21
|
+
add(s.domainError, () => (0, code_1.lines)('/** A business rule was broken. It carries no HTTP meaning — the adapters decide how to report it. */', 'export class DomainError extends Error {', ' constructor(message: string) {', ' super(message);', ' this.name = new.target.name;', ' }', '}', '', '/** The thing a request refers to does not exist. */', 'export class NotFoundError extends DomainError {', ' readonly entity: string;', ' readonly id: string;', '', ' constructor(entity: string, id: string) {', ' super(`${entity} ${id} not found`);', ' this.entity = entity;', ' this.id = id;', ' }', '}', '', '/** The request conflicts with the current state, e.g. a duplicate. */', 'export class ConflictError extends DomainError {}'));
|
|
22
|
+
add(s.guard, (imp) => (0, code_1.lines)(`import { DomainError } from ${imp(s.domainError)};`, '', '/**', ' * Checks for business invariants. Each check returns the (normalized) value or throws a', ' * DomainError, so an aggregate, entity or value object can never hold invalid state.', ' */', 'export const Guard = {', ' /** Non-empty text. Returns it trimmed. */', ' text(value: unknown, field: string): string {', " if (typeof value !== 'string' || value.trim() === '') {", ' throw new DomainError(`${field} must be a non-empty text`);', ' }', ' return value.trim();', ' },', '', ' number(value: unknown, field: string): number {', " if (typeof value !== 'number' || !Number.isFinite(value)) {", ' throw new DomainError(`${field} must be a number`);', ' }', ' return value;', ' },', '', ' integer(value: unknown, field: string): number {', " if (typeof value !== 'number' || !Number.isInteger(value)) {", ' throw new DomainError(`${field} must be a whole number`);', ' }', ' return value;', ' },', '', ' boolean(value: unknown, field: string): boolean {', " if (typeof value !== 'boolean') {", ' throw new DomainError(`${field} must be true or false`);', ' }', ' return value;', ' },', '', ' /** A valid Date. Returns a copy, so the caller cannot change it afterwards. */', ' date(value: unknown, field: string): Date {', ' if (!(value instanceof Date) || Number.isNaN(value.getTime())) {', ' throw new DomainError(`${field} must be a valid date`);', ' }', ' return new Date(value.getTime());', ' },', '', ' oneOf<T extends string>(value: unknown, allowed: readonly T[], field: string): T {', " if (typeof value !== 'string' || !(allowed as readonly string[]).includes(value)) {", " throw new DomainError(`${field} must be one of: ${allowed.join(', ')}`);", ' }', ' return value as T;', ' },', '', ' /** Runs `check` only when a value is given; null and undefined become null. */', ' optional<T>(value: T | null | undefined, check: (value: T) => T): T | null {', ' return value === null || value === undefined ? null : check(value);', ' },', '};'));
|
|
23
|
+
add(s.id, () => (0, code_1.lines)("import { randomUUID } from 'node:crypto';", '', '/** A new unique id for an aggregate or entity. */', 'export function newId(): string {', ' return randomUUID();', '}'));
|
|
24
|
+
add(s.pagination, () => (0, code_1.lines)('/** Which slice of a collection to read. Used by repository ports. */', 'export interface PageQuery {', ' limit: number;', ' offset: number;', '}', '', '/** One slice of a collection, plus the total number of items. */', 'export interface Page<T> {', ' items: T[];', ' total: number;', ' limit: number;', ' offset: number;', '}'));
|
|
25
|
+
add(s.object, () => (0, code_1.lines)('/** Equality used to detect changes: Dates by time, everything else with ===. */', 'export function sameValue(a: unknown, b: unknown): boolean {', ' if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();', ' return a === b;', '}', '', '/** A copy of `object` without the keys whose value is undefined. */', 'export function withoutUndefined<T extends object>(object: T): Partial<T> {', ' return Object.fromEntries(', ' Object.entries(object).filter(([, value]) => value !== undefined),', ' ) as Partial<T>;', '}'));
|
|
26
|
+
// -------------------------------------------------------------------------- application
|
|
27
|
+
add(s.eventBus, (imp) => (0, code_1.lines)(`import type { DomainEvent } from ${imp(s.domainEvent)};`, '', '/** A class of events, e.g. `VisitCompleted` — what a handler subscribes to. */', 'export type EventClass<E extends DomainEvent> = abstract new (...args: never[]) => E;', '', 'export type EventHandler<E extends DomainEvent> = (event: E) => void | Promise<void>;', '', '/**', ' * Port: how the application announces what happened.', ' * The in-memory adapter dispatches in-process; a message-broker adapter can replace it', ' * without touching the domain or the use cases.', ' */', 'export interface EventBus {', ' publish(events: readonly DomainEvent[]): Promise<void>;', ' /** Subscribes to one class of events. Returns a function that unsubscribes. */', ' subscribe<E extends DomainEvent>(type: EventClass<E>, handler: EventHandler<E>): () => void;', '}'));
|
|
28
|
+
// ----------------------------------------------------------------------- infrastructure
|
|
29
|
+
add(s.inMemoryEventBus, (imp) => (0, code_1.lines)(`import type { DomainEvent } from ${imp(s.domainEvent)};`, `import type { EventBus, EventClass, EventHandler } from ${imp(s.eventBus)};`, '', 'type AnyHandler = (event: DomainEvent) => void | Promise<void>;', '', 'export interface InMemoryEventBusOptions {', ' /** Called when a handler fails. Defaults to console.error. */', ' onError?: (error: unknown, event: DomainEvent) => void;', '}', '', '/**', ' * Adapter: dispatches events in-process to every handler subscribed to the event class', ' * (or to one of its parent classes), one after the other.', ' *', ' * A failing handler does not stop the others and does not fail the use case that published:', ' * the change is already saved. When delivery must be guaranteed, use an outbox.', ' */', 'export class InMemoryEventBus implements EventBus {', ' private readonly handlers = new Map<EventClass<DomainEvent>, AnyHandler[]>();', ' private readonly onError: (error: unknown, event: DomainEvent) => void;', '', ' constructor(options: InMemoryEventBusOptions = {}) {', ' this.onError =', ' options.onError ??', ' ((error, event) => console.error(`[event-bus] a ${event.eventName} handler failed:`, error));', ' }', '', ' subscribe<E extends DomainEvent>(type: EventClass<E>, handler: EventHandler<E>): () => void {', ' const list = this.handlers.get(type) ?? [];', ' const entry = handler as AnyHandler;', ' list.push(entry);', ' this.handlers.set(type, list);', ' return () => {', ' const index = list.indexOf(entry);', ' if (index !== -1) list.splice(index, 1);', ' };', ' }', '', ' async publish(events: readonly DomainEvent[]): Promise<void> {', ' for (const event of events) {', ' for (const [type, handlers] of this.handlers) {', ' if (!(event instanceof type)) continue;', ' for (const handler of [...handlers]) {', ' try {', ' await handler(event);', ' } catch (error) {', ' this.onError(error, event);', ' }', ' }', ' }', ' }', ' }', '}'));
|
|
30
|
+
// --------------------------------------------------------------------------------- http
|
|
31
|
+
add(s.httpError, () => (0, code_1.lines)('/** An error with an HTTP status. It belongs to the HTTP adapter — never throw it from the domain. */', 'export class HttpError extends Error {', ' readonly status: number;', ' readonly details: readonly string[];', '', ' constructor(status: number, message: string, details: readonly string[] = []) {', ' super(message);', ' this.name = new.target.name;', ' this.status = status;', ' this.details = details;', ' }', '}', '', '/** 400: the request itself is malformed (wrong types, missing fields, unknown fields). */', 'export class BadRequestError extends HttpError {', ' constructor(message: string, details: readonly string[] = []) {', ' super(400, message, details);', ' }', '}'));
|
|
32
|
+
add(s.asyncHandler, () => (0, code_1.lines)("import type { NextFunction, Request, RequestHandler, Response } from 'express';", '', '/**', ' * Lets a route handler be async: a rejected promise goes to the error handler.', ' * (Express 5 does this by itself; Express 4 needs this wrapper. It works with both.)', ' */', 'export function asyncHandler(', ' handler: (req: Request, res: Response, next: NextFunction) => Promise<unknown>,', '): RequestHandler {', ' return (req, res, next) => {', ' handler(req, res, next).catch(next);', ' };', '}'));
|
|
33
|
+
add(s.routeParam, (imp) => (0, code_1.lines)("import type { Request } from 'express';", `import { BadRequestError } from ${imp(s.httpError)};`, '', '/** A named route parameter (e.g. :id) as a non-empty string. */', 'export function routeParam(req: Request, name: string): string {', ' const value: unknown = req.params[name];', " if (typeof value !== 'string' || value === '') {", ' throw new BadRequestError(`Missing route parameter: ${name}`);', ' }', ' return value;', '}'));
|
|
34
|
+
add(s.requestBody, (imp) => (0, code_1.lines)(`import { BadRequestError } from ${imp(s.httpError)};`, '', '/** Reads one value: returns it, or says what is wrong with it. */', 'export type Parser<T> = (value: unknown) => { ok: true; value: T } | { ok: false; error: string };', '', 'export const asText: Parser<string> = (value) =>', " typeof value === 'string' ? { ok: true, value } : { ok: false, error: 'must be a string' };", '', 'export const asNumber: Parser<number> = (value) =>', " typeof value === 'number' && Number.isFinite(value)", ' ? { ok: true, value }', " : { ok: false, error: 'must be a number' };", '', 'export const asInteger: Parser<number> = (value) =>', " typeof value === 'number' && Number.isInteger(value)", ' ? { ok: true, value }', " : { ok: false, error: 'must be a whole number' };", '', 'export const asBoolean: Parser<boolean> = (value) =>', " typeof value === 'boolean' ? { ok: true, value } : { ok: false, error: 'must be true or false' };", '', '/** An ISO 8601 string such as "2026-01-10T09:00:00Z", turned into a Date. */', 'export const asDate: Parser<Date> = (value) => {', " const date = typeof value === 'string' ? new Date(value) : new Date(Number.NaN);", ' return Number.isNaN(date.getTime())', " ? { ok: false, error: 'must be an ISO 8601 date string' }", ' : { ok: true, value: date };', '};', '', 'export function asOneOf<T extends string>(allowed: readonly T[]): Parser<T> {', ' return (value) =>', " typeof value === 'string' && (allowed as readonly string[]).includes(value)", ' ? { ok: true, value: value as T }', " : { ok: false, error: `must be one of: ${allowed.join(', ')}` };", '}', '', '/**', ' * Reads a JSON request body field by field and collects EVERY problem, so the client gets', ' * all of them in one 400 response. It checks the shape of the request (types, required and', ' * unknown fields). Business rules are not checked here — they live in the domain.', ' */', 'export class RequestBody {', ' private readonly data: Record<string, unknown>;', ' private readonly errors: string[] = [];', ' private readonly seen = new Set<string>();', '', ' constructor(body: unknown) {', " if (body === null || typeof body !== 'object' || Array.isArray(body)) {", ' this.data = {};', " this.errors.push('the body must be a JSON object');", ' } else {', ' this.data = body as Record<string, unknown>;', ' }', ' }', '', ' /** Must be present and not null. */', ' required<T>(key: string, parse: Parser<T>): T {', ' const value = this.take(key);', ' if (value === undefined || value === null) {', ' this.errors.push(`${key} is required`);', ' return undefined as never;', ' }', ' return this.parse(key, value, parse) as T;', ' }', '', ' /** May be left out (undefined) or null (= empty). */', ' optional<T>(key: string, parse: Parser<T>): T | null | undefined {', ' const value = this.take(key);', ' if (value === undefined || value === null) return value;', ' return this.parse(key, value, parse);', ' }', '', ' /** For partial updates: may be left out, but cannot be null. */', ' ifPresent<T>(key: string, parse: Parser<T>): T | undefined {', ' const value = this.take(key);', ' if (value === undefined) return undefined;', ' if (value === null) {', ' this.errors.push(`${key} cannot be null`);', ' return undefined;', ' }', ' return this.parse(key, value, parse);', ' }', '', ' /** Throws a 400 listing every problem, including fields that are not allowed. */', ' assertValid(): void {', ' for (const key of Object.keys(this.data)) {', ' if (!this.seen.has(key)) this.errors.push(`${key} is not an allowed field`);', ' }', " if (this.errors.length > 0) throw new BadRequestError('Invalid request body', this.errors);", ' }', '', ' private take(key: string): unknown {', ' this.seen.add(key);', ' return Object.prototype.hasOwnProperty.call(this.data, key) ? this.data[key] : undefined;', ' }', '', ' private parse<T>(key: string, value: unknown, parse: Parser<T>): T | undefined {', ' const result = parse(value);', ' if (result.ok) return result.value;', ' this.errors.push(`${key} ${result.error}`);', ' return undefined;', ' }', '}'));
|
|
35
|
+
add(s.httpPagination, (imp) => (0, code_1.lines)(`import type { PageQuery } from ${imp(s.pagination)};`, `import { BadRequestError } from ${imp(s.httpError)};`, '', 'export const DEFAULT_PAGE_SIZE = 20;', 'export const MAX_PAGE_SIZE = 100;', '', '/** Reads ?limit=&offset= (defaults: limit 20, offset 0; limit at most 100). */', 'export function parsePageQuery(query: Record<string, unknown>): PageQuery {', ' const errors: string[] = [];', ' const limit = readWholeNumber(query.limit, DEFAULT_PAGE_SIZE);', ' const offset = readWholeNumber(query.offset, 0);', ' if (limit === null || limit < 1 || limit > MAX_PAGE_SIZE) {', ' errors.push(`limit must be a whole number from 1 to ${MAX_PAGE_SIZE}`);', ' }', " if (offset === null) errors.push('offset must be a whole number, 0 or more');", " if (errors.length > 0) throw new BadRequestError('Invalid query string', errors);", ' return { limit: limit ?? DEFAULT_PAGE_SIZE, offset: offset ?? 0 };', '}', '', 'function readWholeNumber(raw: unknown, fallback: number): number | null {', ' if (raw === undefined) return fallback;', " if (typeof raw !== 'string' || !/^\\d{1,15}$/.test(raw)) return null;", ' return Number(raw);', '}'));
|
|
36
|
+
add(s.errorHandler, (imp) => (0, code_1.lines)("import type { ErrorRequestHandler, RequestHandler } from 'express';", `import { ConflictError, DomainError, NotFoundError } from ${imp(s.domainError)};`, `import { HttpError } from ${imp(s.httpError)};`, '', '/** Unknown route → 404, in the same JSON shape as every other error. */', 'export const notFoundHandler: RequestHandler = (req, res) => {', " res.status(404).json({ error: 'NotFoundError', message: `Route ${req.method} ${req.path} not found` });", '};', '', '/**', ' * Turns errors into HTTP responses. The domain knows nothing about HTTP; this adapter', ' * decides the status code:', ' * HttpError → its own status NotFoundError → 404 ConflictError → 409', ' * DomainError (a broken business rule) → 422 anything else → 500', ' * Register it after every route: app.use(errorHandler).', ' */', 'export const errorHandler: ErrorRequestHandler = (err, _req, res, next) => {', ' if (res.headersSent) {', ' next(err);', ' return;', ' }', ' if (err instanceof HttpError) {', ' const details = err.details.length > 0 ? { details: err.details } : {};', ' res.status(err.status).json({ error: err.name, message: err.message, ...details });', ' return;', ' }', ' if (err instanceof NotFoundError) {', ' res.status(404).json({ error: err.name, message: err.message });', ' return;', ' }', ' if (err instanceof ConflictError) {', ' res.status(409).json({ error: err.name, message: err.message });', ' return;', ' }', ' if (err instanceof DomainError) {', ' res.status(422).json({ error: err.name, message: err.message });', ' return;', ' }', ' // Errors from express.json() (invalid JSON, body too large, ...) carry a 4xx status.', ' const status = (err as { status?: unknown }).status;', " if (typeof status === 'number' && status >= 400 && status < 500) {", " res.status(status).json({ error: 'BadRequestError', message: (err as Error).message });", ' return;', ' }', ' console.error(err);', " res.status(500).json({ error: 'InternalServerError', message: 'Something went wrong' });", '};'));
|
|
37
|
+
// ------------------------------------------------------------------------------ testing
|
|
38
|
+
add(s.recordingEventBus, (imp) => (0, code_1.lines)(`import type { DomainEvent } from ${imp(s.domainEvent)};`, `import { InMemoryEventBus } from ${imp(s.inMemoryEventBus)};`, '', '/** Test double: an in-memory event bus that also remembers everything published. */', 'export class RecordingEventBus extends InMemoryEventBus {', ' readonly published: DomainEvent[] = [];', '', ' override async publish(events: readonly DomainEvent[]): Promise<void> {', ' this.published.push(...events);', ' await super.publish(events);', ' }', '', ' /** Names of the published events, in order — handy in assertions. */', ' get names(): string[] {', ' return this.published.map((event) => event.eventName);', ' }', '}'));
|
|
39
|
+
add(s.testServer, (imp) => (0, code_1.lines)("import { once } from 'node:events';", "import type { AddressInfo } from 'node:net';", "import express, { type Express } from 'express';", `import { errorHandler, notFoundHandler } from ${imp(s.errorHandler)};`, '', '/** A fresh Express app with JSON parsing and the error handlers around your routes. */', 'export function createTestApp(mount: (app: Express) => void): Express {', ' const app = express();', ' app.use(express.json());', ' mount(app);', ' app.use(notFoundHandler);', ' app.use(errorHandler);', ' return app;', '}', '', '/** Starts `app` on a free port, runs `test` with its base URL, then stops the server. */', 'export async function withTestServer(', ' app: Express,', ' test: (baseUrl: string) => Promise<void>,', '): Promise<void> {', ' const server = app.listen(0);', " await once(server, 'listening');", ' const { port } = server.address() as AddressInfo;', ' try {', ' await test(`http://127.0.0.1:${port}`);', ' } finally {', ' server.closeAllConnections();', ' await new Promise<void>((resolve) => server.close(() => resolve()));', ' }', '}', '', 'export interface TestResponse {', ' status: number;', ' headers: Headers;', ' /** The parsed JSON body (any, so tests can read fields directly). */', ' body: any;', '}', '', '/** Sends a request (with an optional JSON body) and parses the JSON response. */', 'export async function call(', ' url: string,', ' init: { method?: string; body?: unknown } = {},', '): Promise<TestResponse> {', ' const hasBody = init.body !== undefined;', ' const response = await fetch(url, {', " method: init.method ?? 'GET',", " headers: hasBody ? { 'content-type': 'application/json' } : undefined,", ' body: hasBody ? JSON.stringify(init.body) : undefined,', ' });', ' const text = await response.text();', ' return { status: response.status, headers: response.headers, body: text ? JSON.parse(text) : undefined };', '}'));
|
|
40
|
+
// A test for the event bus itself: the glue between bounded contexts deserves one.
|
|
41
|
+
const busSpec = `${s.inMemoryEventBus}.spec`;
|
|
42
|
+
add(busSpec, (imp) => (0, code_1.lines)((0, code_1.testImports)(project.config.testRunner), `import { DomainEvent } from ${imp(s.domainEvent)};`, `import { InMemoryEventBus } from ${imp(s.inMemoryEventBus)};`, '', 'class ThingHappened extends DomainEvent {', ' readonly aggregateId: string;', '', ' constructor(aggregateId: string) {', ' super();', ' this.aggregateId = aggregateId;', ' }', '}', '', 'class SpecialThingHappened extends ThingHappened {}', '', 'class SomethingElseHappened extends DomainEvent {', " readonly aggregateId = 'other';", '}', '', "describe('InMemoryEventBus', () => {", " it('delivers an event to the handlers of its class, in order', async () => {", ' const bus = new InMemoryEventBus();', ' const received: string[] = [];', ' bus.subscribe(ThingHappened, (event) => {', ' received.push(`first:${event.aggregateId}`);', ' });', ' bus.subscribe(ThingHappened, (event) => {', ' received.push(`second:${event.aggregateId}`);', ' });', ' bus.subscribe(SomethingElseHappened, () => {', " received.push('wrong handler');", ' });', '', " await bus.publish([new ThingHappened('1')]);", '', " assert.deepEqual(received, ['first:1', 'second:1']);", ' });', '', " it('also delivers to the handlers of a parent class', async () => {", ' const bus = new InMemoryEventBus();', ' const received: string[] = [];', ' bus.subscribe(ThingHappened, (event) => {', ' received.push(event.eventName);', ' });', '', " await bus.publish([new SpecialThingHappened('1')]);", '', " assert.deepEqual(received, ['SpecialThingHappened']);", ' });', '', " it('keeps delivering when a handler fails, and reports the error', async () => {", ' const errors: unknown[] = [];', ' const bus = new InMemoryEventBus({ onError: (error) => errors.push(error) });', ' const received: string[] = [];', ' bus.subscribe(ThingHappened, () => {', " throw new Error('boom');", ' });', ' bus.subscribe(ThingHappened, () => {', " received.push('still delivered');", ' });', '', " await bus.publish([new ThingHappened('1')]);", '', " assert.deepEqual(received, ['still delivered']);", ' assert.equal(errors.length, 1);', ' });', '', " it('stops delivering after unsubscribe', async () => {", ' const bus = new InMemoryEventBus();', ' const received: string[] = [];', ' const unsubscribe = bus.subscribe(ThingHappened, (event) => {', ' received.push(event.aggregateId);', ' });', '', " await bus.publish([new ThingHappened('1')]);", ' unsubscribe();', " await bus.publish([new ThingHappened('2')]);", '', " assert.deepEqual(received, ['1']);", ' });', '});'));
|
|
43
|
+
return files;
|
|
44
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ddd-express",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Generate Domain-Driven Design modules for Express + TypeScript in one command: aggregates, value objects, domain events, repository ports and adapters, use cases, REST routes and tests.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"ddd",
|
|
7
|
+
"domain-driven-design",
|
|
8
|
+
"express",
|
|
9
|
+
"typescript",
|
|
10
|
+
"cli",
|
|
11
|
+
"generator",
|
|
12
|
+
"scaffold",
|
|
13
|
+
"boilerplate",
|
|
14
|
+
"aggregate",
|
|
15
|
+
"bounded-context",
|
|
16
|
+
"value-object",
|
|
17
|
+
"domain-events",
|
|
18
|
+
"hexagonal-architecture",
|
|
19
|
+
"ports-and-adapters",
|
|
20
|
+
"clean-architecture"
|
|
21
|
+
],
|
|
22
|
+
"homepage": "https://github.com/Moustafa1997/ddd-express#readme",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/Moustafa1997/ddd-express.git"
|
|
26
|
+
},
|
|
27
|
+
"bugs": {
|
|
28
|
+
"url": "https://github.com/Moustafa1997/ddd-express/issues"
|
|
29
|
+
},
|
|
30
|
+
"author": "Moustafa Aboulazm",
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"type": "commonjs",
|
|
33
|
+
"bin": {
|
|
34
|
+
"ddd-express": "dist/cli.js"
|
|
35
|
+
},
|
|
36
|
+
"main": "dist/index.js",
|
|
37
|
+
"types": "dist/index.d.ts",
|
|
38
|
+
"files": [
|
|
39
|
+
"dist",
|
|
40
|
+
"README.md",
|
|
41
|
+
"README.ar.md",
|
|
42
|
+
"LICENSE",
|
|
43
|
+
"CHANGELOG.md"
|
|
44
|
+
],
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
50
|
+
"typecheck": "tsc --noEmit",
|
|
51
|
+
"test": "node --import tsx --test \"test/**/*.test.ts\"",
|
|
52
|
+
"e2e": "bash scripts/e2e.sh",
|
|
53
|
+
"prepublishOnly": "npm run build && npm test"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@types/node": "^22.0.0",
|
|
57
|
+
"tsx": "^4.20.0",
|
|
58
|
+
"typescript": "^7.0.2"
|
|
59
|
+
}
|
|
60
|
+
}
|