From 2ab80637999b238f595bb63434499fc5fcd65fd3 Mon Sep 17 00:00:00 2001 From: Florian Vogt Date: Fri, 4 Dec 2026 15:33:25 +0100 Subject: [PATCH 1/2] docs: Adds a basic architecture documentation --- docs/Architecture.md | 606 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 606 insertions(+) create mode 100644 docs/Architecture.md diff --git a/docs/Architecture.md b/docs/Architecture.md new file mode 100644 index 00000000000..515d4c4ebe3 --- /dev/null +++ b/docs/Architecture.md @@ -0,0 +1,606 @@ +# UI5 CLI Architecture + +## 1. Summary + +UI5 CLI is an open, modular toolchain for developing OpenUI5 / SAPUI5 applications. It is a Node.js project written in JavaScript (ESM) that provides commands for building, serving, and managing OpenUI5 / SAPUI5 projects. The toolchain consists of six public packages that together cover the full development lifecycle: project graph resolution, build orchestration, file system abstraction, an Express-based development server, and structured logging. + +## 2. Project Status + +The project is actively maintained. The current major version is v5. Development follows conventional commits and semantic versioning. Issues are tracked via GitHub. Contributions are welcome and follow the project's contribution guidelines. + +## 3. Introduction + +The UI5 CLI exposes a `ui5` command-line interface (via yargs) that orchestrates the following concerns: + +- **Project graph construction**: Resolving npm dependency trees into a typed graph of OpenUI5 / SAPUI5 projects, libraries, and extensions. +- **Building**: Running a configurable pipeline of tasks and processors to produce deployable artifacts. +- **Serving**: Running an incremental build server with live reload for local development. +- **Framework management**: Adding, removing, and switching OpenUI5 / SAPUI5 framework versions in `ui5.yaml`. + +This document describes the architecture of UI5 CLI: its packages, the key design patterns within them, the interactions between them, and the rationale behind major technical decisions. + +## 4. Architecture Input + +### Goals + +The primary goal of UI5 CLI is to provide a reliable, extensible, and performant toolchain for UI5 application development. Key objectives include: + +- Abstracting the complexity of building and serving OpenUI5 / SAPUI5 projects behind a simple CLI interface. +- Supporting the full range of OpenUI5 / SAPUI5 project types (Application, Library, ThemeLibrary, Component, Module). +- Enabling extensibility through custom build tasks and server middlewares defined in `ui5.yaml`. +- Providing fast incremental builds and live reload for a productive development experience. + +### Requirements + +- **Modularity**: Each concern is encapsulated in its own npm package with clearly defined public APIs. +- **Extensibility**: Custom tasks and server middlewares can be developed independently and integrated via `ui5.yaml`. +- **Performance**: Builds use a cache to avoid redundant work; heavy processing (minification, theme building) runs in worker processes. +- **Correctness**: All project configuration is validated against JSON schemas using AJV before use. +- **Compatibility**: Supports the full range of UI5 specVersions from `0.1` through `5.0`. + +### Given / Existing Technology and Components + +The toolchain builds on well-established Node.js libraries: + +- **yargs** — CLI argument parsing and command dispatch. +- **Express** — HTTP server for `ui5 serve`. +- **globby / graceful-fs** — Filesystem access within `@ui5/fs`. +- **AJV** — JSON schema validation for `ui5.yaml` and `ui5-workspace.yaml`. +- **Terser** (via workerpool) — JavaScript minification in `@ui5/builder`. +- **less** (via workerpool) — LESS/CSS compilation in `@ui5/builder`. +- **@parcel/watcher** — File watching for incremental builds. +- **js-yaml** — YAML parsing and serialization. + +### Node.js Requirement + +`^22.20.0 || >=24.0.0`. All packages use ESM (`"type": "module"`). + +## 5. Architecture Overview + +The repository is an **npm workspaces monorepo** containing six public packages and four internal packages. + +``` +@ui5/cli CLI entry point (yargs). Commands in lib/cli/commands/ + ├── @ui5/project Project graph, config loading, dependency resolution (AJV schemas) + ├── @ui5/builder Build tasks & processors (JS bundling, minification, CSS, JSDoc) + ├── @ui5/server Express dev server with middleware architecture + ├── @ui5/fs Virtual file system with AbstractReader/AbstractReaderWriter + └── @ui5/logger Logging with configurable levels and progress bars +``` + +Internal packages (never published): + +| Package | Purpose | +|---------|---------| +| `internal/benchmark` | CLI performance benchmarking | +| `internal/documentation` | VitePress docs, JSDoc, and JSON schema generation | +| `internal/e2e-tests` | End-to-end tests for packaged CLI workflows | +| `internal/shrinkwrap-extractor` | Shrinkwrap extraction utility | + +Internal packages must declare all dependencies as `devDependencies`. A CI check enforces this to prevent Dependabot from producing misleading `deps`-type commit subjects for internal tooling updates. + +### Package Dependency Graph + +``` +@ui5/logger (no internal dependencies) + ↑ +@ui5/fs → @ui5/logger + ↑ +@ui5/project → @ui5/fs, @ui5/logger +@ui5/builder → @ui5/fs, @ui5/logger +@ui5/server → @ui5/builder, @ui5/fs, @ui5/logger + ↑ +@ui5/cli → @ui5/project, @ui5/builder, @ui5/server, @ui5/fs, @ui5/logger +``` + +`@ui5/logger` is the leaf. `@ui5/cli` depends on all other packages. + +--- + +### `@ui5/logger` + +The logging foundation used by all other packages. + +**Entry point**: `packages/logger/lib/index.js` + +**Public API**: +- `getLogger(moduleName)` — returns a `Logger` instance scoped to the given module name. +- `setLogLevel(level)`, `getLogLevel()`, `isLogLevelEnabled(level)` — control the global log level. + +**Log levels** (ascending priority): `silly`, `verbose`, `perf`, `info`, `warn`, `error`, `silent`. The default level is `info`, configurable via the `UI5_LOG_LVL` environment variable. + +**Event-based architecture**: `Logger` emits events on the Node.js `process` object (`ui5.log`). Writers attach to these events via `enable()`/`disable()`. If no writer is attached, messages fall back to `process.stderr`. All logging therefore flows through Node.js's built-in `EventEmitter` without any direct I/O coupling in the logger itself. + +**Specialized loggers** (private, used internally): +- `Build` — emits `ui5.build-metadata` and `ui5.build-status` events for overall build progress. +- `ProjectBuild` — emits `ui5.project-build-metadata` and `ui5.project-build-status` for per-project task progress. +- `Serve` — emits `ui5.server-listening` on server start. + +**Writers**: + +| Writer | Description | +|--------|-------------| +| `Console` | Standard writer; outputs to `process.stderr`; renders a `cli-progress` progress bar in interactive TTY mode (suppressed in verbose mode). Filterable by module name via `UI5_LOG_MODULES`. | +| `InteractiveConsole` | Full TUI writer using `log-update`; renders a live-updating build/server status panel with per-project statuses, build steps, and remote connection warnings. | + +--- + +### `@ui5/fs` + +A virtual filesystem abstraction layer that decouples all other packages from real filesystem I/O. Build tasks read and write `Resource` objects through typed reader/writer interfaces; the underlying storage (real FS, memory, or a composition of both) is transparent to the caller. + +**Entry point**: `packages/fs/lib/resourceFactory.js` (factory functions), individual class exports. + +**Core abstraction**: + +``` +AbstractReader (byGlob, byPath) + └── AbstractReaderWriter (+ write) + ├── DuplexCollection — combines a reader and a writer; reads from both (writer takes priority) + ├── WriterCollection — fans writes out to multiple writers + └── adapters/AbstractAdapter + ├── adapters/FileSystem — real FS access via globby + graceful-fs + └── adapters/Memory — in-memory Map +ReaderCollection — unordered union of multiple readers +ReaderCollectionPrioritized — ordered union; first match wins +MonitoredReader — records all read paths/patterns (used for cache validation) +MonitoredReaderWriter — monitored read + write +readers/Filter — predicate-based filtering +readers/Link — virtual path prefix rewriting +readers/Proxy — callback-based virtual resource generation +``` + +**`Resource`** (`packages/fs/lib/Resource.js`): Represents a single file. Holds virtual path, content (buffer, stream, or factory function), stat info, a content integrity hash, project reference, and source metadata. Content access is guarded by an async mutex to prevent concurrent reads during transformation. + +**`ResourceFacade`**: A thin wrapper around a `Resource` that remaps its virtual path. Used by the `Link` reader. + +**`stepWriteBuffer`** (`packages/fs/lib/internal/stepWriteBuffer.js`): Buffers writes within a build step so that partial results are not visible to concurrent readers until the step completes. + +**`ResourceTagCollection`**: Tracks named build tags on resources. Standard tags (defined by `TaskUtil`): + +| Tag | Meaning | +|-----|---------| +| `OmitFromBuildResult` | Resource is excluded from the final output | +| `IsDebugVariant` | Resource is an unminified debug variant | +| `HasDebugVariant` | A minified resource that has a corresponding debug variant | +| `IsBundle` | Resource is a generated bundle file | + +`MonitoredResourceTagCollection` additionally records all tag operations for use in build cache validation. + +**`resourceFactory`** provides convenience factory functions: +- `createAdapter` → FileSystem or Memory adapter +- `createReader` → FileSystem adapter in a ReaderCollection +- `createReaderCollection`, `createReaderCollectionPrioritized` +- `createWorkspace` → DuplexCollection (FileSystem reader + Memory writer) +- `createFilterReader`, `createLinkReader`, `createMonitor`, `createProxy` + +--- + +### `@ui5/project` + +Responsible for constructing and managing the **project graph**: resolving npm dependencies into a typed graph of OpenUI5 / SAPUI5 projects and extensions, loading and validating `ui5.yaml`, and orchestrating multi-project builds. + +**Entry point**: `packages/project/lib/graph/graph.js` + +```js +graphFromPackageDependencies({cwd, rootConfigPath, versionOverride, workspaceConfigPath, ...}) +graphFromStaticFile({filePath, versionOverride, ...}) +``` + +#### Project Graph Construction + +The graph is built by `projectGraphBuilder.js` using a `NodeProvider` interface: + +| Provider | Source | +|----------|--------| +| `NodePackageDependencies` | npm `package.json` + `ui5.yaml` | +| `DependencyTree` | Static in-memory dependency tree object | + +Each npm package becomes a **`Module`** that: +1. Reads and parses `ui5.yaml` (supports multi-document YAML for multiple specs in one file). +2. Validates the config using AJV against the JSON schemas in `packages/project/lib/validation/schema/`. +3. Creates **`Specification`** instances via `Specification.create()`. + +**`ProjectGraph`** (`packages/project/lib/graph/ProjectGraph.js`): A rooted directed dependency graph. Nodes are `Specification` instances (projects or extensions); edges are declared dependencies. After `seal()`, the graph resolves framework info (OpenUI5/SAPUI5 version and library list). + +#### Specification Hierarchy + +``` +Specification (abstract — specVersion, type, id, version, modulePath) + ├── Project (abstract — resource management, namespace, framework detection) + │ ├── ComponentProject (abstract — webapp/ path, component config) + │ │ ├── types/Application (webapp/, namespace from manifest.json, cachebuster) + │ │ └── types/Component (webapp/, namespace) + │ ├── types/Library (src/ + test/, namespace, .library file) + │ ├── types/ThemeLibrary (src/, no namespace) + │ └── types/Module (multiple source paths, no namespace) + └── Extension (abstract) + ├── extensions/Task (custom build task) + ├── extensions/ServerMiddleware (custom server middleware) + └── extensions/ProjectShim (dependency/config shim for legacy packages) +``` + +**`SpecificationVersion`**: Supported versions: `0.1`, `1.0`, `1.1`, `2.0`–`2.6`, `3.0`–`3.2`, `4.0`, `5.0`. Provides comparison helpers (`gte`, `lte`, `eq`, `major`, `minor`). + +#### JSON Schema Validation + +All `ui5.yaml` content is validated against AJV JSON schemas: + +| Schema | Purpose | +|--------|---------| +| `ui5.json` | Top-level `ui5.yaml` envelope | +| `ui5-workspace.json` | `ui5-workspace.yaml` | +| `specVersion/kind/project.json` | Base project fields | +| `specVersion/kind/project/application.json` | Application-specific fields | +| `specVersion/kind/project/library.json` | Library-specific fields | +| `specVersion/kind/project/component.json` | Component-specific fields | +| `specVersion/kind/project/module.json` | Module-specific fields | +| `specVersion/kind/project/theme-library.json` | ThemeLibrary-specific fields | +| `specVersion/kind/extension.json` | Base extension fields | +| `specVersion/kind/extension/task.json` | Custom task extension | +| `specVersion/kind/extension/server-middleware.json` | Custom middleware extension | +| `specVersion/kind/extension/project-shim.json` | Project shim extension | + +#### Framework Resolution + +The `ui5Framework/` module resolves and installs OpenUI5 / SAPUI5 framework libraries. Resolvers extend `AbstractResolver`: + +| Resolver | Source | +|----------|--------| +| `Openui5Resolver` | npm `@openui5/*` packages | +| `Sapui5Resolver` | npm `@sapui5/*` packages | +| `Sapui5MavenSnapshotResolver` | Maven SNAPSHOT builds (configurable endpoint) | + +Libraries install to `~/.ui5/framework/` by default (`UI5_DATA_DIR` overrides the base directory). The endpoint for Maven snapshots is configurable via `~/.ui5rc` (`mavenSnapshotEndpointUrl`). + +#### Build Orchestration + +`@ui5/project` owns the build orchestration layer; `@ui5/builder` provides the actual task and processor implementations. + +| Class | Responsibility | +|-------|---------------| +| `ProjectBuilder` | Iterates the project graph; creates contexts; invokes `TaskRunner` per project | +| `BuildContext` | Holds graph-wide build settings (selfContained, jsdoc, outputStyle, cache mode) | +| `ProjectBuildContext` | Per-project context: source readers, output writers, tag collections | +| `TaskDefinitions` | Loads the per-project-type build definition; merges standard + custom tasks | +| `TaskRunner` | Executes tasks in order; integrates with the build cache | +| `StepRunner` | Runs steps within a task; supports scalar steps and map steps | +| `TaskUtil` | Per-task API: resource tagging, reader/writer access, project type queries | + +**Task types**: +- **Task-based** (legacy): a task module exports an async `task` function. Executed as a single unit. +- **Step-based** (current): a task module exports a `steps` array. Each step is either: + - A **scalar step** `{name, run}` — single invocation for the whole resource set. + - A **map step** `{name, keys, each}` — one invocation per resource key; enables per-resource cache granularity. + +**Build cache** (`packages/project/lib/build/cache/`): + +| Class | Role | +|-------|------| +| `ProjectBuildCache` | Per-project cache; stores build outputs keyed by content hash | +| `CacheManager` | Manages cache directory; enforces cache modes | +| `BuildStageCache` | Per-stage cache within a project build | +| `Cache` (enum) | Cache modes: `Default`, `Force`, `ReadOnly`, `Off` | + +The cache stores processed resources and tag metadata. `MonitoredReader` and `MonitoredResourceTagCollection` capture all reads and tag operations during a build step, producing a deterministic cache key. + +**Incremental build** (`BuildServer`): Used during `ui5 serve`. Watches source files via `@parcel/watcher`; on change, debounces and schedules a rebuild; serves resources on demand via `BuildReader`. + +#### Workspace Support + +`Workspace` (`packages/project/lib/graph/Workspace.js`) loads `ui5-workspace.yaml` and allows overriding dependency resolution paths locally, enabling workspace-based development where local checkouts of libraries replace their npm-installed counterparts. + +--- + +### `@ui5/builder` + +Provides the library of built-in build **tasks** and **processors**. Tasks are the high-level build steps; processors are stateless transformation functions called by tasks. + +**Entry point**: `packages/builder/lib/tasks/taskRepository.js` (task registry), individual task/processor modules. + +#### Task Registry + +`taskRepository.js` maps task names to lazy-loaded modules. The registry is consumed by `@ui5/project`'s `TaskDefinitions` to look up tasks by name. + +**Built-in tasks**: + +| Task | Purpose | +|------|---------| +| `replaceCopyright` | Inserts copyright banners | +| `replaceVersion` | Replaces version placeholders | +| `replaceBuildtime` | Replaces build-timestamp placeholders | +| `enhanceManifest` | Enhances `manifest.json` with computed values | +| `escapeNonAsciiCharacters` | Escapes non-ASCII chars in `.properties` files | +| `minify` | Minifies JS files and generates `.dbg.js` debug variants | +| `buildThemes` | Compiles LESS to CSS theme files | +| `transformBootstrapHtml` | Transforms `index.html` bootstrap for standalone apps | +| `generateLibraryManifest` | Generates `manifest.json` for libraries | +| `generateVersionInfo` | Generates `sap-ui-version.json` | +| `generateFlexChangesBundle` | Bundles flexibility changes | +| `generateComponentPreload` | Generates `Component-preload.js` | +| `generateStandaloneAppBundle` | Generates standalone app bundle | +| `generateBundle` | Generates custom resource bundles | +| `generateLibraryPreload` | Generates `library-preload.js` | +| `generateResourcesJson` | Generates `resources.json` manifest | +| `generateThemeDesignerResources` | Generates resources for SAP Theme Designer | +| `generateCachebusterInfo` | Generates cache buster info file | +| `generateJsdoc` | Generates JSDoc documentation | +| `executeJsdocSdkTransformation` | Transforms JSDoc output for SDK format | +| `generateApiIndex` | Generates API index for SDK documentation | + +#### Processors + +Processors are low-level, stateless transformation functions called directly by tasks (no registry). Key processors: + +| Processor | Description | +|-----------|-------------| +| `minifier.js` | JS minification via workerpool (Terser workers) | +| `themeBuilder.js` | LESS/CSS compilation via workerpool | +| `manifestCreator.js` | Creates `manifest.json` for libraries | +| `manifestEnhancer.js` | Enhances existing `manifest.json` | +| `bundlers/moduleBundler.js` | Module-based resource bundling | +| `bundlers/flexChangesBundler.js` | Flexibility changes bundling | +| `resourceListCreator.js` | Resource list / `resources.json` generation | +| `versionInfoGenerator.js` | `sap-ui-version.json` generation | +| `stringReplacer.js` | Copyright/version/buildtime placeholder replacement | +| `nonAsciiEscaper.js` | Non-ASCII character escaping | +| `bootstrapHtmlTransformer.js` | Bootstrap HTML transformation | +| `jsdoc/jsdocGenerator.js` | JSDoc generation | +| `jsdoc/sdkTransformer.js` | JSDoc SDK format transformation | +| `jsdoc/apiIndexGenerator.js` | API index generation | +| `libraryLessGenerator.js` | LESS source generation for libraries | + +CPU-intensive processors (minification, theme building) run in worker threads via `workerpool` to avoid blocking the main event loop. + +#### LBT — Library Build Tooling + +`packages/builder/lib/lbt/` contains a low-level module analysis and bundling engine: + +| Component | Purpose | +|-----------|---------| +| `analyzer/JSModuleAnalyzer.js` | Analyzes `sap.ui.define`/AMD dependencies in JS modules | +| `analyzer/ComponentAnalyzer.js` | Analyzes `Component.js` for included modules | +| `analyzer/XMLTemplateAnalyzer.js` | Analyzes XML view/fragment dependencies | +| `bundle/Builder.js` | Constructs bundle content from module graph | +| `bundle/Resolver.js` | Resolves bundle section module lists | +| `bundle/AutoSplitter.js` | Auto-splits modules into bundles | +| `bundle/BundleWriter.js` | Serializes bundle to `Resource` | +| `resources/ResourcePool.js` | Pool of LBT resources available for bundling | +| `resources/ResourceCollector.js` | Collects resources from `@ui5/fs` into LBT pool | +| `graph/dependencyGraph.js` | Module dependency graph | +| `graph/topologicalSort.js` | Topological ordering for bundle resolution | + +--- + +### `@ui5/server` + +An Express-based development server that serves OpenUI5 / SAPUI5 project resources, integrates with the incremental `BuildServer`, and provides live reload. + +**Entry point**: `packages/server/lib/server.js` — exports a `serve()` function. + +**Serving flow**: + +``` +serve() + └── Supervisor + └── buildApp() [stack.js] + └── buildRouter() + └── MiddlewareManager.applyMiddleware(expressApp) +``` + +`serveMiddleware.js` additionally exports the router as an Express middleware for embedding inside another application. + +#### Middleware Pipeline + +`MiddlewareManager` assembles and mounts the middleware pipeline in a fixed default order. Custom middlewares from `ui5.yaml` extensions are inserted at declared positions (before/after a named standard middleware): + +| Position | Middleware | Purpose | +|----------|-----------|---------| +| 1 | `compression` | gzip response compression | +| 2 | `cors` | CORS response headers | +| 3 | `csp` | Content Security Policy headers | +| 4 | `liveReloadClient` | Injects live reload WebSocket client script | +| 5 | `serveBuildError` | Renders build error page when build is failing | +| 6 | `serveResources` | Main resource handler: serves project files | +| 7 | `serveIndex` | Directory listing for unmatched requests | +| 8 | `discovery` | Resource discovery endpoint (`.ui5/api/...`) | +| 9 | `versionInfo` | Serves generated `sap-ui-version.json` | +| 10 | `nonReadRequests` | Rejects non-GET/HEAD requests with 404 | + +**`MiddlewareUtil`** provides a helper API to middleware implementations: +- MIME type resolution +- Virtual path → project namespace mapping +- Access to the project graph and build artifacts + +#### Live Reload + +**`Supervisor`** manages live reload and stack reinitializations: +- Coordinates between `BuildServer` (source change events) and the live reload WebSocket server. +- On `sourcesChanged`, triggers a live reload signal to all connected browser clients. +- On unrecoverable build failure, reinitializes the middleware stack to surface the error page. + +--- + +### `@ui5/cli` + +The CLI entry point. Dynamically loads command modules and dispatches to them via yargs. + +**Entry point**: `packages/cli/bin/ui5.cjs` (CJS wrapper for Node.js compatibility) → `packages/cli/bin/ui5.js` (ESM) → `packages/cli/lib/cli/cli.js`. + +**Commands**: + +| Command | File | Description | +|---------|------|-------------| +| `ui5 build` | `commands/build.js` | Build the OpenUI5 / SAPUI5 project (subcommands: `jsdoc`, `preload`, `self-contained`) | +| `ui5 serve` | `commands/serve.js` | Start the development server | +| `ui5 add ` | `commands/add.js` | Add framework library dependencies to `ui5.yaml` | +| `ui5 remove ` | `commands/remove.js` | Remove framework library dependencies | +| `ui5 use ` | `commands/use.js` | Set framework name and/or version in `ui5.yaml` | +| `ui5 init` | `commands/init.js` | Scaffold a `ui5.yaml` for the current project | +| `ui5 tree` | `commands/tree.js` | Print the resolved dependency tree | +| `ui5 versions` | `commands/versions.js` | Show versions of all UI5 CLI packages | +| `ui5 config get/set` | `commands/config.js` | Read/write `~/.ui5rc` configuration | +| `ui5 cache clean` | `commands/cache.js` | Clean the build cache | +| `ui5 certificate add/remove` | `commands/certificate.js` | Manage local HTTPS certificates for `ui5 serve` | + +**Yargs middlewares** (applied globally): +- `lib/cli/middlewares/base.js` — sets up log level and verbosity options. +- `lib/cli/middlewares/logger.js` — initializes the appropriate logger writer. + +**Common option groups** (`lib/cli/options.js`): +- `applyProjectConfigOptions`: `--config`, `--dependency-definition` +- `applyWorkspaceOptions`: `--workspace`, `--workspace-config` +- `applyBuildOptions`: build-specific options shared by `build` and `serve` + +**Framework operations** (`lib/framework/`): +Higher-level logic for `add`, `remove`, and `use` commands. `updateYaml.js` handles position-aware YAML manipulation, preserving comments and formatting. + +**Data directory** (`lib/dataDir.js`): Resolves the UI5 data directory path (`~/.ui5/` or `UI5_DATA_DIR` override). Used for framework library installation and build caches. + +--- + +## 6. Build Pipeline + +A complete `ui5 build` execution follows these steps: + +1. **CLI dispatch**: `commands/build.js` parses arguments; calls `graphFromPackageDependencies()`. +2. **Graph construction**: `NodePackageDependencies` provider walks npm `package.json` trees; each package becomes a `Module`. +3. **Config loading and validation**: Each `Module` reads and AJV-validates `ui5.yaml`; `Specification` instances are created. +4. **Framework resolution**: Framework libraries (OpenUI5/SAPUI5) are resolved from npm or Maven and added to the graph. +5. **Graph sealing**: `ProjectGraph.seal()` finalizes the graph, resolving framework version info. +6. **Build orchestration**: `ProjectBuilder.build()` iterates the sealed graph. +7. **Per-project context**: `BuildContext`, `ProjectBuildContext`, `TaskUtil`, and `TaskDefinitions` are created for each project. +8. **Task list composition**: `TaskDefinitions` loads the per-project-type task list (e.g., `application.js`); standard tasks are merged with any custom tasks from `ui5.yaml`; include/exclude filters and enabled flags are applied. +9. **Task execution**: `TaskRunner` runs each enabled task in order: + - For step-based tasks: `StepRunner` checks the build cache for each step key; runs only uncached steps. + - For task-based tasks: the task function runs directly. + - Tasks read resources via `@ui5/fs` readers and write transformed results to a `DuplexCollection`. +10. **Output**: Build results are written from the in-memory `DuplexCollection` to the output directory (default: `dist/`). + +--- + +## 7. Architecture Decisions + +### Technology Decisions + +- **JavaScript (ESM) over TypeScript**: The project uses JavaScript with JSDoc type annotations. This choice predates TypeScript adoption in the UI5 tooling organization; migration would be a large undertaking. New packages in the UI5 ecosystem (e.g., `@ui5/linter`, the MCP server) use TypeScript. +- **npm workspaces monorepo**: Keeping all packages in one repository simplifies cross-package development, testing, and versioning while keeping packages independently publishable. +- **AJV for schema validation**: JSON Schema with AJV provides declarative, versioned validation for `ui5.yaml`. The `loadSchema` callback enables lazy loading of referenced sub-schemas, keeping memory use proportional to what's actually validated. +- **workerpool for CPU-intensive tasks**: Minification (Terser) and theme building (LESS) are offloaded to worker threads to keep the main event loop responsive during large builds. +- **Event-based logging**: Decoupling `Logger` from writers via Node.js `process` events allows multiple writers (e.g., plain console + interactive TUI) without modifying the logging callsites. +- **Virtual FS abstraction**: The `@ui5/fs` layer ensures that build tasks never reference the real filesystem directly, making them fully testable with in-memory adapters and enabling future storage backends. + +### Extensibility Design + +Custom build tasks and server middlewares are first-class citizens defined as `Extension` entries in `ui5.yaml`. They are loaded at runtime from the project's npm dependencies. This design decision (documented in RFCs `0004` and `0005`) allows the community to publish reusable task/middleware packages. + +### Build Cache Design + +The step-based task format (RFC implied by `StepRunner`/`TaskRunner` implementation) was introduced to enable per-step, per-resource cache granularity. Map steps allow a changed resource to invalidate only its own cache entry rather than the entire task output. The cache key incorporates content hashes of all read resources and all tag operations recorded by the monitored readers/collections. + +## 8. Logging + +All packages use `@ui5/logger`. Log level is controlled globally via `UI5_LOG_LVL` (default: `info`). Module-specific filtering is available via `UI5_LOG_MODULES`. + +The logger emits on `process` and writes to `process.stderr`, keeping `stdout` clean for structured output (e.g., `ui5 tree`). + +The `InteractiveConsole` writer renders a live-updating TUI panel during builds and serve sessions, providing real-time progress without scrolling log noise. + +## 9. Configuration + +User-level configuration is stored in `~/.ui5rc` (or `$UI5_DATA_DIR/.ui5rc`) and managed by `packages/project/lib/config/Configuration.js`. Configurable options: + +| Option | Purpose | +|--------|---------| +| `mavenSnapshotEndpointUrl` | Custom Maven endpoint for SAPUI5 snapshot resolution | +| `ui5DataDir` | Override for the `~/.ui5/` data directory | + +The `UI5_DATA_DIR` environment variable overrides `ui5DataDir` at runtime. + +## 10. Cache Management + +The build cache stores processed resources under `~/.ui5/build-cache/` (within the UI5 data directory). Cache entries are keyed by a deterministic hash derived from: +- Input resource content hashes +- Task and processor configuration +- Resource tag operations + +Cache modes (`Cache` enum): +- **Default**: Use cache when available; write new entries. +- **Force**: Fail if no cached result is available (for CI validation). +- **ReadOnly**: Use cache but do not write new entries. +- **Off**: Disable caching entirely. + +The cache directory can be cleared with `ui5 cache clean`. + +## 11. Security + +### Input + +To be filled + +### Threat Model + +To be filled + +#### Summary + +The UI5 CLI acts as a privileged process on a developer's local machine. It has the authority to read from and write to the filesystem, execute system commands, and make network requests. + +To be filled + +### Overview & Trust Boundaries + +* **Core Asset:** The developer's local machine, including source code, configuration files, credentials, and system integrity. +* **Privileged Component:** To be filled +* **Untrusted Input Source:** To be filled +* **Trust Boundary:** To be filled + +### What UI5 CLI Trusts +To be filled + +### What UI5 CLI DOES NOT Trust +To be filled + +### Security Measures +To be filled + + +## 12. Building and Testing + +### Test Framework + +**AVA** with `esmock` for ESM module mocking and `sinon` for stubs/spies. + +- Tests live in `packages/*/test/lib/**/*.js`. +- Helpers (excluded from test runs): `test/**/__helper__/**`. +- Fixtures: `test/fixtures/`; expected outputs: `test/expected/`. +- Temp files: `test/tmp/` (cleaned before each run via `rimraf`). +- Coverage: NYC (Istanbul) with thresholds of 70–90% depending on package. + +### Key Commands + +```bash +npm ci --engine-strict # Install dependencies +npm test # Lint + coverage + license checks + knip +npm run lint # ESLint across all workspaces +npm run unit # AVA tests across all workspaces +npm run coverage # NYC coverage across all workspaces +npm run unit --workspace=@ui5/builder # Single package +npx ava test/lib/some/test.js # Single test file (from package dir) +``` + +### Code Style + +ESLint flat config with Google style base, JSDoc plugin, and AVA plugin. Enforces: tabs, double quotes, 120-character line length, semicolons, no `console.log()` (use `@ui5/logger`). + +## 13. Distribution + +All six public packages are published to the official npm registry. Releases follow semantic versioning enforced by conventional commits (commitlint + husky). The `ui5` binary is exposed via the `@ui5/cli` package's `bin` field and is typically installed globally (`npm install -g @ui5/cli`) or used via `npx`. + +## 14. Technical Debts + +- **JavaScript vs TypeScript**: All public packages use JavaScript with JSDoc annotations. TypeScript would improve type safety and IDE support, particularly for the complex class hierarchies in `@ui5/project` and `@ui5/fs`. Migration is tracked but has not been prioritized. +- **Task-based vs step-based tasks**: Several built-in tasks still use the older `task` function format rather than the `steps` array format. These do not benefit from per-step cache granularity and cannot participate in incremental rebuilds at step level. +- **LBT isolation**: The Library Build Tooling (`packages/builder/lib/lbt/`) contains substantial legacy code for module analysis and bundling that predates the current architecture. It is not exposed as a separate package and has limited test coverage relative to its complexity. +- **Build logger coupling**: The specialized loggers (`Build`, `ProjectBuild`, `Serve`) are private to `@ui5/logger` but expose event names that callers depend on. The event contract is not formally versioned. +- **Workspace support completeness**: The `ui5-workspace.yaml` feature for local dependency overrides is functional but its interaction with the build cache and framework resolution has edge cases that are not fully documented. From 3e64bccd4893856c56943e99235d27eefa644c08 Mon Sep 17 00:00:00 2001 From: Florian Vogt Date: Fri, 4 Dec 2026 16:10:07 +0100 Subject: [PATCH 2/2] docs: Enhance security section --- docs/Architecture.md | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/docs/Architecture.md b/docs/Architecture.md index 515d4c4ebe3..6922038cfe6 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -536,33 +536,54 @@ The cache directory can be cleared with `ui5 cache clean`. ### Input -To be filled +The CLI receives input from three sources: command-line arguments, project configuration files (`ui5.yaml`, `ui5-workspace.yaml`, `manifest.json`, `package.json`), and resources downloaded from remote registries and CDNs. + +- **Command-line arguments** are parsed and validated by yargs. Unknown options are rejected. +- **Project configuration** is validated against JSON schemas using AJV before any value is used. Configuration that fails validation causes the command to abort with a `ValidationError`. +- **Paths** derived from configuration are resolved relative to the project root. ### Threat Model -To be filled +Unlike a network-exposed service, the UI5 CLI is invoked directly by a developer on their own machine and operates on a project the developer has deliberately chosen. Its inputs are therefore largely under the developer's own control, which substantially narrows the attack surface. The threat model focuses on the two areas where the CLI processes code or data it did not author: third-party dependencies and the local development server. #### Summary The UI5 CLI acts as a privileged process on a developer's local machine. It has the authority to read from and write to the filesystem, execute system commands, and make network requests. -To be filled +The most significant risk is the **supply chain**. A UI5 project's npm dependencies — including custom build tasks and server middleware extensions declared in `ui5.yaml` — execute arbitrary code with the developer's privileges during `ui5 build` and `ui5 serve`. The CLI also downloads framework libraries from npm or Maven endpoints and resources from UI5 CDNs. The `ui5 serve` development server additionally exposes project resources over HTTP on the local machine. The primary threat actor is an attacker who can influence one of these inputs — a compromised or malicious dependency, a tampered remote artifact, or an untrusted client reaching the development server. ### Overview & Trust Boundaries * **Core Asset:** The developer's local machine, including source code, configuration files, credentials, and system integrity. -* **Privileged Component:** To be filled -* **Untrusted Input Source:** To be filled -* **Trust Boundary:** To be filled +* **Privileged Component:** The UI5 CLI (a Node.js process), running with the full permissions of the developer who invoked it. +* **Untrusted Input Source:** Third-party npm dependencies (including custom task and middleware extensions), framework artifacts fetched from remote registries, Maven endpoints, and CDNs, and — for the development server — HTTP clients that can reach it. +* **Trust Boundary:** The interface between the CLI process and any code or data it loads from outside the developer's own project: dependencies resolved from npm, artifacts downloaded from remote sources, and incoming requests to the `ui5 serve` server. ### What UI5 CLI Trusts -To be filled + +The CLI assumes the following components are secure and behave as expected: + +* Its developers and maintainers. +* **Its own codebase:** The published JavaScript code is considered trusted. +* **The local execution environment:** The Node.js runtime, the operating system, and the shell that launched the process. +* **The developer:** The user invoking the CLI and the arguments they pass are trusted. The CLI acts on the developer's behalf with their privileges. +* **The UI5 project it is pointed at:** `ui5.yaml`, source code, `manifest.json`, and `package.json` of the project under development are treated as valid (once schema-validated) and non-malicious. +* **Custom tasks and server middleware:** Extensions declared in a project's `ui5.yaml` execute arbitrary code by design. They are trusted to the same degree as the project's other npm dependencies — that is, the responsibility for vetting them lies with the developer, as it does for any installed package. +* **Its vetted direct dependencies:** Well-known libraries such as yargs, Express, AJV, and the workerpool-based processors are implicitly trusted. ### What UI5 CLI DOES NOT Trust -To be filled + +* **Malformed configuration:** `ui5.yaml` and `ui5-workspace.yaml` are not trusted until validated against their JSON schemas. Invalid configuration is rejected before use. +* **The integrity of remote transport:** Framework libraries and resources downloaded from npm, Maven, or CDNs are not assumed to arrive intact. Downloads use HTTPS, and npm-resolved packages are subject to npm's integrity verification. +* **Arbitrary HTTP clients on the development server:** The `ui5 serve` server performs no authentication and is intended for local development only. It binds to localhost by default; remote connections are surfaced as explicit warnings and the server should never be exposed to an untrusted network. ### Security Measures -To be filled + +* **Input Validation:** All project configuration is validated against JSON schemas via AJV before use; command-line arguments are validated by yargs. +* **Path Handling:** Configuration-derived paths are resolved relative to the project root, and resource access flows through the `@ui5/fs` virtual filesystem rather than ad-hoc filesystem calls. +* **Transport Security:** Remote downloads use HTTPS; packages resolved through npm benefit from npm's package integrity checks. +* **Development Server Hardening:** The server binds to localhost by default, ships a Content Security Policy middleware (`csp`), warns on remote connections, and supports HTTPS via certificates managed with `ui5 certificate`. +* **Process Isolation:** CPU-intensive processing (minification, theme building) runs in worker processes via workerpool, limiting the blast radius of a crash or resource exhaustion in those stages. ## 12. Building and Testing