Compare commits

..
Author SHA1 Message Date
github-actions 19b5d082d5 chore: publish
- appium@4.0.2
 - @appium/archward@1.1.0
 - @appium/base-driver@11.0.2
 - @appium/base-plugin@4.0.2
 - @appium/docutils@4.0.2
 - @appium/driver-test-support@4.0.2
 - @appium/execute-driver-plugin@9.0.1
 - @appium/fake-driver@7.0.2
 - @appium/fake-plugin@5.0.2
 - @appium/http-server@1.0.2
 - @appium/images-plugin@6.0.2
 - @appium/opencv@6.0.1
 - @appium/plugin-test-support@4.0.2
 - @appium/relaxed-caps-plugin@4.0.1
 - @appium/storage-plugin@3.0.2
 - @appium/support@8.0.2
 - @appium/types@3.0.0
 - @appium/universal-xml-plugin@4.0.2
2026-11-27 07:31:35 +00:00
Mykola Mokhnach 67f151f6f3 feat(archward): add package that checks a package against its C4 model (#23225) 2026-11-27 08:27:34 +01:00
Chirag Panchal d3dc4bd9c8 docs: fix dead links to moved base-driver source files (#23229)
basedriver/helpers.ts was split into basedriver/helpers/ (configureApp is in app-cache.ts) and protocol/bidi-commands.ts became the protocol/bidi-commands/ directory.
2026-11-26 21:51:35 +02:00
feca1714c9 docs(appium): Update documentation translations (#23227)
* docs(appium): Update documentation translations

* docs: update authors (ja)

* docs: update authors (zh)

---------

Co-authored-by: mykola-mokhnach <7767781+mykola-mokhnach@users.noreply.github.com>
Co-authored-by: Edgars Eglītis <37242620+eglitise@users.noreply.github.com>
2026-11-26 12:55:22 +02:00
renovate[bot] a2caed50f6 chore(universal-xml-plugin): update dependency xpath to v0.1.0 (#23228)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-26 12:53:48 +02:00
Lê Văn Xuân Hoàn df431dd271 feat(types)!: check method map payload params against command signatures (#23158)
BREAKING CHANGE: MethodMap, DriverMethodMap, PluginMethodMap, DriverMethodDef, and PluginMethodDef now validate command names and payloadParams against driver and plugin command signatures by default. Pass MethodMap<T, false> or DriverMethodDef<T, true> / PluginMethodDef<T, true> for proxied or handle()-dispatched routes.
2026-11-25 21:10:03 +01:00
renovate[bot] c553d48b21 chore(docutils): update dependency mkdocs-git-revision-date-localized-plugin to v1.7.1 (#23226)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-25 11:09:48 +00:00
Edgars Eglītis 3f09891f6a docs: add Appium 4 blogpost (#23224) 2026-11-25 13:00:28 +02:00
Erin Krasniqi a68b15fdae fix(appium): clean up sessions when a createSession plugin fails (#23217) 2026-11-25 11:00:06 +01:00
renovate[bot] 6db045b5e7 chore(deps): update dependency npm-run-all2 to v9.1.0 (#23222)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-24 21:32:40 +01:00
github-actions[bot]andmykola-mokhnach c3f1b23d22 docs(appium): Update documentation translations (#23219)
Co-authored-by: mykola-mokhnach <7767781+mykola-mokhnach@users.noreply.github.com>
2026-11-24 15:00:54 +02:00
renovate[bot] 7d1472051a chore(deps): update dependency lerna to v10.1.3 (#23218)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-24 01:39:45 +00:00
96 changed files with 6053 additions and 387 deletions
+1999 -155
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -102,8 +102,8 @@
"conventional-changelog-conventionalcommits": "9.3.1",
"cross-env": "10.1.0",
"json-schema-to-typescript": "16.0.0",
"lerna": "10.1.2",
"npm-run-all2": "9.0.4",
"lerna": "10.1.3",
"npm-run-all2": "9.1.0",
"sinon": "22.1.0",
"teen_process": "5.0.1",
"tsd": "0.33.0",
+7
View File
@@ -3,6 +3,13 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.0.2](https://github.com/appium/appium/compare/appium@4.0.1...appium@4.0.2) (2026-11-27)
### Bug Fixes
* **appium:** clean up sessions when a createSession plugin fails ([#23217](https://github.com/appium/appium/issues/23217)) ([a68b15f](https://github.com/appium/appium/commit/a68b15fdaef667d7977dbc4c8c73daadc668c88d))
## [4.0.1](https://github.com/appium/appium/compare/appium@4.0.0...appium@4.0.1) (2026-11-23)
### Bug Fixes
@@ -22,3 +22,8 @@ authors:
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/7767781?v=4
slug: 'mykola'
eglitise:
name: 'Edgars Eglitis'
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/37242620?v=4
slug: 'eglitise'
@@ -0,0 +1,41 @@
---
authors:
- eglitise
date: 2026-11-15
---
# 🚀 Appium 4
Appium 4 is here! A major milestone in the evolution of Appium, this release aims to strengthen
Appium's compliance with the W3C WebDriver protocol, modernize the codebase, and as usual, remove
deprecated legacy functionality.
<!-- more -->
While Appium 3 was primarily a cleanup release that removed a lot of deprecated endpoints, Appium 4
has a broader scope of changes. A few legacy endpoints have still been removed, but the key focus
this time has been on various behavioral adjustments for closer alignment with the W3C WebDriver
protocol specification, as well as full removal of support for drivers/plugins who relied on the
obsolete JSONWP/MJSONWP protocols.
The key breaking changes are as follows:
- Minimum Node.js version is raised to 22.22
- All Appium packages are now ESM-only
- The Windows driver is replaced with the WinCore driver
- Some deprecated endpoints have been removed (far fewer than in Appium 3!)
- The server flag for enabling CORS has been renamed
When it comes to new features, Appium 4 adds only a few, similarly to Appium 3:
- New server flag for controlling allowed app URLs in capabilities like `appium:app`
- The `install` and `update` CLI commands now gracefully handle any incompatibilities with the
extension's declared server version range
- The universal XML plugin's translation can now be toggled mid-session
As usual, the full [Appium 4 migration guide](../../guides/migrating-3-to-4.md) describes the full
extent of the important changes included in this major release.
The Appium team is incredibly grateful to all contributors who made this release possible!
Happy testing!
@@ -314,7 +314,7 @@ Websockets. Implementing handlers for BiDi commands works just the same as imple
for WebDriver classic commands (described in the previous section). You simply define a method on
your driver of the appropriate name, and it will be called when the BiDi command is requested by
the client. To see which specific names you should use for BiDi commands, have a look at
[bidi-commands.ts](https://github.com/appium/appium/blob/master/packages/base-driver/lib/protocol/bidi-commands.ts)
[bidi-commands](https://github.com/appium/appium/tree/master/packages/base-driver/lib/protocol/bidi-commands)
You are not limited to BiDi commands that are defined in the official BiDi specification. If you
wish to define new commands, you may do so; you just need to tell Appium about them! See
+1 -1
View File
@@ -15,7 +15,7 @@ bundle for each test.
## What Is Cached
Caching could be applied to application bundles generated by
[`configureApp`](https://github.com/appium/appium/blob/master/packages/base-driver/lib/basedriver/helpers.ts#L99) helper call.
[`configureApp`](https://github.com/appium/appium/blob/master/packages/base-driver/lib/basedriver/helpers/app-cache.ts#L98) helper call.
Inherited drivers can customize their caching logic by providing own `onPostProcess`
(or both `inDownload` and `onPostProcess`) property definition, but the general
rule of thumb is that we need to cache locally all application bundles need to be downloaded and/or extracted
@@ -22,3 +22,8 @@ authors:
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/7767781?v=4
slug: 'mykola'
eglitise:
name: 'Edgars Eglitis'
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/37242620?v=4
slug: 'eglitise'
@@ -0,0 +1,41 @@
---
authors:
- eglitise
date: 2026-11-15
---
# 🚀 Appium 4
Appium 4 is here! A major milestone in the evolution of Appium, this release aims to strengthen
Appium's compliance with the W3C WebDriver protocol, modernize the codebase, and as usual, remove
deprecated legacy functionality.
<!-- more -->
While Appium 3 was primarily a cleanup release that removed a lot of deprecated endpoints, Appium 4
has a broader scope of changes. A few legacy endpoints have still been removed, but the key focus
this time has been on various behavioral adjustments for closer alignment with the W3C WebDriver
protocol specification, as well as full removal of support for drivers/plugins who relied on the
obsolete JSONWP/MJSONWP protocols.
The key breaking changes are as follows:
- Minimum Node.js version is raised to 22.22
- All Appium packages are now ESM-only
- The Windows driver is replaced with the WinCore driver
- Some deprecated endpoints have been removed (far fewer than in Appium 3!)
- The server flag for enabling CORS has been renamed
When it comes to new features, Appium 4 adds only a few, similarly to Appium 3:
- New server flag for controlling allowed app URLs in capabilities like `appium:app`
- The `install` and `update` CLI commands now gracefully handle any incompatibilities with the
extension's declared server version range
- The universal XML plugin's translation can now be toggled mid-session
As usual, the full [Appium 4 migration guide](../../guides/migrating-3-to-4.md) describes the full
extent of the important changes included in this major release.
The Appium team is incredibly grateful to all contributors who made this release possible!
Happy testing!
@@ -22,3 +22,8 @@ authors:
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/7767781?v=4
slug: 'mykola'
eglitise:
name: 'Edgars Eglitis'
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/37242620?v=4
slug: 'eglitise'
@@ -0,0 +1,41 @@
---
authors:
- eglitise
date: 2026-11-15
---
# 🚀 Appium 4
Appium 4 is here! A major milestone in the evolution of Appium, this release aims to strengthen
Appium's compliance with the W3C WebDriver protocol, modernize the codebase, and as usual, remove
deprecated legacy functionality.
<!-- more -->
While Appium 3 was primarily a cleanup release that removed a lot of deprecated endpoints, Appium 4
has a broader scope of changes. A few legacy endpoints have still been removed, but the key focus
this time has been on various behavioral adjustments for closer alignment with the W3C WebDriver
protocol specification, as well as full removal of support for drivers/plugins who relied on the
obsolete JSONWP/MJSONWP protocols.
The key breaking changes are as follows:
- Minimum Node.js version is raised to 22.22
- All Appium packages are now ESM-only
- The Windows driver is replaced with the WinCore driver
- Some deprecated endpoints have been removed (far fewer than in Appium 3!)
- The server flag for enabling CORS has been renamed
When it comes to new features, Appium 4 adds only a few, similarly to Appium 3:
- New server flag for controlling allowed app URLs in capabilities like `appium:app`
- The `install` and `update` CLI commands now gracefully handle any incompatibilities with the
extension's declared server version range
- The universal XML plugin's translation can now be toggled mid-session
As usual, the full [Appium 4 migration guide](../../guides/migrating-3-to-4.md) describes the full
extent of the important changes included in this major release.
The Appium team is incredibly grateful to all contributors who made this release possible!
Happy testing!
@@ -350,11 +350,7 @@ schema 的规则如下:
### 添加驱动脚本
Sometimes you might want users of your driver to be able to run scripts outside the context of
a session (for example, to run a script that pre-builds aspects of your driver). To support this,
you can add a map of script names and JS files to the `scripts` field within your Appium extension
metadata. So let's say you've created a script in your project that lives in a `scripts` directory
in your project, named `driver-prebuild.js`. Then you could add a `scripts` field like this:
有时你可能希望驱动用户能够在会话上下文之外运行脚本(例如运行一个预先构建驱动某些部分的脚本)。为支持这一点,你可以在 Appium 扩展元数据的 `scripts` 字段中添加一个"脚本名 → JS 文件"的映射。假设你在项目的 `scripts` 目录下创建了一个名为 `driver-prebuild.js` 的脚本,那么可以像这样添加`scripts` 字段:
```json
{
@@ -364,20 +360,15 @@ in your project, named `driver-prebuild.js`. Then you could add a `scripts` fiel
}
```
Now, assuming your driver is named `mydriver`, users of your driver can run `appium driver run
mydriver prebuild`, and your script will execute.
假设你的驱动名为 `mydriver`,驱动用户就可以运行 `appium driver run mydriver prebuild`,你的脚本便会执行。
### Proxy commands to another WebDriver implementation
### 把命令代理到另一个 WebDriver 实现
A very common design architecture for Appium drivers is to have some kind of platform-specific
WebDriver implementation that the Appium driver interfaces with. For example, the Appium
UiAutomator2 driver interfaces with a special (Java-based) server running on the Android device. In
webview mode, it also interfaces with Chromedriver.
Appium 驱动一种非常常见的设计架构,是与某种平台专有的 WebDriver 实现对接。例如,Appium 的 UiAutomator2 驱动对接一个运行在 Android 设备上的特殊(基于 Java 的)服务器;在 webview 模式下,它还对接 Chromedriver。
If you find yourself in this situation, it is extremely easy to tell Appium that your driver is
just going to be proxying WebDriver commands straight to another endpoint.
如果你发现自己正处于这种情形,告诉 Appium"这个驱动只是把 WebDriver 命令直接代理转发到另一个端点"是极其简单的。
First, let Appium know that your driver _can_ proxy by implementing the `canProxy` method:
首先,实现 `canProxy` 方法,让 Appium 知道你的驱&#x52A8;_&#x53EF;&#x4EE5;_&#x4EE3;理:
```js
canProxy() {
@@ -385,8 +376,7 @@ canProxy() {
}
```
Next, tell Appium which WebDriver routes it should _not_ attempt to proxy (there often end up being
certain routes that you don't want to forward on):
接下来,告诉 Appium 哪些 WebDriver 路&#x7531;_&#x4E0D;&#x5E94;_&#x5C1D;试代理(通常总有一些路由是你不想转发出去的):
```js
getProxyAvoidList() {
@@ -396,14 +386,9 @@ getProxyAvoidList() {
}
```
The proxy avoidance list should be an array of arrays, where each inner array has an HTTP method as
its first member, and a regular expression as its second. If the regular expression matches the
route, then the route will not be proxied and instead will be handled by your driver. In this
example, we are avoiding proxying all `POST` routes that have the `appium` prefix.
禁止代理列表应是一个二维数组,每个内层数组的第一个成员是 HTTP 方法,第二个是正则表达式。如果正则表达式匹配某条路由,该路由就不会被代理,而是交由你的驱动处理。这个例子中,我们禁止代理所有带 `appium` 前缀的 `POST` 路由。
Next, we have to set up the proxying itself. The way to do this is to use a special class from
Appium called `WebDriverProxy`. You'll want to create a `WebDriverProxy` object using the details
required to connect to the remote server:
然后要设置代理本身。做法是使用 Appium 提供的特殊类 `WebDriverProxy`。你需要用连接远程服务器所需的详细信息创建 `WebDriverProxy` 对象:
```js
// import {WebDriverProxy} from 'appium/driver';
@@ -418,14 +403,9 @@ this.proxyReqRes = proxy.proxyReqRes.bind(proxy);
this.proxyCommand = proxy.command.bind(proxy);
```
Here we are creating a proxy object and assigning some of its methods to `this` under the names
`proxyReqRes` and `proxyCommand`. This is required for Appium to use the proxy, so don't forget
this step! The `WebDriverProxy` has a variety of other options which you can check out in the
source code as well.
这里我们创建了代理对象,并把它的部分方法以 `proxyReqRes` 和 `proxyCommand` 的名字挂到 `this`上。这是 Appium 使用代理的必要条件,千万别漏掉这一步! `WebDriverProxy` 还有许多其他选项,你可以在[源码](https://github.com/appium/appium/blob/master/packages/base-driver/lib/wd-proxy/proxy.ts)中查看。
Finally, we need a way to tell Appium when the proxy is active. For your driver it might always
be active, or it might only be active when in a certain context. You can define the logic as an
implementation of `proxyActive`:
最后,我们需要告诉 Appium 代理何时激活。对你的驱动来说,代理可能一直激活,也可能只在某个特定上下文中激活。你可以把这部分逻辑实现为 `proxyActive`:
```js
proxyActive() {
@@ -433,8 +413,7 @@ proxyActive() {
}
```
With those pieces in play, you won't have to reimplement anything that's already implemented by the
remote endpoint you're proxying to. Appium will take care of all the proxying for you.
有了这几块拼图,你就不必重新实现远程端点已经实现过的功能。所有的代理工作都会由 Appium 代劳。
### Proxy BiDi commands to another BiDi implementation
+66 -19
View File
@@ -411,18 +411,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
await driverInstance.startNewCommandTimeout();
} catch (error: unknown) {
if (registeredSessionId) {
try {
// A failed initialization must not leave a registered session or an idle timer,
// even if the driver's own deleteSession also fails.
try {
await this.sessions[registeredSessionId]?.clearNewCommandTimeout();
} finally {
await this.deleteSession(registeredSessionId);
}
} catch (cleanupError) {
const message = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
this.log.warn(`Could not clean up failed session ${registeredSessionId}: ${message}`);
}
await this.cleanupFailedSession(registeredSessionId);
}
return markResponseEnvelope({
protocol,
@@ -642,6 +631,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
// Each createSession call gets its own plugin instances, so that concurrent calls do not share them
const newSessionPlugins = cmd === CREATE_SESSION_COMMAND ? this.createPluginInstances() : undefined;
const sessionTracker = newSessionPlugins?.length ? this.createSessionTracker() : undefined;
// get any plugins which are registered as handling this command
const candidates = newSessionPlugins ?? this.pluginsForSession(sessionId);
const plugins = candidates.filter((p) => canHandleCmd(p, cmd));
@@ -708,7 +698,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
args,
plugins,
cmdHandledBy,
next: defaultBehavior,
next: sessionTracker?.wrap(defaultBehavior) ?? defaultBehavior,
});
// clear the ambient proxy request while the plugin/default chain runs, so a plugin that
// re-enters executeCommand for a different command doesn't inherit and misuse this one
@@ -725,8 +715,14 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
// And finally, if the command was createSession, we want to attach its plugin instances to the
// new sessionId, so that plugins can share state between their createSession method and other
// instance methods
if (newSessionPlugins?.length && !res.error) {
const newSessionId = (res.value as unknown[])[0] as string;
if (newSessionPlugins?.length) {
const newSessionId =
!res.error && Array.isArray(res.value) && typeof res.value[0] === 'string' ? res.value[0] : undefined;
await sessionTracker?.settle(newSessionId);
if (!newSessionId) {
res.error ??= new Error('A createSession plugin did not return a session ID');
return res;
}
this.log.info(`Attaching ${newSessionPlugins.length} plugins to session ID ${newSessionId}`);
this.sessionPlugins[newSessionId] = newSessionPlugins;
for (const p of newSessionPlugins as (Plugin & ExtensionCore)[]) {
@@ -817,15 +813,17 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
/** Runs the wrapped plugin chain and merges the result into a `SessionHandlerResult` shape. */
async executeWrappedCommand(wrappedCmd: () => Promise<unknown>): Promise<SessionHandlerResult<unknown>> {
let cmdRes: unknown;
let cmdErr: unknown;
const res: SessionHandlerResult<unknown> = {};
try {
// At this point, `wrappedCmd` defines a whole sequence of plugin handlers, culminating in
// our default handler. Whatever it returns is what we're going to want to send back to the
// user.
cmdRes = await wrappedCmd();
} catch (e) {
cmdErr = e;
} catch (error) {
return markResponseEnvelope({
error: error instanceof Error ? error : new Error(String(error)),
protocol: PROTOCOLS.W3C,
});
}
// A marked envelope or a returned Error is passed through. `{protocol: 'W3C', value}` is data.
@@ -833,7 +831,6 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
Object.assign(res, cmdRes);
} else {
res.value = cmdRes;
res.error = cmdErr instanceof Error ? cmdErr : undefined;
res.protocol = PROTOCOLS.W3C;
}
return markResponseEnvelope(res);
@@ -857,11 +854,61 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
return typeof dstSession?.canProxy === 'function' && dstSession.canProxy(sessionId);
}
private async cleanupFailedSession(sessionId: string): Promise<void> {
try {
// Stop the idle timer even if the driver's deleteSession fails before clearing it.
try {
await this.sessions[sessionId]?.clearNewCommandTimeout();
} finally {
await this.deleteSession(sessionId);
}
} catch (cleanupError) {
const message = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
this.log.warn(`Could not clean up failed session ${sessionId}: ${message}`);
}
}
private deleteLinkedSessionObjects(sessionId: string): void {
delete this.sessions[sessionId];
delete this.sessionPlugins[sessionId];
delete this.sessionIpcs[sessionId];
}
private createSessionTracker() {
const createdSessionIds = new Set<string>();
let settled = false;
const cleanupIfRegistered = async (id: string) => {
if (this.sessionExists(id)) {
await this.cleanupFailedSession(id);
}
};
return {
wrap: (next: () => Promise<unknown>) => async () => {
const result = (await next()) as SessionHandlerCreateResult;
const id = result.value?.[0];
if (id) {
if (settled) {
// An unawaited next() may finish after the client has received a response.
await cleanupIfRegistered(id);
} else {
createdSessionIds.add(id);
}
}
return result;
},
settle: async (returnedId: string | undefined) => {
settled = true;
// A retry may create several sessions, but only one is returned to the client.
for (const id of createdSessionIds) {
if (id !== returnedId) {
await cleanupIfRegistered(id);
}
}
},
};
}
}
/**
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "appium",
"version": "4.0.1",
"version": "4.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Automation for Apps.",
"keywords": [
@@ -65,14 +65,14 @@
"test:unit": "node --test --experimental-test-module-mocks --test-concurrency=1 --enable-source-maps --test-timeout=5000 \"./build/test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/base-driver": "11.0.1",
"@appium/base-plugin": "4.0.1",
"@appium/docutils": "4.0.1",
"@appium/http-server": "1.0.1",
"@appium/base-driver": "11.0.2",
"@appium/base-plugin": "4.0.2",
"@appium/docutils": "4.0.2",
"@appium/http-server": "1.0.2",
"@appium/logger": "3.0.0",
"@appium/schema": "2.0.0",
"@appium/support": "8.0.1",
"@appium/types": "2.0.0",
"@appium/support": "8.0.2",
"@appium/types": "3.0.0",
"@sidvind/better-ajv-errors": "7.0.0",
"ajv": "8.20.0",
"ajv-formats": "3.0.1",
@@ -855,6 +855,158 @@ describe('AppiumDriver', function () {
}
});
for (const throwsError of [true, false]) {
it(`should delete a session when a plugin throws ${throwsError ? 'an Error' : 'a string'} after creating it`, async function () {
const failure = throwsError ? new Error('plugin setup failed') : 'plugin setup failed';
let createdSessionId: string | null = null;
class FailingPlugin extends BasePlugin {
async createSession(next: () => Promise<unknown>) {
await next();
createdSessionId = fakeDriver.sessionId;
throw failure;
}
}
setPluginClassesForTest(appium, new Map([[FailingPlugin, 'failing']]));
delete appium.sessions[SESSION_ID]; // Remove the placeholder from the executeCommand fixture.
const deleteSession = sandbox.spy(fakeDriver, 'deleteSession');
const caps = {
...W3C_CAPS,
alwaysMatch: {...W3C_CAPS.alwaysMatch, 'appium:newCommandTimeout': 0},
};
try {
const result = await appium.executeCommand('createSession', caps);
if (failure instanceof Error) {
assert.strictEqual(result.error, failure);
} else {
assert.strictEqual(result.error?.message, failure);
}
assert.ok(createdSessionId, 'the inner driver must create a session before the plugin fails');
assert.strictEqual(appium.sessionExists(createdSessionId), false);
assert.strictEqual(appium.sessionIpcs[createdSessionId], undefined);
assert.strictEqual(fakeDriver.sessionId, null);
assert.deepStrictEqual(deleteSession.args, [[createdSessionId]]);
} finally {
if (createdSessionId && appium.sessionExists(createdSessionId)) {
await appium.deleteSession(createdSessionId);
}
}
});
}
it('should delete a session when driver startup finishes after the plugin fails', async function () {
const failure = new Error('plugin setup failed');
const startupEntered = Promise.withResolvers<void>();
const releaseStartup = Promise.withResolvers<void>();
let pendingStartup: Promise<unknown> | undefined;
class FailingPlugin extends BasePlugin {
async createSession(next: () => Promise<unknown>) {
pendingStartup = next();
await startupEntered.promise;
throw failure;
}
}
setPluginClassesForTest(appium, new Map([[FailingPlugin, 'failing']]));
delete appium.sessions[SESSION_ID];
const createSession = fakeDriver.createSession.bind(fakeDriver);
sandbox.stub(fakeDriver, 'createSession').callsFake(async (caps) => {
startupEntered.resolve();
await releaseStartup.promise;
return await createSession(caps);
});
const deleteSession = sandbox.spy(fakeDriver, 'deleteSession');
const caps = {
...W3C_CAPS,
alwaysMatch: {...W3C_CAPS.alwaysMatch, 'appium:newCommandTimeout': 0},
};
try {
const result = await appium.executeCommand('createSession', caps);
assert.strictEqual(result.error, failure);
assert.strictEqual(deleteSession.callCount, 0);
assert.ok(pendingStartup);
releaseStartup.resolve();
const {value} = (await pendingStartup) as {value: [string]};
const [sessionId] = value;
assert.strictEqual(appium.sessionExists(sessionId), false);
assert.strictEqual(appium.sessionIpcs[sessionId], undefined);
assert.strictEqual(appium.sessionPlugins[sessionId], undefined);
assert.strictEqual(fakeDriver.sessionId, null);
assert.deepStrictEqual(deleteSession.args, [[sessionId]]);
} finally {
releaseStartup.resolve();
await pendingStartup;
if (fakeDriver.sessionId && appium.sessionExists(fakeDriver.sessionId)) {
await appium.deleteSession(fakeDriver.sessionId);
}
}
});
for (const retryFails of [true, false]) {
it(`should delete the first session when a plugin retry ${retryFails ? 'fails' : 'succeeds'}`, async function () {
class RetryingPlugin extends BasePlugin {
async createSession(next: () => Promise<unknown>) {
await next();
return await next();
}
}
const retryDriver = new FakeDriver();
const retryError = new Error('retry driver failed to start');
if (retryFails) {
sandbox.stub(retryDriver, 'createSession').rejects(retryError);
}
const driverMatch = (driver: FakeDriver) => ({
driver: function Driver() {
return driver;
},
version: '1.2.3',
driverName: 'fake',
});
(appium as any).driverConfig = {
findMatchingDriver: sandbox
.stub()
.onFirstCall()
.returns(driverMatch(fakeDriver))
.onSecondCall()
.returns(driverMatch(retryDriver)),
};
setPluginClassesForTest(appium, new Map([[RetryingPlugin, 'retrying']]));
delete appium.sessions[SESSION_ID];
const firstStartup = sandbox.spy(fakeDriver, 'createSession');
const deleteFirstSession = sandbox.spy(fakeDriver, 'deleteSession');
const deleteRetrySession = sandbox.spy(retryDriver, 'deleteSession');
const caps = {
...W3C_CAPS,
alwaysMatch: {...W3C_CAPS.alwaysMatch, 'appium:newCommandTimeout': 0},
};
try {
const result = await appium.executeCommand('createSession', caps);
const [firstId] = await firstStartup.returnValues[0];
if (retryFails) {
assert.strictEqual(result.error, retryError);
assert.deepStrictEqual(Object.keys(appium.sessions), []);
} else {
const [returnedId] = result.value as [string];
assert.strictEqual(returnedId, retryDriver.sessionId);
assert.notStrictEqual(returnedId, firstId);
assert.strictEqual(appium.sessions[returnedId], retryDriver);
assert.ok(appium.sessionIpcs[returnedId]);
assert.ok(appium.sessionPlugins[returnedId][0] instanceof RetryingPlugin);
}
assert.strictEqual(appium.sessionExists(firstId), false);
assert.strictEqual(appium.sessionIpcs[firstId], undefined);
assert.strictEqual(appium.sessionPlugins[firstId], undefined);
assert.deepStrictEqual(deleteFirstSession.args, [[firstId]]);
assert.strictEqual(deleteRetrySession.callCount, 0);
} finally {
for (const id of Object.keys(appium.sessions)) {
await appium.deleteSession(id);
}
}
});
}
it('should not reuse the plugin instances of a failed createSession', async function () {
class SessionStatePlugin extends BasePlugin {
deviceNames: string[] = [];
+10
View File
@@ -0,0 +1,10 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 1.1.0 (2026-11-27)
### Features
* **archward:** add package that checks a package against its C4 model ([#23225](https://github.com/appium/appium/issues/23225)) ([67f151f](https://github.com/appium/appium/commit/67f151f6f3520f7d86c48d1ea52fefc9a51313bb))
+159
View File
@@ -0,0 +1,159 @@
# @appium/archward
> Checks a package's source against its [C4](https://c4model.com) architecture model
## Summary
Keeps a package's architecture honest. The architecture is written once, as text, in a
[LikeC4](https://likec4.dev) model that lives next to the package. `archward` compares the actual
imports against it and fails on:
- an import between components that the model does not declare (domain leaks);
- import cycles, reported separately for runtime and type-only imports;
- source files that no component owns (or that several do);
- optionally, deep imports of scoped packages (e.g. `@appium/support/lib/fs.js`; a subpath is fine
if the installed package lists it in its `exports`, e.g. `@appium/oxc-config/oxlint`), and
imports of packages that are not declared in `package.json`.
Known violations are frozen in a baseline, so a package can adopt the check without fixing
everything first. New violations fail, and baseline entries that are fixed must be removed, so the
baseline can only shrink.
## Usage
```bash
npm install --save-dev @appium/archward
npx archward init [packageDir] # scaffold architecture/ from the current code
npx archward [packageDir...] # check (default: current directory)
npx archward --workspaces [rootDir] # check the workspace packages that have a model
npx archward --update-baseline # tolerate all current violations
npx archward --verbose # list every finding
```
`init` also takes `--source-root <dir>` and `--entry-point-scope <scope>` (repeatable); they are
saved to `config.json`.
Exit code: `0` ok, `1` violations found, `2` usage or runtime error. Relative imports that cannot be
resolved are reported as warnings, as they cannot be checked. `typescript` (5 or 6) must be
installed, as imports are resolved with the package's `tsconfig.json`.
### Getting started
`archward init` creates `architecture/` from the code as it is: one component per top-level
directory and per root file of the source root (`lib`, or `src` if `lib` holds build output; use
`--source-root` to override), allowed dependencies taken from the current imports, and a baseline
for the existing cycles. Then:
1. Edit `model.c4`: delete the dependencies that should not be allowed, merge or rename components,
add descriptions. Run `archward --update-baseline` to tolerate the violations this creates.
2. Run `archward` in CI.
3. Tell agents about the model, see [AI agents](#ai-agents) (`init` prints a ready snippet).
In a monorepo, run `init` in each package, and `archward --workspaces .` from the root.
### Files
The package being checked holds an `architecture/` directory:
| File | Purpose |
|---|---|
| `*.c4` | The LikeC4 model: components, the paths they own, and the dependencies they may have. |
| `baseline.json` | Tolerated violations. Written by `--update-baseline`; each entry may carry a `reason`. |
| `config.json` | Optional settings, see below. |
### The model
Each component declares the files it owns through `metadata.paths` (globs relative to the package,
`*` and `**` supported). Relationships between components are the **allowed** dependencies:
```
specification {
element container
element component
}
model {
app = container 'my-package' {
cli = component 'cli' {
metadata { paths 'lib/cli/**' }
}
utils = component 'utils' {
metadata { paths 'lib/utils/**' }
}
}
app.cli -> app.utils
}
```
Every file under the source root must belong to exactly one component; a file that matches no
component, or several, is an error. Components tagged `#unenforced` (declare `tag unenforced` in the
specification) still own their files, but their dependencies are not checked. Elements without
`metadata.paths` (systems, actors, ...) are for diagrams only. Preview the diagrams with `npx likec4 start architecture`.
### `architecture/config.json`
| Option | Default | Description |
|---|---|---|
| `sourceRoot` | `lib` | Directory to check, relative to the package. |
| `tsconfig` | `tsconfig.json` | Used to resolve imports. |
| `entryPointScopes` | `[]` | npm scopes (e.g. `["@appium"]`) whose packages must be declared in `package.json` and imported through their entry points only (a subpath the installed package lists in its `exports` is allowed). A `devDependency` is enough for `import type`. |
| `typeOnlyCycles` | `error` | `ignore` to stop reporting cycles that exist only through `import type`. They have no runtime effect, and patterns such as command mixins that reference their driver's type produce hundreds of them. Runtime cycles are always reported. |
| `undeclaredDependencies` | `ignore` | `error` to require every package the source imports to be declared in `package.json` (`dependencies`, `peerDependencies` or `optionalDependencies`; a `devDependency` is enough for `import type`), so nothing works only because of hoisting. Built-ins, relative and `#` imports, the package itself and tsconfig `paths` aliases are exempt. Without it, only packages in `entryPointScopes` are checked. |
Unknown options are rejected.
### Baseline
`baseline.json` lists tolerated violations: `boundaries` (`from`/`to` files), and `cycles`
(`runtime` and `typeOnly`, each a list of files). Unowned files and package-import violations cannot
be baselined; they are cheap to fix, and `--update-baseline` warns when it finds any. Treat changes to it like changes to the model:
adding an entry accepts a violation, so it deserves review.
## AI agents
The model is only a single source of truth if agents read it and keep it current. A project that
adopts `archward` must say so in its `AGENTS.md` (or equivalent), so that agents:
- read the model before adding or moving code, and put new code in the component that owns it;
- run `archward` before finishing, as CI does;
- update the model in the same change when a component, path or dependency legitimately changes,
and explain why in the PR description;
- never loosen the model or the baseline to silence a failure, and only ever remove baseline entries
as they get fixed.
A snippet to adapt (replace `packages/foo`):
```markdown
## Architecture
`packages/foo/architecture/*.c4` is the source of truth for the component boundaries of
`packages/foo`. CI runs `npx archward packages/foo`.
- Before adding or moving code, find the owning component (`metadata.paths`) and respect its
allowed dependencies. New files must be covered by a component's `paths`.
- Fix a failing check by changing the code. Do not add edges to the model or entries to
`baseline.json` to make it pass, unless the new dependency is intended; then update the `.c4`
files in the same change and explain why in the PR description.
- Remove `baseline.json` entries when you fix the violation they cover.
- Keep component descriptions and the paths they own in sync with the code.
```
Agents can also query the model directly: `npx likec4 mcp architecture` starts an MCP server for it.
## API
```ts
import {checkPackage, formatReport} from '@appium/archward';
const result = await checkPackage('path/to/package');
console.log(formatReport(result));
process.exitCode = result.ok ? 0 : 1;
```
Also exported: `updateBaseline(dir)`, `initPackage(dir, options)`, `findWorkspacePackages(rootDir)` and
`loadConfig(dir)`, plus the result types.
## License
Apache-2.0
@@ -0,0 +1,7 @@
{
"boundaries": [],
"cycles": {
"runtime": [],
"typeOnly": []
}
}
+79
View File
@@ -0,0 +1,79 @@
// Architecture of @appium/archward, checked by `archward` itself (see ../README.md).
// Each component owns the files in `metadata.paths`; each `a -> b` ALLOWS a to import b.
model {
archward = container '@appium/archward' {
api = component 'index.ts' {
description 'Public programmatic entry point; re-exports only.'
metadata { paths 'lib/index.ts' }
}
cli = component 'cli.ts' {
description 'Argument parsing, exit codes and printing for the `archward` command.'
metadata { paths 'lib/cli.ts' }
}
check = component 'check.ts' {
description 'Runs one package check: analysis, baseline comparison and baseline updates.'
metadata { paths 'lib/check.ts' }
}
analysis = component 'analysis' {
description 'Reads the model and the import graph; finds boundary, cycle and package-import violations.'
metadata { paths 'lib/analysis/**' }
}
init = component 'init' {
description 'Derives a starting model and baseline from the current code (`archward init`).'
metadata { paths 'lib/init/**' }
}
baseline = component 'baseline.ts' {
description 'Reads, writes and diffs the tolerated-violations baseline.'
metadata { paths 'lib/baseline.ts' }
}
config = component 'config.ts' {
description 'Loads and validates `architecture/config.json`.'
metadata { paths 'lib/config.ts' }
}
report = component 'report.ts' {
description 'Formats check results for humans.'
metadata { paths 'lib/report.ts' }
}
workspaces = component 'workspaces.ts' {
description 'Finds the packages of an npm workspaces monorepo.'
metadata { paths 'lib/workspaces.ts' }
}
types = component 'types.ts' {
description 'Shared types. Depends on nothing.'
metadata { paths 'lib/types.ts' }
}
util = component 'util.ts' {
description 'Small dependency-free helpers.'
metadata { paths 'lib/util.ts' }
}
}
archward.cli -> archward.check
archward.cli -> archward.init
archward.cli -> archward.report
archward.cli -> archward.workspaces
archward.api -> archward.check
archward.api -> archward.config
archward.api -> archward.init
archward.api -> archward.report
archward.api -> archward.types
archward.api -> archward.workspaces
archward.check -> archward.analysis
archward.check -> archward.baseline
archward.check -> archward.config
archward.check -> archward.types
archward.check -> archward.util
archward.init -> archward.analysis
archward.init -> archward.check
archward.init -> archward.config
archward.init -> archward.types
archward.init -> archward.util
archward.analysis -> archward.types
archward.analysis -> archward.util
archward.baseline -> archward.config
archward.baseline -> archward.types
archward.baseline -> archward.util
archward.config -> archward.types
archward.report -> archward.types
archward.workspaces -> archward.config
}
+6
View File
@@ -0,0 +1,6 @@
specification {
element container
element component
// Tag a component #unenforced to document it without checking its dependencies.
tag unenforced
}
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env node
// @ts-check
import {main} from '../build/lib/cli.js';
process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,77 @@
import type {IModule} from 'dependency-cruiser';
import type {ImportedBoundary} from '../types.js';
import {boundaryKey, byString} from '../util.js';
import type {Ownership} from './model.js';
export interface BoundaryContext {
/** Source root with a trailing slash, e.g. `lib/`. */
prefix: string;
ownership: Ownership;
/** Allowed `from -> to` component edges. */
allowed: ReadonlySet<string>;
}
export interface BoundaryResult {
/** Source files that no component owns. */
unownedFiles: string[];
/** Imports between enforced components that the model does not allow. */
boundaries: ImportedBoundary[];
/** Allowed edges that no import uses. */
unusedEdges: string[];
}
/**
* Checks which component owns each source file and whether the imports between components are
* allowed. Files of `#unenforced` components are owned, but their imports are not checked.
* @throws if a file belongs to several components
*/
export function findBoundaries(modules: readonly IModule[], context: BoundaryContext): BoundaryResult {
const {prefix, ownership, allowed} = context;
const unownedFiles = new Set<string>();
const ambiguousFiles = new Set<string>();
const boundaries = new Map<string, ImportedBoundary>();
const usedEdges = new Set<string>();
const ownerOf = (file: string): string | undefined => {
const owners = ownership.ownersOf(file);
if (owners.length > 1) {
ambiguousFiles.add(`${file} (${owners.join(', ')})`);
}
return owners[0];
};
for (const mod of modules.filter((m) => m.source.startsWith(prefix))) {
const fromComponent = ownerOf(mod.source);
if (!fromComponent) {
unownedFiles.add(mod.source);
}
for (const dep of mod.dependencies) {
const toComponent = dep.resolved.startsWith(prefix) ? ownerOf(dep.resolved) : undefined;
if (
!fromComponent ||
!toComponent ||
fromComponent === toComponent ||
!ownership.componentIds.has(fromComponent) ||
!ownership.componentIds.has(toComponent)
) {
continue;
}
const edge = `${fromComponent} -> ${toComponent}`;
usedEdges.add(edge);
if (!allowed.has(edge)) {
const boundary = {from: mod.source, to: dep.resolved, fromComponent, toComponent};
boundaries.set(boundaryKey(boundary), boundary);
}
}
}
if (ambiguousFiles.size) {
const files = [...ambiguousFiles].sort(byString).slice(0, 10);
throw new Error(
`Each file must belong to exactly one component, but these match several:\n ${files.join('\n ')}`,
);
}
return {
unownedFiles: [...unownedFiles].sort(byString),
boundaries: [...boundaries.values()].sort((a, b) => byString(boundaryKey(a), boundaryKey(b))),
unusedEdges: [...allowed].filter((edge) => !usedEdges.has(edge)).sort(byString),
};
}
+35
View File
@@ -0,0 +1,35 @@
import {byString} from '../util.js';
import type {SourceGraph} from './graph.js';
export interface ClassifiedCycles {
runtimeCycles: string[];
/** Cycles that exist only through `import type`. */
typeOnlyCycles: string[];
}
/** Whether every import in the cycle exists at runtime (none is type-only). */
export function isRuntimeCycle(files: readonly string[], runtimeEdges: ReadonlySet<string>): boolean {
return files.every((file, i) => runtimeEdges.has(`${file} -> ${files[(i + 1) % files.length]}`));
}
/**
* Splits the cycles of the two graphs into runtime and type-only ones. A cycle of the type-inclusive
* graph that is made only of runtime imports is already covered by the runtime graph.
* @param typeOnlyCycles - `ignore` leaves the type-only list empty
*/
export function classifyCycles(
withTypes: SourceGraph,
runtime: SourceGraph,
typeOnlyCycles: 'error' | 'ignore',
): ClassifiedCycles {
const runtimeEdges = new Set(
runtime.modules.flatMap((m) => m.dependencies.map((d) => `${m.source} -> ${d.resolved}`)),
);
return {
runtimeCycles: [...runtime.cycles].sort(byString),
typeOnlyCycles:
typeOnlyCycles === 'ignore'
? []
: withTypes.cycles.filter((key) => !isRuntimeCycle(key.split(' > '), runtimeEdges)).sort(byString),
};
}
+52
View File
@@ -0,0 +1,52 @@
import {readFile} from 'node:fs/promises';
import path from 'node:path';
/**
* Whether a package's `exports` field makes `subpath` (e.g. `./oxlint`) importable.
* Supports exact keys and `*` patterns; a `null` target blocks the subpath.
*/
export function isExportedSubpath(exportsField: unknown, subpath: string): boolean {
if (typeof exportsField !== 'object' || exportsField === null || Array.isArray(exportsField)) {
return false;
}
const map = exportsField as Record<string, unknown>;
if (!Object.keys(map).some((key) => key.startsWith('.'))) {
return false; // conditions only: the root entry point is the sole export
}
if (subpath in map) {
return map[subpath] !== null;
}
const pattern = Object.keys(map)
.filter((key) => {
const star = key.indexOf('*');
return (
star !== -1 &&
subpath.length >= key.length &&
subpath.startsWith(key.slice(0, star)) &&
subpath.endsWith(key.slice(star + 1))
);
})
// Node's order: the longer prefix before `*` wins, then the longer key
.sort((a, b) => b.indexOf('*') - a.indexOf('*') || b.length - a.length)[0];
return pattern !== undefined && map[pattern] !== null;
}
/**
* Reads the `exports` field of an installed package, looking up `node_modules` from `fromDir`.
* @returns `undefined` if the package is not installed or declares no `exports`
*/
export async function readInstalledExports(fromDir: string, name: string): Promise<unknown> {
for (let dir = fromDir; ; dir = path.dirname(dir)) {
try {
const pkg = JSON.parse(await readFile(path.join(dir, 'node_modules', name, 'package.json'), 'utf8')) as {
exports?: unknown;
};
return pkg.exports;
} catch {
// not installed at this level; keep looking upwards
}
if (path.dirname(dir) === dir) {
return undefined;
}
}
}
+58
View File
@@ -0,0 +1,58 @@
import path from 'node:path';
import {cruise, type ICruiseResult, type IModule} from 'dependency-cruiser';
import type {ResolvedConfig} from '../types.js';
import {byString, cycleKey} from '../util.js';
export interface SourceGraph {
modules: IModule[];
/** Canonical keys of all import cycles. */
cycles: string[];
}
/**
* Extracts the import graph of the package's source root.
* @param typeImports - also follow type-only imports (they are erased at runtime)
*/
export async function cruiseSources(config: ResolvedConfig, typeImports: boolean): Promise<SourceGraph> {
const sourcePrefix = `${config.sourceRoot.replace(/\/$/, '')}/`;
const {output} = await cruise(
[config.sourceRoot],
{
baseDir: config.packageDir,
validate: true,
// Keep external imports in the graph, but do not crawl into them: workspace siblings resolve to
// their build output through symlinks, outside node_modules and outside the source root.
doNotFollow: {path: `^(?!${escapeRegExp(sourcePrefix)})`},
tsPreCompilationDeps: typeImports,
tsConfig: {fileName: path.join(config.packageDir, config.tsconfig)},
ruleSet: {forbidden: [{name: 'no-circular', severity: 'error', from: {}, to: {circular: true}}]},
},
{extensions: ['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs']},
);
const result = output as ICruiseResult;
const cycles = result.summary.violations.flatMap((v) => (v.cycle ? [cycleKey(v.cycle.map((c) => c.name))] : []));
return {modules: result.modules, cycles: [...new Set(cycles)]};
}
/** Runs the two passes one after the other, so they never share dependency-cruiser's process-wide state. */
export async function cruiseBoth(config: ResolvedConfig): Promise<{withTypes: SourceGraph; runtime: SourceGraph}> {
const withTypes = await cruiseSources(config, true);
const runtime = await cruiseSources(config, false);
return {withTypes, runtime};
}
/** Relative imports that could not be resolved, as `file -> specifier`; they cannot be checked. */
export function findUnresolvedImports(modules: readonly IModule[]): string[] {
const unresolved = modules.flatMap((mod) =>
mod.dependencies
.filter((dep) => dep.couldNotResolve && dep.module.startsWith('.'))
.map((dep) => `${mod.source} -> ${dep.module}`),
);
return [...new Set(unresolved)].sort(byString);
}
function escapeRegExp(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
+50
View File
@@ -0,0 +1,50 @@
import {readdir} from 'node:fs/promises';
import type {Analysis, ResolvedConfig} from '../types.js';
import {findBoundaries} from './boundaries.js';
import {classifyCycles} from './cycles.js';
import {cruiseBoth, findUnresolvedImports} from './graph.js';
import {allowedEdges, buildOwnership, exportModel} from './model.js';
import {findPackageImports, readDeclaredDependencies} from './package-imports.js';
/**
* Finds everything in the package's source that the architecture model and the package rules
* object to, before the baseline is applied.
*/
export async function analyze(config: ResolvedConfig): Promise<Analysis> {
await assertModelExists(config.modelDir);
const [model, declared, {withTypes, runtime}] = await Promise.all([
exportModel(config.modelDir),
readDeclaredDependencies(config.packageDir),
cruiseBoth(config),
]);
const ownership = buildOwnership(model);
const prefix = `${config.sourceRoot}/`;
const {unownedFiles, boundaries, unusedEdges} = findBoundaries(withTypes.modules, {
prefix,
ownership,
allowed: allowedEdges(model, ownership.componentIds),
});
return {
unownedFiles,
boundaries,
unusedEdges,
packageImports: await findPackageImports(withTypes.modules, {
packageDir: config.packageDir,
prefix,
entryPointScopes: config.entryPointScopes,
undeclaredDependencies: config.undeclaredDependencies,
declared,
runtimeModules: runtime.modules,
}),
unresolvedImports: findUnresolvedImports(withTypes.modules.filter((m) => m.source.startsWith(prefix))),
...classifyCycles(withTypes, runtime, config.typeOnlyCycles),
};
}
async function assertModelExists(modelDir: string): Promise<void> {
const files = await readdir(modelDir).catch(() => [] as string[]);
if (!files.some((f) => f.endsWith('.c4'))) {
throw new Error(`No architecture model found: expected *.c4 files in ${modelDir}`);
}
}
+102
View File
@@ -0,0 +1,102 @@
import {execFile} from 'node:child_process';
import {existsSync, readFileSync} from 'node:fs';
import {mkdtemp, readFile, rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {promisify} from 'node:util';
import picomatch from 'picomatch';
import type {ArchitectureModel} from '../types.js';
const execFileAsync = promisify(execFile);
/** Components tagged with this are documented but not checked. */
export const UNENFORCED_TAG = 'unenforced';
export interface Ownership {
/** Ids of the enforced components (those that are not `#unenforced`). */
componentIds: Set<string>;
/** Ids of all components (enforced or not) whose paths match `file` (package-relative, `/`-separated). */
ownersOf: (file: string) => string[];
}
/** Exports the LikeC4 model in `modelDir` to JSON using the bundled `likec4` CLI. */
export async function exportModel(modelDir: string): Promise<ArchitectureModel> {
const tmp = await mkdtemp(path.join(tmpdir(), 'archward-'));
try {
const out = path.join(tmp, 'model.json');
await execFileAsync(process.execPath, [await findLikec4Bin(), 'export', 'json', modelDir, '-o', out]);
return parseModel(JSON.parse(await readFile(out, 'utf8')));
} catch (err) {
const stderr = (err as {stderr?: string}).stderr?.trim();
throw new Error(`Cannot export the architecture model in ${modelDir}: ${stderr || (err as Error).message}`, {
cause: err,
});
} finally {
await rm(tmp, {recursive: true, force: true});
}
}
/** Checks that the JSON exported by `likec4` has the shape this tool reads. */
export function parseModel(json: unknown): ArchitectureModel {
const model = json as Partial<ArchitectureModel> | null;
if (!model || typeof model.elements !== 'object' || typeof model.relations !== 'object') {
throw new Error("unexpected `likec4 export json` format: expected 'elements' and 'relations' objects");
}
return model as ArchitectureModel;
}
/** Maps source files to the components that own them (via `metadata.paths` globs). */
export function buildOwnership(model: ArchitectureModel): Ownership {
const components = Object.values(model.elements).filter((e) => e.kind === 'component' && e.metadata?.paths);
const matchers = components.map((c) => ({
id: c.id,
isMatch: picomatch([c.metadata?.paths ?? []].flat(), {dot: true}),
}));
return {
componentIds: new Set(components.filter((c) => !c.tags?.includes(UNENFORCED_TAG)).map((c) => c.id)),
ownersOf: (file) => matchers.filter((m) => m.isMatch(file)).map((m) => m.id),
};
}
/** The component -> component edges the model allows, as `from -> to` keys. */
export function allowedEdges(model: ArchitectureModel, componentIds: ReadonlySet<string>): Set<string> {
const edges = new Set<string>();
for (const {source, target} of Object.values(model.relations)) {
if (componentIds.has(source.model) && componentIds.has(target.model)) {
edges.add(`${source.model} -> ${target.model}`);
}
}
return edges;
}
/** Locates the `likec4` CLI script, without relying on its `exports` map. */
async function findLikec4Bin(): Promise<string> {
const dir = findPackageDir('likec4');
const {bin} = JSON.parse(await readFile(path.join(dir, 'package.json'), 'utf8')) as {
bin?: string | Record<string, string>;
};
const rel = typeof bin === 'string' ? bin : bin?.likec4;
if (!rel) {
throw new Error(`the 'likec4' package at ${dir} declares no 'likec4' executable`);
}
return path.resolve(dir, rel);
}
/** Walks up from the package's resolved entry point to its root directory. */
function findPackageDir(name: string): string {
let dir = path.dirname(fileURLToPath(import.meta.resolve(name)));
while (
!existsSync(path.join(dir, 'package.json')) ||
JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8')).name !== name
) {
const parent = path.dirname(dir);
if (parent === dir) {
throw new Error(`cannot locate the '${name}' package`);
}
dir = parent;
}
return dir;
}
@@ -0,0 +1,149 @@
import {readFile} from 'node:fs/promises';
import {builtinModules} from 'node:module';
import path from 'node:path';
import type {IModule} from 'dependency-cruiser';
import type {ArchwardConfig} from '../types.js';
import {byString} from '../util.js';
import {isExportedSubpath, readInstalledExports} from './exports.js';
const BUILTINS = new Set(builtinModules);
export interface DeclaredDependencies {
name?: string;
/** `dependencies`, `peerDependencies` and `optionalDependencies`. */
runtime: ReadonlySet<string>;
dev: ReadonlySet<string>;
}
export interface PackageImportContext {
packageDir: string;
/** Source root with a trailing slash, e.g. `lib/`. */
prefix: string;
entryPointScopes: readonly string[];
undeclaredDependencies: NonNullable<ArchwardConfig['undeclaredDependencies']>;
declared: DeclaredDependencies;
/** The graph without type-only imports; an import missing from it is erased at runtime. */
runtimeModules: readonly IModule[];
}
export interface PackageImportFinding {
key: string;
message: string;
}
/** Reads the declared dependencies and the name of the package in `packageDir`. */
export async function readDeclaredDependencies(packageDir: string): Promise<DeclaredDependencies> {
const pkg = JSON.parse(await readFile(path.join(packageDir, 'package.json'), 'utf8')) as {
name?: string;
} & Record<string, Record<string, string> | undefined>;
const names = (fields: string[]) => new Set(fields.flatMap((field) => Object.keys(pkg[field] ?? {})));
return {
name: pkg.name,
runtime: names(['dependencies', 'peerDependencies', 'optionalDependencies']),
dev: names(['devDependencies']),
};
}
/**
* Checks the packages the source imports: deep imports of packages in `entryPointScopes` (unless
* the installed package exports the subpath), and packages missing from `package.json`.
*/
export async function findPackageImports(
modules: readonly IModule[],
context: PackageImportContext,
): Promise<PackageImportFinding[]> {
const {prefix, entryPointScopes, undeclaredDependencies, declared, runtimeModules} = context;
const runtimeImports = new Set(runtimeModules.flatMap((m) => m.dependencies.map((d) => `${m.source}\0${d.module}`)));
const exportsOf = createExportsLookup(context.packageDir);
const findings = new Map<string, string>();
for (const mod of modules.filter((m) => m.source.startsWith(prefix))) {
for (const dep of mod.dependencies) {
const spec = parseScopedSpecifier(dep.module, entryPointScopes);
if (spec?.subpath && !isExportedSubpath(await exportsOf(spec.pkg), spec.subpath)) {
findings.set(
`${mod.source} -> ${dep.module}`,
`${mod.source} deep-imports '${dep.module}'. Import from '${spec.pkg}' entry points only.`,
);
}
const external =
undeclaredDependencies === 'error'
? isLocalFile(dep)
? null
: externalPackageName(dep.module)
: (spec?.pkg ?? null);
// Unresolved imports carry no type-only marker, so type-only is "absent from the runtime graph".
const isTypeOnly = !runtimeImports.has(`${mod.source}\0${dep.module}`);
if (
external &&
external !== declared.name &&
!declared.runtime.has(external) &&
!(declared.dev.has(external) && isTypeOnly)
) {
findings.set(
`${mod.source} -> ${external}`,
`${mod.source} imports '${external}', which is not declared in package.json (devDependencies are enough for type-only imports).`,
);
}
}
}
return [...findings].map(([key, message]) => ({key, message})).sort((a, b) => byString(a.key, b.key));
}
/**
* Parses an import specifier of a package within one of the given npm scopes.
* @returns the package name, and the subpath (e.g. `./oxlint`) if the specifier reaches past the
* package's root entry point, or `null`
*/
export function parseScopedSpecifier(
specifier: string,
scopes: readonly string[],
): {pkg: string; subpath?: string} | null {
for (const scope of scopes) {
const escaped = scope.replace(/[.+^${}()|[\]\\]/g, '\\$&');
const match = new RegExp(`^(${escaped}/[^/]+)(/.*)?$`).exec(specifier);
if (match) {
return {pkg: match[1], ...(match[2] ? {subpath: `.${match[2]}`} : {})};
}
}
return null;
}
/**
* The npm package an import specifier refers to (`@scope/name` or `name`), or `null` for relative
* and absolute paths, `#` imports, `node:`/URL-style specifiers and Node.js built-in modules.
*/
export function externalPackageName(specifier: string): string | null {
if (/^[./#]/.test(specifier) || specifier.includes(':')) {
return null;
}
const parts = specifier.split('/');
const name = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
return !name || (!specifier.startsWith('@') && BUILTINS.has(name)) ? null : name;
}
/**
* Whether an import resolved to a file of this package that is not in `node_modules`: a relative
* import, or a tsconfig `paths` alias (wherever in the package it points). Packages resolve into
* `node_modules`, or, for linked workspace packages, outside the package directory.
*/
function isLocalFile(dep: {resolved: string; couldNotResolve?: boolean}): boolean {
return (
!dep.couldNotResolve &&
!dep.resolved.startsWith('..') &&
!path.isAbsolute(dep.resolved) &&
!dep.resolved.split('/').includes('node_modules')
);
}
/** Looks up the `exports` of installed packages, reading each package at most once. */
function createExportsLookup(fromDir: string): (pkg: string) => Promise<unknown> {
const cache = new Map<string, Promise<unknown>>();
return (pkg) => {
if (!cache.has(pkg)) {
cache.set(pkg, readInstalledExports(fromDir, pkg));
}
return cache.get(pkg) as Promise<unknown>;
};
}
+58
View File
@@ -0,0 +1,58 @@
import {randomUUID} from 'node:crypto';
import {mkdir, rename, rm, writeFile} from 'node:fs/promises';
import path from 'node:path';
import {readOptionalJson} from './config.js';
import type {Analysis, Baseline, CycleEntry} from './types.js';
import {boundaryKey, byString, cycleKey} from './util.js';
/** Splits `current` keys against a baseline into new (not baselined) and stale (no longer present). */
export function diffAgainstBaseline(
currentKeys: Iterable<string>,
baselineKeys: Iterable<string>,
): {added: string[]; stale: string[]} {
const current = new Set(currentKeys);
const baseline = new Set(baselineKeys);
return {
added: [...current].filter((k) => !baseline.has(k)).sort(byString),
stale: [...baseline].filter((k) => !current.has(k)).sort(byString),
};
}
/** Reads the baseline file; a missing file is an empty baseline. */
export async function readBaseline(file: string): Promise<Baseline> {
const raw = await readOptionalJson<Partial<Baseline>>(file);
return {
boundaries: raw.boundaries ?? [],
cycles: {runtime: raw.cycles?.runtime ?? [], typeOnly: raw.cycles?.typeOnly ?? []},
};
}
/** Writes a baseline of everything in `analysis`, keeping the reasons of entries that remain. */
export async function writeBaseline(file: string, analysis: Analysis, previous: Baseline): Promise<void> {
const reasons = new Map<string, string | undefined>([
...previous.boundaries.map((b) => [boundaryKey(b), b.reason] as const),
...[...previous.cycles.runtime, ...previous.cycles.typeOnly].map((c) => [cycleKey(c.cycle), c.reason] as const),
]);
const withReason = (key: string) => (reasons.get(key) ? {reason: reasons.get(key)} : {});
const cycleEntry = (key: string): CycleEntry => ({cycle: key.split(' > '), ...withReason(key)});
const next: Baseline = {
boundaries: analysis.boundaries
.map((b) => ({from: b.from, to: b.to, ...withReason(boundaryKey(b))}))
.sort((a, b) => byString(boundaryKey(a), boundaryKey(b))),
cycles: {
runtime: analysis.runtimeCycles.map(cycleEntry),
typeOnly: analysis.typeOnlyCycles.map(cycleEntry),
},
};
await mkdir(path.dirname(file), {recursive: true});
// Write to a temp file and rename it into place, so a failure never leaves a partial baseline.
const tmp = `${file}.${randomUUID()}.tmp`;
try {
await writeFile(tmp, `${JSON.stringify(next, null, 2)}\n`);
await rename(tmp, file);
} catch (err) {
await rm(tmp, {force: true});
throw err;
}
}
+80
View File
@@ -0,0 +1,80 @@
import {analyze} from './analysis/index.js';
import {diffAgainstBaseline, readBaseline, writeBaseline} from './baseline.js';
import {loadConfig} from './config.js';
import type {Analysis, CheckResult, Finding, ImportedBoundary} from './types.js';
import {boundaryKey} from './util.js';
/**
* Checks the package in `packageDir` against its architecture model and baseline.
* @returns the findings; `ok` is false if there are any new violations or stale baseline entries
*/
export async function checkPackage(packageDir: string): Promise<CheckResult> {
const config = await loadConfig(packageDir);
const analysis = await analyze(config);
const baseline = await readBaseline(config.baselineFile);
const boundariesByKey = new Map(analysis.boundaries.map((b) => [boundaryKey(b), b]));
const findings: Finding[] = [
...analysis.unownedFiles.map((file) => ({
rule: 'unowned-file' as const,
status: 'new' as const,
key: file,
message: `${file} is not owned by any component. Add its path to a component in architecture/model.c4.`,
})),
...analysis.packageImports.map((p) => ({rule: 'package-import' as const, status: 'new' as const, ...p})),
...compare('boundary', [...boundariesByKey.keys()], baseline.boundaries.map(boundaryKey), (key) =>
describeBoundary(key, boundariesByKey),
),
...compare(
'runtime-cycle',
analysis.runtimeCycles,
baseline.cycles.runtime.map((c) => c.cycle.join(' > ')),
),
...compare(
'type-cycle',
analysis.typeOnlyCycles,
baseline.cycles.typeOnly.map((c) => c.cycle.join(' > ')),
),
];
const count = (rule: Finding['rule'], total: number) =>
total - findings.filter((f) => f.rule === rule && f.status === 'new').length;
return {
ok: findings.length === 0,
findings,
warnings: [
...analysis.unusedEdges.map((edge) => `edge '${edge}' is declared in the model but never used in the code.`),
...analysis.unresolvedImports.map((imp) => `${imp} could not be resolved, so it was not checked.`),
],
analysis,
baselined: {
boundaries: count('boundary', analysis.boundaries.length),
runtimeCycles: count('runtime-cycle', analysis.runtimeCycles.length),
typeOnlyCycles: count('type-cycle', analysis.typeOnlyCycles.length),
},
};
}
/** Rewrites the baseline to tolerate every current violation, keeping existing reasons. */
export async function updateBaseline(packageDir: string): Promise<Analysis> {
const config = await loadConfig(packageDir);
const analysis = await analyze(config);
await writeBaseline(config.baselineFile, analysis, await readBaseline(config.baselineFile));
return analysis;
}
function compare(
rule: Finding['rule'],
currentKeys: string[],
baselineKeys: string[],
describe: (key: string) => string = (key) => key,
): Finding[] {
const {added, stale} = diffAgainstBaseline(currentKeys, baselineKeys);
return [
...added.map((key) => ({rule, status: 'new' as const, key, message: describe(key)})),
...stale.map((key) => ({rule, status: 'stale' as const, key, message: key})),
];
}
function describeBoundary(key: string, boundaries: ReadonlyMap<string, ImportedBoundary>): string {
const b = boundaries.get(key);
return b ? `${key} (component '${b.fromComponent}' may not depend on '${b.toComponent}')` : key;
}
+168
View File
@@ -0,0 +1,168 @@
import path from 'node:path';
import {parseArgs} from 'node:util';
import {checkPackage, updateBaseline} from './check.js';
import {initPackage} from './init/index.js';
import {formatReport} from './report.js';
import {findWorkspacePackages} from './workspaces.js';
const USAGE = `Usage:
archward [packageDir...] [--workspaces] [--update-baseline] [--verbose]
archward init [packageDir] [--source-root <dir>] [--entry-point-scope <scope>]...
Checks each package (default: the current directory) against its architecture/*.c4.
--workspaces treat each packageDir as a monorepo root and check its workspace packages
that have an architecture/ directory
--update-baseline tolerate all current violations by rewriting architecture/baseline.json
--verbose list every finding instead of the first few per rule
init creates architecture/ for a package from its current code (components = top-level
directories and files of the source root, dependencies = current imports) and a baseline.
`;
const EXIT_OK = 0;
const EXIT_VIOLATIONS = 1;
const EXIT_ERROR = 2;
interface CliArgs {
help: boolean;
init: boolean;
workspaces: boolean;
updateBaseline: boolean;
verbose: boolean;
sourceRoot?: string;
entryPointScopes: string[];
dirs: string[];
}
/**
* Runs the CLI.
* @param argv - arguments after the program name
* @returns the process exit code: 0 ok, 1 violations found, 2 usage or runtime error
*/
export async function main(argv: string[]): Promise<number> {
let args: CliArgs;
try {
args = parseCliArgs(argv);
} catch (err) {
process.stderr.write(`${(err as Error).message}\n${USAGE}`);
return EXIT_ERROR;
}
if (args.help) {
process.stdout.write(USAGE);
return EXIT_OK;
}
try {
if (args.init) {
return await runInit(args);
}
const dirs = args.workspaces ? (await Promise.all(args.dirs.map(findWorkspacePackages))).flat() : args.dirs;
if (!dirs.length) {
throw new Error('No packages with an architecture/ directory found');
}
let exitCode = EXIT_OK;
for (const dir of dirs) {
if (dirs.length > 1) {
process.stdout.write(`== ${path.relative(process.cwd(), dir) || '.'}\n`);
}
exitCode = Math.max(exitCode, await runOne(dir, args));
}
return exitCode;
} catch (err) {
process.stderr.write(`${(err as Error).message}\n`);
return EXIT_ERROR;
}
}
function parseCliArgs(argv: string[]): CliArgs {
const {values, positionals} = parseArgs({
args: argv,
allowPositionals: true,
options: {
workspaces: {type: 'boolean'},
'update-baseline': {type: 'boolean'},
verbose: {type: 'boolean'},
'source-root': {type: 'string'},
'entry-point-scope': {type: 'string', multiple: true},
help: {type: 'boolean', short: 'h'},
},
});
const init = positionals[0] === 'init';
const dirs = (init ? positionals.slice(1) : positionals).map((d) => path.resolve(d));
if (init && dirs.length > 1) {
throw new Error(`init takes at most one package directory, got ${dirs.length}`);
}
if (init && (values.workspaces || values['update-baseline'])) {
throw new Error('init does not take --workspaces or --update-baseline');
}
if (!init && (values['source-root'] || values['entry-point-scope'])) {
throw new Error('--source-root and --entry-point-scope only apply to init');
}
return {
help: Boolean(values.help),
init,
workspaces: Boolean(values.workspaces),
updateBaseline: Boolean(values['update-baseline']),
verbose: Boolean(values.verbose),
sourceRoot: values['source-root'],
entryPointScopes: values['entry-point-scope'] ?? [],
dirs: dirs.length ? dirs : [path.resolve('.')],
};
}
async function runOne(dir: string, args: CliArgs): Promise<number> {
if (args.updateBaseline) {
return runUpdateBaseline(dir);
}
const result = await checkPackage(dir);
process.stdout.write(`${formatReport(result, {verbose: args.verbose})}\n`);
return result.ok ? EXIT_OK : EXIT_VIOLATIONS;
}
async function runUpdateBaseline(packageDir: string): Promise<number> {
const analysis = await updateBaseline(packageDir);
process.stdout.write(
`Baseline updated: ${analysis.boundaries.length} boundary imports, ` +
`${analysis.runtimeCycles.length} runtime cycles, ${analysis.typeOnlyCycles.length} type-only cycles.\n`,
);
const unbaselinable = analysis.unownedFiles.length + analysis.packageImports.length;
if (unbaselinable) {
process.stderr.write(
`warning: ${analysis.unownedFiles.length} unowned files and ${analysis.packageImports.length} package ` +
'import violations cannot be baselined and still fail the check. Fix them (see `archward`).\n',
);
}
return EXIT_OK;
}
async function runInit(args: CliArgs): Promise<number> {
const [dir] = args.dirs;
const result = await initPackage(dir, {sourceRoot: args.sourceRoot, entryPointScopes: args.entryPointScopes});
const rel = path.relative(process.cwd(), dir) || '.';
process.stdout.write(
`Created ${result.files.join(', ')} in ${rel}: ${result.components} components, ` +
`${result.edges} allowed dependencies (taken from the current imports).\n\n` +
'Next steps:\n' +
' 1. Delete the dependencies in model.c4 that should not be allowed, add descriptions.\n' +
` 2. Run \`archward ${rel} --update-baseline\` to tolerate the violations that creates.\n` +
' 3. Run `archward` in CI, and add the following to AGENTS.md:\n\n' +
`${agentsSnippet(rel)}`,
);
return EXIT_OK;
}
function agentsSnippet(packageDir: string): string {
return `## Architecture
\`${packageDir}/architecture/*.c4\` is the source of truth for the component boundaries of
\`${packageDir}\`. CI runs \`npx archward ${packageDir}\`.
- Before adding or moving code, find the owning component (\`metadata.paths\`) and respect its
allowed dependencies. New files must be covered by a component's \`paths\`.
- Fix a failing check by changing the code. Do not add edges to the model or entries to
\`baseline.json\` to make it pass, unless the new dependency is intended; then update the \`.c4\`
files in the same change and explain why in the PR description.
- Remove \`baseline.json\` entries when you fix the violation they cover.
- Keep component descriptions and the paths they own in sync with the code.
`;
}
+85
View File
@@ -0,0 +1,85 @@
import {readFile, realpath} from 'node:fs/promises';
import path from 'node:path';
import type {ArchwardConfig, ResolvedConfig} from './types.js';
export const ARCHITECTURE_DIR = 'architecture';
const CONFIG_KEYS = new Set(['sourceRoot', 'tsconfig', 'entryPointScopes', 'typeOnlyCycles', 'undeclaredDependencies']);
/**
* Resolves the settings of the package in `packageDir`, applying defaults over the optional
* `architecture/config.json`.
*/
export async function loadConfig(packageDir: string): Promise<ResolvedConfig> {
// dependency-cruiser reports real paths, so symlinked directories (e.g. macOS /tmp) must be resolved
const root = await realpath(path.resolve(packageDir));
const modelDir = path.join(root, ARCHITECTURE_DIR);
const configFile = path.join(modelDir, 'config.json');
const user = parseConfig(await readOptionalJson<ArchwardConfig>(configFile), configFile);
return {
packageDir: root,
sourceRoot: normalizeSourceRoot(user.sourceRoot ?? 'lib', configFile),
tsconfig: user.tsconfig ?? 'tsconfig.json',
entryPointScopes: user.entryPointScopes ?? [],
typeOnlyCycles: user.typeOnlyCycles ?? 'error',
undeclaredDependencies: user.undeclaredDependencies ?? 'ignore',
modelDir,
baselineFile: path.join(modelDir, 'baseline.json'),
};
}
/**
* Normalizes a source directory to the form used in the import graph: relative to the package,
* `/`-separated, without a leading `./` or trailing slash.
*/
export function normalizeSourceRoot(sourceRoot: string, origin = 'sourceRoot'): string {
const normalized = path.posix.normalize(sourceRoot.replace(/\\/g, '/')).replace(/\/+$/, '');
if (!normalized || normalized === '.' || normalized.startsWith('..') || path.posix.isAbsolute(normalized)) {
throw new Error(`${origin}: the source root must be a subdirectory of the package, got '${sourceRoot}'`);
}
return normalized;
}
/** Validates the contents of `architecture/config.json`; unknown options are rejected to catch typos. */
export function parseConfig(raw: unknown, file: string): ArchwardConfig {
const fail = (msg: string): never => {
throw new Error(`${file}: ${msg}`);
};
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
return fail('expected a JSON object');
}
const config = raw as Record<string, unknown>;
for (const key of Object.keys(config)) {
if (!CONFIG_KEYS.has(key)) {
fail(`unknown option '${key}' (known: ${[...CONFIG_KEYS].join(', ')})`);
}
}
for (const key of ['sourceRoot', 'tsconfig'] as const) {
if (config[key] !== undefined && typeof config[key] !== 'string') {
fail(`'${key}' must be a string`);
}
}
const scopes = config.entryPointScopes;
if (scopes !== undefined && !(Array.isArray(scopes) && scopes.every((s) => typeof s === 'string'))) {
fail("'entryPointScopes' must be an array of strings");
}
for (const key of ['typeOnlyCycles', 'undeclaredDependencies'] as const) {
if (config[key] !== undefined && config[key] !== 'error' && config[key] !== 'ignore') {
fail(`'${key}' must be 'error' or 'ignore'`);
}
}
return config as ArchwardConfig;
}
/** Reads and parses a JSON file, returning `{}` if it does not exist. */
export async function readOptionalJson<T extends object>(file: string): Promise<T> {
try {
return JSON.parse(await readFile(file, 'utf8')) as T;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
return {} as T;
}
throw new Error(`Cannot read ${file}: ${(err as Error).message}`, {cause: err});
}
}
+6
View File
@@ -0,0 +1,6 @@
export {checkPackage, updateBaseline} from './check.js';
export {loadConfig} from './config.js';
export {initPackage, type InitOptions, type InitResult} from './init/index.js';
export {formatReport, type ReportOptions} from './report.js';
export {findWorkspacePackages} from './workspaces.js';
export type {Analysis, ArchwardConfig, Baseline, CheckResult, Finding, ResolvedConfig, Rule} from './types.js';
+93
View File
@@ -0,0 +1,93 @@
import path from 'node:path';
import picomatch from 'picomatch';
import {byString} from '../util.js';
/** Words LikeC4 does not accept as element names. */
const RESERVED = new Set(
`views specification global dynamic extend import include exclude with from to view of style tag kind
color icon title description technology metadata link this it self extends where and or not is true false
navigateTo shape border opacity size autoLayout rank`.split(/\s+/),
);
export interface DerivedComponent {
id: string;
title: string;
/** Glob of the files the component owns, relative to the package. */
paths: string;
}
/**
* One component per top-level directory of the source root, and one per file directly in it.
* @param files - package-relative paths of the source files
*/
export function deriveComponents(files: readonly string[], sourceRoot: string): DerivedComponent[] {
const prefix = `${sourceRoot.replace(/\/$/, '')}/`;
const globPrefix = escapeGlob(prefix);
const dirs = new Set<string>();
const rootFiles = new Set<string>();
for (const file of files) {
const rel = file.slice(prefix.length);
const slash = rel.indexOf('/');
if (slash === -1) {
rootFiles.add(rel);
} else {
dirs.add(rel.slice(0, slash));
}
}
const used = new Set<string>();
const uniqueId = (name: string): string => {
const base = toIdentifier(name);
let id = base;
for (let n = 2; used.has(id); n++) {
id = `${base}_${n}`;
}
used.add(id);
return id;
};
return [
...[...dirs].sort(byString).map((dir) => ({
id: uniqueId(dir),
title: dir,
paths: `${globPrefix}${escapeGlob(dir)}/**`,
})),
...[...rootFiles].sort(byString).map((file) => ({
id: uniqueId(dirs.has(path.parse(file).name) ? `${path.parse(file).name}_file` : path.parse(file).name),
title: file,
paths: `${globPrefix}${escapeGlob(file)}`,
})),
];
}
/**
* The dependencies between components that exist in the code.
* @param imports - `[from, to]` pairs of package-relative file paths
*/
export function deriveEdges(
imports: readonly (readonly string[])[],
components: readonly DerivedComponent[],
): string[] {
// Same matching rules as the check itself, so derived edges agree with the model's ownership.
const owners = components.map((c) => ({id: c.id, isMatch: picomatch(c.paths, {dot: true})}));
const ownerOf = (file: string) => owners.find((o) => o.isMatch(file))?.id;
const edges = new Set<string>();
for (const [from, to] of imports) {
const [a, b] = [ownerOf(from), ownerOf(to)];
if (a && b && a !== b) {
edges.add(`${a} -> ${b}`);
}
}
return [...edges].sort(byString);
}
/** Makes `name` usable as a LikeC4 element name. */
export function toIdentifier(name: string): string {
const id = name.replace(/[^A-Za-z0-9_-]/g, '_').replace(/^[^A-Za-z]/, (c) => `c${c}`);
return RESERVED.has(id) ? `${id}_` : id;
}
/** Escapes glob metacharacters so that a literal path segment matches only itself. */
function escapeGlob(literal: string): string {
return literal.replace(/[\\*?[\]{}()!+@]/g, '\\$&');
}
+126
View File
@@ -0,0 +1,126 @@
import {existsSync} from 'node:fs';
import {mkdir, readFile, readdir, realpath, rm, rmdir, writeFile} from 'node:fs/promises';
import path from 'node:path';
import {cruiseSources} from '../analysis/graph.js';
import {exportModel} from '../analysis/model.js';
import {updateBaseline} from '../check.js';
import {ARCHITECTURE_DIR, normalizeSourceRoot} from '../config.js';
import type {ArchwardConfig, ResolvedConfig} from '../types.js';
import {deriveComponents, deriveEdges} from './derive.js';
import {renderModel} from './render.js';
import {detectSourceRoot} from './source-root.js';
export interface InitOptions {
/** Source directory, relative to the package. Default: `lib`, or `src` if there is no `lib`. */
sourceRoot?: string;
entryPointScopes?: string[];
}
export interface InitResult {
files: string[];
components: number;
edges: number;
}
/**
* Scaffolds `architecture/` for the package in `packageDir` from its current code: one component
* per top-level directory or root file of the source root, and the dependencies that exist today.
* Review the result and delete the dependencies that should not be allowed; then run
* `updateBaseline` to tolerate the violations.
*/
export async function initPackage(packageDir: string, options: InitOptions = {}): Promise<InitResult> {
const root = await realpath(path.resolve(packageDir));
const modelDir = path.join(root, ARCHITECTURE_DIR);
const existing = await readdir(modelDir).catch(() => [] as string[]);
if (existing.some((f) => f.endsWith('.c4'))) {
throw new Error(`${modelDir} already contains a model`);
}
const sourceRoot = normalizeSourceRoot(options.sourceRoot ?? (await detectSourceRoot(root)), '--source-root');
if (!existsSync(path.join(root, sourceRoot))) {
throw new Error(`No '${sourceRoot}' directory in ${root}; pass the source directory with --source-root`);
}
const config: ResolvedConfig = {
packageDir: root,
sourceRoot,
tsconfig: 'tsconfig.json',
entryPointScopes: options.entryPointScopes ?? [],
typeOnlyCycles: 'error',
undeclaredDependencies: 'ignore',
modelDir,
baselineFile: path.join(modelDir, 'baseline.json'),
};
const prefix = `${sourceRoot.replace(/\/$/, '')}/`;
const graph = await cruiseSources(config, true);
const sources = graph.modules.filter((m) => m.source.startsWith(prefix));
const components = deriveComponents(
sources.map((m) => m.source),
sourceRoot,
);
const edges = deriveEdges(
sources.flatMap((m) =>
m.dependencies.filter((d) => d.resolved.startsWith(prefix)).map((d) => [m.source, d.resolved]),
),
components,
);
const pkgName = (JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')) as {name?: string}).name;
const rendered = renderModel(pkgName ?? path.basename(root), components, edges);
const userConfig: ArchwardConfig = {
...(sourceRoot === 'lib' ? {} : {sourceRoot}),
...(options.entryPointScopes?.length ? {entryPointScopes: options.entryPointScopes} : {}),
};
const written = [
['spec.c4', rendered.spec],
['model.c4', rendered.model],
...(Object.keys(userConfig).length ? [['config.json', `${JSON.stringify(userConfig, null, 2)}\n`]] : []),
];
const targets = written.map(([name]) => path.join(modelDir, name));
const previous = new Map(await Promise.all(targets.map(async (file) => [file, await readIfExists(file)] as const)));
// Only the files this invocation started writing are rolled back.
const touched = new Set<string>();
const createdDir = await mkdir(modelDir, {recursive: true});
try {
await Promise.all(
written.map(([name, content]) => {
const file = path.join(modelDir, name);
touched.add(file);
return writeFile(file, content);
}),
);
// Fail now if a generated name is not valid LikeC4, rather than on the first check.
await exportModel(modelDir);
// The baseline is written atomically as the last step, so a failure never leaves one of ours.
await updateBaseline(root);
} catch (err) {
// Leave no half-initialized model behind, so that a retry is not refused.
await Promise.all(
[...touched].map((file) => {
const before = previous.get(file);
return before === undefined ? rm(file, {force: true}) : writeFile(file, before);
}),
);
if (createdDir) {
// Not recursive: keep files that something else added in the meantime.
await rmdir(modelDir).catch(() => undefined);
}
throw err;
}
return {
files: [...written.map(([name]) => `${ARCHITECTURE_DIR}/${name}`), `${ARCHITECTURE_DIR}/baseline.json`],
components: components.length,
edges: edges.length,
};
}
/** File content, or undefined if it does not exist; other read errors propagate. */
async function readIfExists(file: string): Promise<string | undefined> {
try {
return await readFile(file, 'utf8');
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
return undefined;
}
throw err;
}
}
+42
View File
@@ -0,0 +1,42 @@
import {type DerivedComponent, toIdentifier} from './derive.js';
/** Renders `spec.c4` and `model.c4`. */
export function renderModel(
packageName: string,
components: readonly DerivedComponent[],
edges: readonly string[],
): {spec: string; model: string} {
const container = toIdentifier(packageName.replace(/^@/, '').replace(/\//g, '-'));
const quote = (s: string) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
const spec = `specification {
element container
element component
// Tag a component #unenforced to document it without checking its dependencies.
tag unenforced
}
`;
const model = `// Architecture of ${packageName}, derived from the code by \`archward init\`.
// Each component owns the files in \`metadata.paths\`; each \`a -> b\` below ALLOWS a to import b.
// Delete the dependencies you do not want (archward then reports them), and add descriptions.
model {
${container} = container ${quote(packageName)} {
${components
.map(
(c) => ` ${c.id} = component ${quote(c.title)} {
description 'TODO: describe the responsibility of ${c.title.replace(/'/g, '')}'
metadata { paths ${quote(c.paths)} }
}`,
)
.join('\n')}
}
${edges
.map((e) => {
const [from, to] = e.split(' -> ');
return ` ${container}.${from} -> ${container}.${to}`;
})
.join('\n')}
}
`;
return {spec, model};
}
+26
View File
@@ -0,0 +1,26 @@
import {existsSync} from 'node:fs';
import {readFile} from 'node:fs/promises';
import path from 'node:path';
/** Directories that usually hold a package's source, in order of preference. */
const SOURCE_ROOT_CANDIDATES = ['lib', 'src'];
/**
* Picks `lib` or `src`. A directory that holds build output is skipped: the tsconfig `outDir`, or,
* when both exist, the one the `main` entry points into.
*/
export async function detectSourceRoot(root: string): Promise<string> {
const pkg = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')) as {main?: string};
const tsconfig = await readFile(path.join(root, 'tsconfig.json'), 'utf8').catch(() => '');
const outDir = /"outDir"\s*:\s*"(?:\.\/)?([^"/]+)\/?"/.exec(tsconfig)?.[1];
const main = pkg.main?.replace(/^\.\//, '');
let candidates = SOURCE_ROOT_CANDIDATES.filter((dir) => existsSync(path.join(root, dir)) && dir !== outDir);
if (candidates.length > 1) {
const rest = candidates.filter((dir) => !main?.startsWith(`${dir}/`));
candidates = rest.length ? rest : candidates;
}
if (!candidates.length) {
throw new Error(`Cannot tell where the source is in ${root}; pass it with --source-root`);
}
return candidates[0];
}
+65
View File
@@ -0,0 +1,65 @@
import type {CheckResult, Finding, Rule} from './types.js';
const MAX_PER_RULE = 5;
const TITLES: Record<Rule, string> = {
'unowned-file': 'Files owned by no component',
'package-import': 'Package imports',
boundary: 'Component boundaries',
'runtime-cycle': 'Runtime import cycles',
'type-cycle': 'Type-only import cycles',
};
const HINTS: Record<Rule, string> = {
'unowned-file': 'Add the file to a component in architecture/model.c4.',
'package-import': 'Fix the import, or declare the dependency in package.json.',
boundary: 'Remove the import, or declare the edge in architecture/model.c4 if it is intended.',
'runtime-cycle': 'Break the cycle (extract shared code to a lower layer).',
'type-cycle': 'Move the shared type to a lower layer so the cycle disappears.',
};
export interface ReportOptions {
/** List every finding instead of the first few per rule. */
verbose?: boolean;
}
/** Renders the check result as text for a terminal. */
export function formatReport(result: CheckResult, {verbose = false}: ReportOptions = {}): string {
const lines = result.warnings.map((w) => `warning: ${w}`);
if (result.ok) {
const {boundaries, runtimeCycles, typeOnlyCycles} = result.baselined;
lines.push(
`Architecture OK (baselined: ${boundaries} boundary imports, ${runtimeCycles} runtime cycles, ` +
`${typeOnlyCycles} type-only cycles).`,
);
return lines.join('\n');
}
lines.push('Architecture check failed:');
for (const rule of Object.keys(TITLES) as Rule[]) {
const findings = result.findings.filter((f) => f.rule === rule);
if (findings.length) {
lines.push(...formatRule(rule, findings, verbose));
}
}
return lines.join('\n');
}
function formatRule(rule: Rule, findings: Finding[], verbose: boolean): string[] {
const added = findings.filter((f) => f.status === 'new');
const stale = findings.filter((f) => f.status === 'stale');
const lines = [`${TITLES[rule]}:`];
for (const [label, group, suffix] of [
['NEW ', added, ''],
['STALE ', stale, ' (fixed? run with --update-baseline)'],
] as const) {
const shown = verbose ? group : group.slice(0, MAX_PER_RULE);
lines.push(...shown.map((f) => ` ${label} ${f.message}${suffix}`));
if (shown.length < group.length) {
lines.push(` ... and ${group.length - shown.length} more ${label.trim()} (use --verbose to list all)`);
}
}
if (added.length) {
lines.push(` -> ${HINTS[rule]}`);
}
return lines;
}
+110
View File
@@ -0,0 +1,110 @@
/** Optional per-package settings, read from `architecture/config.json`. */
export interface ArchwardConfig {
/** Directory (relative to the package) that holds the source to check. Default: `lib`. */
sourceRoot?: string;
/** tsconfig (relative to the package) used to resolve imports. Default: `tsconfig.json`. */
tsconfig?: string;
/**
* npm scopes (e.g. `@appium`) whose packages must be declared in `package.json` and imported
* through their entry points only. Default: none.
*/
entryPointScopes?: string[];
/**
* What to do about import cycles that exist only through `import type`. They have no runtime
* effect, and patterns like command mixins that reference their driver's type produce hundreds of
* them. Default: `error`.
*/
typeOnlyCycles?: 'error' | 'ignore';
/**
* `error`: every package the source imports must be declared in `package.json` (a
* `devDependency` is enough for `import type`), so nothing works only thanks to hoisting. By
* default only packages in `entryPointScopes` are checked.
*/
undeclaredDependencies?: 'error' | 'ignore';
}
export interface ResolvedConfig {
packageDir: string;
sourceRoot: string;
tsconfig: string;
entryPointScopes: string[];
typeOnlyCycles: 'error' | 'ignore';
undeclaredDependencies: 'error' | 'ignore';
modelDir: string;
baselineFile: string;
}
/** The subset of the exported LikeC4 model this tool reads. */
export interface ArchitectureModel {
elements: Record<string, ModelElement>;
relations: Record<string, ModelRelation>;
}
export interface ModelElement {
id: string;
kind: string;
tags?: string[];
metadata?: {paths?: string | string[]};
}
export interface ModelRelation {
source: {model: string};
target: {model: string};
}
export interface BoundaryEntry {
from: string;
to: string;
reason?: string;
}
export interface CycleEntry {
cycle: string[];
reason?: string;
}
/** Known violations that are tolerated until fixed. */
export interface Baseline {
boundaries: BoundaryEntry[];
cycles: {runtime: CycleEntry[]; typeOnly: CycleEntry[]};
}
export type Rule = 'unowned-file' | 'boundary' | 'runtime-cycle' | 'type-cycle' | 'package-import';
export interface Finding {
rule: Rule;
/** `new`: not in the baseline. `stale`: in the baseline, but no longer present. */
status: 'new' | 'stale';
/** Identifies the finding in the baseline. */
key: string;
message: string;
}
/** An import between two components that the model does not allow. */
export interface ImportedBoundary {
from: string;
to: string;
fromComponent: string;
toComponent: string;
}
/** Everything found in the source, before comparing against the baseline. */
export interface Analysis {
unownedFiles: string[];
packageImports: {key: string; message: string}[];
boundaries: ImportedBoundary[];
/** Relative imports that could not be resolved, so they could not be checked. */
unresolvedImports: string[];
runtimeCycles: string[];
typeOnlyCycles: string[];
unusedEdges: string[];
}
export interface CheckResult {
ok: boolean;
findings: Finding[];
warnings: string[];
analysis: Analysis;
/** Number of baselined entries still present, for the summary. */
baselined: {boundaries: number; runtimeCycles: number; typeOnlyCycles: number};
}
+11
View File
@@ -0,0 +1,11 @@
/** Orders strings by code unit. */
export const byString = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
/** Returns the baseline key for an import between two files. */
export const boundaryKey = (b: {from: string; to: string}): string => `${b.from} -> ${b.to}`;
/** Canonical key of a cycle: rotated to start at its smallest file. */
export function cycleKey(files: readonly string[]): string {
const start = files.indexOf([...files].sort(byString)[0]);
return [...files.slice(start), ...files.slice(0, start)].join(' > ');
}
+49
View File
@@ -0,0 +1,49 @@
import {readdir, readFile} from 'node:fs/promises';
import path from 'node:path';
import picomatch from 'picomatch';
import {ARCHITECTURE_DIR} from './config.js';
/**
* Lists the workspace packages of the monorepo at `rootDir` that have an `architecture/` model.
* Only `*` wildcards are supported in the `workspaces` patterns of `package.json`.
*/
export async function findWorkspacePackages(rootDir: string): Promise<string[]> {
const pkg = JSON.parse(await readFile(path.join(rootDir, 'package.json'), 'utf8')) as {
workspaces?: string[] | {packages?: string[]};
};
const patterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces?.packages ?? []);
if (!patterns.length) {
throw new Error(`${rootDir}/package.json declares no workspaces`);
}
const included = patterns.filter((p) => !p.startsWith('!'));
const isExcluded = picomatch(patterns.filter((p) => p.startsWith('!')).map((p) => p.slice(1)));
const dirs = (await Promise.all(included.map((pattern) => expand(rootDir, pattern.split('/').filter(Boolean)))))
.flat()
.filter((dir) => !isExcluded(path.relative(rootDir, dir).split(path.sep).join('/')));
const modeled = await Promise.all(dirs.map(async (dir) => ((await hasModel(dir)) ? dir : null)));
return [...new Set(modeled.filter((d): d is string => d !== null))].sort();
}
async function expand(base: string, segments: string[]): Promise<string[]> {
if (!segments.length) {
return [base];
}
const [head, ...rest] = segments;
if (head.includes('**')) {
throw new Error(`Unsupported workspace pattern segment '${head}': only '*' wildcards are supported`);
}
if (!head.includes('*')) {
return expand(path.join(base, head), rest);
}
const isMatch = picomatch(head);
const entries = await readdir(base, {withFileTypes: true}).catch(() => []);
const matches = entries.filter((e) => e.isDirectory() && e.name !== 'node_modules' && isMatch(e.name));
return (await Promise.all(matches.map((e) => expand(path.join(base, e.name), rest)))).flat();
}
async function hasModel(dir: string): Promise<boolean> {
const files = await readdir(path.join(dir, ARCHITECTURE_DIR)).catch(() => [] as string[]);
return files.some((f) => f.endsWith('.c4'));
}
+68
View File
@@ -0,0 +1,68 @@
{
"name": "@appium/archward",
"version": "1.1.0",
"description": "Checks a package's source against its C4 architecture model (component boundaries, import cycles)",
"keywords": [
"appium",
"architecture",
"c4",
"dependency-cruiser",
"likec4"
],
"homepage": "https://appium.io",
"bugs": {
"url": "https://github.com/appium/appium/issues"
},
"license": "Apache-2.0",
"author": "https://github.com/appium",
"repository": {
"type": "git",
"url": "https://github.com/appium/appium.git",
"directory": "packages/archward"
},
"bin": {
"archward": "./bin/archward.js"
},
"directories": {
"lib": "lib"
},
"files": [
"bin",
"build/lib",
"lib",
"tsconfig.json"
],
"type": "module",
"main": "./build/lib/index.js",
"types": "./build/lib/index.d.ts",
"exports": {
".": {
"types": "./build/lib/index.d.ts",
"import": "./build/lib/index.js"
},
"./package.json": "./package.json"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"test": "run-p test:unit",
"test:unit": "node --test --enable-source-maps --test-timeout=5000 \"./build/test/unit/**/*.spec.js\"",
"test:e2e": "node --test --enable-source-maps --test-force-exit --test-concurrency=1 --test-timeout=60000 \"./build/test/e2e/**/*.e2e.spec.js\""
},
"dependencies": {
"dependency-cruiser": "^18.9.0",
"likec4": "^1.61.1",
"picomatch": "^4.0.0"
},
"devDependencies": {
"@types/picomatch": "^4.0.0"
},
"peerDependencies": {
"typescript": ">=5.0.0 <7"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0",
"npm": ">=10"
}
}
+142
View File
@@ -0,0 +1,142 @@
import assert from 'node:assert/strict';
import {appendFile, chmod, cp, mkdir, mkdtemp, readFile, readdir, rm, writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {afterEach, beforeEach, describe, it} from 'node:test';
import {fileURLToPath} from 'node:url';
import {main} from '../../lib/cli.js';
import {checkPackage, initPackage, updateBaseline, type Finding} from '../../lib/index.js';
// Compiled to build/test/e2e, so the package root is three levels up.
const PACKAGE_DIR = fileURLToPath(new URL('../../../', import.meta.url));
describe('archward on itself', () => {
it('conforms to its own architecture model', async () => {
const result = await checkPackage(PACKAGE_DIR);
assert.deepEqual(result.findings, []);
assert.deepEqual(result.warnings, []);
assert.ok(result.ok);
});
it('exits 0 from the CLI', async () => {
assert.equal(await main([PACKAGE_DIR]), 0);
});
it('derives a conforming model for its own sources', async () => {
const dir = await copyOfSources();
await initPackage(dir);
assert.deepEqual((await checkPackage(dir)).findings, []);
});
it('leaves no model behind when init fails, so that it can be retried', async () => {
const dir = await copyOfSources();
// The model is generated before the baseline is read, so this fails midway.
await mkdir(path.join(dir, 'architecture'));
await writeFile(path.join(dir, 'architecture/baseline.json'), '{');
await assert.rejects(initPackage(dir));
assert.deepEqual(await readdir(path.join(dir, 'architecture')), ['baseline.json']);
await rm(path.join(dir, 'architecture/baseline.json'));
await initPackage(dir);
assert.deepEqual((await checkPackage(dir)).findings, []);
});
it('does not touch an existing baseline it cannot read', {skip: process.platform === 'win32'}, async () => {
const dir = await copyOfSources();
const baseline = path.join(dir, 'architecture/baseline.json');
await mkdir(path.join(dir, 'architecture'));
await writeFile(baseline, '{}');
await chmod(baseline, 0o000);
try {
// Running as root ignores the mode, so the read succeeds and there is nothing to check.
if (
await readFile(baseline).then(
() => true,
() => false,
)
) {
return;
}
await assert.rejects(initPackage(dir), /EACCES/);
assert.deepEqual(await readdir(path.join(dir, 'architecture')), ['baseline.json']);
} finally {
await chmod(baseline, 0o600);
}
});
describe('on a copy with violations', () => {
let dir: string;
const file = (name: string) => path.join(dir, name);
const keys = (findings: Finding[], rule: Finding['rule'], status: Finding['status'] = 'new') =>
findings.filter((f) => f.rule === rule && f.status === status).map((f) => f.key);
beforeEach(async () => {
dir = await copyOfSources(true);
});
it('flags an import between components that the model does not allow', async () => {
await appendFile(file('lib/types.ts'), "import {byString} from './util.js';\nexport const x = byString;\n");
const result = await checkPackage(dir);
assert.deepEqual(keys(result.findings, 'boundary'), ['lib/types.ts -> lib/util.ts']);
assert.ok(!result.ok);
assert.equal(await main([dir]), 1);
});
it('flags runtime and type-only cycles separately', async () => {
await writeFile(file('lib/analysis/a.ts'), "import {b} from './b.js';\nexport const a = () => b;\n");
await writeFile(file('lib/analysis/b.ts'), "import {a} from './a.js';\nexport const b = () => a;\n");
const runtime = await checkPackage(dir);
assert.equal(keys(runtime.findings, 'runtime-cycle').length, 1);
await writeFile(
file('lib/analysis/b.ts'),
"import type {a} from './a.js';\nexport const b = (f?: typeof a) => f;\n",
);
const typeOnly = await checkPackage(dir);
assert.equal(keys(typeOnly.findings, 'runtime-cycle').length, 0);
assert.equal(keys(typeOnly.findings, 'type-cycle').length, 1);
});
it('flags files owned by no component', async () => {
await writeFile(file('lib/stray.ts'), 'export {};\n');
assert.deepEqual(keys((await checkPackage(dir)).findings, 'unowned-file'), ['lib/stray.ts']);
});
it('tolerates baselined violations and reports them as stale once fixed', async () => {
const original = await readFile(file('lib/types.ts'), 'utf8');
await appendFile(file('lib/types.ts'), "import {byString} from './util.js';\nexport const x = byString;\n");
await updateBaseline(dir);
const tolerated = await checkPackage(dir);
assert.ok(tolerated.ok);
assert.equal(tolerated.baselined.boundaries, 1);
assert.equal(await main([dir]), 0);
await writeFile(file('lib/types.ts'), original);
const stale = await checkPackage(dir);
assert.ok(!stale.ok);
assert.deepEqual(keys(stale.findings, 'boundary', 'stale'), ['lib/types.ts -> lib/util.ts']);
assert.equal(await main([dir]), 1);
});
it('exits 2 when the package cannot be checked', async () => {
assert.equal(await main([path.join(dir, 'nope')]), 2);
await rm(file('architecture'), {recursive: true});
assert.equal(await main([dir]), 2);
});
});
});
const dirs: string[] = [];
afterEach(async () => {
await Promise.all(dirs.splice(0).map((d) => rm(d, {recursive: true, force: true})));
});
/** Copies the package's sources (and its model, if asked to) into a temp directory. */
async function copyOfSources(withModel = false): Promise<string> {
const dir = await mkdtemp(path.join(tmpdir(), 'archward-self-'));
dirs.push(dir);
for (const entry of ['lib', 'package.json', 'tsconfig.json', ...(withModel ? ['architecture'] : [])]) {
await cp(path.join(PACKAGE_DIR, entry), path.join(dir, entry), {recursive: true});
}
return dir;
}
@@ -0,0 +1,65 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {findBoundaries} from '../../../lib/analysis/boundaries.js';
import {allowedEdges, buildOwnership} from '../../../lib/analysis/model.js';
import type {ArchitectureModel} from '../../../lib/types.js';
import {mod} from './modules.js';
function context(paths: Record<string, string>, edges: [string, string][], unenforced: string[] = []) {
const model: ArchitectureModel = {
elements: Object.fromEntries(
Object.entries(paths).map(([id, glob]) => [
id,
{id, kind: 'component', metadata: {paths: glob}, ...(unenforced.includes(id) ? {tags: ['unenforced']} : {})},
]),
),
relations: Object.fromEntries(edges.map(([a, b], i) => [`r${i}`, {source: {model: a}, target: {model: b}}])),
};
const ownership = buildOwnership(model);
return {prefix: 'lib/', ownership, allowed: allowedEdges(model, ownership.componentIds)};
}
const imp = (resolved: string) => ({module: `./${resolved}`, resolved});
describe('findBoundaries', () => {
const paths = {a: 'lib/a/**', b: 'lib/b/**', c: 'lib/c/**'};
it('reports imports between components that the model does not allow', () => {
const result = findBoundaries(
[mod('lib/a/x.ts', [imp('lib/b/y.ts'), imp('lib/c/z.ts')]), mod('lib/b/y.ts')],
context(paths, [['a', 'b']]),
);
assert.deepEqual(result.boundaries, [{from: 'lib/a/x.ts', to: 'lib/c/z.ts', fromComponent: 'a', toComponent: 'c'}]);
assert.deepEqual(result.unusedEdges, []);
});
it('reports files that no component owns, and allowed edges nobody uses', () => {
const result = findBoundaries([mod('lib/stray.ts'), mod('lib/a/x.ts')], context(paths, [['a', 'b']]));
assert.deepEqual(result.unownedFiles, ['lib/stray.ts']);
assert.deepEqual(result.unusedEdges, ['a -> b']);
});
it('ignores files outside the source root, and imports within a component', () => {
const result = findBoundaries(
[mod('../other/x.ts', [imp('lib/b/y.ts')]), mod('lib/a/x.ts', [imp('lib/a/w.ts')])],
context(paths, []),
);
assert.deepEqual(result, {unownedFiles: [], boundaries: [], unusedEdges: []});
});
it('owns, but does not check, the files of unenforced components', () => {
const result = findBoundaries(
[mod('lib/c/z.ts', [imp('lib/a/x.ts')]), mod('lib/a/x.ts', [imp('lib/c/z.ts')])],
context(paths, [], ['c']),
);
assert.deepEqual(result, {unownedFiles: [], boundaries: [], unusedEdges: []});
});
it('rejects a file that belongs to several components', () => {
assert.throws(
() => findBoundaries([mod('lib/a/x.ts')], context({a: 'lib/a/**', all: 'lib/**'}, [])),
/exactly one component[\s\S]*lib\/a\/x\.ts \(a, all\)/,
);
});
});
@@ -0,0 +1,43 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {classifyCycles, isRuntimeCycle} from '../../../lib/analysis/cycles.js';
import type {SourceGraph} from '../../../lib/analysis/graph.js';
import {cycleKey} from '../../../lib/util.js';
import {mod} from './modules.js';
describe('cycles', () => {
it('canonicalizes cycles regardless of rotation', () => {
assert.equal(cycleKey(['b', 'c', 'a']), cycleKey(['a', 'b', 'c']));
assert.notEqual(cycleKey(['a', 'b']), cycleKey(['a', 'b', 'c']));
});
it('tells runtime cycles from cycles that use a type-only import', () => {
const runtimeEdges = new Set(['a -> b', 'b -> a', 'b -> c']);
assert.ok(isRuntimeCycle(['a', 'b'], runtimeEdges));
assert.ok(!isRuntimeCycle(['a', 'b', 'c'], runtimeEdges));
});
describe('classifyCycles', () => {
const runtime: SourceGraph = {
modules: [mod('a', [{module: './b', resolved: 'b'}]), mod('b', [{module: './a', resolved: 'a'}])],
cycles: ['a > b'],
};
const withTypes: SourceGraph = {
modules: [],
// `a > b` is the runtime cycle again; `c > d` needs a type-only import
cycles: ['c > d', 'a > b'],
};
it('keeps runtime cycles and drops them from the type-only list', () => {
assert.deepEqual(classifyCycles(withTypes, runtime, 'error'), {
runtimeCycles: ['a > b'],
typeOnlyCycles: ['c > d'],
});
});
it('leaves the type-only list empty when they are ignored', () => {
assert.deepEqual(classifyCycles(withTypes, runtime, 'ignore'), {runtimeCycles: ['a > b'], typeOnlyCycles: []});
});
});
});
@@ -0,0 +1,37 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {isExportedSubpath} from '../../../lib/analysis/exports.js';
describe('isExportedSubpath', () => {
const exportsField = {
'.': './index.js',
'./oxlint': {types: './oxlint.d.ts', import: './oxlint.js'},
'./features/*': './src/features/*.js',
'./features/internal/*': null,
'./hidden': null,
};
it('allows listed subpaths', () => {
assert.ok(isExportedSubpath(exportsField, './oxlint'));
assert.ok(isExportedSubpath(exportsField, './features/a'));
});
it('rejects unlisted, blocked and non-exported subpaths', () => {
assert.ok(!isExportedSubpath(exportsField, './lib/fs.js'));
assert.ok(!isExportedSubpath(exportsField, './hidden'));
assert.ok(!isExportedSubpath(exportsField, './features/internal/x'));
});
it('picks the most specific pattern, like Node', () => {
assert.ok(!isExportedSubpath({'./features/*': './src/*.js', './features/*.js': null}, './features/private.js'));
assert.ok(!isExportedSubpath({'./features/*.js': null, './features/*': './src/*.js'}, './features/private.js'));
assert.ok(isExportedSubpath({'./features/*': null, './features/*.js': './src/*.js'}, './features/public.js'));
});
it('treats packages without a subpath map as having only a root entry point', () => {
assert.ok(!isExportedSubpath(undefined, './oxlint'));
assert.ok(!isExportedSubpath('./index.js', './oxlint'));
assert.ok(!isExportedSubpath({import: './index.js', default: './index.cjs'}, './oxlint'));
});
});
@@ -0,0 +1,19 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {findUnresolvedImports} from '../../../lib/analysis/graph.js';
import {mod} from './modules.js';
describe('findUnresolvedImports', () => {
it('lists unresolved relative imports only', () => {
const modules = [
mod('lib/b.ts', [{module: './missing.js', couldNotResolve: true}]),
mod('lib/a.ts', [
{module: './missing.js', couldNotResolve: true},
{module: 'not-installed', couldNotResolve: true},
{module: './fine.js', resolved: 'lib/fine.ts'},
]),
];
assert.deepEqual(findUnresolvedImports(modules), ['lib/a.ts -> ./missing.js', 'lib/b.ts -> ./missing.js']);
});
});
@@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {allowedEdges, buildOwnership, parseModel} from '../../../lib/analysis/model.js';
import type {ArchitectureModel} from '../../../lib/types.js';
const model: ArchitectureModel = {
elements: {
'a.x': {id: 'a.x', kind: 'component', metadata: {paths: ['lib/x/**']}},
'a.y': {id: 'a.y', kind: 'component', metadata: {paths: 'lib/y.ts'}},
'a.t': {id: 'a.t', kind: 'component', tags: ['unenforced'], metadata: {paths: 'types/**'}},
a: {id: 'a', kind: 'container'},
},
relations: {
r1: {source: {model: 'a.x'}, target: {model: 'a.y'}},
r2: {source: {model: 'a.x'}, target: {model: 'a.t'}},
r3: {source: {model: 'a.x'}, target: {model: 'ext'}},
},
};
describe('model', () => {
it('maps files to the components that own them, enforced or not', () => {
const {ownersOf, componentIds} = buildOwnership(model);
assert.deepEqual(ownersOf('lib/x/f.ts'), ['a.x']);
assert.deepEqual(ownersOf('lib/y.ts'), ['a.y']);
assert.deepEqual(ownersOf('types/i.ts'), ['a.t']);
assert.deepEqual(ownersOf('other/i.ts'), []);
assert.deepEqual([...componentIds].sort(), ['a.x', 'a.y']);
});
it('matches globs, including `**` over zero directories and `?`', () => {
const {ownersOf} = buildOwnership({
elements: {
'a.i': {id: 'a.i', kind: 'component', metadata: {paths: 'lib/**/index.ts'}},
'a.q': {id: 'a.q', kind: 'component', metadata: {paths: 'lib/q?.ts'}},
},
relations: {},
});
assert.deepEqual(ownersOf('lib/index.ts'), ['a.i']);
assert.deepEqual(ownersOf('lib/a/b/index.ts'), ['a.i']);
assert.deepEqual(ownersOf('lib/q1.ts'), ['a.q']);
assert.deepEqual(ownersOf('lib/q.ts'), []);
});
it('keeps only edges between enforced components', () => {
const {componentIds} = buildOwnership(model);
assert.deepEqual([...allowedEdges(model, componentIds)], ['a.x -> a.y']);
});
it('rejects an unexpected export format', () => {
assert.throws(() => parseModel({}), /unexpected `likec4 export json` format/);
assert.throws(() => parseModel(null), /unexpected `likec4 export json` format/);
assert.equal(parseModel(model), model);
});
});
@@ -0,0 +1,15 @@
import type {IModule} from 'dependency-cruiser';
type DepSpec = string | {module: string; resolved?: string; couldNotResolve?: boolean};
/** Builds the part of a dependency-cruiser module that the analysis reads. */
export function mod(source: string, deps: DepSpec[] = []): IModule {
return {
source,
dependencies: deps.map((d) => {
const dep = typeof d === 'string' ? {module: d} : d;
// like dependency-cruiser, treat a bare specifier without a resolved path as not installed
return {couldNotResolve: !dep.resolved && !dep.module.startsWith('.'), resolved: dep.module, ...dep};
}),
} as unknown as IModule;
}
@@ -0,0 +1,136 @@
import assert from 'node:assert/strict';
import {mkdtemp, rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {afterEach, beforeEach, describe, it} from 'node:test';
import {
externalPackageName,
findPackageImports,
parseScopedSpecifier,
type PackageImportContext,
} from '../../../lib/analysis/package-imports.js';
import {mod} from './modules.js';
describe('parseScopedSpecifier', () => {
it('parses scoped specifiers', () => {
assert.deepEqual(parseScopedSpecifier('@appium/support', ['@appium']), {pkg: '@appium/support'});
assert.deepEqual(parseScopedSpecifier('@appium/support/lib/fs.js', ['@appium']), {
pkg: '@appium/support',
subpath: './lib/fs.js',
});
assert.equal(parseScopedSpecifier('@other/x', ['@appium']), null);
assert.equal(parseScopedSpecifier('@appium/support', []), null);
});
});
describe('externalPackageName', () => {
it('names the package behind an import specifier', () => {
assert.equal(externalPackageName('lodash'), 'lodash');
assert.equal(externalPackageName('lodash/fp.js'), 'lodash');
assert.equal(externalPackageName('@appium/support/lib/fs.js'), '@appium/support');
});
it('skips paths, `#` and `node:` imports and built-ins', () => {
for (const skipped of [
'./a.js',
'../a.js',
'/abs.js',
'#internal',
'node:fs',
'fs',
'fs/promises',
'data:text/js,1',
]) {
assert.equal(externalPackageName(skipped), null, skipped);
}
});
});
describe('findPackageImports', () => {
let packageDir: string;
beforeEach(async () => {
packageDir = await mkdtemp(path.join(tmpdir(), 'archward-pi-'));
});
afterEach(async () => {
await rm(packageDir, {recursive: true, force: true});
});
const context = (overrides: Partial<PackageImportContext> = {}): PackageImportContext => ({
packageDir,
prefix: 'lib/',
entryPointScopes: ['@scope'],
undeclaredDependencies: 'error',
declared: {name: 'me', runtime: new Set(['dep']), dev: new Set(['dev-only'])},
runtimeModules: [],
...overrides,
});
const keys = async (modules: ReturnType<typeof mod>[], ctx = context()) =>
(await findPackageImports(modules, ctx)).map((f) => f.key);
it('accepts declared packages, built-ins, the package itself and aliases into the source root', async () => {
const modules = [
mod('lib/a.ts', ['dep', 'dep/sub.js', 'node:fs', 'path', 'me', './x.js', {module: '@/x', resolved: 'lib/x.ts'}]),
];
assert.deepEqual(await keys(modules, context({runtimeModules: modules})), []);
});
it('exempts tsconfig aliases that resolve to files of the package, wherever they point', async () => {
const modules = [
mod('lib/a.ts', [
{module: '@shared/models', resolved: 'types/models.ts'},
{module: '@/x', resolved: 'lib/x.ts'},
]),
];
assert.deepEqual(await keys(modules, context({runtimeModules: modules})), []);
});
it('still checks packages that resolve into node_modules or to linked workspace packages', async () => {
const modules = [
mod('lib/a.ts', [
{module: 'a', resolved: 'node_modules/a/index.js'},
{module: 'b', resolved: '../../node_modules/b/index.js'},
{module: 'c', resolved: '../c/build/lib/index.js'},
{module: 'd', resolved: 'd', couldNotResolve: true},
]),
];
assert.deepEqual(await keys(modules, context({runtimeModules: modules})), [
'lib/a.ts -> a',
'lib/a.ts -> b',
'lib/a.ts -> c',
'lib/a.ts -> d',
]);
});
it('reports undeclared packages', async () => {
const modules = [mod('lib/a.ts', ['lodash', '@scope/x'])];
assert.deepEqual(await keys(modules, context({runtimeModules: modules})), [
'lib/a.ts -> @scope/x',
'lib/a.ts -> lodash',
]);
});
it('accepts a devDependency for type-only imports only', async () => {
const typeOnly = [mod('lib/a.ts', ['dev-only'])];
assert.deepEqual(await keys(typeOnly), []);
assert.deepEqual(await keys(typeOnly, context({runtimeModules: typeOnly})), ['lib/a.ts -> dev-only']);
});
it('reports deep imports of scoped packages that are not exported', async () => {
const modules = [mod('lib/a.ts', ['@scope/dep/lib/x.js'])];
const ctx = context({runtimeModules: modules, declared: {runtime: new Set(['@scope/dep']), dev: new Set()}});
assert.deepEqual(await keys(modules, ctx), ['lib/a.ts -> @scope/dep/lib/x.js']);
});
it('checks only scoped packages unless asked for more', async () => {
const modules = [mod('lib/a.ts', ['lodash', '@scope/x'])];
const ctx = context({runtimeModules: modules, undeclaredDependencies: 'ignore'});
assert.deepEqual(await keys(modules, ctx), ['lib/a.ts -> @scope/x']);
});
it('ignores files outside the source root', async () => {
assert.deepEqual(await keys([mod('../other/a.ts', ['lodash'])]), []);
});
});
@@ -0,0 +1,14 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {diffAgainstBaseline} from '../../lib/baseline.js';
describe('diffAgainstBaseline', () => {
it('splits keys into new and stale', () => {
assert.deepEqual(diffAgainstBaseline(['a', 'b'], ['b', 'c']), {added: ['a'], stale: ['c']});
});
it('sorts both lists', () => {
assert.deepEqual(diffAgainstBaseline(['z', 'y'], ['x', 'w']), {added: ['y', 'z'], stale: ['w', 'x']});
});
});
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {normalizeSourceRoot, parseConfig} from '../../lib/config.js';
describe('parseConfig', () => {
it('accepts valid options', () => {
const config = {
sourceRoot: 'src',
tsconfig: 't.json',
entryPointScopes: ['@a'],
typeOnlyCycles: 'ignore',
undeclaredDependencies: 'error',
};
assert.deepEqual(parseConfig(config, 'config.json'), config);
assert.deepEqual(parseConfig({}, 'config.json'), {});
});
it('rejects unknown options and bad values', () => {
assert.throws(() => parseConfig({sourceroot: 'src'}, 'config.json'), /unknown option 'sourceroot'/);
assert.throws(() => parseConfig({sourceRoot: 1}, 'config.json'), /'sourceRoot' must be a string/);
assert.throws(() => parseConfig({entryPointScopes: '@a'}, 'config.json'), /array of strings/);
assert.throws(
() => parseConfig({typeOnlyCycles: 'warn'}, 'config.json'),
/'typeOnlyCycles' must be 'error' or 'ignore'/,
);
assert.throws(() => parseConfig({undeclaredDependencies: true}, 'config.json'), /'undeclaredDependencies' must be/);
assert.throws(() => parseConfig([], 'config.json'), /expected a JSON object/);
});
});
describe('normalizeSourceRoot', () => {
it('normalizes to a package-relative, slash-separated path', () => {
for (const input of ['src', './src', 'src/', './src/', 'src\\\\', 'a/../src']) {
assert.equal(normalizeSourceRoot(input), 'src', input);
}
assert.equal(normalizeSourceRoot('.\\\\packages\\\\x'), 'packages/x');
});
it('rejects paths outside the package', () => {
for (const input of ['.', '..', '../src', '/abs', '']) {
assert.throws(() => normalizeSourceRoot(input), /subdirectory of the package/, input);
}
});
});
@@ -0,0 +1,69 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {deriveComponents, deriveEdges} from '../../../lib/init/derive.js';
import {renderModel} from '../../../lib/init/render.js';
describe('init', () => {
const files = [
'lib/driver.ts',
'lib/utils.ts',
'lib/utils/hash.ts',
'lib/web-execution/a.ts',
'lib/2fa/b.ts',
'lib/title/c.ts',
];
const components = deriveComponents(files, 'lib');
it('derives one component per top-level directory and per root file', () => {
assert.deepEqual(
components.map((c) => [c.id, c.paths]),
[
['c2fa', 'lib/2fa/**'],
['title_', 'lib/title/**'],
['utils', 'lib/utils/**'],
['web-execution', 'lib/web-execution/**'],
['driver', 'lib/driver.ts'],
['utils_file', 'lib/utils.ts'],
],
);
});
it('derives the dependencies between components', () => {
const edges = deriveEdges(
[
['lib/driver.ts', 'lib/utils/hash.ts'],
['lib/driver.ts', 'lib/utils.ts'],
['lib/utils/hash.ts', 'lib/utils/hash.ts'],
['lib/web-execution/a.ts', 'lib/driver.ts'],
],
components,
);
assert.deepEqual(edges, ['driver -> utils', 'driver -> utils_file', 'web-execution -> driver']);
});
it('escapes glob metacharacters so that components own only their own files', () => {
const odd = deriveComponents(['src/[id].ts', 'src/i.ts', 'src/(group)/a.ts', 'src/group/b.ts'], 'src');
assert.deepEqual(
odd.map((c) => c.paths),
['src/\\(group\\)/**', 'src/group/**', 'src/\\[id\\].ts', 'src/i.ts'],
);
assert.deepEqual(
deriveEdges(
[
['src/i.ts', 'src/[id].ts'],
['src/group/b.ts', 'src/(group)/a.ts'],
],
odd,
),
['group -> c_group_', 'i -> c_id_'].sort(),
);
});
it('renders the model', () => {
const {model, spec} = renderModel('@scope/pkg', components.slice(0, 1), []);
assert.match(spec, /tag unenforced/);
assert.match(model, /scope-pkg = container '@scope\/pkg'/);
assert.match(model, /metadata \{ paths 'lib\/2fa\/\*\*' \}/);
});
});
@@ -0,0 +1,57 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {formatReport} from '../../lib/report.js';
import type {CheckResult, Finding} from '../../lib/types.js';
const emptyAnalysis = {
unownedFiles: [],
packageImports: [],
boundaries: [],
unresolvedImports: [],
runtimeCycles: [],
typeOnlyCycles: [],
unusedEdges: [],
};
function result(findings: Finding[], warnings: string[] = []): CheckResult {
return {
ok: findings.length === 0,
findings,
warnings,
analysis: emptyAnalysis,
baselined: {boundaries: 1, runtimeCycles: 2, typeOnlyCycles: 3},
};
}
const boundary = (key: string, status: Finding['status'] = 'new'): Finding => ({
rule: 'boundary',
status,
key,
message: key,
});
describe('formatReport', () => {
it('summarizes an ok result with warnings', () => {
const text = formatReport(result([], ['unused']));
assert.match(text, /^warning: unused/);
assert.match(text, /Architecture OK \(baselined: 1 boundary imports, 2 runtime cycles, 3 type-only cycles\)/);
});
it('truncates new findings unless verbose', () => {
const findings = Array.from({length: 8}, (_, i) => boundary(`a${i} -> b${i}`));
assert.match(formatReport(result(findings)), /and 3 more/);
assert.doesNotMatch(formatReport(result(findings), {verbose: true}), /more/);
});
it('truncates stale entries too', () => {
const findings = Array.from({length: 8}, (_, i) => boundary(`a${i} -> b${i}`, 'stale'));
assert.match(formatReport(result(findings)), /and 3 more STALE/);
});
it('reports stale entries without the fix hint', () => {
const text = formatReport(result([boundary('a -> b', 'stale')]));
assert.match(text, /STALE {2}a -> b/);
assert.doesNotMatch(text, /->\s+Remove the import/);
});
});
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import {mkdir, mkdtemp, rm, writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {afterEach, beforeEach, describe, it} from 'node:test';
import {findWorkspacePackages} from '../../lib/workspaces.js';
describe('findWorkspacePackages', () => {
let root: string;
beforeEach(async () => {
root = await mkdtemp(path.join(tmpdir(), 'archward-ws-'));
});
afterEach(async () => {
await rm(root, {recursive: true, force: true});
});
async function pkg(dir: string, model = true) {
await mkdir(path.join(root, dir, model ? 'architecture' : ''), {recursive: true});
if (model) {
await writeFile(path.join(root, dir, 'architecture/model.c4'), 'model {}\n');
}
}
it('lists workspace packages that have a model', async () => {
await writeFile(path.join(root, 'package.json'), JSON.stringify({workspaces: ['packages/*', '!packages/skip']}));
await pkg('packages/a');
await pkg('packages/b', false);
await pkg('packages/skip');
await pkg('other');
assert.deepEqual(await findWorkspacePackages(root), [path.join(root, 'packages/a')]);
});
it('supports the object form and nested patterns', async () => {
await writeFile(path.join(root, 'package.json'), JSON.stringify({workspaces: {packages: ['apps/*/web']}}));
await pkg('apps/x/web');
assert.deepEqual(await findWorkspacePackages(root), [path.join(root, 'apps/x/web')]);
});
it('rejects roots without workspaces and unsupported patterns', async () => {
await writeFile(path.join(root, 'package.json'), '{}');
await assert.rejects(findWorkspacePackages(root), /declares no workspaces/);
await writeFile(path.join(root, 'package.json'), JSON.stringify({workspaces: ['packages/**']}));
await assert.rejects(findWorkspacePackages(root), /only '\*' wildcards/);
});
});
+14
View File
@@ -0,0 +1,14 @@
{
"extends": "@appium/tsconfig/tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "build",
"strict": true,
"checkJs": true,
"module": "NodeNext",
"moduleResolution": "NodeNext",
"types": ["node"]
},
"include": ["lib", "test/unit", "test/e2e"],
"exclude": ["build"]
}
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [11.0.2](https://github.com/appium/appium/compare/@appium/base-driver@11.0.1...@appium/base-driver@11.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/base-driver
## [11.0.1](https://github.com/appium/appium/compare/@appium/base-driver@11.0.0...@appium/base-driver@11.0.1) (2026-11-23)
### Bug Fixes
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/base-driver",
"version": "11.0.1",
"version": "11.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Base driver class for Appium drivers",
"keywords": [
@@ -53,8 +53,8 @@
"test:types": "tsd"
},
"dependencies": {
"@appium/support": "~8.0.1",
"@appium/types": "~2.0.0",
"@appium/support": "~8.0.2",
"@appium/types": "~3.0.0",
"asyncbox": "^7.0.0",
"axios": "^1.20.0",
"lru-cache": "^11.5.2",
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.0.2](https://github.com/appium/appium/compare/@appium/base-plugin@4.0.1...@appium/base-plugin@4.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/base-plugin
## [4.0.1](https://github.com/appium/appium/compare/@appium/base-plugin@4.0.0...@appium/base-plugin@4.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/base-plugin
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/base-plugin",
"version": "4.0.1",
"version": "4.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "The base plugin used to create Appium plugins",
"keywords": [
@@ -52,9 +52,9 @@
"test:unit": "node --test --experimental-test-module-mocks --test-concurrency=1 --enable-source-maps \"./build/test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/base-driver": "~11.0.1",
"@appium/support": "~8.0.1",
"@appium/types": "~2.0.0"
"@appium/base-driver": "~11.0.2",
"@appium/support": "~8.0.2",
"@appium/types": "~3.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0",
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.0.2](https://github.com/appium/appium/compare/@appium/docutils@4.0.1...@appium/docutils@4.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/docutils
## [4.0.1](https://github.com/appium/appium/compare/@appium/docutils@4.0.0...@appium/docutils@4.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/docutils
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/docutils",
"version": "4.0.1",
"version": "4.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Documentation generation utilities for Appium and related projects",
"keywords": [
@@ -58,7 +58,7 @@
"start": "node ./build/lib/cli/index.js"
},
"dependencies": {
"@appium/support": "~8.0.1",
"@appium/support": "~8.0.2",
"consola": "^3.4.2",
"diff": "^9.0.0",
"lilconfig": "^3.1.3",
@@ -69,7 +69,7 @@
"yargs-parser": "^22.0.0"
},
"devDependencies": {
"@appium/types": "~2.0.0"
"@appium/types": "~3.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0",
+1 -1
View File
@@ -1,5 +1,5 @@
mkdocs==1.6.1
mkdocs-git-revision-date-localized-plugin==1.7.0
mkdocs-git-revision-date-localized-plugin==1.7.1
mkdocs-material==9.8.2
mkdocs-redirects==1.2.3
mike==2.2.0
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.0.2](https://github.com/appium/appium/compare/@appium/driver-test-support@4.0.1...@appium/driver-test-support@4.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/driver-test-support
## [4.0.1](https://github.com/appium/appium/compare/@appium/driver-test-support@4.0.0...@appium/driver-test-support@4.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/driver-test-support
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/driver-test-support",
"version": "4.0.1",
"version": "4.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Test utilities for Appium drivers",
"keywords": [
@@ -53,11 +53,11 @@
"test:unit": "node --test --enable-source-maps \"./build/test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/support": "~8.0.1",
"@appium/support": "~8.0.2",
"asyncbox": "^7.0.0"
},
"devDependencies": {
"@appium/types": "~2.0.0"
"@appium/types": "~3.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0",
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [9.0.1](https://github.com/appium/appium/compare/@appium/execute-driver-plugin@9.0.0...@appium/execute-driver-plugin@9.0.1) (2026-11-27)
**Note:** Version bump only for package @appium/execute-driver-plugin
## [9.0.0](https://github.com/appium/appium/compare/@appium/execute-driver-plugin@8.0.0...@appium/execute-driver-plugin@9.0.0) (2026-11-23)
### ⚠ BREAKING CHANGES
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/execute-driver-plugin",
"version": "9.0.0",
"version": "9.0.1",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Plugin for batching and executing Appium driver commands",
"keywords": [
@@ -49,11 +49,11 @@
"test:e2e": "node --test --enable-source-maps --test-force-exit --test-concurrency=1 --test-timeout=60000 \"./build/test/e2e/**/*.spec.js\""
},
"dependencies": {
"@appium/support": "8.0.1",
"@appium/support": "8.0.2",
"webdriverio": "10.2.0"
},
"devDependencies": {
"@appium/types": "2.0.0"
"@appium/types": "3.0.0"
},
"peerDependencies": {
"appium": "^4.0.0-beta.0"
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [7.0.2](https://github.com/appium/appium/compare/@appium/fake-driver@7.0.1...@appium/fake-driver@7.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/fake-driver
## [7.0.1](https://github.com/appium/appium/compare/@appium/fake-driver@7.0.0...@appium/fake-driver@7.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/fake-driver
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/fake-driver",
"version": "7.0.1",
"version": "7.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Mock driver used internally by Appium for testing. Ignore",
"keywords": [
@@ -47,15 +47,15 @@
"test:unit": "node --test --enable-source-maps --test-timeout=10000 \"./build/test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/http-server": "1.0.1",
"@appium/http-server": "1.0.2",
"@xmldom/xmldom": "0.9.12",
"asyncbox": "7.1.0",
"xpath": "0.0.36",
"xpath": "0.1.0",
"yocto-spinner": "1.2.2"
},
"devDependencies": {
"@appium/driver-test-support": "4.0.1",
"@appium/types": "2.0.0",
"@appium/driver-test-support": "4.0.2",
"@appium/types": "3.0.0",
"@types/express": "5.0.6"
},
"peerDependencies": {
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [5.0.2](https://github.com/appium/appium/compare/@appium/fake-plugin@5.0.1...@appium/fake-plugin@5.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/fake-plugin
## [5.0.1](https://github.com/appium/appium/compare/@appium/fake-plugin@5.0.0...@appium/fake-plugin@5.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/fake-plugin
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/fake-plugin",
"version": "5.0.1",
"version": "5.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "A fake Appium plugin",
"keywords": [
@@ -44,12 +44,12 @@
"test:unit": "node --test --enable-source-maps --test-timeout=5000 \"./build/test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/base-plugin": "4.0.1",
"@appium/support": "8.0.1",
"@appium/base-plugin": "4.0.2",
"@appium/support": "8.0.2",
"asyncbox": "7.1.0"
},
"devDependencies": {
"@appium/types": "2.0.0",
"@appium/types": "3.0.0",
"@types/express": "5.0.6"
},
"peerDependencies": {
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.0.2](https://github.com/appium/appium/compare/@appium/http-server@1.0.1...@appium/http-server@1.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/http-server
## [1.0.1](https://github.com/appium/appium/compare/@appium/http-server@1.0.0...@appium/http-server@1.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/http-server
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/http-server",
"version": "1.0.1",
"version": "1.0.2",
"description": "The HTTP server that fronts an Appium driver's command protocol",
"keywords": [
"android",
@@ -51,9 +51,9 @@
"test:unit": "node --test --experimental-test-module-mocks --test-concurrency=1 --enable-source-maps --test-timeout=10000 \"./build/test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/base-driver": "~11.0.1",
"@appium/support": "~8.0.1",
"@appium/types": "~2.0.0",
"@appium/base-driver": "~11.0.2",
"@appium/support": "~8.0.2",
"@appium/types": "~3.0.0",
"@types/express": "^5.0.6",
"body-parser": "^2.4.0",
"express": "^5.2.1",
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.2](https://github.com/appium/appium/compare/@appium/images-plugin@6.0.1...@appium/images-plugin@6.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/images-plugin
## [6.0.1](https://github.com/appium/appium/compare/@appium/images-plugin@6.0.0...@appium/images-plugin@6.0.1) (2026-11-23)
### Bug Fixes
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/images-plugin",
"version": "6.0.1",
"version": "6.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Plugin for working with images and image elements in Appium",
"keywords": [
@@ -50,14 +50,14 @@
"test:e2e": "node --test --enable-source-maps --test-force-exit --test-concurrency=1 --test-timeout=20000 \"./build/test/e2e/**/*.spec.js\""
},
"dependencies": {
"@appium/opencv": "6.0.0",
"@appium/support": "8.0.1",
"@appium/opencv": "6.0.1",
"@appium/support": "8.0.2",
"asyncbox": "7.1.0",
"lru-cache": "11.5.3",
"sharp": "0.35.5"
},
"devDependencies": {
"@appium/types": "2.0.0"
"@appium/types": "3.0.0"
},
"peerDependencies": {
"appium": "^4.0.0-beta.0"
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.1](https://github.com/appium/appium/compare/@appium/opencv@6.0.0...@appium/opencv@6.0.1) (2026-11-27)
**Note:** Version bump only for package @appium/opencv
## [6.0.0](https://github.com/appium/appium/compare/@appium/opencv@5.0.2...@appium/opencv@6.0.0) (2026-11-15)
### ⚠ BREAKING CHANGES
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/opencv",
"version": "6.0.0",
"version": "6.0.1",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "OpenCV-related helper library",
"keywords": [
@@ -56,7 +56,7 @@
"sharp": "^0.35.5"
},
"devDependencies": {
"@appium/types": "~2.0.0"
"@appium/types": "~3.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0",
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.0.2](https://github.com/appium/appium/compare/@appium/plugin-test-support@4.0.1...@appium/plugin-test-support@4.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/plugin-test-support
## [4.0.1](https://github.com/appium/appium/compare/@appium/plugin-test-support@4.0.0...@appium/plugin-test-support@4.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/plugin-test-support
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/plugin-test-support",
"version": "4.0.1",
"version": "4.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Testing utilities for Appium plugins",
"keywords": [
@@ -55,7 +55,7 @@
"teen_process": "^5.0.0"
},
"devDependencies": {
"@appium/types": "~2.0.0"
"@appium/types": "~3.0.0"
},
"peerDependencies": {
"appium": "^4.0.0-beta.0"
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.0.1](https://github.com/appium/appium/compare/@appium/relaxed-caps-plugin@4.0.0...@appium/relaxed-caps-plugin@4.0.1) (2026-11-27)
**Note:** Version bump only for package @appium/relaxed-caps-plugin
## [4.0.0](https://github.com/appium/appium/compare/@appium/relaxed-caps-plugin@3.0.2...@appium/relaxed-caps-plugin@4.0.0) (2026-11-15)
### ⚠ BREAKING CHANGES
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/relaxed-caps-plugin",
"version": "4.0.0",
"version": "4.0.1",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "An Appium plugin that loosens requirements for vendor prefixes on caps",
"keywords": [
@@ -52,7 +52,7 @@
},
"dependencies": {},
"devDependencies": {
"@appium/types": "2.0.0"
"@appium/types": "3.0.0"
},
"peerDependencies": {
"appium": "^4.0.0-beta.0"
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [3.0.2](https://github.com/appium/appium/compare/@appium/storage-plugin@3.0.1...@appium/storage-plugin@3.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/storage-plugin
## [3.0.1](https://github.com/appium/appium/compare/@appium/storage-plugin@3.0.0...@appium/storage-plugin@3.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/storage-plugin
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/storage-plugin",
"version": "3.0.1",
"version": "3.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Server-side storage plugin for Appium",
"keywords": [
@@ -52,13 +52,13 @@
"test:e2e": "node --test --enable-source-maps --test-force-exit --test-concurrency=1 --test-timeout=20000 \"./build/test/e2e/**/*.spec.js\""
},
"dependencies": {
"@appium/support": "8.0.1",
"@appium/support": "8.0.2",
"asyncbox": "7.1.0",
"lru-cache": "11.5.3",
"ws": "8.23.0"
},
"devDependencies": {
"@appium/types": "2.0.0"
"@appium/types": "3.0.0"
},
"peerDependencies": {
"appium": "^4.0.0"
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [8.0.2](https://github.com/appium/appium/compare/@appium/support@8.0.1...@appium/support@8.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/support
## [8.0.1](https://github.com/appium/appium/compare/@appium/support@8.0.0...@appium/support@8.0.1) (2026-11-23)
### Bug Fixes
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/support",
"version": "8.0.1",
"version": "8.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Support libs used across Appium packages",
"keywords": [
@@ -53,7 +53,7 @@
},
"dependencies": {
"@appium/logger": "~3.0.0",
"@appium/types": "~2.0.0",
"@appium/types": "~3.0.0",
"archiver": "^8.0.0",
"asyncbox": "^7.0.0",
"axios": "^1.20.0",
+11
View File
@@ -3,6 +3,17 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [3.0.0](https://github.com/appium/appium/compare/@appium/types@2.0.0...@appium/types@3.0.0) (2026-11-27)
### ⚠ BREAKING CHANGES
* **types:** MethodMap, DriverMethodMap, PluginMethodMap, DriverMethodDef, and PluginMethodDef now validate command names and payloadParams against driver and plugin command signatures by default. Pass MethodMap&lt;T, false&gt; or DriverMethodDef&lt;T, true&gt; / PluginMethodDef&lt;T, true&gt; for proxied or handle()-dispatched routes.
### Features
* **types:** check method map payload params against command signatures ([#23158](https://github.com/appium/appium/issues/23158)) ([df431dd](https://github.com/appium/appium/commit/df431dd2719d55e29fdf504947282e6f972cae69))
## [2.0.0](https://github.com/appium/appium/compare/@appium/types@1.7.2...@appium/types@2.0.0) (2026-11-15)
### ⚠ BREAKING CHANGES
+316 -112
View File
@@ -1,4 +1,4 @@
import type {Driver, DriverCommand} from './driver.js';
import type {Driver, DriverCommand, ExternalDriver} from './driver.js';
import type {Plugin, PluginCommand} from './plugin.js';
import type {ConditionalPick, IsAny, IsNever, MultidimensionalReadonlyArray, StringRecord} from './util.js';
@@ -18,31 +18,33 @@ export interface PayloadParams {
*
* Extensions can define new methods for the Appium server to map to command names, of the same
* format as used in Appium's `routes.js`.
* Pass `true` as `Loose` to opt out of checking `command` and `payloadParams`; annotate with `MethodMap<MyDriver>` or use `as const satisfies MethodMap<MyDriver>` to preserve literals and tuple lengths (`makeArgs` skips positional-count checks when the command accepts arguments).
* Note: Because route keys are typed as `string`, trailing `string` parameters on a command are always treated as potentially supplied by URL `:param` segments, so omitting them from `payloadParams` is allowed even on routes without a matching `:param`.
*
* @example
* ```js
* ```ts
* {
* '/session/:sessionId/new_method': {
* GET: {command: 'getNewThing'},
* POST: {command: 'setNewThing', payloadParams: {required: ['someParam']}}
* }
* }
* } as const satisfies MethodMap<MyDriver>
* ```
*/
export type MethodMap<T extends Plugin | Driver> = T extends Plugin
? Readonly<PluginMethodMap<T>>
export type MethodMap<T extends Plugin | Driver, Loose extends boolean = false> = T extends Plugin
? Readonly<PluginMethodMap<T, Loose>>
: T extends Driver
? Readonly<DriverMethodMap<T>>
? Readonly<DriverMethodMap<T, Loose>>
: never;
/**
* A {@linkcode MethodMap} for a {@linkcode Driver}.
*/
export interface DriverMethodMap<T extends Driver> {
export interface DriverMethodMap<T extends Driver, Loose extends boolean = false> {
[key: string]: {
GET?: DriverMethodDef<T>;
POST?: DriverMethodDef<T>;
DELETE?: DriverMethodDef<T>;
GET?: DriverMethodDef<T, Loose>;
POST?: DriverMethodDef<T, Loose>;
DELETE?: DriverMethodDef<T, Loose>;
};
}
@@ -68,34 +70,310 @@ export interface BaseMethodDef {
readonly info?: string;
}
type IsEqual<A, B> = (<G>() => G extends A ? 1 : 2) extends <G>() => G extends B ? 1 : 2 ? true : false;
type IsPureRestArray<P extends readonly unknown[]> = P extends P
? IsAny<P> extends true
? true
: number extends P['length']
? [] extends P
? [undefined] extends P
? IsEqual<P, P[number][]> extends true
? true
: IsEqual<P, readonly P[number][]>
: true
: false
: false
: never;
type CanAcceptUndefined<T> = [undefined] extends [T] ? true : false;
type IsTopType<T> = unknown extends T ? true : false;
type CanOmitWithUrl<T, AllowUrlString extends boolean> = AllowUrlString extends true
? true extends IsTopType<T>
? true
: [string] extends [T]
? true
: false
: false;
type CanOmitTrailing<P extends readonly unknown[], AllowUrlString extends boolean> = P extends readonly []
? true
: IsPureRestArray<P> extends true
? true
: P extends readonly [infer H, ...infer T]
? IsTopType<H> extends true
? CanOmitTrailing<T, AllowUrlString>
: CanAcceptUndefined<H> extends true
? CanOmitTrailing<T, false>
: AllowUrlString extends true
? [string] extends [H]
? CanOmitTrailing<T, true>
: false
: false
: [] extends P
? P extends readonly [(infer _)?, ...infer T]
? CanOmitTrailing<T, false>
: false
: P extends readonly [...infer Head, infer Last]
? true extends CanOmitWithUrl<Last, AllowUrlString>
? CanOmitTrailing<Head, true>
: false
: false;
type ParamOptionalTag =
| {readonly kind: 'exact'; readonly tuple: readonly string[]}
| {readonly kind: 'rest'; readonly min: readonly string[]};
type ParamSplit = {
readonly r: readonly string[];
readonly o: ParamOptionalTag;
};
/** Collects optional tails by shifting nullable/optional args into `[...OAcc, string]` (`undefined` when omitted); `AllowUrlString` permits trailing `string` URL params before any omitted arg. */
type CollectOptionalSplits<
CurP extends readonly unknown[],
AllowUrlString extends boolean,
RAcc extends string[],
OAcc extends string[] = [],
AllowOptional extends boolean = true,
> = CurP extends readonly unknown[]
? | (IsPureRestArray<CurP> extends true
? {
readonly r: Readonly<OAcc extends [] ? [...RAcc, ...string[]] : RAcc>;
readonly o: AllowOptional extends true
? CanAcceptUndefined<CurP[number]> extends true
? {readonly kind: 'rest'; readonly min: Readonly<OAcc>}
: {readonly kind: 'exact'; readonly tuple: Readonly<OAcc>}
: {readonly kind: 'exact'; readonly tuple: Readonly<OAcc>};
}
: CanOmitTrailing<CurP, AllowUrlString> extends true
? {readonly r: Readonly<RAcc>; readonly o: {readonly kind: 'exact'; readonly tuple: Readonly<OAcc>}}
: never)
| (AllowOptional extends false
? never
: CurP extends readonly []
? never
: IsPureRestArray<CurP> extends true
? never
: CurP extends readonly [infer H, ...infer T]
? CanAcceptUndefined<H> extends true
? CollectOptionalSplits<T, AllowUrlString, RAcc, [...OAcc, string], AllowOptional>
: never
: [] extends CurP
? CurP extends readonly [(infer _)?, ...infer T]
? CollectOptionalSplits<T, AllowUrlString, RAcc, [...OAcc, string], AllowOptional>
: never
: never)
: never;
/** Enumerates `(r, o)` splits across `CurP` (`AllowUrlString`: `true` for REST URL `:param`s, `false` for execute). */
type CollectParamSplits<
CurP extends readonly unknown[],
AllowUrlString extends boolean,
RAcc extends string[] = [],
AllowOptional extends boolean = true,
> = CurP extends readonly unknown[]
? | CollectOptionalSplits<CurP, AllowUrlString, RAcc, [], AllowOptional>
| (CurP extends readonly []
? never
: IsPureRestArray<CurP> extends true
? never
: CurP extends readonly [infer _, ...infer T]
? CollectParamSplits<T, AllowUrlString, [...RAcc, string], AllowOptional>
: [] extends CurP
? CurP extends readonly [(infer _)?, ...infer T]
? CollectParamSplits<T, AllowUrlString, [...RAcc, string], AllowOptional>
: never
: CurP extends readonly [...infer Head, infer Last]
? | (CanOmitWithUrl<Last, AllowUrlString> extends true
? CollectParamSplits<Head, true, RAcc, AllowOptional>
: never)
| CollectParamSplits<
Head,
false,
[...RAcc, string],
CanAcceptUndefined<Last> extends true ? AllowOptional : false
>
: never)
: never;
type NonEmptyStringTuple<R extends readonly string[]> = Exclude<R, readonly []>;
type RequiredParamProp<R extends readonly string[], Nested extends boolean> = readonly [] extends R
? {
required?:
| R
| (Nested extends true
? IsNever<NonEmptyStringTuple<R>> extends true
? never
: readonly [NonEmptyStringTuple<R>, ...NonEmptyStringTuple<R>[]]
: string[]);
}
: {required: R | (Nested extends true ? readonly [R, ...R[]] : string[])};
type OptionalParamProp<O extends ParamOptionalTag, AllowMutable extends boolean> = O extends {
readonly kind: 'rest';
readonly min: infer Min extends readonly string[];
}
? Min extends readonly []
? {optional?: readonly string[]}
: {optional: Readonly<[...Min, ...string[]]> | (AllowMutable extends true ? string[] : never)}
: O extends {readonly kind: 'exact'; readonly tuple: infer Tuple extends readonly string[]}
? Tuple extends readonly []
? {optional?: readonly [] | (AllowMutable extends true ? string[] : never)}
: {optional: Readonly<Tuple> | (AllowMutable extends true ? string[] : never)}
: never;
/** Groups `Splits` by `o` so valid `required` shapes form one union per `optional` rule (`Nested` is `true` for REST `payloadParams`, `false` for execute `params`). */
type BuildParamShapes<
Splits,
Nested extends boolean,
OKey = Splits extends ParamSplit ? Splits['o'] : never,
> = OKey extends ParamOptionalTag
? Extract<Splits, {readonly o: OKey}> extends infer Matched extends ParamSplit
? RequiredParamProp<Matched['r'], Nested> & OptionalParamProp<OKey, Nested extends true ? false : true>
: never
: never;
/** REST `payloadParams` shapes for `P`: runtime passes `required` first, then `optional` (`undefined` if omitted), then URL `:param` strings. */
type PayloadParamsFor<P extends readonly unknown[]> = BuildParamShapes<
P extends readonly unknown[] ? CollectParamSplits<P, true> : never,
true
>;
type HasPositionalParams<P extends readonly unknown[]> = P extends readonly [] ? false : true;
type MakeArgsFn<Ret extends readonly unknown[] = readonly unknown[]> = (
...args: Parameters<NonNullable<PayloadParams['makeArgs']>>
) => Ret;
type PayloadParamsConstraint<P extends readonly unknown[]> = PayloadParams &
(
| (PayloadParamsFor<P> & {
makeArgs?: MakeArgsFn<true extends HasPositionalParams<P> ? readonly unknown[] : readonly never[]>;
})
| (true extends HasPositionalParams<P> ? {makeArgs: MakeArgsFn} : never)
);
type PayloadParamsProp<P extends readonly unknown[]> =
true extends CanOmitTrailing<P, true>
? {[Q in keyof Pick<BaseMethodDef, 'payloadParams'>]?: PayloadParamsConstraint<P>}
: {[Q in keyof Pick<BaseMethodDef, 'payloadParams'>]-?: PayloadParamsConstraint<P>};
/** Checks up to the last 5 overload signatures (`P1`-`P5`); earlier overloads on 6+ signature methods are dropped (`Loose = true` opts out), and a public catch-all `(...args: unknown[] | any[])` overload permits any param count. */
type OverloadParams<F> =
IsAny<F> extends true
? any[]
: F extends {
(...args: infer P1 extends readonly unknown[]): any;
(...args: infer P2 extends readonly unknown[]): any;
(...args: infer P3 extends readonly unknown[]): any;
(...args: infer P4 extends readonly unknown[]): any;
(...args: infer P5 extends readonly unknown[]): any;
}
? P1 | P2 | P3 | P4 | P5
: never;
type StripPluginPrefix<P extends readonly unknown[]> = P extends readonly unknown[]
? ((...args: P) => any) extends (next: any, driver: any, ...args: infer Rest extends readonly unknown[]) => any
? Rest
: never
: never;
type PluginCommandParams<F> = StripPluginPrefix<OverloadParams<F>>;
type CommandProp<K> = {
/** Name of the command. */
readonly command: K;
};
type LooseMethodDef = BaseMethodDef & {
/** Name of the command. */
readonly command?: string;
};
type CheckedMethodDef<Commands, Kind extends 'driver' | 'plugin'> =
IsNever<Commands> extends true
? LooseMethodDef
: IsNever<keyof Commands> extends true
? LooseMethodDef
: [string] extends [keyof Commands]
? LooseMethodDef
: | (BaseMethodDef & Partial<CommandProp<never>>)
| {
[K in keyof Commands]: Omit<BaseMethodDef, 'payloadParams'> &
CommandProp<K> &
PayloadParamsProp<
Kind extends 'driver' ? OverloadParams<Commands[K]> : PluginCommandParams<Commands[K]>
>;
}[keyof Commands];
type IsExactDriver<T> =
T extends Driver<infer C, infer CArgs, infer Settings, infer CR, infer DR>
? true extends IsEqual<T, Driver<C, CArgs, Settings, CR, DR>>
? true
: IsEqual<T, Driver & Driver<C, CArgs, Settings, CR, DR>>
: false;
type IsExactExternalDriver<T> =
T extends ExternalDriver<infer C, infer Ctx, infer CArgs, infer Settings, infer CR, infer DR>
? true extends IsEqual<T, ExternalDriver<C, Ctx, CArgs, Settings, CR, DR>>
? true
: IsEqual<T, Driver & ExternalDriver<C, Ctx, CArgs, Settings, CR, DR>>
: false;
type IsExactBaseDriver<T> = T extends unknown
? true extends IsExactDriver<T>
? true
: IsExactExternalDriver<T>
: never;
type IsLooseDriverCheck<T, Loose extends boolean> = [true] extends [Loose]
? true
: IsAny<T> extends true
? true
: IsNever<T> extends true
? false
: IsExactBaseDriver<T> extends true
? true
: false;
type IsLoosePluginCheck<T, Loose extends boolean> = [true] extends [Loose]
? true
: IsAny<T> extends true
? true
: IsNever<T> extends true
? false
: IsEqual<T, Plugin>;
/**
* A definition of an exposed API command in a {@linkcode Driver}.
* Validates `command` and `payloadParams` by default; `Loose = true` opts out.
*/
export interface DriverMethodDef<T extends Driver, D extends boolean = boolean> extends BaseMethodDef {
/**
* Name of the command.
*/
readonly command?: D extends true ? string : keyof ConditionalPick<Required<T>, DriverCommand>;
}
export type DriverMethodDef<T extends Driver, Loose extends boolean = false> = LooseMethodDef &
(IsLooseDriverCheck<T, Loose> extends true
? unknown
: CheckedMethodDef<ConditionalPick<Required<T>, DriverCommand>, 'driver'>);
/**
* A definition of an exposed API command in a {@linkcode Plugin}.
* Validates `command` and `payloadParams` by default; `Loose = true` opts out.
*/
export interface PluginMethodDef<T extends Plugin> extends BaseMethodDef {
/**
* Name of the command.
*/
readonly command?: keyof ConditionalPick<Required<T>, PluginCommand>;
}
export type PluginMethodDef<T extends Plugin, Loose extends boolean = false> = LooseMethodDef &
(IsLoosePluginCheck<T, Loose> extends true
? unknown
: CheckedMethodDef<ConditionalPick<Required<T>, PluginCommand>, 'plugin'>);
/**
* A mapping of URL paths to HTTP methods to {@linkcode PluginMethodDef}.
*/
export interface PluginMethodMap<T extends Plugin> {
export interface PluginMethodMap<T extends Plugin, Loose extends boolean = false> {
[key: string]: {
GET?: PluginMethodDef<T>;
POST?: PluginMethodDef<T>;
DELETE?: PluginMethodDef<T>;
GET?: PluginMethodDef<T, Loose>;
POST?: PluginMethodDef<T, Loose>;
DELETE?: PluginMethodDef<T, Loose>;
};
}
@@ -126,97 +404,19 @@ export interface BaseExecuteMethodDef {
readonly info?: string;
}
/**
* The elements of `P` preceding its first optional or rest element, i.e. the parameters a method
* accepting `P` requires.
*/
type RequiredParams<P extends readonly unknown[]> = P extends readonly [infer H, ...infer T]
? [H, ...RequiredParams<T>]
: [];
type ExecuteMethodParamsFor<P extends readonly unknown[]> = BuildParamShapes<
P extends readonly unknown[] ? CollectParamSplits<P, false> : never,
false
>;
/**
* Tuple of `string`s with the same length as `T`.
*/
type StringTupleLike<T extends readonly unknown[]> = {[K in keyof T]: string};
/**
* Tuple of `any`s with the same length as `T`.
*/
type AnyTupleLike<T extends readonly unknown[]> = {[K in keyof T]: any};
/**
* The shape of `params` declaring the given required and optional param names.
*
* Non-tuple (`string[]`) values are also accepted, since their length cannot be checked; this is
* the case for maps not declared `as const`.
*/
type ExecuteMethodParamsShape<R extends string[], O extends string[]> = (R extends []
? {required?: readonly [] | string[]}
: {required: Readonly<R> | string[]}) &
(O extends [] ? {optional?: readonly [] | string[]} : {optional: Readonly<O> | string[]});
/**
* Union of `params` shapes with exactly `R` required params and any number of optional params up
* to the length of `Budget`.
*/
type ExecuteMethodParamsWithRequired<R extends string[], Budget extends unknown[], O extends string[] = []> =
| ExecuteMethodParamsShape<R, O>
| (Budget extends [unknown, ...infer BudgetTail]
? ExecuteMethodParamsWithRequired<R, BudgetTail, [...O, string]>
: never);
/**
* Union of `params` shapes with at least `R` required params, where the total number of params
* does not exceed the length of `R` plus the length of `Budget`.
*/
type ExecuteMethodParamsWithin<R extends string[], Budget extends unknown[]> =
| ExecuteMethodParamsWithRequired<R, Budget>
| (Budget extends [unknown, ...infer BudgetTail] ? ExecuteMethodParamsWithin<[...R, string], BudgetTail> : never);
/**
* The shape of `params` for a method with a rest parameter: at least `R` required params, and any
* number of further required and optional params.
*/
type ExecuteMethodParamsShapeWithRest<R extends string[]> = (R extends []
? {required?: readonly string[]}
: {required: Readonly<[...R, ...string[]]> | string[]}) & {optional?: readonly string[]};
/**
* Union of all `params` shapes whose `required`/`optional` param counts are compatible with a
* method accepting `P`: at runtime, the values of the `required` params are passed first (in
* order), followed by the values of the `optional` params (in order, `undefined` if not provided).
* So the method must accept at least as many required parameters as there are `required` params,
* must not require any of the `optional` ones, and must accept all of them.
*/
type ExecuteMethodParamsFor<P extends readonly unknown[]> = number extends Required<P>['length']
? ExecuteMethodParamsShapeWithRest<StringTupleLike<RequiredParams<P>>>
: Required<P> extends readonly [...AnyTupleLike<RequiredParams<P>>, ...infer Optional]
? ExecuteMethodParamsWithin<StringTupleLike<RequiredParams<P>>, Optional>
: never;
/**
* The `params` property of an execute method definition for a method accepting `P`. It is
* mandatory if the method has required parameters, since omitting it means the method is invoked
* without any arguments.
*/
type ExecuteMethodParamsProp<P extends readonly unknown[]> =
RequiredParams<P> extends [] ? {params?: ExecuteMethodParamsFor<P>} : {params: ExecuteMethodParamsFor<P>};
true extends CanOmitTrailing<P, false> ? {params?: ExecuteMethodParamsFor<P>} : {params: ExecuteMethodParamsFor<P>};
/**
* An execute method definition which cannot be cross-checked against a method signature.
*/
type LooseExecuteMethodDef = BaseExecuteMethodDef & {command: string};
/**
* Parameters of a {@linkcode DriverCommand}.
*/
type DriverCommandParams<F> = F extends (...args: infer P) => any ? P : never;
/**
* Parameters of a {@linkcode PluginCommand}, i.e. those following `next` and `driver`.
*/
type PluginCommandParams<F> = F extends (next: any, driver: any, ...args: infer P) => any ? P : never;
/**
* Union of execute method definitions for the given command methods (`Commands`), one per
* command, whose `params` are cross-checked against the signature of the command they map to.
@@ -229,7 +429,7 @@ type CheckedExecuteMethodDef<Commands, Kind extends 'driver' | 'plugin'> =
? LooseExecuteMethodDef
: {
[K in keyof Commands]: Omit<BaseExecuteMethodDef, 'params'> & {command: K} & ExecuteMethodParamsProp<
Kind extends 'driver' ? DriverCommandParams<Commands[K]> : PluginCommandParams<Commands[K]>
Kind extends 'driver' ? OverloadParams<Commands[K]> : PluginCommandParams<Commands[K]>
>;
}[keyof Commands];
@@ -271,9 +471,13 @@ export type PluginExecuteMethodDef<T extends Plugin> =
* Definition of an execute method (which overloads the behavior of the `execute` command) in a {@linkcode Driver} or {@linkcode Plugin}.
*/
export type ExecuteMethodMap<T extends Plugin | Driver> = T extends Plugin
? Readonly<StringRecord<PluginExecuteMethodDef<T>>>
? Readonly<
StringRecord<IsLoosePluginCheck<T, false> extends true ? LooseExecuteMethodDef : PluginExecuteMethodDef<T>>
>
: T extends Driver
? Readonly<StringRecord<DriverExecuteMethodDef<T>>>
? Readonly<
StringRecord<IsLooseDriverCheck<T, false> extends true ? LooseExecuteMethodDef : DriverExecuteMethodDef<T>>
>
: never;
export interface BidiMethodParams extends Pick<PayloadParams, 'makeArgs' | 'validate'> {
+1
View File
@@ -331,6 +331,7 @@ export interface DriverStatic<T extends Driver> {
* (see {@linkcode AppiumServer.frontRouter}).
*/
updateServer?: UpdateServerCallback;
/** Drivers can define new methods mapped to command names; see {@linkcode MethodMap} (use `as const satisfies MethodMap<MyDriver>`). */
newMethodMap?: MethodMap<T>;
/**
* Drivers can define new custom bidi commands and map them to driver methods. The format must
+1 -1
View File
@@ -21,7 +21,7 @@ export interface PluginStatic<P extends Plugin> {
* GET: {command: 'getNewThing'},
* POST: {command: 'setNewThing', payloadParams: {required: ['someParam']}}
* }
* }
* } as const satisfies MethodMap<MyPlugin>
*/
newMethodMap?: MethodMap<P>;
executeMethodMap?: ExecuteMethodMap<P>;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/types",
"version": "2.0.0",
"version": "3.0.0",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Various type declarations used across Appium",
"keywords": [
+616 -5
View File
@@ -1,26 +1,63 @@
import {expectAssignable, expectNotAssignable} from 'tsd';
import {expectAssignable, expectDocCommentIncludes, expectNotAssignable} from 'tsd';
import type {
Constraints,
Driver,
DriverClass,
DriverExecuteMethodDef,
DriverMethodDef,
ExecuteMethodMap,
ExternalDriver,
MethodMap,
NextPluginCallback,
Plugin,
PluginExecuteMethodDef,
PluginMethodDef,
} from '../lib/index.js';
/**
* A driver with execute methods of various arities. Only the members relevant to the checks
* below are declared; the rest are stubbed via the intersection with `Driver`.
*/
type TestDriver = Driver & {
noArgs(): Promise<void>;
oneRequired(a: string): Promise<void>;
oneRequiredNumber(a: number): Promise<void>;
twoRequiredOneOptional(a: string, b: number, c?: boolean): Promise<void>;
allOptional(a?: string, b?: number): Promise<void>;
threeRequired(a: string, b: string, c: string): Promise<void>;
elementRequiredOnly(a: number, elementId: string): Promise<void>;
elementWithOptional(a: number, b: number | undefined, elementId: string): Promise<void>;
elementWithStringOptional(a: number, b: string | undefined, elementId: string): Promise<void>;
twoTrailingOptionals(a: number, b: number | undefined, c?: string): Promise<void>;
overloaded(x: string): Promise<void>;
overloaded(x: number, y: number): Promise<void>;
overloadedZero(): Promise<void>;
overloadedZero(x: number): Promise<void>;
sixOverloads(a: number): Promise<void>;
sixOverloads(a: number, b: number): Promise<void>;
sixOverloads(a: number, b: number, c: number): Promise<void>;
sixOverloads(a: number, b: number, c: number, d: number): Promise<void>;
sixOverloads(a: number, b: number, c: number, d: number, e: number): Promise<void>;
sixOverloads(a: number, b: number, c: number, d: number, e: number, f: number): Promise<void>;
mixedRest(x: number): Promise<void>;
mixedRest(a: number, b: number, ...rest: unknown[]): Promise<void>;
mixedCatchAll(x: number): Promise<void>;
mixedCatchAll(...args: unknown[]): Promise<void>;
mixedRestOverload(x: undefined): Promise<void>;
mixedRestOverload(...rest: number[]): Promise<void>;
optWithRest(a: number, b?: string, ...rest: number[]): Promise<void>;
optSameTypeWithRest(a: number, b?: number, ...rest: number[]): Promise<void>;
restArgs(a: string, ...rest: unknown[]): Promise<void>;
restStrings(a: number, ...rest: string[]): Promise<void>;
roRest(...rest: readonly number[]): Promise<void>;
variadicTail(...args: [...number[], boolean]): Promise<void>;
variadicUrlTail(...args: [...number[], string]): Promise<void>;
varUndefBool(...args: [...(number | undefined)[], boolean]): Promise<void>;
varBoolStr(...args: [...number[], boolean, string]): Promise<void>;
untyped(...args: any[]): Promise<void>;
unk(a: unknown): Promise<void>;
anyArg(a: any): Promise<void>;
unionReq(a: string | number): Promise<void>;
unionOpt(a: boolean | undefined): Promise<void>;
litUnion(a: 'x' | 'y'): Promise<void>;
optionalCmd?: (a: string) => Promise<void>;
notACommand: string;
};
@@ -98,6 +135,10 @@ expectAssignable<DriverExecuteMethodDef<ExternalDriver>>({command: 'getPageSourc
type TestPlugin = Plugin & {
noArgs(next: NextPluginCallback, driver: ExternalDriver): Promise<void>;
oneRequiredOneOptional(next: NextPluginCallback, driver: ExternalDriver, a: string, b?: number): Promise<void>;
oneRequiredNumber(next: NextPluginCallback, driver: ExternalDriver, a: number): Promise<void>;
overloadedPlugin(next: NextPluginCallback, driver: ExternalDriver, x: string): Promise<void>;
overloadedPlugin(next: NextPluginCallback, driver: ExternalDriver, x: number, y: number): Promise<void>;
optionalPluginCmd?: (next: NextPluginCallback, driver: ExternalDriver, a: string) => Promise<void>;
};
type TestPluginDef = PluginExecuteMethodDef<TestPlugin>;
@@ -114,3 +155,573 @@ expectNotAssignable<TestPluginDef>({command: 'handle'} as const);
expectAssignable<ExecuteMethodMap<TestPlugin>>({
'test: one': {command: 'oneRequiredOneOptional', params: {required: ['a'], optional: ['b']}},
} as const);
type TestMethodDef = DriverMethodDef<TestDriver>;
expectAssignable<TestMethodDef>({} as const);
expectAssignable<TestMethodDef>({neverProxy: true} as const);
expectAssignable<TestMethodDef>({command: 'noArgs'} as const);
expectAssignable<TestMethodDef>({command: 'noArgs', payloadParams: {}} as const);
expectAssignable<TestMethodDef>({command: 'noArgs', payloadParams: {required: []}} as const);
expectAssignable<TestMethodDef>({command: 'noArgs', payloadParams: {makeArgs: () => []}} as const);
expectAssignable<TestMethodDef>({command: 'oneRequired'} as const);
expectAssignable<TestMethodDef>({command: 'oneRequired', payloadParams: {required: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'oneRequired', payloadParams: {required: [['a'], ['b']]}} as const);
expectAssignable<TestMethodDef>({command: 'oneRequiredNumber', payloadParams: {required: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'oneRequiredNumber', payloadParams: {required: [['a'], ['b']]}} as const);
expectAssignable<TestMethodDef>({command: 'oneRequiredNumber', payloadParams: {makeArgs: () => [1]}} as const);
expectAssignable<TestMethodDef>({command: 'twoRequiredOneOptional', payloadParams: {required: ['a', 'b']}} as const);
expectAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {required: ['a', 'b'], optional: ['c']},
} as const);
expectAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {required: ['a', 'b', 'c']},
} as const);
expectAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {
required: [
['a', 'b'],
['a', 'c'],
],
},
} as const);
expectAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {
required: [
['a', 'b'],
['a', 'b', 'c'],
],
},
} as const);
expectAssignable<TestMethodDef>({command: 'allOptional'} as const);
expectAssignable<TestMethodDef>({command: 'allOptional', payloadParams: {optional: ['a', 'b']}} as const);
expectAssignable<TestMethodDef>({command: 'allOptional', payloadParams: {required: ['a'], optional: ['b']}} as const);
expectAssignable<TestMethodDef>({command: 'threeRequired'} as const);
expectAssignable<TestMethodDef>({command: 'threeRequired', payloadParams: {required: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'elementRequiredOnly', payloadParams: {required: ['a']}} as const);
expectAssignable<TestMethodDef>({
command: 'elementRequiredOnly',
payloadParams: {required: ['a', 'elementId']},
} as const);
expectAssignable<TestMethodDef>({
command: 'elementWithOptional',
payloadParams: {required: ['a'], optional: ['b']},
} as const);
expectAssignable<TestMethodDef>({
command: 'elementWithOptional',
payloadParams: {required: ['a', 'b']},
} as const);
expectAssignable<TestMethodDef>({
command: 'elementWithStringOptional',
payloadParams: {required: ['a'], optional: ['b']},
} as const);
expectAssignable<TestMethodDef>({command: 'twoTrailingOptionals', payloadParams: {required: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'overloaded'} as const);
expectAssignable<TestMethodDef>({command: 'overloaded', payloadParams: {required: ['x']}} as const);
expectAssignable<TestMethodDef>({command: 'overloaded', payloadParams: {required: ['x', 'y']}} as const);
expectAssignable<TestMethodDef>({
command: 'overloaded',
payloadParams: {required: [['x'], ['x', 'y']]},
} as const);
expectAssignable<TestMethodDef>({command: 'overloadedZero'} as const);
expectAssignable<TestMethodDef>({command: 'overloadedZero', payloadParams: {}} as const);
expectAssignable<TestMethodDef>({command: 'overloadedZero', payloadParams: {required: []}} as const);
expectAssignable<TestMethodDef>({command: 'overloadedZero', payloadParams: {required: ['x']}} as const);
expectAssignable<TestMethodDef>({
command: 'oneRequiredNumber',
payloadParams: {required: ['x', 'y'], makeArgs: ({x, y}) => [x + y]},
} as const);
expectAssignable<TestMethodDef>({command: 'restArgs'} as const);
expectAssignable<TestMethodDef>({
command: 'restArgs',
payloadParams: {required: ['a', 'b', 'c'], optional: ['d', 'e']},
} as const);
expectAssignable<TestMethodDef>({
command: 'restArgs',
payloadParams: {required: [['a', 'b'], ['a']], optional: ['c']},
} as const);
expectAssignable<TestMethodDef>({command: 'restStrings', payloadParams: {required: ['a', 'b']}} as const);
expectAssignable<TestMethodDef>({command: 'untyped', payloadParams: {optional: ['a', 'b', 'c']}} as const);
expectAssignable<TestMethodDef>({command: 'untyped', payloadParams: {required: [['a'], ['b', 'c']]}} as const);
expectNotAssignable<TestMethodDef>({command: 'noArgs', payloadParams: {required: ['a']}} as const);
expectNotAssignable<TestMethodDef>({command: 'noArgs', payloadParams: {optional: ['a']}} as const);
expectNotAssignable<TestMethodDef>({command: 'noArgs', payloadParams: {required: [['a']]}} as const);
expectNotAssignable<TestMethodDef>({command: 'oneRequired', payloadParams: {optional: ['a']}} as const);
expectNotAssignable<TestMethodDef>({command: 'oneRequired', payloadParams: {required: ['a', 'b']}} as const);
expectNotAssignable<TestMethodDef>({command: 'oneRequiredNumber'} as const);
expectNotAssignable<TestMethodDef>({command: 'oneRequiredNumber', payloadParams: {}} as const);
expectNotAssignable<TestMethodDef>({command: 'oneRequiredNumber', payloadParams: {required: []}} as const);
expectNotAssignable<TestMethodDef>({command: 'oneRequiredNumber', payloadParams: {optional: ['a']}} as const);
expectNotAssignable<TestMethodDef>({command: 'oneRequiredNumber', payloadParams: {required: ['a', 'b']}} as const);
expectNotAssignable<TestMethodDef>({
command: 'oneRequiredNumber',
payloadParams: {required: [['a', 'b'], ['c']]},
} as const);
expectNotAssignable<TestMethodDef>({command: 'twoRequiredOneOptional'} as const);
expectNotAssignable<TestMethodDef>({command: 'twoRequiredOneOptional', payloadParams: {required: ['a']}} as const);
expectNotAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {required: ['a'], optional: ['b', 'c']},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {required: ['a', 'b'], optional: ['c', 'd']},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {required: [['a'], ['b', 'c']]},
} as const);
expectNotAssignable<TestMethodDef>({command: 'allOptional', payloadParams: {optional: ['a', 'b', 'c']}} as const);
expectNotAssignable<TestMethodDef>({command: 'threeRequired', payloadParams: {optional: ['a']}} as const);
expectNotAssignable<TestMethodDef>({
command: 'threeRequired',
payloadParams: {required: ['a', 'b', 'c', 'd']},
} as const);
expectNotAssignable<TestMethodDef>({command: 'elementRequiredOnly'} as const);
expectNotAssignable<TestMethodDef>({
command: 'elementRequiredOnly',
payloadParams: {required: ['a'], optional: ['opt']},
} as const);
expectNotAssignable<TestMethodDef>({command: 'elementWithOptional', payloadParams: {required: ['a']}} as const);
expectNotAssignable<TestMethodDef>({command: 'elementWithOptional'} as const);
expectNotAssignable<TestMethodDef>({
command: 'elementWithStringOptional',
payloadParams: {required: ['a']},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'elementWithOptional',
payloadParams: {required: ['a', 'b'], optional: ['elementId']},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'overloaded',
payloadParams: {required: ['x', 'y', 'z']},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'overloadedZero',
payloadParams: {required: ['x', 'y']},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'noArgs',
payloadParams: {required: ['x', 'y', 'z'], makeArgs: () => []},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'noArgs',
payloadParams: {optional: ['x'], makeArgs: () => []},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'noArgs',
payloadParams: {makeArgs: () => [1]},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'oneRequiredNumber',
payloadParams: {makeArgs: () => 123},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'oneRequired',
payloadParams: {required: [['a'], []]},
} as const);
expectNotAssignable<TestMethodDef>({command: 'restArgs', payloadParams: {optional: ['a']}} as const);
expectNotAssignable<TestMethodDef>({
command: 'restArgs',
payloadParams: {required: [['a'], []], optional: ['b']},
} as const);
expectNotAssignable<TestMethodDef>({command: 'restStrings'} as const);
expectNotAssignable<TestMethodDef>({
command: 'restStrings',
payloadParams: {required: ['a'], optional: ['b']},
} as const);
expectNotAssignable<TestMethodDef>({command: 'doesNotExist'} as const);
expectNotAssignable<TestMethodDef>({command: 'notACommand'} as const);
expectNotAssignable<DriverMethodDef<TestDriver>>({
command: 'anyCustomCommand',
payloadParams: {required: ['a', 'b']},
} as const);
expectAssignable<DriverMethodDef<TestDriver, true>>({
command: 'anyCustomCommand',
payloadParams: {required: ['a', 'b']},
} as const);
expectAssignable<DriverMethodDef<TestDriver, boolean>>({
command: 'anyCustomCommand',
payloadParams: {required: ['a', 'b']},
} as const);
const contextuallyTypedMethodMap: MethodMap<TestDriver> = {
'/test': {
POST: {command: 'oneRequiredNumber', payloadParams: {required: ['a']}},
DELETE: {command: 'overloaded', payloadParams: {required: ['x']}},
},
};
expectAssignable<MethodMap<TestDriver>>(contextuallyTypedMethodMap);
expectNotAssignable<MethodMap<TestDriver>>({
'/test': {
POST: {command: 'oneRequiredNumber' as const, payloadParams: {required: ['a', 'b']}},
},
});
const driverMethodMap = {
'/test': {
GET: {command: 'noArgs'},
POST: {command: 'twoRequiredOneOptional', payloadParams: {required: ['a', 'b'], optional: ['c']}},
},
} as const satisfies MethodMap<TestDriver>;
expectAssignable<MethodMap<TestDriver>>(driverMethodMap);
expectAssignable<MethodMap<TestDriver, true>>(driverMethodMap);
expectAssignable<MethodMap<Driver>>(driverMethodMap);
expectAssignable<MethodMap<ExternalDriver>>(driverMethodMap);
expectAssignable<MethodMap<TestDriver, true>>({
'/proxied': {
GET: {command: 'proxiedCommand'},
POST: {command: 'anotherProxied', payloadParams: {required: ['x']}},
},
} as const);
expectNotAssignable<MethodMap<TestDriver, false>>({
'/proxied': {
GET: {command: 'proxiedCommand'},
},
} as const);
expectNotAssignable<MethodMap<TestDriver>>({
'/proxied': {GET: {command: 'proxiedCommand'}},
} as const);
expectNotAssignable<MethodMap<TestDriver>>({
'/invalid-params': {POST: {command: 'oneRequiredNumber', payloadParams: {optional: ['a']}}},
} as const);
const nonConstMethodMap = {
'/test': {GET: {command: 'noArgs'}},
};
expectNotAssignable<MethodMap<TestDriver>>(nonConstMethodMap);
expectAssignable<MethodMap<any>>({
'/any': {POST: {command: 'whatever', payloadParams: {required: ['a']}}},
} as const);
expectAssignable<DriverMethodDef<ExternalDriver>>({command: 'getPageSource'} as const);
type ExtendedExternalDriver = ExternalDriver & {extra?(a: number): Promise<void>};
expectAssignable<DriverMethodDef<ExtendedExternalDriver>>({command: 'getPageSource'} as const);
expectAssignable<DriverMethodDef<ExtendedExternalDriver>>({
command: 'extra',
payloadParams: {required: ['a']},
} as const);
expectNotAssignable<DriverMethodDef<ExtendedExternalDriver>>({command: 'bogus'} as const);
expectNotAssignable<DriverMethodDef<ExtendedExternalDriver>>({command: 'extra'} as const);
type ExtendedBaseDriver = Driver & {extra?(a: number): Promise<void>};
expectAssignable<DriverMethodDef<ExtendedBaseDriver>>({command: 'extra', payloadParams: {required: ['a']}} as const);
expectNotAssignable<DriverMethodDef<ExtendedBaseDriver>>({command: 'bogus'} as const);
expectNotAssignable<DriverMethodDef<ExtendedBaseDriver>>({command: 'extra'} as const);
type TestPluginMethodDef = PluginMethodDef<TestPlugin>;
expectAssignable<TestPluginMethodDef>({} as const);
expectAssignable<TestPluginMethodDef>({command: 'noArgs'} as const);
expectAssignable<TestPluginMethodDef>({
command: 'oneRequiredOneOptional',
payloadParams: {required: ['a'], optional: ['b']},
} as const);
expectAssignable<TestPluginMethodDef>({
command: 'oneRequiredOneOptional',
payloadParams: {required: [['a'], ['a', 'b']]},
} as const);
expectAssignable<TestPluginMethodDef>({command: 'oneRequiredOneOptional'} as const);
expectNotAssignable<TestPluginMethodDef>({command: 'oneRequiredNumber'} as const);
expectAssignable<TestPluginMethodDef>({command: 'oneRequiredNumber', payloadParams: {required: ['a']}} as const);
expectNotAssignable<TestPluginMethodDef>({
command: 'oneRequiredOneOptional',
payloadParams: {optional: ['a', 'b']},
} as const);
expectNotAssignable<TestPluginMethodDef>({
command: 'oneRequiredOneOptional',
payloadParams: {required: ['a', 'b', 'c']},
} as const);
expectAssignable<TestPluginMethodDef>({command: 'handle', payloadParams: {required: ['cmdName']}} as const);
expectNotAssignable<PluginMethodDef<TestPlugin>>({
command: 'handledCommand',
payloadParams: {required: ['a']},
} as const);
expectAssignable<PluginMethodDef<TestPlugin, true>>({
command: 'handledCommand',
payloadParams: {required: ['a']},
} as const);
expectAssignable<MethodMap<TestPlugin, true>>({
'/handled': {POST: {command: 'handledCommand', payloadParams: {required: ['x']}}},
} as const);
expectNotAssignable<MethodMap<TestPlugin>>({
'/handled': {GET: {command: 'handledCommand'}},
} as const);
const pluginMethodMap = {
'/plugin': {
POST: {command: 'oneRequiredOneOptional', payloadParams: {required: ['a'], optional: ['b']}},
},
} as const satisfies MethodMap<TestPlugin>;
expectAssignable<MethodMap<TestPlugin>>(pluginMethodMap);
expectAssignable<MethodMap<TestPlugin, true>>(pluginMethodMap);
expectAssignable<MethodMap<Plugin>>(pluginMethodMap);
type ExtendedPlugin = Plugin & {
extra?(next: NextPluginCallback, driver: ExternalDriver, a: number): Promise<void>;
};
expectAssignable<PluginMethodDef<ExtendedPlugin>>({command: 'extra', payloadParams: {required: ['a']}} as const);
expectNotAssignable<PluginMethodDef<ExtendedPlugin>>({command: 'bogus'} as const);
expectNotAssignable<PluginMethodDef<ExtendedPlugin>>({command: 'extra'} as const);
expectAssignable<TestMethodDef>({command: 'unk', payloadParams: {optional: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'unk', payloadParams: {required: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'unk'} as const);
expectAssignable<TestMethodDef>({command: 'anyArg', payloadParams: {optional: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'anyArg'} as const);
expectAssignable<TestDef>({command: 'unk', params: {optional: ['a']}} as const);
expectAssignable<TestDef>({command: 'unk', params: {required: ['a']}} as const);
expectAssignable<TestDef>({command: 'unk'} as const);
expectAssignable<TestDef>({command: 'anyArg', params: {optional: ['a']}} as const);
expectAssignable<TestDef>({command: 'unionOpt', params: {optional: ['a']}} as const);
expectAssignable<TestDef>({command: 'unionReq', params: {required: ['a']}} as const);
expectNotAssignable<TestDef>({command: 'unionReq'} as const);
expectNotAssignable<TestDef>({command: 'unionReq', params: {optional: ['a']}} as const);
expectNotAssignable<TestDef>({command: 'restStrings', params: {required: ['a'], optional: ['b']}} as const);
expectAssignable<TestMethodDef>({command: 'optionalCmd', payloadParams: {required: ['a']}} as const);
expectNotAssignable<TestMethodDef>({command: 'optionalCmd', payloadParams: {optional: ['a']}} as const);
expectAssignable<TestPluginMethodDef>({
command: 'optionalPluginCmd',
payloadParams: {required: ['a']},
} as const);
expectNotAssignable<TestPluginMethodDef>({
command: 'optionalPluginCmd',
payloadParams: {optional: ['a']},
} as const);
expectAssignable<TestMethodDef>({command: 'unionReq', payloadParams: {required: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'unionReq'} as const);
expectNotAssignable<TestMethodDef>({command: 'unionReq', payloadParams: {optional: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'unionOpt', payloadParams: {optional: ['a']}} as const);
expectAssignable<TestMethodDef>({command: 'litUnion', payloadParams: {required: ['a']}} as const);
expectNotAssignable<TestMethodDef>({command: 'litUnion'} as const);
expectNotAssignable<TestMethodDef>({command: 'litUnion', payloadParams: {optional: ['a']}} as const);
expectAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {wrap: 'gesture', required: ['a', 'b'], validate: (obj: any) => Boolean(obj)},
} as const);
expectAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {unwrap: 'data', required: ['a', 'b'], optional: ['c']},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'twoRequiredOneOptional',
payloadParams: {wrap: 'gesture', required: ['a'], validate: () => true},
} as const);
expectAssignable<TestDef>({command: 'overloaded', params: {required: ['x']}} as const);
expectAssignable<TestDef>({command: 'overloaded', params: {required: ['x', 'y']}} as const);
expectNotAssignable<TestDef>({command: 'overloaded'} as const);
expectNotAssignable<TestDef>({command: 'overloaded', params: {required: ['x', 'y', 'z']}} as const);
expectAssignable<TestDef>({command: 'overloadedZero'} as const);
expectAssignable<TestDef>({command: 'overloadedZero', params: {}} as const);
expectAssignable<TestDef>({command: 'overloadedZero', params: {required: ['x']}} as const);
expectAssignable<TestMethodDef>({command: 'sixOverloads', payloadParams: {required: ['a', 'b']}} as const);
expectAssignable<TestMethodDef>({
command: 'sixOverloads',
payloadParams: {required: ['a', 'b', 'c', 'd', 'e', 'f']},
} as const);
expectNotAssignable<TestMethodDef>({command: 'sixOverloads', payloadParams: {required: ['a']}} as const);
expectAssignable<DriverMethodDef<TestDriver, true>>({
command: 'sixOverloads',
payloadParams: {required: ['a']},
} as const);
expectAssignable<MethodMap<TestDriver, true>>({
'/six': {POST: {command: 'sixOverloads', payloadParams: {required: ['a']}}},
} as const);
expectAssignable<TestPluginMethodDef>({command: 'overloadedPlugin', payloadParams: {required: ['x']}} as const);
expectAssignable<TestPluginMethodDef>({command: 'overloadedPlugin', payloadParams: {required: ['x', 'y']}} as const);
expectNotAssignable<TestPluginMethodDef>({
command: 'overloadedPlugin',
payloadParams: {required: ['x', 'y', 'z']},
} as const);
expectAssignable<TestPluginDef>({command: 'overloadedPlugin', params: {required: ['x']}} as const);
expectAssignable<TestPluginDef>({command: 'overloadedPlugin', params: {required: ['x', 'y']}} as const);
expectNotAssignable<TestPluginDef>({command: 'overloadedPlugin', params: {required: ['x', 'y', 'z']}} as const);
expectAssignable<TestMethodDef>({command: 'mixedRest', payloadParams: {required: ['x']}} as const);
expectAssignable<TestMethodDef>({
command: 'mixedRest',
payloadParams: {required: ['a', 'b'], optional: ['c']},
} as const);
expectNotAssignable<TestMethodDef>({command: 'mixedRest'} as const);
expectNotAssignable<TestMethodDef>({
command: 'mixedRest',
payloadParams: {required: ['x'], optional: ['y']},
} as const);
expectAssignable<TestDef>({command: 'mixedRest', params: {required: ['x']}} as const);
expectAssignable<TestDef>({
command: 'mixedRest',
params: {required: ['a', 'b'], optional: ['c']},
} as const);
expectNotAssignable<TestDef>({command: 'mixedRest'} as const);
expectNotAssignable<TestDef>({command: 'mixedRest', params: {required: ['x'], optional: ['y']}} as const);
expectAssignable<TestMethodDef>({command: 'mixedCatchAll'} as const);
expectAssignable<TestMethodDef>({
command: 'mixedCatchAll',
payloadParams: {required: ['a', 'b'], optional: ['c']},
} as const);
expectAssignable<TestDef>({command: 'mixedCatchAll'} as const);
expectAssignable<TestDef>({
command: 'mixedCatchAll',
params: {required: ['a', 'b'], optional: ['c']},
} as const);
declare const BaseTestDriver: new () => Driver;
class ImplOverloadDriver extends BaseTestDriver {
cmd(x: number): Promise<void>;
cmd(x: number, y: number): Promise<void>;
async cmd(..._args: unknown[]): Promise<void> {}
}
expectAssignable<DriverMethodDef<ImplOverloadDriver>>({command: 'cmd', payloadParams: {required: ['x']}} as const);
expectNotAssignable<DriverMethodDef<ImplOverloadDriver>>({command: 'cmd'} as const);
expectNotAssignable<DriverMethodDef<ImplOverloadDriver>>({
command: 'cmd',
payloadParams: {required: ['x', 'y', 'z']},
} as const);
expectAssignable<MethodMap<TestDriver>>({
'/no-url-params': {POST: {command: 'threeRequired'}},
} as const);
expectAssignable<DriverMethodDef<Driver>>({command: 'anyCustomCommand'} as const);
expectAssignable<DriverMethodDef<ExternalDriver>>({command: 'anyCustomCommand'} as const);
expectAssignable<PluginMethodDef<Plugin>>({command: 'anyCustomCommand'} as const);
type CustomCapConstraints = {customCap: {isString: true}};
expectAssignable<DriverMethodDef<Driver<CustomCapConstraints>>>({command: 'anyCustomCommand'} as const);
expectAssignable<DriverMethodDef<ExternalDriver<CustomCapConstraints>>>({command: 'anyCustomCommand'} as const);
expectAssignable<DriverMethodDef<Driver | ExternalDriver>>({command: 'anyCustomCommand'} as const);
expectAssignable<DriverMethodDef<Driver<CustomCapConstraints> | ExternalDriver<CustomCapConstraints>>>({
command: 'anyCustomCommand',
} as const);
expectNotAssignable<DriverExecuteMethodDef<Driver>>({command: 'anyCustomCommand'} as const);
expectNotAssignable<DriverExecuteMethodDef<ExternalDriver>>({command: 'anyCustomCommand'} as const);
expectNotAssignable<DriverExecuteMethodDef<Driver<CustomCapConstraints>>>({command: 'anyCustomCommand'} as const);
expectNotAssignable<DriverExecuteMethodDef<ExternalDriver<CustomCapConstraints>>>({
command: 'anyCustomCommand',
} as const);
expectNotAssignable<DriverExecuteMethodDef<Driver | ExternalDriver>>({command: 'anyCustomCommand'} as const);
expectNotAssignable<
PluginExecuteMethodDef<Plugin & {customPluginCmd(next: NextPluginCallback, driver: ExternalDriver): Promise<void>}>
>({command: 'anyCustomCommand'} as const);
expectNotAssignable<DriverMethodDef<Driver | (Driver & {getStatus(a: number): Promise<any>})>>({
command: 'anyCustomCommand',
} as const);
expectNotAssignable<DriverMethodDef<Driver & {getStatus(a: number): Promise<any>}>>({
command: 'anyCustomCommand',
} as const);
expectNotAssignable<DriverExecuteMethodDef<Driver & {getStatus(a: number): Promise<any>}>>({
command: 'anyCustomCommand',
} as const);
declare const ConstrainedBaseDriver: new () => Driver<CustomCapConstraints>;
class ConstrainedDriver extends ConstrainedBaseDriver {
static baseVersion = '1.0.0';
static newMethodMap = {
'/constrained': {GET: {command: 'customCmd'}},
} as const satisfies MethodMap<ConstrainedDriver>;
static executeMethodMap = {
'test: constrained': {command: 'customCmd'},
} as const satisfies ExecuteMethodMap<ConstrainedDriver>;
async customCmd(): Promise<void> {}
}
expectAssignable<DriverClass<Driver<CustomCapConstraints>>>(ConstrainedDriver);
declare const ConstrainedExtBaseDriver: new () => ExternalDriver<CustomCapConstraints>;
class ExtSubDriver extends ConstrainedExtBaseDriver {
static baseVersion = '1.0.0';
static newMethodMap = {
'/ext': {GET: {command: 'extCmd'}},
} as const satisfies MethodMap<ExtSubDriver>;
static executeMethodMap = {
'test: ext': {command: 'extCmd'},
} as const satisfies ExecuteMethodMap<ExtSubDriver>;
async extCmd(): Promise<void> {}
}
expectAssignable<DriverClass<ExternalDriver>>(ExtSubDriver);
expectAssignable<DriverClass<ExternalDriver<CustomCapConstraints>>>(ExtSubDriver);
expectAssignable<ExecuteMethodMap<ExternalDriver>>(ExtSubDriver.executeMethodMap);
expectAssignable<TestMethodDef>({command: 'mixedRestOverload', payloadParams: {optional: ['a']}} as const);
expectNotAssignable<TestMethodDef>({
command: 'mixedRestOverload',
payloadParams: {optional: ['a', 'b', 'c']},
} as const);
expectAssignable<TestMethodDef>({command: 'optWithRest', payloadParams: {required: ['a'], optional: ['b']}} as const);
expectAssignable<TestMethodDef>({command: 'optWithRest', payloadParams: {required: ['a', 'b', 'c']}} as const);
expectNotAssignable<TestMethodDef>({
command: 'optWithRest',
payloadParams: {required: ['a'], optional: ['b', 'c']},
} as const);
expectAssignable<TestMethodDef>({
command: 'optSameTypeWithRest',
payloadParams: {required: ['a'], optional: ['b']},
} as const);
expectNotAssignable<TestMethodDef>({
command: 'optSameTypeWithRest',
payloadParams: {required: ['a'], optional: ['b', 'c']},
} as const);
expectAssignable<TestMethodDef>({command: 'roRest', payloadParams: {required: ['a', 'b']}} as const);
expectAssignable<TestMethodDef>({command: 'variadicTail', payloadParams: {required: ['b']}} as const);
expectAssignable<TestMethodDef>({command: 'variadicUrlTail'} as const);
expectNotAssignable<TestMethodDef>({command: 'variadicTail'} as const);
expectNotAssignable<TestDef>({command: 'variadicTail'} as const);
expectNotAssignable<TestMethodDef>({command: 'variadicTail', payloadParams: {optional: ['x']}} as const);
expectAssignable<TestMethodDef>({command: 'varBoolStr', payloadParams: {required: ['b']}} as const);
expectNotAssignable<TestDef>({command: 'varBoolStr', params: {required: ['b']}} as const);
expectNotAssignable<TestMethodDef>({
command: 'varUndefBool',
payloadParams: {required: ['a'], optional: ['b']},
} as const);
expectNotAssignable<TestDef>({command: 'varUndefBool', params: {required: ['a'], optional: ['b']}} as const);
export function genericMethodMapLookup<C extends Constraints>(d: DriverClass<Driver<C>>, route: string) {
return d.newMethodMap?.[route]?.GET;
}
export function wrappedGenericMethodLookup(d: DriverClass<Driver<CustomCapConstraints>>, route: string) {
return genericMethodMapLookup(d, route);
}
export function genericExecMapLookup<C extends Constraints>(d: DriverClass<Driver<C>>, script: string) {
return d.executeMethodMap?.[script];
}
export function genericExecSpread<C extends Constraints>(d: DriverClass<Driver<C>>, script: string) {
return {...d.executeMethodMap?.[script]};
}
export function genericMethodSpread<C extends Constraints>(d: DriverClass<Driver<C>>, route: string) {
return {...d.newMethodMap?.[route]?.GET};
}
export function genericPluginMethodLookup<P extends Plugin>(m: MethodMap<P>, route: string) {
return m[route]?.GET;
}
export function genericPluginExecSpread<P extends Plugin>(m: ExecuteMethodMap<P>, script: string) {
return {...m[script]};
}
expectAssignable<DriverMethodDef<Driver<CustomCapConstraints>> | undefined>(
genericMethodMapLookup(ConstrainedDriver, '/constrained'),
);
expectAssignable<ExecuteMethodMap<Driver<CustomCapConstraints>>[string] | undefined>(
genericExecMapLookup(ConstrainedDriver, 'test: constrained'),
);
expectAssignable<{command?: string}>(genericExecSpread(ConstrainedDriver, 'test: constrained'));
expectAssignable<{command?: string}>(genericMethodSpread(ConstrainedDriver, '/constrained'));
declare const strictDriverDef: Extract<TestMethodDef, {readonly command: 'oneRequiredNumber'}>;
declare const optionalPayloadDriverDef: Extract<TestMethodDef, {readonly command: 'noArgs'}>;
declare const looseDriverDef: DriverMethodDef<TestDriver, true>;
declare const strictPluginDef: Extract<TestPluginMethodDef, {readonly command: 'oneRequiredNumber'}>;
expectDocCommentIncludes<'Name of the command.'>(strictDriverDef.command);
expectDocCommentIncludes<'Specifies shape of payload'>(strictDriverDef.payloadParams);
expectDocCommentIncludes<'Specifies shape of payload'>(optionalPayloadDriverDef.payloadParams);
expectDocCommentIncludes<'Name of the command.'>(looseDriverDef.command);
expectDocCommentIncludes<'Specifies shape of payload'>(looseDriverDef.payloadParams);
expectDocCommentIncludes<'Name of the command.'>(strictPluginDef.command);
expectDocCommentIncludes<'Specifies shape of payload'>(strictPluginDef.payloadParams);
+13
View File
@@ -6,11 +6,13 @@ import type {
DriverCommandToPluginCommand,
ExecuteMethodMap,
ExternalDriver,
MethodMap,
NextPluginCallback,
Plugin,
PluginClass,
PluginCommand,
PluginExecuteMethodDef,
PluginMethodDef,
PluginStatic,
StringRecord,
} from '../lib/index.js';
@@ -20,6 +22,13 @@ class TestPlugin implements Plugin {
command: 'testMethod',
},
} as const satisfies ExecuteMethodMap<TestPlugin>;
static newMethodMap = {
'/session/:sessionId/test': {
GET: {
command: 'testMethod',
},
},
} as const satisfies MethodMap<TestPlugin>;
public logger: AppiumLogger = {} as AppiumLogger;
@@ -50,6 +59,10 @@ const instance = new TestPlugin('test-plugin');
expectAssignable<Plugin>(instance);
expectAssignable<PluginExecuteMethodDef<TestPlugin>>(TestPlugin.executeMethodMap['test: method']);
expectAssignable<ExecuteMethodMap<TestPlugin>>(TestPlugin.executeMethodMap);
expectAssignable<PluginMethodDef<TestPlugin>>(TestPlugin.newMethodMap['/session/:sessionId/test'].GET);
expectAssignable<PluginMethodDef<TestPlugin, true>>(TestPlugin.newMethodMap['/session/:sessionId/test'].GET);
expectAssignable<MethodMap<TestPlugin>>(TestPlugin.newMethodMap);
expectAssignable<MethodMap<TestPlugin, true>>(TestPlugin.newMethodMap);
expectAssignable<PluginStatic<TestPlugin>>(TestPlugin);
expectAssignable<PluginClass<TestPlugin>>(TestPlugin);
expectAssignable<PluginClass>(TestPlugin);
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.0.2](https://github.com/appium/appium/compare/@appium/universal-xml-plugin@4.0.1...@appium/universal-xml-plugin@4.0.2) (2026-11-27)
**Note:** Version bump only for package @appium/universal-xml-plugin
## [4.0.1](https://github.com/appium/appium/compare/@appium/universal-xml-plugin@4.0.0...@appium/universal-xml-plugin@4.0.1) (2026-11-23)
**Note:** Version bump only for package @appium/universal-xml-plugin
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/universal-xml-plugin",
"version": "4.0.1",
"version": "4.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Appium plugin for making XML source and XPath queries the same across iOS and Android",
"keywords": [
@@ -48,13 +48,13 @@
"test:unit": "node --test --enable-source-maps \"./build/test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/support": "8.0.1",
"@appium/support": "8.0.2",
"@xmldom/xmldom": "0.9.12",
"fast-xml-parser": "5.12.1",
"xpath": "0.0.36"
"xpath": "0.1.0"
},
"devDependencies": {
"@appium/types": "2.0.0"
"@appium/types": "3.0.0"
},
"peerDependencies": {
"appium": "^4.0.0-beta.0"
+1 -1
View File
@@ -15,7 +15,7 @@ const APPIUM_PACKAGE_README = path.join(ROOT_PACKAGES_DIR, 'appium', 'README.md'
const COMMON_FIELDS_TO_COPY = ['author', 'license', 'bugs', 'homepage'];
const LOGGER_COMMON_FIELDS_TO_COPY = ['author', 'bugs', 'homepage'];
const KEYWORD_EXCLUDED_PACKAGES = new Set(['oxc-config', 'semantic-release-config', 'types']);
const KEYWORD_EXCLUDED_PACKAGES = new Set(['archward', 'oxc-config', 'semantic-release-config', 'types']);
// Package names in this set will not receive the LICENSE file from the root,
// as they have their own license terms (e.g., ISC for logger).
const LICENSE_EXCLUDED_PACKAGES = new Set(['logger']);
+3
View File
@@ -67,6 +67,9 @@
},
{
"path": "packages/storage-plugin"
},
{
"path": "packages/archward"
}
]
}