Skip to content

AI-native design editor. Open-source Figma alternative.

feat: publish the generic lint rules as @open-pencil/oxlint-plugin (#1704)

Danila Poyarkovda72d9260159
diff --git a/AGENTS.md b/AGENTS.md
index 4e9b6d7f3..4f79c214d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -16,6 +16,7 @@ This file holds the repository map and the rules that apply everywhere. Rules fo
| `packages/core` | Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, document I/O; depends on scene-graph and the format packages (pen, drawio, kiwi, fig, dom-css, design-jsx); no browser DOM | `packages/core/AGENTS.md` |
| `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and emit, and takes engine services such as web-font resolution as injected options | `packages/dom-css/AGENTS.md` |
| `packages/emit` | Source emission for exporters: ESTree and JSX builders, template filling, and esrap printing, with the literal rules that keep exported strings from being reinterpreted | — |
+| `packages/oxlint-plugin` | Published Oxlint plugin with the conventions any TypeScript project can follow; this repository adds its own rules from `tools/checks/lint` through `lint/plugin.js` | `packages/oxlint-plugin/AGENTS.md` |
| `packages/design-jsx` | OpenPencil design JSX: elements, paint/effect helpers, variables, schema and authoring reference, JSX export, and a renderer that takes icons, SVG, and layout as injected services | `packages/design-jsx/AGENTS.md` |
| `packages/vue` | Headless Vue 3 SDK primitives, composables, commands, i18n, menu model | `packages/vue/AGENTS.md` |
| `packages/cli` | Headless `.fig` inspection, export, linting, `eval` | `packages/cli/AGENTS.md` |
diff --git a/bun.lock b/bun.lock
index 259b12284..a5050f54c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -586,6 +586,17 @@
"typescript": "npm:@typescript/typescript6@^6.0.2",
},
},
+ "packages/oxlint-plugin": {
+ "name": "@open-pencil/oxlint-plugin",
+ "version": "0.17.0-beta.1",
+ "dependencies": {
+ "@oxlint/plugins": "1.57.0",
+ "es-toolkit": "^1.52.0",
+ },
+ "peerDependencies": {
+ "oxlint": ">=1.90.0",
+ },
+ },
"packages/pen": {
"name": "@open-pencil/pen",
"version": "0.17.0-beta.1",
@@ -1734,6 +1745,8 @@
"@open-pencil/navigation-benchmark-tools": ["@open-pencil/navigation-benchmark-tools@workspace:tools/dev/navigation-benchmark"],
+ "@open-pencil/oxlint-plugin": ["@open-pencil/oxlint-plugin@workspace:packages/oxlint-plugin"],
+
"@open-pencil/package-artifacts-tools": ["@open-pencil/package-artifacts-tools@workspace:tools/release/package-artifacts"],
"@open-pencil/package-quality-tools": ["@open-pencil/package-quality-tools@workspace:tools/checks/package-quality"],
diff --git a/changes/1704/added.md b/changes/1704/added.md
new file mode 100644
index 000000000..b446c7c60
--- /dev/null
+++ b/changes/1704/added.md
@@ -0,0 +1 @@
+- New npm package `@open-pencil/oxlint-plugin`: OpenPencil's code conventions as Oxlint rules for any TypeScript project, such as validated JSON, Valibot schema placement, no broad type casts or silent catches, and no secrets in logs or URL query strings.
diff --git a/lint/plugin.js b/lint/plugin.js
index daa599d27..a3bc17ce1 100644
--- a/lint/plugin.js
+++ b/lint/plugin.js
@@ -1 +1,9 @@
-export { default } from '../tools/checks/lint/src/plugin.ts'
+// Oxlint loads one `open-pencil` plugin: the published rules from packages/oxlint-plugin and the
+// rules only this repository needs from tools/checks/lint, both read from source.
+import shared from '../packages/oxlint-plugin/src/index.ts'
+import repository from '../tools/checks/lint/src/plugin.ts'
+
+export default {
+ meta: { name: 'open-pencil' },
+ rules: { ...shared.rules, ...repository.rules }
+}
diff --git a/oxlint.json b/oxlint.json
index c61516487..ce0acbc0d 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -213,11 +213,7 @@
"max": 260
}
],
- "open-pencil/no-core-parent-relative-imports": "error",
"open-pencil/no-document-change-capture": "error",
- "open-pencil/no-mcp-parent-relative-imports": "error",
- "open-pencil/no-vue-parent-relative-imports": "error",
- "open-pencil/no-cli-parent-relative-imports": "error",
"open-pencil/no-core-self-package-imports": "error",
"open-pencil/no-inline-prompt-constants": "error",
"open-pencil/no-direct-graph-emitter-subscriptions": "error",
@@ -227,7 +223,33 @@
"open-pencil/prefer-vueuse-timeouts": "error",
"open-pencil/vue-component-file-pascal-case": "error",
"open-pencil/component-namespace-casing": "error",
- "open-pencil/no-mixed-case-acronym-identifiers": "error",
+ "open-pencil/no-mixed-case-acronym-identifiers": [
+ "error",
+ {
+ "ignoredImports": [
+ "@agentclientprotocol/sdk",
+ "@realfavicongenerator/generate-favicon",
+ "@tauri-apps/plugin-clipboard-manager",
+ "@tauri-apps/plugin-opener",
+ "@vueuse/core",
+ "culori",
+ "reka-ui"
+ ],
+ "ignoredIdentifiers": [
+ "convertToHsb",
+ "convertToHsl",
+ "convertToRgb",
+ "formatCss",
+ "formatRgb",
+ "McpServer",
+ "ndJsonStream",
+ "openUrl",
+ "useObjectUrl",
+ "useUrlSearchParams",
+ "writeHtml"
+ ]
+ }
+ ],
"open-pencil/non-component-source-directories-kebab-case": "error",
"open-pencil/no-component-root-sibling-folder": "error",
"open-pencil/no-flat-kiwi-modules": "error",
@@ -440,6 +462,30 @@
"open-pencil/no-widen-then-assert": "error"
},
"overrides": [
+ {
+ "files": ["packages/core/src/**"],
+ "rules": {
+ "open-pencil/no-deep-parent-relative-imports": ["error", { "minDepth": 1, "alias": "#core/*" }]
+ }
+ },
+ {
+ "files": ["packages/mcp/src/**"],
+ "rules": {
+ "open-pencil/no-deep-parent-relative-imports": ["error", { "minDepth": 1, "alias": "#mcp/*" }]
+ }
+ },
+ {
+ "files": ["packages/vue/src/**"],
+ "rules": {
+ "open-pencil/no-deep-parent-relative-imports": ["error", { "minDepth": 1, "alias": "#vue/*" }]
+ }
+ },
+ {
+ "files": ["packages/cli/src/**"],
+ "rules": {
+ "open-pencil/no-deep-parent-relative-imports": ["error", { "minDepth": 1, "alias": "#cli/*" }]
+ }
+ },
{
"files": ["packages/cloud/src/server/db/migrations/*.ts"],
"rules": {
@@ -470,7 +516,7 @@
"files": ["packages/cloud/src/server/**/*.ts"],
"rules": {
"open-pencil/no-raw-sql": "error",
- "open-pencil/no-cloud-dynamic-html": "error"
+ "open-pencil/no-dynamic-html": "error"
}
},
{
@@ -497,8 +543,8 @@
"src/app/integrations/storage/cloud/**/*.ts"
],
"rules": {
- "open-pencil/no-cloud-secret-in-query": "error",
- "open-pencil/no-cloud-secret-logging": "error"
+ "open-pencil/no-secret-in-query": "error",
+ "open-pencil/no-secret-logging": "error"
}
},
{
@@ -508,7 +554,7 @@
}
},
{
- "files": ["tools/checks/lint/src/rules/quality/widen-then-assert.ts"],
+ "files": ["packages/oxlint-plugin/src/rules/quality/widen-then-assert.ts"],
"rules": {
"complexity": "off"
}
@@ -516,7 +562,9 @@
{
"files": [
"tools/checks/lint/src/**/*.ts",
- "tools/checks/lint/tests/**/*.ts"
+ "tools/checks/lint/tests/**/*.ts",
+ "packages/oxlint-plugin/src/**/*.ts",
+ "packages/oxlint-plugin/tests/**/*.ts"
],
"rules": {
"open-pencil/no-generated-test-id-literals": "off",
@@ -542,7 +590,10 @@
{
"files": ["src/**/*.{ts,vue}", "packages/*/src/**/*.{ts,vue}"],
"rules": {
- "open-pencil/valibot-schema-conventions": "error"
+ "open-pencil/valibot-schema-conventions": [
+ "error",
+ { "schemaModules": ["/packages/cloud/src/contract/"] }
+ ]
}
},
{
diff --git a/package.json b/package.json
index 15feb0cfc..5f4dbaa79 100644
--- a/package.json
+++ b/package.json
@@ -14,6 +14,7 @@
"packages/dom-css",
"packages/design-jsx",
"packages/emit",
+ "packages/oxlint-plugin",
"packages/vue",
"packages/cli",
"packages/mcp",
@@ -66,9 +67,9 @@
"build:native-test": "bun run generate:icons --target desktop && bun run build:packages && bun tauri build --debug --no-bundle --features native-test --config desktop/tauri.native-test.conf.json",
"benchmark:navigation": "bun tools/dev/navigation-benchmark/src/cli.ts run",
"test:native": "bun run build:native-test && wdio run wdio.conf.ts",
- "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/kiwi/src/ packages/fig/src/ packages/drawio/src/ packages/mermaid/src/ packages/docs/.vitepress/theme/landing/",
- "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",
- "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/",
+ "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/oxlint-plugin/src/ packages/kiwi/src/ packages/fig/src/ packages/drawio/src/ packages/mermaid/src/ packages/docs/.vitepress/theme/landing/",
+ "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/oxlint-plugin/src/ packages/oxlint-plugin/tests/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",
+ "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/oxlint-plugin/src/ packages/oxlint-plugin/tests/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/",
"format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)",
"check": "bun run check:icons && bun run build:packages && bun run lint && tsc --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:cloud-off && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes",
"check:commits": "commitlint",
@@ -102,10 +103,10 @@
"test:unit:heavy": "bun tools/dev/unit-tests/src/run.ts all --heavy-only -- --timeout 180000",
"test:coverage": "bun tools/dev/unit-tests/src/run.ts all --include-heavy -- --coverage",
"test:type-shapes": "bun tools/checks/type-shapes/src/index.ts",
- "test:tools": "bun --filter '@open-pencil/*-tools' test && bun --filter @open-pencil/harness test",
+ "test:tools": "bun --filter '@open-pencil/*-tools' test && bun --filter @open-pencil/harness test && bun --filter @open-pencil/oxlint-plugin test",
"test:feedback": "bun --filter @open-pencil/feedback typecheck && bun --filter @open-pencil/feedback check:types && bun --filter @open-pencil/feedback test",
"test:cloud": "bun --filter @open-pencil/cloud typecheck && bun --filter @open-pencil/cloud test",
- "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/emit/src packages/core/src packages/cli/src packages/feedback/src packages/cloud/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
+ "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/emit/src packages/oxlint-plugin/src packages/core/src packages/cli/src packages/feedback/src packages/cloud/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
"test:packages": "bun tools/checks/package-quality/src/cli.ts verify",
"build:packages": "bun tools/release/package-artifacts/src/build.ts",
"open-pencil": "bun packages/cli/src/index.ts",
diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.md
index 04001ef17..17f875993 100644
--- a/packages/cloud/AGENTS.md
+++ b/packages/cloud/AGENTS.md
@@ -25,7 +25,7 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo
- A revision's images live in `revision_image`; code that makes a revision from another copies them with `copyRevisionImages`, and a storage object a `workspace_image` holds is never unreferenced (`src/server/documents/images.ts`, `tests/integration/server/documents/images.test.ts`).
- Add schema changes as a new numbered migration in `src/server/db/migrations/` registered in `src/server/db/migrate.ts`; never edit a migration that has shipped. Better Auth's tables have their own versioned migration (`016_auth_schema.ts`).
- Raw SQL lives only in migrations and the reviewed helpers in `src/server/db/expressions.ts`; everything else uses typed Kysely queries (`open-pencil/no-cloud-raw-sql`).
-- Cloud code keeps secrets out of query strings and logs, and the server never builds an HTML response from values (`open-pencil/no-cloud-secret-in-query`, `open-pencil/no-cloud-secret-logging`, `open-pencil/no-cloud-dynamic-html`).
+- Cloud code keeps secrets out of query strings and logs, and the server never builds an HTML response from values (`open-pencil/no-secret-in-query`, `open-pencil/no-secret-logging`, `open-pencil/no-dynamic-html`).
## Collaboration relay
diff --git a/packages/oxlint-plugin/AGENTS.md b/packages/oxlint-plugin/AGENTS.md
new file mode 100644
index 000000000..63c75412d
--- /dev/null
+++ b/packages/oxlint-plugin/AGENTS.md
@@ -0,0 +1,9 @@
+# @open-pencil/oxlint-plugin
+
+The published Oxlint plugin. `lint/plugin.js` combines it with this repository's own rules from `tools/checks/lint` into the one `open-pencil` plugin `oxlint.json` configures.
+
+- A rule belongs here only when it holds for any TypeScript project. Paths, packages, and names a project chooses are rule options, set in `oxlint.json`, never constants in the rule (`schemaModules` in `src/rules/quality/valibot-schemas.ts`, `ignoredImports` in `src/rules/naming.ts`); rules about the app, Vue, Tauri, or the scene graph stay in `tools/checks/lint`.
+- Type rules with `@oxlint/plugins` (`defineRule`, `ESTree`), never `@typescript-eslint/utils`, so the published declarations need no other package (`check:packages`).
+- Import the package's own modules through `#oxlint-plugin/*` without an extension: `lint/plugin.js` loads the source under Node, which resolves the alias to the `.ts` file, so `bun run lint` needs no build.
+- A new rule is registered in `src/index.ts`, listed in `README.md`, and tested in `tests/rules/`, mirroring its source file, through `tests/helpers/lint.ts`, which runs Oxlint on the package source.
+- Renaming or removing a rule breaks consumers' configurations; record it under `breaking` in the changelog.
diff --git a/packages/oxlint-plugin/README.md b/packages/oxlint-plugin/README.md
new file mode 100644
index 000000000..38961c374
--- /dev/null
+++ b/packages/oxlint-plugin/README.md
@@ -0,0 +1,70 @@
+# @open-pencil/oxlint-plugin
+
+OpenPencil's code conventions as [Oxlint](https://oxc.rs/docs/guide/usage/linter) rules, for any TypeScript project that wants them. The rules cover runtime validation, type assertions, error handling, secrets, imports, and file layout.
+
+```sh
+npm install --save-dev oxlint @open-pencil/oxlint-plugin
+```
+
+```json
+{
+ "jsPlugins": ["@open-pencil/oxlint-plugin"],
+ "rules": {
+ "open-pencil/no-unvalidated-json-parse": "error",
+ "open-pencil/no-silent-catch": "error",
+ "open-pencil/valibot-schema-conventions": ["error", { "schemaModules": ["/src/contract/"] }]
+ }
+}
+```
+
+The plugin is named `open-pencil`. Every rule is off until the configuration turns it on, so a project picks the ones it follows.
+
+## Rules
+
+### Validation and data
+
+| Rule | What it asks for |
+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `no-unvalidated-json-parse` | Validate parsed JSON with a schema, `v.safeParse(v.pipe(v.string(), v.parseJson(), Schema), text)`, instead of asserting a type on `JSON.parse` or `.json()`. |
+| `valibot-schema-conventions` | Name module-level Valibot schemas `<name>Schema` and export them only from a `schema.ts`, or from a directory in `schemaModules`. `{ "placement": false }` checks names only. |
+| `no-hand-rolled-base64` | Use `js-base64` instead of `atob`, `btoa`, or `Buffer` Base64 conversions. |
+| `prefer-es-toolkit` | Use `es-toolkit`'s `uniq` and `compact` instead of `Set` round trips and `filter(Boolean)`. |
+| `no-reduce-accumulator-copy` | Do not copy the accumulator on every `reduce` step. |
+| `no-raw-sql` | Use Kysely's typed query builder instead of `sql` templates. Turn it off for migrations and reviewed helpers. |
+
+### Types
+
+| Rule | What it asks for |
+| ---------------------------------- | ------------------------------------------------------------------------- |
+| `no-broad-double-cast` | No `as unknown as T`. |
+| `no-unknown-record-double-cast` | No `as unknown as Record<string, unknown>`. |
+| `no-broad-unknown-type-assertions` | No assertions to `Record<string, unknown>` or inline shapes of `unknown`. |
+| `no-widen-then-assert` | Do not widen a known value and assert it back to a narrower type. |
+| `no-duplicate-type-shapes` | One named type per object shape in a file. |
+| `no-function-type` | An explicit signature instead of `Function`. |
+| `no-import-type-annotations` | A top-level `import type` instead of an inline `import()` type. |
+| `no-ts-suppression-comments` | No `@ts-ignore`, `@ts-expect-error`, or `@ts-nocheck`. |
+
+### Runtime and security
+
+| Rule | What it asks for |
+| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `no-silent-catch` | No empty `catch` blocks. |
+| `no-math-random` | `crypto.getRandomValues()` instead of `Math.random()`. |
+| `no-reflect-delete-global-this-outside-tests` | No `Reflect.deleteProperty(globalThis, …)` outside `tests/`. |
+| `no-module-mocking` | Inject dependencies instead of mocking modules in tests. |
+| `no-secret-in-query` | Secrets and tokens in a URL fragment or request body, never its query string. |
+| `no-secret-logging` | Never log secrets, tokens, cookies, or authorization values. |
+| `no-dynamic-html` | Return typed JSON or a constant body; never build an HTML response from values. Every `.html(...)` call counts as a response, as Hono's `context.html` is, so turn it on for server code only. |
+| `no-conditional-object-spreads` | An explicit branch instead of several or large conditional spreads in one object. |
+
+### Imports, naming, and layout
+
+| Rule | What it asks for |
+| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `no-deep-parent-relative-imports` | An alias instead of `../../` imports. `minDepth` (default 2) sets how many `../` are too many, and `alias` names the alias in the message. |
+| `no-deep-parent-relative-paths` | A path helper or alias instead of climbing two directories from `import.meta`. |
+| `no-function-alias-imports` | No imports renamed to end in `Fn`. |
+| `no-useless-pass-through-wrappers` | No functions that only call another with the same arguments. |
+| `no-mixed-case-acronym-identifiers` | `baseURL`, not `baseUrl`. `ignoredImports` lists packages whose names keep their casing where imported, and `ignoredIdentifiers` lists upstream names used as they are. |
+| `no-sibling-domain-prefixed-files` | `list/actions.ts`, not `list-actions.ts` beside a `list/` folder. |
diff --git a/packages/oxlint-plugin/package.json b/packages/oxlint-plugin/package.json
new file mode 100644
index 000000000..a64779120
--- /dev/null
+++ b/packages/oxlint-plugin/package.json
@@ -0,0 +1,58 @@
+{
+ "name": "@open-pencil/oxlint-plugin",
+ "version": "0.17.0-beta.1",
+ "description": "OpenPencil's code conventions as Oxlint rules: validated JSON, Valibot schema placement, no broad casts, no silent catches, no secrets in logs or URLs, and more.",
+ "keywords": [
+ "lint",
+ "oxlint",
+ "oxlint-plugin"
+ ],
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/open-pencil/open-pencil.git",
+ "directory": "packages/oxlint-plugin"
+ },
+ "files": [
+ "dist",
+ "src",
+ "README.md"
+ ],
+ "type": "module",
+ "sideEffects": false,
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "imports": {
+ "#oxlint-plugin/*": "./src/*.ts",
+ "#oxlint-plugin-tests/*": "./tests/*.ts"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "bun": "./src/index.ts",
+ "import": "./dist/index.js",
+ "default": "./dist/index.js"
+ }
+ },
+ "publishConfig": {
+ "access": "public",
+ "provenance": true
+ },
+ "scripts": {
+ "build": "bunx tsdown --config tsdown.config.ts",
+ "check": "bun run typecheck && bun run test && bun run build",
+ "prepack": "bun run build",
+ "test": "bun test tests",
+ "typecheck": "bunx tsc --noEmit -p tsconfig.json"
+ },
+ "dependencies": {
+ "@oxlint/plugins": "1.57.0",
+ "es-toolkit": "^1.52.0"
+ },
+ "peerDependencies": {
+ "oxlint": ">=1.90.0"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+}
diff --git a/packages/oxlint-plugin/src/index.ts b/packages/oxlint-plugin/src/index.ts
new file mode 100644
index 000000000..676460244
--- /dev/null
+++ b/packages/oxlint-plugin/src/index.ts
@@ -0,0 +1,79 @@
+import {
+ noDeepParentRelativeImports,
+ noDeepParentRelativePaths,
+ noFunctionAliasImports
+} from '#oxlint-plugin/rules/imports'
+import { noMixedCaseAcronymIdentifiers } from '#oxlint-plugin/rules/naming'
+import { noHandRolledBase64Rule } from '#oxlint-plugin/rules/quality/base64'
+import { preferEsToolkitRule } from '#oxlint-plugin/rules/quality/es-toolkit'
+import { noUnvalidatedJSONParseRule } from '#oxlint-plugin/rules/quality/json-parse'
+import { noModuleMockingRule } from '#oxlint-plugin/rules/quality/module-mocking'
+import { noReduceAccumulatorCopyRule } from '#oxlint-plugin/rules/quality/reduce-accumulator-copy'
+import { valibotSchemaConventionsRule } from '#oxlint-plugin/rules/quality/valibot-schemas'
+import { noWidenThenAssertRule } from '#oxlint-plugin/rules/quality/widen-then-assert'
+import {
+ noConditionalObjectSpreads,
+ noMathRandom,
+ noReflectDeleteGlobalThisOutsideTests,
+ noSilentCatch
+} from '#oxlint-plugin/rules/runtime'
+import {
+ noDynamicHTMLRule,
+ noSecretInQueryRule,
+ noSecretLoggingRule
+} from '#oxlint-plugin/rules/security'
+import { noRawSQLRule } from '#oxlint-plugin/rules/sql'
+import {
+ noSiblingDomainPrefixedFiles,
+ noUselessPassThroughWrappers
+} from '#oxlint-plugin/rules/structure'
+import {
+ noBroadDoubleCast,
+ noBroadUnknownTypeAssertions,
+ noDuplicateTypeShapes,
+ noFunctionType,
+ noImportTypeAnnotations,
+ noTsSuppressionComments,
+ noUnknownRecordDoubleCast
+} from '#oxlint-plugin/rules/typescript'
+import { definePlugin } from '@oxlint/plugins'
+
+/**
+ * OpenPencil's code conventions as Oxlint rules, named `open-pencil/<rule>`. Every rule is off
+ * until a configuration turns it on.
+ */
+const plugin = definePlugin({
+ meta: { name: 'open-pencil' },
+ rules: {
+ 'no-broad-double-cast': noBroadDoubleCast,
+ 'no-broad-unknown-type-assertions': noBroadUnknownTypeAssertions,
+ 'no-conditional-object-spreads': noConditionalObjectSpreads,
+ 'no-deep-parent-relative-imports': noDeepParentRelativeImports,
+ 'no-deep-parent-relative-paths': noDeepParentRelativePaths,
+ 'no-duplicate-type-shapes': noDuplicateTypeShapes,
+ 'no-dynamic-html': noDynamicHTMLRule,
+ 'no-function-alias-imports': noFunctionAliasImports,
+ 'no-function-type': noFunctionType,
+ 'no-hand-rolled-base64': noHandRolledBase64Rule,
+ 'no-import-type-annotations': noImportTypeAnnotations,
+ 'no-math-random': noMathRandom,
+ 'no-mixed-case-acronym-identifiers': noMixedCaseAcronymIdentifiers,
+ 'no-module-mocking': noModuleMockingRule,
+ 'no-raw-sql': noRawSQLRule,
+ 'no-reduce-accumulator-copy': noReduceAccumulatorCopyRule,
+ 'no-reflect-delete-global-this-outside-tests': noReflectDeleteGlobalThisOutsideTests,
+ 'no-secret-in-query': noSecretInQueryRule,
+ 'no-secret-logging': noSecretLoggingRule,
+ 'no-sibling-domain-prefixed-files': noSiblingDomainPrefixedFiles,
+ 'no-silent-catch': noSilentCatch,
+ 'no-ts-suppression-comments': noTsSuppressionComments,
+ 'no-unknown-record-double-cast': noUnknownRecordDoubleCast,
+ 'no-unvalidated-json-parse': noUnvalidatedJSONParseRule,
+ 'no-useless-pass-through-wrappers': noUselessPassThroughWrappers,
+ 'no-widen-then-assert': noWidenThenAssertRule,
+ 'prefer-es-toolkit': preferEsToolkitRule,
+ 'valibot-schema-conventions': valibotSchemaConventionsRule
+ }
+})
+
+export default plugin
diff --git a/packages/oxlint-plugin/src/rules/imports.ts b/packages/oxlint-plugin/src/rules/imports.ts
new file mode 100644
index 000000000..d6f78f2b1
--- /dev/null
+++ b/packages/oxlint-plugin/src/rules/imports.ts
@@ -0,0 +1,149 @@
+import { importSource } from '#oxlint-plugin/support/context'
+import { defineRule } from '@oxlint/plugins'
+import type { ESTree } from '@oxlint/plugins'
+
+type ParentRelativeImportOptions = {
+ /** How many `../` segments an import may climb before it needs an alias; 2 by default. */
+ minDepth?: number
+ /** The alias to name in the message, such as `#core/*`. */
+ alias?: string
+}
+
+/** How many `../` segments a module path starts with. */
+function parentDepth(source: string): number {
+ return (source.match(/^(?:\.\.\/)+/)?.[0].length ?? 0) / '../'.length
+}
+
+const noDeepParentRelativeImports = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow deep parent-relative imports — use package or test aliases instead'
+ },
+ schema: [
+ {
+ type: 'object',
+ properties: { minDepth: { type: 'integer', minimum: 1 }, alias: { type: 'string' } },
+ additionalProperties: false
+ }
+ ]
+ },
+ create(context) {
+ const options: ParentRelativeImportOptions =
+ (context.options[0] as ParentRelativeImportOptions | undefined) ?? {}
+ const minDepth = options.minDepth ?? 2
+ const message = options.alias
+ ? `Use the ${options.alias} alias instead of parent-relative imports.`
+ : 'Use an import alias instead of path drilling with ../.. imports.'
+
+ function check(
+ node:
+ | ESTree.ImportDeclaration
+ | ESTree.ExportAllDeclaration
+ | ESTree.ExportNamedDeclaration
+ | ESTree.ImportExpression
+ ) {
+ const source = importSource(node)
+ if (!source?.startsWith('../')) return
+ if (parentDepth(source) < minDepth) return
+ if (/^(?:\.\.\/)+package\.json$/.test(source)) return
+ context.report({ node, message })
+ }
+
+ return {
+ ExportAllDeclaration: check,
+ ExportNamedDeclaration: check,
+ ImportDeclaration: check,
+ ImportExpression: check
+ }
+ }
+})
+
+/**
+ * A path that climbs two or more directories, written as `../..`, `..\\..`, or `'..', '..'`.
+ * An unknown part, such as a template expression, ends the run of parent segments.
+ */
+function climbsTwoLevels(values: (string | null)[]): boolean {
+ const joined = values
+ .map((value) => value ?? '\u0000')
+ .join('/')
+ .replaceAll('\\', '/')
+ return /(^|\/)\.\.\/+\.\.(\/|$)/.test(joined)
+}
+
+function staticString(node: ESTree.Node): string | null {
+ if (node.type === 'Literal' && typeof node.value === 'string') return node.value
+ if (node.type === 'TemplateLiteral') {
+ const head = node.quasis[0]?.value.cooked ?? null
+ return head !== null && node.expressions.length ? `${head}\u0000` : head
+ }
+ return null
+}
+
+/** `import.meta.url`, `.dir`, or `.dirname`, directly or wrapped, as in `dirname(fileURLToPath(import.meta.url))`. */
+function isImportMetaLocation(node: ESTree.Node): boolean {
+ if (node.type === 'MemberExpression') {
+ if (node.object.type === 'MetaProperty') {
+ return (
+ node.property.type === 'Identifier' &&
+ ['url', 'dir', 'dirname'].includes(node.property.name)
+ )
+ }
+ return isImportMetaLocation(node.object)
+ }
+ if (node.type === 'CallExpression') return node.arguments.some(isImportMetaLocation)
+ return false
+}
+
+const noDeepParentRelativePaths = defineRule({
+ meta: {
+ docs: {
+ description:
+ 'Disallow climbing two or more directories from import.meta — use a path helper or alias'
+ }
+ },
+ create(context) {
+ const message =
+ 'Resolve the file through a path helper or an import alias instead of climbing with ../..'
+ function check(node: ESTree.Node, relative: readonly ESTree.Node[]) {
+ if (relative.length && climbsTwoLevels(relative.map(staticString))) {
+ context.report({ node, message })
+ }
+ }
+ return {
+ NewExpression(node) {
+ if (node.callee.type !== 'Identifier' || node.callee.name !== 'URL') return
+ const [path, base] = node.arguments
+ if (!path || !base || !isImportMetaLocation(base)) return
+ check(node, [path])
+ },
+ CallExpression(node) {
+ const start = node.arguments.findIndex(isImportMetaLocation)
+ if (start !== -1) check(node, node.arguments.slice(start + 1))
+ }
+ }
+ }
+})
+
+const noFunctionAliasImports = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow import aliases ending in Fn for facade delegation'
+ }
+ },
+ create(context) {
+ return {
+ ImportSpecifier(node) {
+ if (node.imported.type !== 'Identifier') return
+ if (node.imported.name === node.local.name) return
+ if (!node.local.name.endsWith('Fn')) return
+ context.report({
+ node,
+ message:
+ 'Avoid aliasing imports as *Fn. Use a namespace import or give the exported helper a clearer domain name.'
+ })
+ }
+ }
+ }
+})
+
+export { noDeepParentRelativeImports, noDeepParentRelativePaths, noFunctionAliasImports }
diff --git a/packages/oxlint-plugin/src/rules/naming.ts b/packages/oxlint-plugin/src/rules/naming.ts
new file mode 100644
index 000000000..8bd4b6b9a
--- /dev/null
+++ b/packages/oxlint-plugin/src/rules/naming.ts
@@ -0,0 +1,85 @@
+import { defineRule } from '@oxlint/plugins'
+import type { ESTree } from '@oxlint/plugins'
+
+const ACRONYMS =
+ /(?:Acp|Ai|Api|Cli|Cors|Css|Html|Ime|Json|Jsx|Mcp|Pdf|Png|Rgb|Rpc|Rtl|Svg|Ui|Url|Uri|Xml)/g
+
+type AcronymOptions = {
+ /** Packages whose exported names keep their own casing where they are imported. */
+ ignoredImports?: string[]
+ /** Upstream names used without importing them by name, such as members and callbacks. */
+ ignoredIdentifiers?: string[]
+}
+
+function isObjectKey(node: ESTree.Node): boolean {
+ const { parent } = node
+ return (
+ (parent?.type === 'Property' || parent?.type === 'TSPropertySignature') &&
+ parent.key === node &&
+ !parent.computed &&
+ (parent.type !== 'Property' || parent.value !== node)
+ )
+}
+
+function isExternalMember(node: ESTree.Node): boolean {
+ const { parent } = node
+ return (
+ parent?.type === 'MemberExpression' &&
+ parent.property === node &&
+ !parent.computed &&
+ parent.object.type !== 'ThisExpression'
+ )
+}
+
+/** Names another package chose: imported by name from an ignored package, or under any default or namespace import. */
+function isUpstreamImport(node: ESTree.Node, ignoredImports: ReadonlySet<string>): boolean {
+ const { parent } = node
+ if (parent?.type === 'ImportSpecifier' && parent.imported === node) {
+ const declaration = parent.parent
+ return declaration.type !== 'ImportDeclaration' || ignoredImports.has(declaration.source.value)
+ }
+ return parent?.type === 'ImportDefaultSpecifier' || parent?.type === 'ImportNamespaceSpecifier'
+}
+
+const noMixedCaseAcronymIdentifiers = defineRule({
+ meta: {
+ docs: {
+ description: 'Require canonical uppercase casing for acronyms in first-party identifiers'
+ },
+ schema: [
+ {
+ type: 'object',
+ properties: {
+ ignoredImports: { type: 'array', items: { type: 'string' } },
+ ignoredIdentifiers: { type: 'array', items: { type: 'string' } }
+ },
+ additionalProperties: false
+ }
+ ]
+ },
+ create(context) {
+ const options: AcronymOptions = (context.options[0] as AcronymOptions | undefined) ?? {}
+ const ignoredImports = new Set(options.ignoredImports)
+ const ignoredIdentifiers = new Set(options.ignoredIdentifiers)
+
+ return {
+ Identifier(node) {
+ if (ignoredIdentifiers.has(node.name)) return
+ const mixedCase = [...node.name.matchAll(ACRONYMS)].some((match) => {
+ const end = match.index + match[0].length
+ return end === node.name.length || /[A-Z0-9_$]/.test(node.name[end] ?? '')
+ })
+ if (!mixedCase) return
+ if (isObjectKey(node) || isExternalMember(node) || isUpstreamImport(node, ignoredImports)) {
+ return
+ }
+ context.report({
+ node,
+ message: `Use canonical uppercase acronym casing in "${node.name}".`
+ })
+ }
+ }
+ }
+})
+
+export { noMixedCaseAcronymIdentifiers }
diff --git a/tools/checks/lint/src/rules/quality/base64.ts b/packages/oxlint-plugin/src/rules/quality/base64.ts
similarity index 84%
rename from tools/checks/lint/src/rules/quality/base64.ts
rename to packages/oxlint-plugin/src/rules/quality/base64.ts
index 28e1a3821..952e194c7 100644
--- a/tools/checks/lint/src/rules/quality/base64.ts
+++ b/packages/oxlint-plugin/src/rules/quality/base64.ts
@@ -1,4 +1,5 @@
-import { resolveVariable } from '#lint/support/scope.ts'
+import { staticMemberName } from '#oxlint-plugin/support/ast'
+import { resolveVariable } from '#oxlint-plugin/support/scope'
import { defineRule } from '@oxlint/plugins'
import type { ESTree, SourceCode } from '@oxlint/plugins'
@@ -18,13 +19,6 @@ function isGlobalBase64Function(sourceCode: SourceCode, node: ESTree.IdentifierR
return variable === null || variable.defs.length === 0
}
-function propertyName(node: ESTree.MemberExpression): string | null {
- if (!node.computed && node.property.type === 'Identifier') return node.property.name
- if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
- return node.property.value
- return null
-}
-
/** Require js-base64 instead of the platform's string-based or Node-only Base64 conversions. */
export const noHandRolledBase64Rule = defineRule({
meta: {
@@ -47,7 +41,7 @@ export const noHandRolledBase64Rule = defineRule({
return
}
if (callee.type !== 'MemberExpression') return
- const name = propertyName(callee)
+ const name = staticMemberName(callee)
const onGlobal =
callee.object.type === 'Identifier' && GLOBAL_OBJECTS.has(callee.object.name)
const bufferFrom =
diff --git a/tools/checks/lint/src/rules/quality/es-toolkit.ts b/packages/oxlint-plugin/src/rules/quality/es-toolkit.ts
similarity index 90%
rename from tools/checks/lint/src/rules/quality/es-toolkit.ts
rename to packages/oxlint-plugin/src/rules/quality/es-toolkit.ts
index a950998a5..19b5f8516 100644
--- a/tools/checks/lint/src/rules/quality/es-toolkit.ts
+++ b/packages/oxlint-plugin/src/rules/quality/es-toolkit.ts
@@ -1,4 +1,5 @@
-import { resolveVariable } from '#lint/support/scope.ts'
+import { staticMemberName } from '#oxlint-plugin/support/ast'
+import { resolveVariable } from '#oxlint-plugin/support/scope'
import { defineRule } from '@oxlint/plugins'
import type { ESTree, SourceCode } from '@oxlint/plugins'
@@ -29,13 +30,6 @@ const SERIALIZED_CALLBACK_METHODS = new Set([
'waitForFunction'
])
-function propertyName(node: ESTree.MemberExpression): string | null {
- if (!node.computed && node.property.type === 'Identifier') return node.property.name
- if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
- return node.property.value
- return null
-}
-
/** A global such as `Set` or `Boolean` that no local binding shadows. */
function isGlobal(sourceCode: SourceCode, node: ESTree.Node, name: string): boolean {
if (node.type !== 'Identifier' || node.name !== name) return false
@@ -61,7 +55,7 @@ function isSetOfArray(sourceCode: SourceCode, node: ESTree.Node | undefined): bo
function isMethodCall(node: ESTree.Node, methods: ReadonlySet<string>): boolean {
if (node.type !== 'CallExpression' || node.callee.type !== 'MemberExpression') return false
- const name = propertyName(node.callee)
+ const name = staticMemberName(node.callee)
return name !== null && methods.has(name)
}
@@ -109,7 +103,7 @@ export const preferEsToolkitRule = defineRule({
CallExpression(node) {
const { sourceCode } = context
if (node.callee.type !== 'MemberExpression' || insideSerializedCallback(node)) return
- const name = propertyName(node.callee)
+ const name = staticMemberName(node.callee)
const [argument] = node.arguments
if (
name === 'from' &&
diff --git a/tools/checks/lint/src/rules/quality/json-parse.ts b/packages/oxlint-plugin/src/rules/quality/json-parse.ts
similarity index 86%
rename from tools/checks/lint/src/rules/quality/json-parse.ts
rename to packages/oxlint-plugin/src/rules/quality/json-parse.ts
index 702ae6602..78de164e5 100644
--- a/tools/checks/lint/src/rules/quality/json-parse.ts
+++ b/packages/oxlint-plugin/src/rules/quality/json-parse.ts
@@ -1,4 +1,5 @@
-import { resolveVariable } from '#lint/support/scope.ts'
+import { staticMemberName } from '#oxlint-plugin/support/ast'
+import { resolveVariable } from '#oxlint-plugin/support/scope'
import { defineRule } from '@oxlint/plugins'
import type { ESTree, SourceCode } from '@oxlint/plugins'
@@ -6,13 +7,6 @@ type Assertion = Extract<ESTree.Node, { type: 'TSAsExpression' | 'TSTypeAssertio
const GLOBAL_OBJECTS = new Set(['globalThis', 'window', 'self'])
-function propertyName(node: ESTree.MemberExpression): string | null {
- if (!node.computed && node.property.type === 'Identifier') return node.property.name
- if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
- return node.property.value
- return null
-}
-
/** The global `JSON`, directly or through `globalThis`, that no local binding shadows. */
function isGlobalJSON(sourceCode: SourceCode, node: ESTree.Expression): boolean {
if (node.type === 'Identifier') {
@@ -24,13 +18,13 @@ function isGlobalJSON(sourceCode: SourceCode, node: ESTree.Expression): boolean
node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
GLOBAL_OBJECTS.has(node.object.name) &&
- propertyName(node) === 'JSON'
+ staticMemberName(node) === 'JSON'
)
}
function isJSONParseCall(sourceCode: SourceCode, node: ESTree.Expression): boolean {
if (node.type !== 'CallExpression' || node.callee.type !== 'MemberExpression') return false
- return propertyName(node.callee) === 'parse' && isGlobalJSON(sourceCode, node.callee.object)
+ return staticMemberName(node.callee) === 'parse' && isGlobalJSON(sourceCode, node.callee.object)
}
/** `response.json()`, `Bun.file(path).json()` and the like: a parse with no schema. */
@@ -39,7 +33,7 @@ function isJSONMethodCall(node: ESTree.Expression): boolean {
node.type === 'CallExpression' &&
node.arguments.length === 0 &&
node.callee.type === 'MemberExpression' &&
- propertyName(node.callee) === 'json'
+ staticMemberName(node.callee) === 'json'
)
}
diff --git a/tools/checks/lint/src/rules/quality/module-mocking.ts b/packages/oxlint-plugin/src/rules/quality/module-mocking.ts
similarity index 97%
rename from tools/checks/lint/src/rules/quality/module-mocking.ts
rename to packages/oxlint-plugin/src/rules/quality/module-mocking.ts
index f04280f4b..5ab1cb67d 100644
--- a/tools/checks/lint/src/rules/quality/module-mocking.ts
+++ b/packages/oxlint-plugin/src/rules/quality/module-mocking.ts
@@ -1,4 +1,4 @@
-import { resolveVariable } from '#lint/support/scope.ts'
+import { resolveVariable } from '#oxlint-plugin/support/scope'
import { defineRule } from '@oxlint/plugins'
import type { ESTree, SourceCode } from '@oxlint/plugins'
diff --git a/tools/checks/lint/src/rules/quality/reduce-accumulator-copy.ts b/packages/oxlint-plugin/src/rules/quality/reduce-accumulator-copy.ts
similarity index 91%
rename from tools/checks/lint/src/rules/quality/reduce-accumulator-copy.ts
rename to packages/oxlint-plugin/src/rules/quality/reduce-accumulator-copy.ts
index 5cf907b81..bd155fec1 100644
--- a/tools/checks/lint/src/rules/quality/reduce-accumulator-copy.ts
+++ b/packages/oxlint-plugin/src/rules/quality/reduce-accumulator-copy.ts
@@ -3,7 +3,8 @@ import {
isKnownArrayExpression,
resolveArrayBinding,
unwrapArrayExpression
-} from '#lint/support/array-method.ts'
+} from '#oxlint-plugin/support/array-method'
+import { constInitializer } from '#oxlint-plugin/support/scope'
import { defineRule } from '@oxlint/plugins'
import type { ESTree, SourceCode, Variable } from '@oxlint/plugins'
@@ -48,18 +49,8 @@ function referencesAccumulator(
if (variable === accumulator) return true
visited.add(variable)
if (variable.references.some((reference) => reference.isWrite() && !reference.init)) return false
- for (const definition of variable.defs) {
- if (
- definition.type === 'Variable' &&
- definition.node.type === 'VariableDeclarator' &&
- definition.node.id.type === 'Identifier' &&
- definition.node.init !== null &&
- definition.node.parent.type === 'VariableDeclaration' &&
- definition.node.parent.kind === 'const'
- ) {
- return referencesAccumulator(sourceCode, definition.node.init, accumulator, visited)
- }
- }
+ const initializer = constInitializer(variable)
+ if (initializer) return referencesAccumulator(sourceCode, initializer, accumulator, visited)
return false
}
diff --git a/tools/checks/lint/src/rules/quality/valibot-schemas.ts b/packages/oxlint-plugin/src/rules/quality/valibot-schemas.ts
similarity index 85%
rename from tools/checks/lint/src/rules/quality/valibot-schemas.ts
rename to packages/oxlint-plugin/src/rules/quality/valibot-schemas.ts
index 57e49d31c..21656d828 100644
--- a/tools/checks/lint/src/rules/quality/valibot-schemas.ts
+++ b/packages/oxlint-plugin/src/rules/quality/valibot-schemas.ts
@@ -1,4 +1,4 @@
-import { normalizedFilename } from '#lint/support/context.ts'
+import { normalizedFilename } from '#oxlint-plugin/support/context'
import { defineRule } from '@oxlint/plugins'
import type { ESTree } from '@oxlint/plugins'
@@ -102,9 +102,18 @@ const SCHEMA_BUILDERS = new Set([
])
const SCHEMA_NAME = /^[a-z][A-Za-z0-9]*Schema$/
-/** Exported schemas live in a `schema.ts`, or in a Cloud contract module, where a reader looks. */
-function placesExportedSchemas(file: string): boolean {
- return file.endsWith('/schema.ts') || file.includes('/packages/cloud/src/contract/')
+/**
+ * Exported schemas live in a `schema.ts`, or under one of the `schemaModules` directories a
+ * project names, such as a contract shared with other services, where a reader looks.
+ */
+function placesExportedSchemas(file: string, schemaModules: readonly string[]): boolean {
+ return (
+ file.endsWith('/schema.ts') ||
+ // A directory matches whole, so `src/contract` does not also take in `src/contracts/`.
+ schemaModules.some((directory) =>
+ file.includes(directory.endsWith('/') ? directory : `${directory}/`)
+ )
+ )
}
/** The call a declaration's value is, past `as` and `satisfies`. */
@@ -116,11 +125,11 @@ function callOf(node: ESTree.Expression | null | undefined): ESTree.CallExpressi
return current?.type === 'CallExpression' ? current : null
}
-type Options = { placement?: boolean }
+type Options = { placement?: boolean; schemaModules?: string[] }
/**
* Name every module-level Valibot schema `<name>Schema` in camelCase, and export schemas only
- * from a `schema.ts` (or a Cloud contract module), so schemas read alike and are found in one
+ * from a `schema.ts` or a `schemaModules` directory, so schemas read alike and are found in one
* place per domain. `placement: false` checks names only, as for repository tooling.
*/
export const valibotSchemaConventionsRule = defineRule({
@@ -132,7 +141,10 @@ export const valibotSchemaConventionsRule = defineRule({
schema: [
{
type: 'object',
- properties: { placement: { type: 'boolean' } },
+ properties: {
+ placement: { type: 'boolean' },
+ schemaModules: { type: 'array', items: { type: 'string' } }
+ },
additionalProperties: false
}
],
@@ -145,6 +157,7 @@ export const valibotSchemaConventionsRule = defineRule({
create(context) {
const options: Options = (context.options[0] as Options | undefined) ?? {}
const placement = options.placement !== false
+ const schemaModules = options.schemaModules ?? []
/** Local names bound to the Valibot namespace, and to its builders imported by name. */
const namespaces = new Set<string>()
const builders = new Set<string>()
@@ -165,7 +178,7 @@ export const valibotSchemaConventionsRule = defineRule({
}
function reportPlacement(node: ESTree.Node, name: string) {
- if (placement && !placesExportedSchemas(normalizedFilename(context))) {
+ if (placement && !placesExportedSchemas(normalizedFilename(context), schemaModules)) {
context.report({ node, messageId: 'place', data: { name } })
}
}
diff --git a/tools/checks/lint/src/rules/quality/widen-then-assert.ts b/packages/oxlint-plugin/src/rules/quality/widen-then-assert.ts
similarity index 98%
rename from tools/checks/lint/src/rules/quality/widen-then-assert.ts
rename to packages/oxlint-plugin/src/rules/quality/widen-then-assert.ts
index b87c1086b..01f440bda 100644
--- a/tools/checks/lint/src/rules/quality/widen-then-assert.ts
+++ b/packages/oxlint-plugin/src/rules/quality/widen-then-assert.ts
@@ -1,4 +1,4 @@
-import { resolveVariable } from '#lint/support/scope.ts'
+import { resolveVariable } from '#oxlint-plugin/support/scope'
import { defineRule } from '@oxlint/plugins'
import type { ESTree, SourceCode, Variable } from '@oxlint/plugins'
@@ -223,8 +223,7 @@ function knownValueEvidence(
const declarator = variableDeclarator(variable)
if (
- declarator === null ||
- declarator.parent.type !== 'VariableDeclaration' ||
+ declarator?.parent.type !== 'VariableDeclaration' ||
declarator.parent.kind !== 'const' ||
declarator.init === null ||
variable.references.some((reference) => reference.isWrite() && !reference.init) ||
@@ -259,8 +258,7 @@ function widenedBinding(
const declarator = variableDeclarator(variable)
const declaredType = declarator === null ? undefined : nodeTypeAnnotation(declarator.id)
if (
- declarator === null ||
- declarator.parent.type !== 'VariableDeclaration' ||
+ declarator?.parent.type !== 'VariableDeclaration' ||
declarator.parent.kind !== 'const' ||
declarator.id.type !== 'Identifier' ||
declarator.init === null ||
diff --git a/packages/oxlint-plugin/src/rules/runtime.ts b/packages/oxlint-plugin/src/rules/runtime.ts
new file mode 100644
index 000000000..227e7267b
--- /dev/null
+++ b/packages/oxlint-plugin/src/rules/runtime.ts
@@ -0,0 +1,116 @@
+import { isTestFile, normalizedFilename } from '#oxlint-plugin/support/context'
+import { defineRule } from '@oxlint/plugins'
+
+const noMathRandom = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow Math.random() — use crypto.getRandomValues() instead'
+ }
+ },
+ create(context) {
+ return {
+ CallExpression(node) {
+ const { callee } = node
+ if (
+ callee.type === 'MemberExpression' &&
+ callee.object.type === 'Identifier' &&
+ callee.object.name === 'Math' &&
+ callee.property.type === 'Identifier' &&
+ callee.property.name === 'random'
+ ) {
+ context.report({
+ node,
+ message: 'Use crypto.getRandomValues() instead of Math.random().'
+ })
+ }
+ }
+ }
+ }
+})
+
+const noSilentCatch = defineRule({
+ meta: {
+ docs: {
+ description:
+ 'Disallow empty catch blocks — log a warning or re-throw instead of silently swallowing errors'
+ }
+ },
+ create(context) {
+ return {
+ CatchClause(node) {
+ const statements = node.body.body.filter((statement) => statement.type !== 'EmptyStatement')
+ if (statements.length > 0) return
+ context.report({
+ node,
+ message:
+ 'Empty catch block silently swallows errors. Add console.warn(), re-throw, or an explicit // oxlint-ignore-next-line comment.'
+ })
+ }
+ }
+ }
+})
+
+const noReflectDeleteGlobalThisOutsideTests = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow Reflect.deleteProperty(globalThis, ...) outside tests'
+ }
+ },
+ create(context) {
+ if (isTestFile(normalizedFilename(context))) return {}
+
+ return {
+ CallExpression(node) {
+ const { callee } = node
+ if (callee.type !== 'MemberExpression') return
+ if (callee.object.type !== 'Identifier' || callee.object.name !== 'Reflect') return
+ if (callee.property.type !== 'Identifier' || callee.property.name !== 'deleteProperty')
+ return
+ const [first] = node.arguments
+ if (first?.type !== 'Identifier' || first.name !== 'globalThis') return
+ context.report({
+ node,
+ message:
+ 'Do not mutate globalThis outside tests; isolate platform state behind a boundary.'
+ })
+ }
+ }
+ }
+})
+
+const noConditionalObjectSpreads = defineRule({
+ meta: {
+ docs: {
+ description: 'Require explicit branches instead of complex conditional object spreads'
+ }
+ },
+ create(context) {
+ return {
+ SpreadElement(node) {
+ const { parent } = node
+ if (parent.type !== 'ObjectExpression') return
+ if (node.argument.type !== 'ConditionalExpression') return
+ const branchSizes = [node.argument.consequent, node.argument.alternate]
+ .filter((branch) => branch.type === 'ObjectExpression')
+ .map((branch) => branch.properties.length)
+ const conditionalSpreadCount = parent.properties.filter(
+ (property) =>
+ property.type === 'SpreadElement' && property.argument.type === 'ConditionalExpression'
+ ).length
+ if (conditionalSpreadCount < 2 && branchSizes.every((size) => size < 2)) return
+ context.report({
+ node,
+ message:
+ 'Extract conditional object construction into an explicit branch or named domain projection.'
+ })
+ }
+ }
+ }
+})
+
+export {
+ noConditionalObjectSpreads,
+ noMathRandom,
+ noReflectDeleteGlobalThisOutsideTests,
+ noSilentCatch
+}
diff --git a/tools/checks/lint/src/rules/cloud.ts b/packages/oxlint-plugin/src/rules/security.ts
similarity index 79%
rename from tools/checks/lint/src/rules/cloud.ts
rename to packages/oxlint-plugin/src/rules/security.ts
index e16000079..12c07f383 100644
--- a/tools/checks/lint/src/rules/cloud.ts
+++ b/packages/oxlint-plugin/src/rules/security.ts
@@ -1,7 +1,7 @@
+import { staticMemberName } from '#oxlint-plugin/support/ast'
import { defineRule } from '@oxlint/plugins'
import type { ESTree } from '@oxlint/plugins'
-/** Names that hold Cloud credentials: secrets, tokens, cookies, authorization values, room keys. */
/** Names that end in a credential noun: `accessToken` and `authSecret`, not `tokenCount`. */
const SECRET_NAME = /(?:secret|token|authorization|cookie|room_?key|private_?key)s?$/i
/** A secret or token written into a URL's query string. */
@@ -10,13 +10,6 @@ const QUERY_SECRET_NAMES = new Set(['secret', 'token'])
const QUERY_METHODS = new Set(['set', 'append'])
const CONSOLE_METHODS = new Set(['log', 'info', 'warn', 'error', 'debug'])
-function memberName(node: ESTree.MemberExpression): string | null {
- if (!node.computed && node.property.type === 'Identifier') return node.property.name
- if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
- return node.property.value
- return null
-}
-
function isStringLiteral(node: ESTree.Node | undefined): boolean {
if (node?.type === 'Literal') return typeof node.value === 'string'
return node?.type === 'TemplateLiteral' && node.expressions.length === 0
@@ -25,7 +18,7 @@ function isStringLiteral(node: ESTree.Node | undefined): boolean {
/** The name a logged value is read through: `token`, `session.token`, `headers['cookie']`. */
function valueName(node: ESTree.Node): string | null {
if (node.type === 'Identifier') return node.name
- if (node.type === 'MemberExpression') return memberName(node)
+ if (node.type === 'MemberExpression') return staticMemberName(node)
return null
}
@@ -64,11 +57,17 @@ function loggedNames(node: ESTree.Node | null): string[] {
}
}
-/** Cloud APIs answer with typed JSON or a constant body, never HTML assembled from values. */
-export const noCloudDynamicHTMLRule = defineRule({
+/**
+ * APIs answer with typed JSON or a constant body, never HTML assembled from values. It reads every
+ * `.html(...)` call as a response, as Hono's `context.html` is, so turn it on for server code only.
+ */
+export const noDynamicHTMLRule = defineRule({
meta: {
type: 'problem',
- docs: { description: 'Disallow HTML responses built from values in the Cloud server.' },
+ docs: {
+ description:
+ 'Disallow HTML responses built from values; for server code, where `.html()` sends a response.'
+ },
messages: {
dynamic:
'Return typed JSON or a constant HTML body; never build an HTML response from values.'
@@ -78,7 +77,7 @@ export const noCloudDynamicHTMLRule = defineRule({
return {
CallExpression(node) {
const { callee } = node
- if (callee.type !== 'MemberExpression' || memberName(callee) !== 'html') return
+ if (callee.type !== 'MemberExpression' || staticMemberName(callee) !== 'html') return
if (!isStringLiteral(node.arguments[0])) context.report({ node, messageId: 'dynamic' })
}
}
@@ -86,10 +85,10 @@ export const noCloudDynamicHTMLRule = defineRule({
})
/** Capability secrets travel in URL fragments or request bodies, which never reach access logs. */
-export const noCloudSecretInQueryRule = defineRule({
+export const noSecretInQueryRule = defineRule({
meta: {
type: 'problem',
- docs: { description: 'Disallow putting Cloud secrets or tokens in URL query strings.' },
+ docs: { description: 'Disallow putting secrets or tokens in URL query strings.' },
messages: {
query:
'Put capability secrets in the URL fragment or the request body, never the query string.'
@@ -100,10 +99,11 @@ export const noCloudSecretInQueryRule = defineRule({
CallExpression(node) {
const { callee } = node
if (callee.type !== 'MemberExpression') return
- const method = memberName(callee)
+ const method = staticMemberName(callee)
if (!method || !QUERY_METHODS.has(method)) return
const target = callee.object
- if (target.type !== 'MemberExpression' || memberName(target) !== 'searchParams') return
+ if (target.type !== 'MemberExpression' || staticMemberName(target) !== 'searchParams')
+ return
const [key] = node.arguments
if (
key?.type === 'Literal' &&
@@ -132,11 +132,11 @@ export const noCloudSecretInQueryRule = defineRule({
})
/** Logs outlive sessions and leave the machine; credentials never go into them. */
-export const noCloudSecretLoggingRule = defineRule({
+export const noSecretLoggingRule = defineRule({
meta: {
type: 'problem',
docs: {
- description: 'Disallow logging Cloud secrets, tokens, cookies, or authorization values.'
+ description: 'Disallow logging secrets, tokens, cookies, or authorization values.'
},
messages: {
logged: 'Do not log secrets, tokens, cookies, room keys, or authorization values.'
@@ -148,7 +148,7 @@ export const noCloudSecretLoggingRule = defineRule({
const { callee } = node
if (callee.type !== 'MemberExpression') return
if (callee.object.type !== 'Identifier' || callee.object.name !== 'console') return
- const method = memberName(callee)
+ const method = staticMemberName(callee)
if (!method || !CONSOLE_METHODS.has(method)) return
const leaks = node.arguments.some((argument) =>
loggedNames(argument).some((name) => SECRET_NAME.test(name))
diff --git a/tools/checks/lint/src/rules/sql.ts b/packages/oxlint-plugin/src/rules/sql.ts
similarity index 92%
rename from tools/checks/lint/src/rules/sql.ts
rename to packages/oxlint-plugin/src/rules/sql.ts
index 01587b582..05fb84687 100644
--- a/tools/checks/lint/src/rules/sql.ts
+++ b/packages/oxlint-plugin/src/rules/sql.ts
@@ -2,7 +2,7 @@ import { defineRule } from '@oxlint/plugins'
/**
* Kysely's typed builder everywhere; raw `sql` templates only in migrations and reviewed helpers.
- * Applied to the Cloud server and the feedback Worker in oxlint.json.
+ * Turn it on for the code that uses Kysely and off for those files.
*/
export const noRawSQLRule = defineRule({
meta: {
diff --git a/packages/oxlint-plugin/src/rules/structure.ts b/packages/oxlint-plugin/src/rules/structure.ts
new file mode 100644
index 000000000..9a873513e
--- /dev/null
+++ b/packages/oxlint-plugin/src/rules/structure.ts
@@ -0,0 +1,93 @@
+import { existsSync } from 'node:fs'
+
+import { normalizedFilename } from '#oxlint-plugin/support/context'
+import { defineRule } from '@oxlint/plugins'
+import type { ESTree } from '@oxlint/plugins'
+
+const noSiblingDomainPrefixedFiles = defineRule({
+ meta: {
+ type: 'suggestion',
+ docs: {
+ description: 'Disallow files that repeat an existing sibling domain folder in the filename'
+ },
+ schema: []
+ },
+ create(context) {
+ const file = normalizedFilename(context)
+ const match = file.match(/^(.*\/)([^/]+?)(?:\.test|\.spec)?\.(?:ts|tsx|vue)$/)
+ if (!match) return {}
+ const [, directory = '', name = ''] = match
+ // Only the prefix names a domain; suffixes describe kinds (page-list, color-input).
+ const [prefix, ...rest] = name.split('-')
+ if (!prefix || rest.length === 0 || !existsSync(`${directory}${prefix}`)) return {}
+ const message = `Move '${file.slice(directory.length)}' under the existing '${prefix}/' folder instead of repeating the domain in the filename.`
+ return { Program: (node) => context.report({ node, message }) }
+ }
+})
+
+type FunctionBody = ESTree.FunctionBody | ESTree.Expression | null | undefined
+
+function parameterNames(params: readonly ESTree.Node[]): string[] | null {
+ const names: string[] = []
+ for (const param of params) {
+ if (param.type !== 'Identifier') return null
+ names.push(param.name)
+ }
+ return names
+}
+
+function returnedCall(body: FunctionBody): ESTree.CallExpression | null {
+ if (!body) return null
+ if (body.type === 'CallExpression') return body
+ if (body.type !== 'BlockStatement') return null
+ const statements = body.body.filter((statement) => statement.type !== 'EmptyStatement')
+ const [statement] = statements
+ if (statements.length !== 1 || statement?.type !== 'ReturnStatement') return null
+ return statement.argument?.type === 'CallExpression' ? statement.argument : null
+}
+
+const noUselessPassThroughWrappers = defineRule({
+ meta: {
+ docs: {
+ description:
+ 'Disallow functions that only return another function call with the same arguments'
+ }
+ },
+ create(context) {
+ function check(
+ node: ESTree.Node,
+ name: string,
+ params: readonly ESTree.Node[],
+ body: FunctionBody
+ ) {
+ const names = parameterNames(params)
+ if (!names) return
+ const call = returnedCall(body)
+ if (!call || call.arguments.length !== names.length) return
+ const forwards = call.arguments.every(
+ (argument, index) => argument.type === 'Identifier' && argument.name === names[index]
+ )
+ if (!forwards || call.callee.type !== 'Identifier') return
+ const target = call.callee.name
+ if (target === name) return
+ context.report({
+ node,
+ message: `Remove pass-through wrapper '${name}'. Call '${target}' directly or give the wrapper real domain logic.`
+ })
+ }
+
+ return {
+ FunctionDeclaration(node) {
+ if (node.id) check(node, node.id.name, node.params, node.body)
+ },
+ VariableDeclarator(node) {
+ if (node.id.type !== 'Identifier') return
+ const { init } = node
+ if (init?.type !== 'ArrowFunctionExpression' && init?.type !== 'FunctionExpression') return
+ check(node, node.id.name, init.params, init.body)
+ }
+ }
+ }
+})
+
+export { noSiblingDomainPrefixedFiles, noUselessPassThroughWrappers }
diff --git a/packages/oxlint-plugin/src/rules/typescript.ts b/packages/oxlint-plugin/src/rules/typescript.ts
new file mode 100644
index 000000000..f5d490102
--- /dev/null
+++ b/packages/oxlint-plugin/src/rules/typescript.ts
@@ -0,0 +1,322 @@
+import { defineRule } from '@oxlint/plugins'
+import type { ESTree } from '@oxlint/plugins'
+import { compact } from 'es-toolkit/array'
+
+type TypeNode = ESTree.TSType
+
+function typeParameterNodes(node: ESTree.TSTypeReference): TypeNode[] {
+ return node.typeArguments?.params ?? []
+}
+
+function isRecordStringUnknownType(node: TypeNode | null | undefined): boolean {
+ if (node?.type !== 'TSTypeReference') return false
+ if (node.typeName.type !== 'Identifier' || node.typeName.name !== 'Record') return false
+ const params = typeParameterNodes(node)
+ return params[0]?.type === 'TSStringKeyword' && params[1]?.type === 'TSUnknownKeyword'
+}
+
+function hasASTChild(
+ node: unknown,
+ predicate: (node: TypeNode) => boolean,
+ seen = new WeakSet<object>()
+): boolean {
+ if (!node || typeof node !== 'object') return false
+ if (seen.has(node)) return false
+ seen.add(node)
+ if (predicate(node as TypeNode)) return true
+
+ for (const [key, value] of Object.entries(node)) {
+ if (key === 'parent' || key === 'range' || key === 'loc') continue
+ if (Array.isArray(value)) {
+ if (value.some((child) => hasASTChild(child, predicate, seen))) return true
+ } else if (value && typeof value === 'object' && hasASTChild(value, predicate, seen)) {
+ return true
+ }
+ }
+ return false
+}
+
+function containsRecordStringUnknownType(node: TypeNode | null | undefined): boolean {
+ if (isRecordStringUnknownType(node)) return true
+ if (node?.type === 'TSArrayType') return isRecordStringUnknownType(node.elementType)
+ if (node?.type === 'TSUnionType') return node.types.some(containsRecordStringUnknownType)
+ return false
+}
+
+function isUnknownArrayType(node: TypeNode | null | undefined): boolean {
+ return node?.type === 'TSArrayType' && node.elementType.type === 'TSUnknownKeyword'
+}
+
+function hasInlineUnknownArrayProperty(node: TypeNode): boolean {
+ if (node.type !== 'TSTypeLiteral') return false
+ return node.members.some((member) => {
+ if (member.type !== 'TSPropertySignature') return false
+ const typeNode = member.typeAnnotation?.typeAnnotation
+ return isUnknownArrayType(typeNode)
+ })
+}
+
+function containsInlineUnknownObjectType(node: TypeNode): boolean {
+ return hasASTChild(node, hasInlineUnknownArrayProperty)
+}
+
+const noBroadUnknownTypeAssertions = defineRule({
+ meta: {
+ docs: {
+ description:
+ 'Disallow broad unknown object type assertions. Add a named domain type or a type guard instead.'
+ }
+ },
+ create(context) {
+ function check(node: ESTree.TSAsExpression | ESTree.TSTypeAssertion) {
+ if (containsRecordStringUnknownType(node.typeAnnotation)) {
+ context.report({
+ node,
+ message:
+ 'Do not cast to Record<string, unknown>. Add a named domain type or a type guard.'
+ })
+ return
+ }
+ if (containsInlineUnknownObjectType(node.typeAnnotation)) {
+ context.report({
+ node,
+ message: 'Do not cast to an inline unknown object shape. Add a named domain type.'
+ })
+ }
+ }
+
+ return {
+ TSAsExpression: check,
+ TSTypeAssertion: check
+ }
+ }
+})
+
+function typeNameText(node: ESTree.TSTypeName | null | undefined): string {
+ if (!node) return 'unknown'
+ if (node.type === 'Identifier') return node.name
+ if (node.type === 'TSQualifiedName')
+ return `${typeNameText(node.left)}.${typeNameText(node.right)}`
+ return node.type
+}
+
+function parameterType(parameter: ESTree.ParamPattern): string {
+ return canonicalType(
+ 'typeAnnotation' in parameter ? parameter.typeAnnotation?.typeAnnotation : null
+ )
+}
+
+function canonicalType(node: TypeNode | null | undefined): string {
+ if (!node) return 'unknown'
+ switch (node.type) {
+ case 'TSStringKeyword':
+ return 'string'
+ case 'TSNumberKeyword':
+ return 'number'
+ case 'TSBooleanKeyword':
+ return 'boolean'
+ case 'TSUnknownKeyword':
+ return 'unknown'
+ case 'TSNullKeyword':
+ return 'null'
+ case 'TSUndefinedKeyword':
+ return 'undefined'
+ case 'TSLiteralType':
+ return `literal:${'value' in node.literal ? node.literal.value : node.literal.type}`
+ case 'TSArrayType':
+ return `array<${canonicalType(node.elementType)}>`
+ case 'TSTypeReference': {
+ const params = typeParameterNodes(node).map(canonicalType).join(',')
+ return `ref:${typeNameText(node.typeName)}<${params}>`
+ }
+ case 'TSUnionType':
+ return `union<${node.types.map(canonicalType).sort().join('|')}>`
+ case 'TSTypeLiteral':
+ return `object{${canonicalMembers(node.members)}}`
+ case 'TSFunctionType': {
+ const parameters = node.params.map(parameterType).join(',')
+ return `function<${parameters}=>${canonicalType(node.returnType.typeAnnotation)}>`
+ }
+ default:
+ return node.type
+ }
+}
+
+function propertyKeyName(key: ESTree.PropertyKey): string | null {
+ if (key.type === 'Identifier') return key.name
+ if (key.type === 'Literal') return String(key.value)
+ return null
+}
+
+function canonicalMember(member: ESTree.TSSignature): string | null {
+ if (member.type === 'TSIndexSignature') {
+ const keyType = member.parameters[0]?.typeAnnotation.typeAnnotation
+ return `index:${canonicalType(keyType)}:${canonicalType(member.typeAnnotation.typeAnnotation)}`
+ }
+ if (member.type !== 'TSPropertySignature') return null
+ const name = propertyKeyName(member.key)
+ if (!name) return null
+ const optional = member.optional ? '?' : ''
+ return `prop:${name}${optional}:${canonicalType(member.typeAnnotation?.typeAnnotation)}`
+}
+
+function canonicalMembers(members: readonly ESTree.TSSignature[] | undefined): string {
+ return compact((members ?? []).map(canonicalMember))
+ .sort()
+ .join(';')
+}
+
+function namedTypeShape(
+ node: ESTree.TSInterfaceDeclaration | ESTree.TSTypeAliasDeclaration
+): string | null {
+ if (node.type === 'TSInterfaceDeclaration') return canonicalMembers(node.body.body)
+ if (node.typeAnnotation.type === 'TSTypeLiteral') {
+ return canonicalMembers(node.typeAnnotation.members)
+ }
+ return null
+}
+
+const noDuplicateTypeShapes = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow duplicate local object type/interface shapes in one file'
+ }
+ },
+ create(context) {
+ const seen = new Set<string>()
+ function check(node: ESTree.TSInterfaceDeclaration | ESTree.TSTypeAliasDeclaration) {
+ const shape = namedTypeShape(node)
+ if (!shape || compact(shape.split(';')).length < 2) return
+ if (!seen.has(shape)) {
+ seen.add(shape)
+ return
+ }
+ context.report({
+ node,
+ message:
+ 'Duplicate object type shape. Reuse the existing named type instead of redeclaring the same members.'
+ })
+ }
+ return { TSInterfaceDeclaration: check, TSTypeAliasDeclaration: check }
+ }
+})
+
+const noImportTypeAnnotations = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow inline import() type annotations — use top-level import type instead'
+ }
+ },
+ create(context) {
+ return {
+ TSImportType(node) {
+ context.report({
+ node,
+ message:
+ 'Use a top-level import type instead of an inline import() type annotation. Dynamic imports are only for runtime lazy loading.'
+ })
+ }
+ }
+ }
+})
+
+function isUnknownKeyword(node: { type: string } | null | undefined): boolean {
+ return node?.type === 'TSUnknownKeyword'
+}
+
+/** The type asserted first in `value as unknown as T`, `<unknown>value as T`, and the like. */
+function innerAssertion(node: ESTree.TSAsExpression): { type: string } | null | undefined {
+ const inner = node.expression
+ return 'typeAnnotation' in inner ? inner.typeAnnotation : undefined
+}
+
+const noBroadDoubleCast = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow broad `as unknown as` casts'
+ }
+ },
+ create(context) {
+ return {
+ TSAsExpression(node) {
+ if (!isUnknownKeyword(innerAssertion(node))) return
+ context.report({
+ node,
+ message: 'Avoid `as unknown as ...`; model the value with a precise type or helper.'
+ })
+ }
+ }
+ }
+})
+
+const noUnknownRecordDoubleCast = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow `as unknown as Record<string, unknown>` broad object casts'
+ }
+ },
+ create(context) {
+ return {
+ TSAsExpression(node) {
+ if (!isUnknownKeyword(innerAssertion(node))) return
+ if (!isRecordStringUnknownType(node.typeAnnotation)) return
+ context.report({
+ node,
+ message:
+ 'Avoid `as unknown as Record<string, unknown>`; use a precise type or direct public API.'
+ })
+ }
+ }
+ }
+})
+
+const noFunctionType = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow the broad Function type; use an explicit callable signature'
+ }
+ },
+ create(context) {
+ return {
+ TSTypeReference(node) {
+ if (node.typeName.type !== 'Identifier' || node.typeName.name !== 'Function') return
+ context.report({
+ node,
+ message: 'Use an explicit function signature instead of the broad Function type.'
+ })
+ }
+ }
+ }
+})
+
+const noTsSuppressionComments = defineRule({
+ meta: {
+ docs: {
+ description: 'Disallow TypeScript suppression comments; fix types instead'
+ }
+ },
+ create(context) {
+ return {
+ Program() {
+ for (const comment of context.sourceCode.getAllComments()) {
+ if (!/@ts-(?:ignore|expect-error|nocheck)\b/.test(comment.value)) continue
+ context.report({
+ node: comment,
+ message:
+ 'Do not use TypeScript suppression comments; fix the type or add a typed helper.'
+ })
+ }
+ }
+ }
+ }
+})
+
+export {
+ noBroadDoubleCast,
+ noBroadUnknownTypeAssertions,
+ noDuplicateTypeShapes,
+ noFunctionType,
+ noImportTypeAnnotations,
+ noTsSuppressionComments,
+ noUnknownRecordDoubleCast
+}
diff --git a/tools/checks/lint/src/support/array-method.ts b/packages/oxlint-plugin/src/support/array-method.ts
similarity index 86%
rename from tools/checks/lint/src/support/array-method.ts
rename to packages/oxlint-plugin/src/support/array-method.ts
index 3bfec47f9..8656e2a09 100644
--- a/tools/checks/lint/src/support/array-method.ts
+++ b/packages/oxlint-plugin/src/support/array-method.ts
@@ -1,7 +1,6 @@
+import { constInitializer, resolveVariable } from '#oxlint-plugin/support/scope'
import type { ESTree, SourceCode, Variable } from '@oxlint/plugins'
-import { resolveVariable } from './scope.ts'
-
/** Unwrap syntax-only wrappers when inspecting array methods and accumulator references. */
export function unwrapArrayExpression(node: ESTree.Node): ESTree.Node {
while (
@@ -87,17 +86,7 @@ export function isKnownArrayExpression(
const annotation = identifier.typeAnnotation?.typeAnnotation
if (annotation !== undefined) return isArrayAnnotation(annotation)
}
- for (const definition of variable.defs) {
- if (
- definition.type === 'Variable' &&
- definition.node.type === 'VariableDeclarator' &&
- definition.node.id.type === 'Identifier' &&
- definition.node.init !== null &&
- definition.node.parent.type === 'VariableDeclaration' &&
- definition.node.parent.kind === 'const'
- ) {
- return isKnownArrayExpression(sourceCode, definition.node.init, visited)
- }
- }
+ const initializer = constInitializer(variable)
+ if (initializer) return isKnownArrayExpression(sourceCode, initializer, visited)
return false
}
diff --git a/packages/oxlint-plugin/src/support/ast.ts b/packages/oxlint-plugin/src/support/ast.ts
new file mode 100644
index 000000000..88a78af38
--- /dev/null
+++ b/packages/oxlint-plugin/src/support/ast.ts
@@ -0,0 +1,9 @@
+import type { ESTree } from '@oxlint/plugins'
+
+/** The member a fixed property access names: `object.name` or `object['name']`. */
+export function staticMemberName(node: ESTree.MemberExpression): string | null {
+ if (!node.computed && node.property.type === 'Identifier') return node.property.name
+ if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
+ return node.property.value
+ return null
+}
diff --git a/packages/oxlint-plugin/src/support/context.ts b/packages/oxlint-plugin/src/support/context.ts
new file mode 100644
index 000000000..775b60690
--- /dev/null
+++ b/packages/oxlint-plugin/src/support/context.ts
@@ -0,0 +1,34 @@
+import type { ESTree } from '@oxlint/plugins'
+
+export function normalizedPath(path: string): string {
+ return path.replaceAll('\\', '/')
+}
+
+export interface FilenameContext {
+ filename?: string
+ physicalFilename?: string
+}
+
+export function normalizedFilename(context: FilenameContext): string {
+ return normalizedPath(context.physicalFilename ?? context.filename ?? '')
+}
+
+export function isTestFile(file: string): boolean {
+ return file.includes('/tests/')
+}
+
+/** The module an import or re-export names, or an inline `import()` given a fixed string. */
+export function importSource(
+ node:
+ | ESTree.ImportDeclaration
+ | ESTree.ExportAllDeclaration
+ | ESTree.ExportNamedDeclaration
+ | ESTree.ImportExpression
+): string | null {
+ const { source } = node
+ if (source?.type === 'Literal') return typeof source.value === 'string' ? source.value : null
+ if (source?.type === 'TemplateLiteral' && source.expressions.length === 0) {
+ return source.quasis[0]?.value.cooked ?? null
+ }
+ return null
+}
diff --git a/packages/oxlint-plugin/src/support/scope.ts b/packages/oxlint-plugin/src/support/scope.ts
new file mode 100644
index 000000000..18f538e89
--- /dev/null
+++ b/packages/oxlint-plugin/src/support/scope.ts
@@ -0,0 +1,32 @@
+import type { ESTree, Scope, SourceCode, Variable } from '@oxlint/plugins'
+
+/** Resolve an identifier to its binding by walking lexical scopes upward. */
+export function resolveVariable(
+ sourceCode: SourceCode,
+ identifier: Extract<ESTree.Node, { type: 'Identifier' }>
+): Variable | null {
+ let scope: Scope | null = sourceCode.getScope(identifier)
+ while (scope !== null) {
+ const variable = scope.set.get(identifier.name)
+ if (variable !== undefined) return variable
+ scope = scope.upper
+ }
+ return null
+}
+
+/** The value a `const` binding is declared with, when it is one; `null` for any other binding. */
+export function constInitializer(variable: Variable): ESTree.Expression | null {
+ for (const definition of variable.defs) {
+ if (
+ definition.type === 'Variable' &&
+ definition.node.type === 'VariableDeclarator' &&
+ definition.node.id.type === 'Identifier' &&
+ definition.node.init !== null &&
+ definition.node.parent.type === 'VariableDeclaration' &&
+ definition.node.parent.kind === 'const'
+ ) {
+ return definition.node.init
+ }
+ }
+ return null
+}
diff --git a/packages/oxlint-plugin/tests/helpers/lint.ts b/packages/oxlint-plugin/tests/helpers/lint.ts
new file mode 100644
index 000000000..cb567a61c
--- /dev/null
+++ b/packages/oxlint-plugin/tests/helpers/lint.ts
@@ -0,0 +1,82 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import * as v from 'valibot'
+
+const diagnosticSchema = v.object({
+ code: v.optional(v.string()),
+ filename: v.optional(v.string()),
+ message: v.string(),
+ severity: v.picklist(['error', 'warning', 'advice'])
+})
+const resultSchema = v.pipe(
+ v.string(),
+ v.parseJson(),
+ v.object({ diagnostics: v.array(diagnosticSchema) })
+)
+export type Diagnostic = v.InferOutput<typeof diagnosticSchema>
+
+/** The plugin's source entry, which Oxlint loads as it would the published build. */
+const PLUGIN = fileURLToPath(import.meta.resolve('#oxlint-plugin/index'))
+const OXLINT = join(dirname(Bun.resolveSync('oxlint/package.json', import.meta.dir)), 'bin/oxlint')
+
+export async function lint(
+ source: string,
+ rules: Record<string, string | readonly unknown[]>,
+ relativePath = 'fixture.ts'
+): Promise<Diagnostic[]> {
+ return lintFiles({ [relativePath]: source }, rules)
+}
+
+/**
+ * Lint several fixtures in one Oxlint run, by their path relative to a temporary directory;
+ * each diagnostic's `filename` ends with that path.
+ */
+export async function lintFiles(
+ sources: Record<string, string>,
+ rules: Record<string, string | readonly unknown[]>
+): Promise<Diagnostic[]> {
+ const directory = await mkdtemp(join(tmpdir(), 'open-pencil-oxlint-plugin-'))
+ try {
+ const sourcePaths = await Promise.all(
+ Object.entries(sources).map(async ([relativePath, source]) => {
+ const sourcePath = join(directory, relativePath)
+ await mkdir(dirname(sourcePath), { recursive: true })
+ await writeFile(sourcePath, source)
+ return sourcePath
+ })
+ )
+ const configPath = join(directory, 'oxlint.json')
+ await writeFile(
+ configPath,
+ JSON.stringify({ plugins: ['typescript'], jsPlugins: [PLUGIN], rules })
+ )
+ const child = Bun.spawn([OXLINT, '-c', configPath, '--format', 'json', ...sourcePaths], {
+ cwd: directory,
+ stdout: 'pipe',
+ stderr: 'pipe'
+ })
+ const [stdout, stderr, code] = await Promise.all([
+ new Response(child.stdout).text(),
+ new Response(child.stderr).text(),
+ child.exited
+ ])
+ if (code !== 0 && code !== 1) throw new Error(`Oxlint exited ${code}: ${stderr}`)
+ const { diagnostics } = v.parse(resultSchema, stdout)
+ const parserFailure = diagnostics.find(
+ (item) => item.severity === 'error' && item.code === undefined
+ )
+ if (parserFailure) {
+ throw new Error(`Oxlint could not parse the fixture: ${parserFailure.message}`)
+ }
+ return diagnostics
+ } finally {
+ await rm(directory, { recursive: true, force: true })
+ }
+}
+
+export function ruleDiagnostics(diagnostics: Diagnostic[], rule: string): Diagnostic[] {
+ return diagnostics.filter((diagnostic) => diagnostic.code === `open-pencil(${rule})`)
+}
diff --git a/packages/oxlint-plugin/tests/rules/imports.test.ts b/packages/oxlint-plugin/tests/rules/imports.test.ts
new file mode 100644
index 000000000..3b51fda3e
--- /dev/null
+++ b/packages/oxlint-plugin/tests/rules/imports.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, test } from 'bun:test'
+
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
+
+const rule = 'no-deep-parent-relative-imports'
+
+async function diagnostics(source: string, options?: Record<string, unknown>) {
+ const config = options ? ['error', options] : 'error'
+ return ruleDiagnostics(await lint(source, { [`open-pencil/${rule}`]: config }), rule)
+}
+
+describe(rule, () => {
+ test.each([
+ "import { point } from '../../geometry/point'",
+ "export { point } from '../../geometry/point'",
+ "export * from '../../../geometry'",
+ "const point = await import('../../geometry/point')"
+ ])('rejects %s', async (source) => {
+ expect(await diagnostics(source)).toHaveLength(1)
+ })
+
+ test.each([
+ "import { point } from '../geometry/point'",
+ "import { point } from './point'",
+ "import { point } from '#app/geometry/point'",
+ "import manifest from '../../package.json'"
+ ])('accepts %s', async (source) => {
+ expect(await diagnostics(source)).toHaveLength(0)
+ })
+
+ test('minDepth: 1 rejects any parent import and names the alias', async () => {
+ const found = await diagnostics("import { point } from '../geometry/point'", {
+ minDepth: 1,
+ alias: '#core/*'
+ })
+ expect(found.map((diagnostic) => diagnostic.message)).toEqual([
+ 'Use the #core/* alias instead of parent-relative imports.'
+ ])
+ })
+})
+
+describe('no-function-alias-imports', () => {
+ const aliasRule = 'no-function-alias-imports'
+ const count = async (source: string) =>
+ ruleDiagnostics(await lint(source, { [`open-pencil/${aliasRule}`]: 'error' }), aliasRule).length
+
+ test('rejects an import renamed to end in Fn', async () => {
+ expect(await count("import { parse as parseFn } from './parse'")).toBe(1)
+ })
+
+ test('accepts other renames and plain imports', async () => {
+ expect(await count("import { parse as parsePoint } from './parse'")).toBe(0)
+ expect(await count("import { parseFn } from './parse'")).toBe(0)
+ })
+})
+
+// A template that climbs one level and then names a folder, assembled so it stays source text.
+const oneLevelTemplate = ['join(import.meta.dir, `../', '$', "{folder}`, '..', 'assets')"].join('')
+
+describe('no-deep-parent-relative-paths', () => {
+ const rule = 'no-deep-parent-relative-paths'
+ const rules = { [`open-pencil/${rule}`]: 'error' }
+
+ test.each([
+ "new URL('../../fixtures/a.fig', import.meta.url)",
+ 'new URL(`../../fixtures/a.fig`, import.meta.url)',
+ "resolve(import.meta.dir, '../../../tests/fixtures')",
+ "join(import.meta.dirname, '..', '..', 'assets')",
+ "path.resolve(import.meta.dir, '../..')",
+ "join(import.meta.dir, '..\\\\..\\\\assets')",
+ "join(dirname(fileURLToPath(import.meta.url)), '../../fixtures')"
+ ])('rejects %s', async (source) => {
+ expect(ruleDiagnostics(await lint(source, rules), rule)).toHaveLength(1)
+ })
+
+ test.each([
+ "new URL('../fixtures/a.fig', import.meta.url)",
+ "new URL('./worker.ts', import.meta.url)",
+ "join(import.meta.dir, '..', 'fixtures')",
+ "credentialRef('../../other-app', 'api-key')",
+ "resolve(root, '../../somewhere')",
+ "join(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures')",
+ oneLevelTemplate
+ ])('accepts %s', async (source) => {
+ expect(ruleDiagnostics(await lint(source, rules), rule)).toHaveLength(0)
+ })
+})
diff --git a/packages/oxlint-plugin/tests/rules/naming.test.ts b/packages/oxlint-plugin/tests/rules/naming.test.ts
new file mode 100644
index 000000000..657cec88e
--- /dev/null
+++ b/packages/oxlint-plugin/tests/rules/naming.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from 'bun:test'
+
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
+
+const rule = 'no-mixed-case-acronym-identifiers'
+
+async function count(source: string, options?: Record<string, unknown>): Promise<number> {
+ const config = options ? ['error', options] : 'error'
+ return ruleDiagnostics(await lint(source, { [`open-pencil/${rule}`]: config }), rule).length
+}
+
+describe(rule, () => {
+ test.each([
+ 'export const baseUrl = 1',
+ 'export function parseJson() {}',
+ 'export const htmlUrl = 1',
+ 'export class ApiClient {}'
+ ])('rejects %s', async (source) => {
+ expect(await count(source)).toBe(1)
+ })
+
+ test.each([
+ 'export const baseURL = 1',
+ 'export const builder = 1',
+ 'export const aiModel = 1',
+ 'export const options = { baseUrl: 1 }',
+ 'export const value = request.baseUrl',
+ "import Url from 'vendor'\nexport {}"
+ ])('accepts %s', async (source) => {
+ expect(await count(source)).toBe(0)
+ })
+
+ test("ignoredImports accepts a package's names where they are imported", async () => {
+ const source = "import { openUrl as openLink } from 'vendor'\nopenLink()"
+ expect(await count(source)).toBe(1)
+ expect(await count(source, { ignoredImports: ['vendor'] })).toBe(0)
+ })
+
+ test('ignoredImports leaves the local binding to ignoredIdentifiers', async () => {
+ const source = "import { openUrl } from 'vendor'\nopenUrl()"
+ expect(await count(source, { ignoredImports: ['vendor'] })).toBe(2)
+ expect(
+ await count(source, { ignoredImports: ['vendor'], ignoredIdentifiers: ['openUrl'] })
+ ).toBe(0)
+ })
+
+ test('ignoredIdentifiers accepts upstream names everywhere', async () => {
+ const source = 'export const useObjectUrl = 1'
+ expect(await count(source, { ignoredIdentifiers: ['useObjectUrl'] })).toBe(0)
+ })
+})
diff --git a/tools/checks/lint/tests/base64.test.ts b/packages/oxlint-plugin/tests/rules/quality/base64.test.ts
similarity index 92%
rename from tools/checks/lint/tests/base64.test.ts
rename to packages/oxlint-plugin/tests/rules/quality/base64.test.ts
index 806c771f8..163b42332 100644
--- a/tools/checks/lint/tests/base64.test.ts
+++ b/packages/oxlint-plugin/tests/rules/quality/base64.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
const rule = 'no-hand-rolled-base64'
const rules = { [`open-pencil/${rule}`]: 'error' }
diff --git a/tools/checks/lint/tests/es-toolkit.test.ts b/packages/oxlint-plugin/tests/rules/quality/es-toolkit.test.ts
similarity index 94%
rename from tools/checks/lint/tests/es-toolkit.test.ts
rename to packages/oxlint-plugin/tests/rules/quality/es-toolkit.test.ts
index 77b2b095c..2760a7e5d 100644
--- a/tools/checks/lint/tests/es-toolkit.test.ts
+++ b/packages/oxlint-plugin/tests/rules/quality/es-toolkit.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
const rule = 'prefer-es-toolkit'
const rules = { [`open-pencil/${rule}`]: 'error' }
diff --git a/tools/checks/lint/tests/json-parse.test.ts b/packages/oxlint-plugin/tests/rules/quality/json-parse.test.ts
similarity index 95%
rename from tools/checks/lint/tests/json-parse.test.ts
rename to packages/oxlint-plugin/tests/rules/quality/json-parse.test.ts
index 5ad578d13..a2da6f206 100644
--- a/tools/checks/lint/tests/json-parse.test.ts
+++ b/packages/oxlint-plugin/tests/rules/quality/json-parse.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
const rule = 'no-unvalidated-json-parse'
const rules = { [`open-pencil/${rule}`]: 'error' }
diff --git a/tools/checks/lint/tests/module-mocking.test.ts b/packages/oxlint-plugin/tests/rules/quality/module-mocking.test.ts
similarity index 94%
rename from tools/checks/lint/tests/module-mocking.test.ts
rename to packages/oxlint-plugin/tests/rules/quality/module-mocking.test.ts
index 398471f0c..e10c318f8 100644
--- a/tools/checks/lint/tests/module-mocking.test.ts
+++ b/packages/oxlint-plugin/tests/rules/quality/module-mocking.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
const rule = 'no-module-mocking'
const rules = { [`open-pencil/${rule}`]: 'error' }
diff --git a/tools/checks/lint/tests/reduce-accumulator-copy.test.ts b/packages/oxlint-plugin/tests/rules/quality/reduce-accumulator-copy.test.ts
similarity index 95%
rename from tools/checks/lint/tests/reduce-accumulator-copy.test.ts
rename to packages/oxlint-plugin/tests/rules/quality/reduce-accumulator-copy.test.ts
index 4f0e43ab6..ea46f4325 100644
--- a/tools/checks/lint/tests/reduce-accumulator-copy.test.ts
+++ b/packages/oxlint-plugin/tests/rules/quality/reduce-accumulator-copy.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
const rule = 'no-reduce-accumulator-copy'
const rules = { [`open-pencil/${rule}`]: 'error' }
diff --git a/tools/checks/lint/tests/valibot-schemas.test.ts b/packages/oxlint-plugin/tests/rules/quality/valibot-schemas.test.ts
similarity index 62%
rename from tools/checks/lint/tests/valibot-schemas.test.ts
rename to packages/oxlint-plugin/tests/rules/quality/valibot-schemas.test.ts
index 918d1d143..8d8a85101 100644
--- a/tools/checks/lint/tests/valibot-schemas.test.ts
+++ b/packages/oxlint-plugin/tests/rules/quality/valibot-schemas.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
const rule = 'valibot-schema-conventions'
const rules = { [`open-pencil/${rule}`]: 'error' }
@@ -27,18 +27,40 @@ describe(rule, () => {
expect(ruleDiagnostics(await lint(source, rules, 'geometry/point.ts'), rule)).toHaveLength(1)
})
- test('rejects a schema exported from a contract folder outside Cloud', async () => {
- const source = `${valibot}export const metricsSchema = v.object({})`
- const path = 'packages/feedback/src/contract/metrics.ts'
- expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(1)
+ describe('schemaModules', () => {
+ const withContract = {
+ [`open-pencil/${rule}`]: ['error', { schemaModules: ['/packages/cloud/src/contract/'] }]
+ }
+ const source = `${valibot}export const documentSchema = v.object({})`
+
+ test('accepts a schema exported from a named module directory', async () => {
+ const path = 'packages/cloud/src/contract/documents.ts'
+ expect(ruleDiagnostics(await lint(source, withContract, path), rule)).toHaveLength(0)
+ })
+
+ test('rejects one exported from another contract folder', async () => {
+ const path = 'packages/feedback/src/contract/metrics.ts'
+ expect(ruleDiagnostics(await lint(source, withContract, path), rule)).toHaveLength(1)
+ })
+
+ test('matches a named directory whole, not as a prefix of another', async () => {
+ const prefixOnly = {
+ [`open-pencil/${rule}`]: ['error', { schemaModules: ['/packages/cloud/src/contract'] }]
+ }
+ const inside = 'packages/cloud/src/contract/documents.ts'
+ const beside = 'packages/cloud/src/contracts-extra/documents.ts'
+ expect(ruleDiagnostics(await lint(source, prefixOnly, inside), rule)).toHaveLength(0)
+ expect(ruleDiagnostics(await lint(source, prefixOnly, beside), rule)).toHaveLength(1)
+ })
+
+ test('rejects one from a contract folder no option names', async () => {
+ const path = 'packages/cloud/src/contract/documents.ts'
+ expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(1)
+ })
})
test.each([
['geometry/schema.ts', `${valibot}export const pointSchema = v.object({ x: v.number() })`],
- [
- 'packages/cloud/src/contract/documents.ts',
- `${valibot}export const documentSchema = v.object({})`
- ],
['geometry/point.ts', `${valibot}const pointSchema = v.object({ x: v.number() })`],
['geometry/point.ts', `${valibot}export const point = v.parse(v.number(), 1)`],
['geometry/point.ts', `${valibot}export const title = v.getTitle(v.string())`],
diff --git a/tools/checks/lint/tests/widen-then-assert.test.ts b/packages/oxlint-plugin/tests/rules/quality/widen-then-assert.test.ts
similarity index 94%
rename from tools/checks/lint/tests/widen-then-assert.test.ts
rename to packages/oxlint-plugin/tests/rules/quality/widen-then-assert.test.ts
index e899603b0..f983f785b 100644
--- a/tools/checks/lint/tests/widen-then-assert.test.ts
+++ b/packages/oxlint-plugin/tests/rules/quality/widen-then-assert.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
const rule = 'no-widen-then-assert'
const rules = { [`open-pencil/${rule}`]: 'error' }
diff --git a/packages/oxlint-plugin/tests/rules/runtime.test.ts b/packages/oxlint-plugin/tests/rules/runtime.test.ts
new file mode 100644
index 000000000..63c3c68f1
--- /dev/null
+++ b/packages/oxlint-plugin/tests/rules/runtime.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from 'bun:test'
+
+import { lint, lintFiles, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
+
+function on(rule: string) {
+ return { [`open-pencil/${rule}`]: 'error' }
+}
+
+async function count(rule: string, source: string, path?: string): Promise<number> {
+ return ruleDiagnostics(await lint(source, on(rule), path), rule).length
+}
+
+describe('no-math-random', () => {
+ test('rejects Math.random()', async () => {
+ expect(await count('no-math-random', 'export const pick = Math.random()')).toBe(1)
+ })
+
+ test('accepts crypto.getRandomValues()', async () => {
+ const source = 'export const bytes = crypto.getRandomValues(new Uint8Array(4))'
+ expect(await count('no-math-random', source)).toBe(0)
+ })
+})
+
+describe('no-silent-catch', () => {
+ test('rejects an empty catch block', async () => {
+ expect(await count('no-silent-catch', 'try { run() } catch {}')).toBe(1)
+ expect(await count('no-silent-catch', 'try { run() } catch (error) { ; }')).toBe(1)
+ })
+
+ test('accepts a catch block that handles the error', async () => {
+ const source = 'try { run() } catch (error) { console.warn(error) }'
+ expect(await count('no-silent-catch', source)).toBe(0)
+ })
+})
+
+describe('no-reflect-delete-global-this-outside-tests', () => {
+ const rule = 'no-reflect-delete-global-this-outside-tests'
+ const source = "Reflect.deleteProperty(globalThis, 'fetch')"
+
+ test('rejects deleting a global outside tests and accepts it in tests', async () => {
+ const diagnostics = ruleDiagnostics(
+ await lintFiles({ 'src/setup.ts': source, 'tests/setup.ts': source }, on(rule)),
+ rule
+ )
+ expect(diagnostics.map((diagnostic) => diagnostic.filename?.endsWith('src/setup.ts'))).toEqual([
+ true
+ ])
+ })
+
+ test('accepts deleting from another object', async () => {
+ expect(await count(rule, "Reflect.deleteProperty(cache, 'fetch')")).toBe(0)
+ })
+})
+
+describe('no-conditional-object-spreads', () => {
+ const rule = 'no-conditional-object-spreads'
+
+ test('accepts a simple one-property projection', async () => {
+ const source = 'export const result = { ...(enabled ? { value: 1 } : {}) }'
+ expect(await count(rule, source)).toBe(0)
+ })
+
+ test('reports a multi-property conditional projection', async () => {
+ const source = 'export const result = { ...(enabled ? { value: 1, label: "yes" } : {}) }'
+ expect(await count(rule, source)).toBe(1)
+ })
+
+ test('reports multiple conditional projections in one object', async () => {
+ const source =
+ 'export const result = { ...(first ? { a: 1 } : {}), ...(second ? { b: 2 } : {}) }'
+ expect(await count(rule, source)).toBe(2)
+ })
+})
diff --git a/tools/checks/lint/tests/cloud.test.ts b/packages/oxlint-plugin/tests/rules/security.test.ts
similarity index 72%
rename from tools/checks/lint/tests/cloud.test.ts
rename to packages/oxlint-plugin/tests/rules/security.test.ts
index b438174a6..6e12edd1f 100644
--- a/tools/checks/lint/tests/cloud.test.ts
+++ b/packages/oxlint-plugin/tests/rules/security.test.ts
@@ -1,28 +1,28 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
async function diagnostics(rule: string, source: string) {
return ruleDiagnostics(await lint(source, { [`open-pencil/${rule}`]: 'error' }), rule)
}
-describe('no-cloud-dynamic-html', () => {
+describe('no-dynamic-html', () => {
test.each(['c.html(page)', 'c.html(`<p>` + name + `</p>`)', "c.html('<p>' + name + '</p>')"])(
'rejects %s',
async (source) => {
- expect(await diagnostics('no-cloud-dynamic-html', source)).toHaveLength(1)
+ expect(await diagnostics('no-dynamic-html', source)).toHaveLength(1)
}
)
test.each(["c.html('<p>Done</p>')", 'c.html(`<p>Done</p>`, 200)', 'c.json(body)'])(
'accepts %s',
async (source) => {
- expect(await diagnostics('no-cloud-dynamic-html', source)).toHaveLength(0)
+ expect(await diagnostics('no-dynamic-html', source)).toHaveLength(0)
}
)
})
-describe('no-cloud-secret-in-query', () => {
+describe('no-secret-in-query', () => {
test.each([
"url.searchParams.set('secret', value)",
"url.searchParams.append('token', value)",
@@ -31,7 +31,7 @@ describe('no-cloud-secret-in-query', () => {
"new URLSearchParams({ 'secret': value })",
`fetch(\`\${base}/share?token=\${value}\`)`
])('rejects %s', async (source) => {
- expect(await diagnostics('no-cloud-secret-in-query', source)).toHaveLength(1)
+ expect(await diagnostics('no-secret-in-query', source)).toHaveLength(1)
})
test.each([
@@ -41,11 +41,11 @@ describe('no-cloud-secret-in-query', () => {
'new URLSearchParams({ server })',
`fetch(\`\${base}/share#secret=\${value}\`)`
])('accepts %s', async (source) => {
- expect(await diagnostics('no-cloud-secret-in-query', source)).toHaveLength(0)
+ expect(await diagnostics('no-secret-in-query', source)).toHaveLength(0)
})
})
-describe('no-cloud-secret-logging', () => {
+describe('no-secret-logging', () => {
test.each([
'console.log(token)',
"console.error('[Cloud]', session.accessToken)",
@@ -58,7 +58,7 @@ describe('no-cloud-secret-logging', () => {
"console.log('x: ' + session.accessToken)",
'console.log(...[token])'
])('rejects %s', async (source) => {
- expect(await diagnostics('no-cloud-secret-logging', source)).toHaveLength(1)
+ expect(await diagnostics('no-secret-logging', source)).toHaveLength(1)
})
test.each([
@@ -69,6 +69,6 @@ describe('no-cloud-secret-logging', () => {
`console.log(\`\${tokenizer.name}\`)`,
'console.log({ documentId, size })'
])('accepts %s', async (source) => {
- expect(await diagnostics('no-cloud-secret-logging', source)).toHaveLength(0)
+ expect(await diagnostics('no-secret-logging', source)).toHaveLength(0)
})
})
diff --git a/tools/checks/lint/tests/sql.test.ts b/packages/oxlint-plugin/tests/rules/sql.test.ts
similarity index 89%
rename from tools/checks/lint/tests/sql.test.ts
rename to packages/oxlint-plugin/tests/rules/sql.test.ts
index 22c4d6a6f..d70e73a8a 100644
--- a/tools/checks/lint/tests/sql.test.ts
+++ b/packages/oxlint-plugin/tests/rules/sql.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
async function diagnostics(source: string) {
return ruleDiagnostics(await lint(source, { 'open-pencil/no-raw-sql': 'error' }), 'no-raw-sql')
diff --git a/packages/oxlint-plugin/tests/rules/structure.test.ts b/packages/oxlint-plugin/tests/rules/structure.test.ts
new file mode 100644
index 000000000..f6a4b2d37
--- /dev/null
+++ b/packages/oxlint-plugin/tests/rules/structure.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from 'bun:test'
+
+import { lint, lintFiles, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
+
+describe('no-sibling-domain-prefixed-files', () => {
+ const rule = 'no-sibling-domain-prefixed-files'
+
+ test('reports a prefix that names a sibling folder, not a suffix that does', async () => {
+ const found = ruleDiagnostics(
+ await lintFiles(
+ {
+ 'list/index.ts': 'export {}',
+ 'page-list.ts': 'export {}',
+ 'list-actions.ts': 'export {}',
+ 'list-actions.test.ts': 'export {}'
+ },
+ { [`open-pencil/${rule}`]: 'error' }
+ ),
+ rule
+ )
+ expect(
+ found
+ .map((diagnostic) => diagnostic.filename?.split('/').at(-1) ?? '')
+ .toSorted((left, right) => left.localeCompare(right))
+ ).toEqual(['list-actions.test.ts', 'list-actions.ts'])
+ })
+})
+
+describe('no-useless-pass-through-wrappers', () => {
+ const rule = 'no-useless-pass-through-wrappers'
+ const count = async (source: string) =>
+ ruleDiagnostics(await lint(source, { [`open-pencil/${rule}`]: 'error' }), rule).length
+
+ test.each([
+ 'function save(document) { return write(document) }',
+ 'const save = (document, options) => write(document, options)',
+ 'const save = function (document) { return write(document) }'
+ ])('rejects %s', async (source) => {
+ expect(await count(source)).toBe(1)
+ })
+
+ test.each([
+ 'function save(document) { return write(document, true) }',
+ 'function save(document) { log(document); return write(document) }',
+ 'const save = ({ id }) => write(id)',
+ 'function save(document) { return save(document) }'
+ ])('accepts %s', async (source) => {
+ expect(await count(source)).toBe(0)
+ })
+})
diff --git a/packages/oxlint-plugin/tests/rules/typescript.test.ts b/packages/oxlint-plugin/tests/rules/typescript.test.ts
new file mode 100644
index 000000000..37c0cb1c1
--- /dev/null
+++ b/packages/oxlint-plugin/tests/rules/typescript.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, test } from 'bun:test'
+
+import { lint, ruleDiagnostics } from '#oxlint-plugin-tests/helpers/lint'
+
+async function count(rule: string, source: string): Promise<number> {
+ return ruleDiagnostics(await lint(source, { [`open-pencil/${rule}`]: 'error' }), rule).length
+}
+
+describe('no-broad-double-cast', () => {
+ test.each([
+ 'export const result = value as unknown as Point',
+ 'export const result = <unknown>value as Point',
+ 'export const result = ((value as unknown)) as Point'
+ ])('rejects %s', async (source) => {
+ expect(await count('no-broad-double-cast', source)).toBe(1)
+ })
+
+ test('accepts a single assertion', async () => {
+ expect(await count('no-broad-double-cast', 'export const result = value as Point')).toBe(0)
+ })
+})
+
+describe('no-unknown-record-double-cast', () => {
+ test('recognizes Record<string, unknown> from the TypeScript AST', async () => {
+ const source = 'export const result = value as unknown as Record< string, unknown >'
+ expect(await count('no-unknown-record-double-cast', source)).toBe(1)
+ })
+
+ test('accepts a double cast to a named type', async () => {
+ const source = 'export const result = value as unknown as Point'
+ expect(await count('no-unknown-record-double-cast', source)).toBe(0)
+ })
+})
+
+describe('no-broad-unknown-type-assertions', () => {
+ const rule = 'no-broad-unknown-type-assertions'
+
+ test.each([
+ 'export const result = value as Record<string, unknown>',
+ 'export const result = value as Record<string, unknown>[]',
+ 'export const result = value as { items: unknown[]; name: string }'
+ ])('rejects %s', async (source) => {
+ expect(await count(rule, source)).toBe(1)
+ })
+
+ test('accepts an assertion to a named type', async () => {
+ expect(await count(rule, 'export const result = value as Settings')).toBe(0)
+ })
+})
+
+describe('no-duplicate-type-shapes', () => {
+ const rule = 'no-duplicate-type-shapes'
+
+ test('reports an interface and alias with the same members', async () => {
+ const source = [
+ 'interface First { name: string; size: number }',
+ 'type Second = { size: number; name: string }'
+ ].join('\n')
+ expect(await count(rule, source)).toBe(1)
+ })
+
+ test('keeps distinct callback signatures apart', async () => {
+ const source = [
+ 'interface First { handler: (value: string) => number; enabled: boolean }',
+ 'interface Second { handler: (value: number) => number; enabled: boolean }'
+ ].join('\n')
+ expect(await count(rule, source)).toBe(0)
+ })
+
+ test('keeps distinct index signatures apart', async () => {
+ const source = [
+ 'interface First { [key: string]: number; size: number }',
+ 'interface Second { [key: number]: number; size: number }'
+ ].join('\n')
+ expect(await count(rule, source)).toBe(0)
+ })
+})
+
+describe('no-import-type-annotations', () => {
+ test('rejects an inline import() type', async () => {
+ const source = "export let value: import('./point').Point"
+ expect(await count('no-import-type-annotations', source)).toBe(1)
+ })
+
+ test('accepts a top-level import type', async () => {
+ const source = "import type { Point } from './point'\nexport let value: Point"
+ expect(await count('no-import-type-annotations', source)).toBe(0)
+ })
+})
+
+describe('no-function-type', () => {
+ test('rejects the Function type and accepts a signature', async () => {
+ expect(await count('no-function-type', 'export let handler: Function')).toBe(1)
+ expect(await count('no-function-type', 'export let handler: () => void')).toBe(0)
+ })
+})
+
+describe('no-ts-suppression-comments', () => {
+ test.each(['// @ts-ignore', '// @ts-expect-error', '/* @ts-nocheck */'])(
+ 'rejects %s',
+ async (comment) => {
+ expect(await count('no-ts-suppression-comments', `${comment}\nexport const a = 1`)).toBe(1)
+ }
+ )
+
+ test('accepts other comments and @ts-check, which turns checking on', async () => {
+ expect(await count('no-ts-suppression-comments', '// ts is fine\nexport const a = 1')).toBe(0)
+ expect(await count('no-ts-suppression-comments', '// @ts-check\nexport const a = 1')).toBe(0)
+ })
+})
diff --git a/packages/oxlint-plugin/tests/support/context.test.ts b/packages/oxlint-plugin/tests/support/context.test.ts
new file mode 100644
index 000000000..6ee109def
--- /dev/null
+++ b/packages/oxlint-plugin/tests/support/context.test.ts
@@ -0,0 +1,20 @@
+import { expect, test } from 'bun:test'
+
+import { importSource, normalizedFilename } from '#oxlint-plugin/support/context'
+
+test('prefers and normalizes the physical filename', () => {
+ const context = {
+ filename: 'virtual.ts',
+ physicalFilename: String.raw`C:\repo\src\physical.ts`
+ }
+ expect(normalizedFilename(context)).toBe('C:/repo/src/physical.ts')
+})
+
+test('reads a module path from a template without expressions only', () => {
+ const quasi = { type: 'TemplateElement', value: { raw: './point', cooked: './point' } }
+ const fixed = {
+ type: 'ImportExpression',
+ source: { type: 'TemplateLiteral', quasis: [quasi], expressions: [] }
+ }
+ expect(importSource(fixed as never)).toBe('./point')
+})
diff --git a/packages/oxlint-plugin/tsconfig.json b/packages/oxlint-plugin/tsconfig.json
new file mode 100644
index 000000000..a9bfaf699
--- /dev/null
+++ b/packages/oxlint-plugin/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "lib": ["ES2023"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "declaration": true,
+ "declarationDir": "./dist/src",
+ "declarationMap": true,
+ "outDir": "./dist",
+ "skipLibCheck": true,
+ "types": ["bun"],
+ "paths": {
+ "#oxlint-plugin/*": ["./src/*"],
+ "#oxlint-plugin-tests/*": ["./tests/*"]
+ }
+ },
+ "include": ["src/**/*.ts", "tests/**/*.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/packages/oxlint-plugin/tsdown.config.ts b/packages/oxlint-plugin/tsdown.config.ts
new file mode 100644
index 000000000..a76e67c4b
--- /dev/null
+++ b/packages/oxlint-plugin/tsdown.config.ts
@@ -0,0 +1,39 @@
+import { defineConfig } from 'tsdown'
+
+export default defineConfig({
+ entry: {
+ index: './src/index.ts'
+ },
+ platform: 'neutral',
+ format: ['esm'],
+ dts: true,
+ sourcemap: true,
+ hash: false,
+ clean: true,
+ outDir: './dist',
+ treeshake: {
+ moduleSideEffects: false
+ },
+ deps: {
+ neverBundle: [/^node:/],
+ onlyBundle: false
+ },
+ outputOptions: {
+ minifyInternalExports: false,
+ codeSplitting: {
+ groups: [
+ {
+ test: /(?<!\.d\.c?ts)$/,
+ name: (id) => {
+ const cleanId = id.split('?')[0]
+ const parts = cleanId.split(/[\\/]/g)
+ const srcIndex = parts.lastIndexOf('src')
+ const file =
+ srcIndex >= 0 ? parts.slice(srcIndex + 1).join('/') : (parts.at(-1) ?? 'chunk')
+ return `chunks/${file.replace(/\.(ts|tsx)$/, '')}`
+ }
+ }
+ ]
+ }
+ }
+})
diff --git a/tools/checks/architecture/tests/acronym-casing.test.ts b/tools/checks/architecture/tests/acronym-casing.test.ts
index 881f53d0f..9a88766c3 100644
--- a/tools/checks/architecture/tests/acronym-casing.test.ts
+++ b/tools/checks/architecture/tests/acronym-casing.test.ts
@@ -1,14 +1,22 @@
import { afterEach, describe, expect, test } from 'bun:test'
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import * as v from 'valibot'
+
import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'
const temporaryDirectories: string[] = []
const repositoryRoot = await resolveWorkspaceRoot(import.meta.dir)
const oxlint = join(repositoryRoot, 'node_modules/.bin/oxlint')
const plugin = join(repositoryRoot, 'lint/plugin.js')
+const RULE = 'open-pencil/no-mixed-case-acronym-identifiers'
+/** The rule as oxlint.json configures it, with the upstream names this repository accepts. */
+const ruleConfig = v.parse(
+ v.pipe(v.string(), v.parseJson(), v.object({ rules: v.object({ [RULE]: v.unknown() }) })),
+ readFileSync(join(repositoryRoot, 'oxlint.json'), 'utf8')
+).rules[RULE]
function lint(source: string): ReturnType<typeof Bun.spawnSync> {
const directory = mkdtempSync(join(tmpdir(), 'open-pencil-acronym-lint-'))
@@ -19,7 +27,7 @@ function lint(source: string): ReturnType<typeof Bun.spawnSync> {
config,
JSON.stringify({
jsPlugins: [plugin],
- rules: { 'open-pencil/no-mixed-case-acronym-identifiers': 'error' }
+ rules: { [RULE]: ruleConfig }
})
)
writeFileSync(file, source)
diff --git a/tools/checks/lint/src/plugin.ts b/tools/checks/lint/src/plugin.ts
index 22b5d3a81..2afbbb6d6 100644
--- a/tools/checks/lint/src/plugin.ts
+++ b/tools/checks/lint/src/plugin.ts
@@ -1,26 +1,8 @@
-import {
- noCloudDynamicHTMLRule,
- noCloudSecretInQueryRule,
- noCloudSecretLoggingRule
-} from '#lint/rules/cloud.ts'
-import {
- noEditorProfileInputs,
- noConditionalObjectSpreads,
- noFlatKiwiModules,
- noMixedCaseAcronymIdentifiers
-} from '#lint/rules/policy.ts'
-import { noHandRolledBase64Rule } from '#lint/rules/quality/base64.ts'
-import { preferEsToolkitRule } from '#lint/rules/quality/es-toolkit.ts'
-import { noUnvalidatedJSONParseRule } from '#lint/rules/quality/json-parse.ts'
-import { noModuleMockingRule } from '#lint/rules/quality/module-mocking.ts'
-import { noReduceAccumulatorCopyRule } from '#lint/rules/quality/reduce-accumulator-copy.ts'
+import { noEditorProfileInputs, noFlatKiwiModules } from '#lint/rules/policy.ts'
import {
noPxTailwindValuesRule,
noUnknownTailwindClassesRule
} from '#lint/rules/quality/tailwind-classes.ts'
-import { valibotSchemaConventionsRule } from '#lint/rules/quality/valibot-schemas.ts'
-import { noWidenThenAssertRule } from '#lint/rules/quality/widen-then-assert.ts'
-import { noRawSQLRule } from '#lint/rules/sql.ts'
import { noOverlayContentFromOpenState } from '#lint/rules/vue/overlays.ts'
import { normalizedFilename } from '#lint/support/context.ts'
import type { PluginRule, RuleDefinition } from '#lint/support/types.ts'
@@ -182,32 +164,6 @@ const noDirectSelectionToolStateMutation = {
}
} satisfies RuleDefinition
-const noMathRandom = {
- meta: {
- docs: {
- description: 'Disallow Math.random() — use crypto.getRandomValues() instead'
- }
- },
- create(context) {
- return {
- CallExpression(node) {
- if (
- node.callee?.type === 'MemberExpression' &&
- node.callee.object?.type === 'Identifier' &&
- node.callee.object.name === 'Math' &&
- node.callee.property?.type === 'Identifier' &&
- node.callee.property.name === 'random'
- ) {
- context.report({
- node,
- message: 'Use crypto.getRandomValues() instead of Math.random().'
- })
- }
- }
- }
- }
-} satisfies RuleDefinition
-
function isNumericLiteral(node: TSESTree.Node | undefined, value: number): boolean {
return node?.type === 'Literal' && node.value === value
}
@@ -328,31 +284,6 @@ const noRawConsoleFormat = {
}
} satisfies RuleDefinition
-const noSilentCatch = {
- meta: {
- docs: {
- description:
- 'Disallow empty catch blocks — log a warning or re-throw instead of silently swallowing errors'
- }
- },
- create(context) {
- return {
- CatchClause(node) {
- const body = node.body
- if (!body || !body.body) return
- const stmts = body.body.filter((s) => s.type !== 'EmptyStatement')
- if (stmts.length === 0) {
- context.report({
- node,
- message:
- 'Empty catch block silently swallows errors. Add console.warn(), re-throw, or an explicit // oxlint-ignore-next-line comment.'
- })
- }
- }
- }
- }
-} satisfies RuleDefinition
-
const noTypeofWindowCheck = {
meta: {
docs: {
@@ -386,13 +317,7 @@ const noTypeofWindowCheck = {
import {
noVueSelfPackageImports,
noCrossPackageSourceImports,
- noDeepParentRelativeImports,
- noDeepParentRelativePaths,
- noCoreParentRelativeImports,
noDocumentChangeCapture,
- noMcpParentRelativeImports,
- noVueParentRelativeImports,
- noCliParentRelativeImports,
noCoreSelfPackageImports,
noInlinePromptConstants,
noAppImportsInPackages,
@@ -401,11 +326,6 @@ import {
} from '#lint/rules/imports.ts'
import {
noDirectStorageAccess,
- noBroadDoubleCast,
- noUnknownRecordDoubleCast,
- noFunctionType,
- noReflectDeleteGlobalThisOutsideTests,
- noTsSuppressionComments,
noCoreBrowserGlobals,
noZoomInSceneDrawing,
noDirectGraphEmitterSubscriptions,
@@ -420,26 +340,18 @@ import {
componentNamespaceCasing,
nonComponentSourceDirectoriesKebabCase,
noComponentRootSiblingFolder,
- noUselessPassThroughWrappers,
- noFunctionAliasImports,
noDirectOpenPencilBrowserStore,
noDirectOpenPencilWindowInternals,
noBunGlobalsInCli,
- noTopLevelPrefixedTestFiles,
- noSiblingDomainPrefixedFiles
+ noTopLevelPrefixedTestFiles
} from '#lint/rules/structure.ts'
-import {
- noBroadUnknownTypeAssertions,
- noDuplicateTypeShapes,
- noLocalJsonObjectAliases,
- noImportTypeAnnotations
-} from '#lint/rules/typescript.ts'
+import { noLocalJsonObjectAliases } from '#lint/rules/typescript.ts'
+/** The rules only this repository needs; `lint/plugin.js` adds `@open-pencil/oxlint-plugin`'s. */
const plugin = {
meta: { name: 'open-pencil' },
rules: {
'no-inline-named-types': noInlineNamedTypes,
- 'no-import-type-annotations': noImportTypeAnnotations,
'no-structuredclone-scene-arrays': noStructuredCloneSceneArrays,
'no-vue-style-blocks': noVueStyleBlocks,
'no-native-title-attributes-in-vue': noNativeTitleAttributesInVue,
@@ -457,37 +369,22 @@ const plugin = {
'no-browser-side-effects-in-vue': noBrowserSideEffectsInVue,
'no-document-query-selector-in-vue': noDocumentQuerySelectorInVue,
'no-direct-selection-tool-state-mutation': noDirectSelectionToolStateMutation,
- 'no-math-random': noMathRandom,
'no-hardcoded-color-constants': noHardcodedColorConstants,
'no-unknown-tailwind-classes': noUnknownTailwindClassesRule,
'no-px-tailwind-values': noPxTailwindValuesRule,
'no-hand-rolled-color': noHandRolledColor,
'no-raw-console-format': noRawConsoleFormat,
- 'no-silent-catch': noSilentCatch,
'no-typeof-window-check': noTypeofWindowCheck,
'no-vue-self-package-imports': noVueSelfPackageImports,
'no-cross-package-source-imports': noCrossPackageSourceImports,
- 'no-deep-parent-relative-imports': noDeepParentRelativeImports,
- 'no-deep-parent-relative-paths': noDeepParentRelativePaths,
- 'no-core-parent-relative-imports': noCoreParentRelativeImports,
'no-document-change-capture': noDocumentChangeCapture,
- 'no-mcp-parent-relative-imports': noMcpParentRelativeImports,
- 'no-vue-parent-relative-imports': noVueParentRelativeImports,
- 'no-cli-parent-relative-imports': noCliParentRelativeImports,
'no-core-self-package-imports': noCoreSelfPackageImports,
'no-inline-prompt-constants': noInlinePromptConstants,
'no-app-imports-in-packages': noAppImportsInPackages,
'no-core-framework-imports': noCoreFrameworkImports,
'no-inline-tauri-imports': noInlineTauriImports,
'no-direct-storage-access': noDirectStorageAccess,
- 'no-broad-double-cast': noBroadDoubleCast,
- 'no-unknown-record-double-cast': noUnknownRecordDoubleCast,
- 'no-broad-unknown-type-assertions': noBroadUnknownTypeAssertions,
'no-local-json-object-aliases': noLocalJsonObjectAliases,
- 'no-duplicate-type-shapes': noDuplicateTypeShapes,
- 'no-ts-suppression-comments': noTsSuppressionComments,
- 'no-function-type': noFunctionType,
- 'no-reflect-delete-global-this-outside-tests': noReflectDeleteGlobalThisOutsideTests,
'no-core-browser-globals': noCoreBrowserGlobals,
'no-zoom-in-scene-drawing': noZoomInSceneDrawing,
'no-direct-open-pencil-window-internals': noDirectOpenPencilWindowInternals,
@@ -502,26 +399,10 @@ const plugin = {
'component-namespace-casing': componentNamespaceCasing,
'non-component-source-directories-kebab-case': nonComponentSourceDirectoriesKebabCase,
'no-component-root-sibling-folder': noComponentRootSiblingFolder,
- 'no-useless-pass-through-wrappers': noUselessPassThroughWrappers,
- 'no-function-alias-imports': noFunctionAliasImports,
- 'no-mixed-case-acronym-identifiers': noMixedCaseAcronymIdentifiers,
'no-flat-kiwi-modules': noFlatKiwiModules,
'no-bun-globals-in-cli': noBunGlobalsInCli,
'no-top-level-prefixed-test-files': noTopLevelPrefixedTestFiles,
- 'no-editor-profile-inputs': noEditorProfileInputs,
- 'no-conditional-object-spreads': noConditionalObjectSpreads,
- 'no-hand-rolled-base64': noHandRolledBase64Rule,
- 'no-raw-sql': noRawSQLRule,
- 'no-cloud-dynamic-html': noCloudDynamicHTMLRule,
- 'no-cloud-secret-in-query': noCloudSecretInQueryRule,
- 'no-cloud-secret-logging': noCloudSecretLoggingRule,
- 'no-unvalidated-json-parse': noUnvalidatedJSONParseRule,
- 'prefer-es-toolkit': preferEsToolkitRule,
- 'no-module-mocking': noModuleMockingRule,
- 'no-reduce-accumulator-copy': noReduceAccumulatorCopyRule,
- 'no-widen-then-assert': noWidenThenAssertRule,
- 'no-sibling-domain-prefixed-files': noSiblingDomainPrefixedFiles,
- 'valibot-schema-conventions': valibotSchemaConventionsRule
+ 'no-editor-profile-inputs': noEditorProfileInputs
} satisfies Record<string, PluginRule>
}
diff --git a/tools/checks/lint/src/rules/imports.ts b/tools/checks/lint/src/rules/imports.ts
index f6ac30e35..3077effc8 100644
--- a/tools/checks/lint/src/rules/imports.ts
+++ b/tools/checks/lint/src/rules/imports.ts
@@ -1,7 +1,6 @@
-import { importSource, inlineImportSource, normalizedFilename } from '#lint/support/context.ts'
+import { inlineImportSource, normalizedFilename } from '#lint/support/context.ts'
import { createImportSourceRule } from '#lint/support/factories.ts'
import type { RuleContext, RuleDefinition } from '#lint/support/types.ts'
-import type { TSESTree } from '@typescript-eslint/utils'
function isPackageOrSubpath(source: string, packageName: string): boolean {
return source === packageName || source.startsWith(`${packageName}/`)
@@ -25,159 +24,6 @@ const noCrossPackageSourceImports = createImportSourceRule({
`Use workspace package exports or package-local aliases instead of cross-package source import '${source}'.`
})
-interface ImportBoundaryRuleOptions {
- description: string
- applies(file: string): boolean
- message: string
- minDepth?: number
-}
-
-function createParentRelativeImportRule({
- description,
- applies,
- message,
- minDepth = 1
-}: ImportBoundaryRuleOptions): RuleDefinition {
- return {
- meta: {
- docs: { description }
- },
- create(context: RuleContext) {
- const file = normalizedFilename(context)
- if (!applies(file)) return {}
-
- function reportSource(node: TSESTree.Node, source: string | null) {
- if (!source?.startsWith('../')) return
- const parentPrefix = source.match(/^(?:\.\.\/)+/)?.[0]
- const depth = parentPrefix ? parentPrefix.split('../').length - 1 : 0
- if ((depth ?? 0) < minDepth) return
- if (/^(?:\.\.\/)+package\.json$/.test(source)) return
- context.report({ node, message })
- }
-
- function reportParentRelative(
- node:
- | TSESTree.ImportDeclaration
- | TSESTree.ExportAllDeclaration
- | TSESTree.ExportNamedDeclaration
- ) {
- reportSource(node, importSource(node))
- }
-
- return {
- ExportAllDeclaration: reportParentRelative,
- ExportNamedDeclaration: reportParentRelative,
- ImportDeclaration: reportParentRelative,
- ImportExpression(node) {
- reportSource(
- node,
- node.source?.type === 'Literal' && typeof node.source.value === 'string'
- ? node.source.value
- : null
- )
- }
- }
- }
- }
-}
-
-const noDeepParentRelativeImports = createParentRelativeImportRule({
- description: 'Disallow deep parent-relative imports — use package/test aliases instead',
- applies: () => true,
- message: 'Use an import alias instead of path drilling with ../.. imports.',
- minDepth: 2
-})
-
-/**
- * A path that climbs two or more directories, written as `../..`, `..\\..`, or `'..', '..'`.
- * An unknown part, such as a template expression, ends the run of parent segments.
- */
-function climbsTwoLevels(values: (string | null)[]): boolean {
- const joined = values
- .map((value) => value ?? '\u0000')
- .join('/')
- .replaceAll('\\', '/')
- return /(^|\/)\.\.\/+\.\.(\/|$)/.test(joined)
-}
-
-function staticString(node: TSESTree.Node): string | null {
- if (node.type === 'Literal' && typeof node.value === 'string') return node.value
- if (node.type === 'TemplateLiteral') {
- const head = node.quasis[0]?.value.cooked ?? null
- return head !== null && node.expressions.length ? `${head}\u0000` : head
- }
- return null
-}
-
-/** `import.meta.url`, `.dir`, or `.dirname`, directly or wrapped, as in `dirname(fileURLToPath(import.meta.url))`. */
-function isImportMetaLocation(node: TSESTree.Node): boolean {
- if (node.type === 'MemberExpression') {
- if (node.object.type === 'MetaProperty') {
- return (
- node.property.type === 'Identifier' &&
- ['url', 'dir', 'dirname'].includes(node.property.name)
- )
- }
- return isImportMetaLocation(node.object)
- }
- if (node.type === 'CallExpression') return node.arguments.some(isImportMetaLocation)
- return false
-}
-
-const noDeepParentRelativePaths: RuleDefinition = {
- meta: {
- docs: {
- description:
- 'Disallow climbing two or more directories from import.meta — use a path helper or alias'
- }
- },
- create(context: RuleContext) {
- const message =
- 'Resolve the file through a path helper such as repoPath() or an import alias instead of climbing with ../..'
- function check(node: TSESTree.Node, relative: TSESTree.CallExpressionArgument[]) {
- if (relative.length && climbsTwoLevels(relative.map(staticString))) {
- context.report({ node, message })
- }
- }
- return {
- NewExpression(node) {
- if (node.callee.type !== 'Identifier' || node.callee.name !== 'URL') return
- if (!node.arguments[1] || !isImportMetaLocation(node.arguments[1])) return
- check(node, node.arguments.slice(0, 1))
- },
- CallExpression(node) {
- const start = node.arguments.findIndex(isImportMetaLocation)
- if (start !== -1) check(node, node.arguments.slice(start + 1))
- }
- }
- }
-}
-
-const noCoreParentRelativeImports = createParentRelativeImportRule({
- description: 'Disallow parent-relative imports in core internals — use #core/* aliases',
- applies: (file) =>
- file.includes('/packages/core/src/') && !file.includes('/packages/core/src/kiwi/kiwi-schema/'),
- message: 'Use the #core/* package-local alias instead of parent-relative core imports.'
-})
-
-const noMcpParentRelativeImports = createParentRelativeImportRule({
- description: 'Disallow parent-relative imports in MCP internals — use #mcp/* aliases',
- applies: (file) => file.includes('/packages/mcp/src/'),
- message: 'Use the #mcp/* package-local alias instead of parent-relative MCP imports.'
-})
-
-const noVueParentRelativeImports = createParentRelativeImportRule({
- description: 'Disallow parent-relative imports in Vue SDK internals — use #vue/* aliases',
- applies: (file) => file.includes('/packages/vue/src/'),
- message: 'Use the #vue/* package-local alias instead of parent-relative Vue SDK imports.'
-})
-
-const noCliParentRelativeImports = createParentRelativeImportRule({
- description: 'Disallow parent-relative imports in CLI internals — use #cli/* aliases',
- applies: (file) => file.includes('/packages/cli/src/'),
- message: 'Use the #cli/* package-local alias instead of parent-relative CLI imports.'
-})
-
const noCoreSelfPackageImports = createImportSourceRule({
description: 'Disallow @open-pencil/core self-imports inside packages/core/src',
applies: (file) => file.includes('/packages/core/src/'),
@@ -293,12 +139,6 @@ export {
noDocumentChangeCapture,
noVueSelfPackageImports,
noCrossPackageSourceImports,
- noDeepParentRelativeImports,
- noDeepParentRelativePaths,
- noCoreParentRelativeImports,
- noMcpParentRelativeImports,
- noVueParentRelativeImports,
- noCliParentRelativeImports,
noCoreSelfPackageImports,
noInlinePromptConstants,
noAppImportsInPackages,
diff --git a/tools/checks/lint/src/rules/policy.ts b/tools/checks/lint/src/rules/policy.ts
index 319fcb6cf..c5a9e1b32 100644
--- a/tools/checks/lint/src/rules/policy.ts
+++ b/tools/checks/lint/src/rules/policy.ts
@@ -11,92 +11,6 @@ import {
} from '#lint/support/vue.ts'
import type { TSESTree } from '@typescript-eslint/utils'
-function isObjectKeyIdentifier(node: TSESTree.Identifier): boolean {
- const parent = node.parent
- return (
- (parent?.type === 'Property' || parent?.type === 'TSPropertySignature') &&
- parent.key === node &&
- !parent.computed &&
- (parent.type !== 'Property' || parent.value !== node)
- )
-}
-
-function isExternalMemberIdentifier(node: TSESTree.Identifier): boolean {
- const parent = node.parent
- return (
- parent?.type === 'MemberExpression' &&
- parent.property === node &&
- !parent.computed &&
- parent.object.type !== 'ThisExpression'
- )
-}
-
-function isIgnoredAcronymIdentifier(
- node: TSESTree.Identifier,
- ignoredImports: ReadonlySet<string>
-): boolean {
- if (isObjectKeyIdentifier(node) || isExternalMemberIdentifier(node)) return true
- const parent = node.parent
- if (parent?.type === 'ImportSpecifier' && parent.imported === node) {
- return (
- parent.parent?.source?.type !== 'Literal' || ignoredImports.has(parent.parent.source.value)
- )
- }
- return parent?.type === 'ImportDefaultSpecifier' || parent?.type === 'ImportNamespaceSpecifier'
-}
-
-const noMixedCaseAcronymIdentifiers = {
- meta: {
- docs: {
- description: 'Require canonical uppercase casing for acronyms in first-party identifiers'
- }
- },
- create(context) {
- const file = normalizedFilename(context)
- if (file.includes('/tools/checks/lint/')) return {}
- const canonicalAcronym =
- /(?:Acp|Ai|Api|Cli|Cors|Css|Html|Ime|Json|Jsx|Mcp|Pdf|Png|Rgb|Rpc|Rtl|Svg|Ui|Url|Uri|Xml)/g
- const ignoredImports = new Set([
- '@agentclientprotocol/sdk',
- '@realfavicongenerator/generate-favicon',
- '@tauri-apps/plugin-clipboard-manager',
- '@tauri-apps/plugin-opener',
- '@vueuse/core',
- 'culori',
- 'reka-ui'
- ])
- const upstreamIdentifiers = new Set([
- 'convertToHsb',
- 'convertToHsl',
- 'convertToRgb',
- 'formatCss',
- 'formatRgb',
- 'McpServer',
- 'ndJsonStream',
- 'openUrl',
- 'useObjectUrl',
- 'useUrlSearchParams',
- 'writeHtml'
- ])
-
- return {
- Identifier(node) {
- if (upstreamIdentifiers.has(node.name)) return
- const mixedCaseAcronym = [...node.name.matchAll(canonicalAcronym)].find((match) => {
- const end = (match.index ?? 0) + match[0].length
- return end === node.name.length || /[A-Z0-9_$]/.test(node.name[end] ?? '')
- })
- if (!mixedCaseAcronym) return
- if (isIgnoredAcronymIdentifier(node, ignoredImports)) return
- context.report({
- node,
- message: `Use canonical uppercase acronym casing in "${node.name}".`
- })
- }
- }
- }
-} satisfies RuleDefinition
-
const noFlatKiwiModules = createProgramFilenameRule({
description: 'Disallow flat top-level Kiwi modules — group code under Kiwi subdomains',
check(file) {
@@ -111,35 +25,6 @@ const noFlatKiwiModules = createProgramFilenameRule({
}
})
-const noConditionalObjectSpreads = {
- meta: {
- docs: {
- description: 'Require explicit branches instead of complex conditional object spreads'
- }
- },
- create(context) {
- return {
- SpreadElement(node) {
- if (node.parent?.type !== 'ObjectExpression') return
- if (node.argument?.type !== 'ConditionalExpression') return
- const branchSizes = [node.argument.consequent, node.argument.alternate]
- .filter((branch) => branch.type === 'ObjectExpression')
- .map((branch) => branch.properties.length)
- const conditionalSpreadCount = node.parent.properties.filter(
- (property) =>
- property.type === 'SpreadElement' && property.argument.type === 'ConditionalExpression'
- ).length
- if (conditionalSpreadCount < 2 && branchSizes.every((size) => size < 2)) return
- context.report({
- node,
- message:
- 'Extract conditional object construction into an explicit branch or named domain projection.'
- })
- }
- }
- }
-} satisfies RuleDefinition
-
/** A key when it is fixed (`key`, `'key'`, `` `key` ``), not one read from a variable. */
function fixedKey(key: TSESTree.Node, computed: boolean): string | null {
if (key.type === 'Identifier') return computed ? null : key.name
@@ -250,9 +135,4 @@ const noEditorProfileInputs: RuleDefinition = {
}
}
-export {
- noEditorProfileInputs,
- noMixedCaseAcronymIdentifiers,
- noFlatKiwiModules,
- noConditionalObjectSpreads
-}
+export { noEditorProfileInputs, noFlatKiwiModules }
diff --git a/tools/checks/lint/src/rules/runtime.ts b/tools/checks/lint/src/rules/runtime.ts
index 65bbe8ad1..8a69a2f12 100644
--- a/tools/checks/lint/src/rules/runtime.ts
+++ b/tools/checks/lint/src/rules/runtime.ts
@@ -2,15 +2,6 @@ import { normalizedFilename } from '#lint/support/context.ts'
import type { RuleDefinition } from '#lint/support/types.ts'
import type { TSESTree } from '@typescript-eslint/utils'
-function isUnknownTypeAnnotation(typeAnnotation: unknown): boolean {
- return (
- typeAnnotation !== null &&
- typeof typeAnnotation === 'object' &&
- 'type' in typeAnnotation &&
- typeAnnotation.type === 'TSUnknownKeyword'
- )
-}
-
const noDirectStorageAccess = {
meta: {
docs: {
@@ -49,140 +40,6 @@ const noDirectStorageAccess = {
}
} satisfies RuleDefinition
-function nestedAsType(node: { expression: unknown }): unknown {
- const expression = node.expression
- return expression && typeof expression === 'object' && 'typeAnnotation' in expression
- ? expression.typeAnnotation
- : null
-}
-
-const noBroadDoubleCast = {
- meta: {
- docs: {
- description: 'Disallow broad `as unknown as` casts outside vendored code'
- }
- },
- create(context) {
- const file = normalizedFilename(context)
- if (file.includes('/packages/core/src/kiwi/kiwi-schema/')) return {}
-
- return {
- TSAsExpression(node) {
- if (isUnknownTypeAnnotation(nestedAsType(node))) {
- context.report({
- node,
- message: 'Avoid `as unknown as ...`; model the value with a precise type or helper.'
- })
- }
- }
- }
- }
-} satisfies RuleDefinition
-
-function isRecordStringUnknownType(typeAnnotation: TSESTree.TypeNode): boolean {
- if (typeAnnotation?.type !== 'TSTypeReference') return false
- if (typeAnnotation.typeName?.type !== 'Identifier' || typeAnnotation.typeName.name !== 'Record') {
- return false
- }
- const parameters = typeAnnotation.typeArguments?.params ?? []
- return parameters[0]?.type === 'TSStringKeyword' && parameters[1]?.type === 'TSUnknownKeyword'
-}
-
-const noUnknownRecordDoubleCast = {
- meta: {
- docs: {
- description: 'Disallow `as unknown as Record<string, unknown>` broad object casts'
- }
- },
- create(context) {
- return {
- TSAsExpression(node) {
- if (!isUnknownTypeAnnotation(nestedAsType(node))) return
- if (!isRecordStringUnknownType(node.typeAnnotation)) return
- context.report({
- node,
- message:
- 'Avoid `as unknown as Record<string, unknown>`; use a precise type or direct public API.'
- })
- }
- }
- }
-} satisfies RuleDefinition
-
-const noFunctionType = {
- meta: {
- docs: {
- description: 'Disallow the broad Function type; use an explicit callable signature'
- }
- },
- create(context) {
- return {
- TSTypeReference(node) {
- if (node.typeName?.type !== 'Identifier' || node.typeName.name !== 'Function') return
- context.report({
- node,
- message: 'Use an explicit function signature instead of the broad Function type.'
- })
- }
- }
- }
-} satisfies RuleDefinition
-
-const noReflectDeleteGlobalThisOutsideTests = {
- meta: {
- docs: {
- description: 'Disallow Reflect.deleteProperty(globalThis, ...) outside tests'
- }
- },
- create(context) {
- const file = normalizedFilename(context)
- if (file.includes('/tests/')) return {}
-
- return {
- CallExpression(node) {
- if (node.callee?.type !== 'MemberExpression') return
- if (node.callee.object?.type !== 'Identifier' || node.callee.object.name !== 'Reflect')
- return
- if (
- node.callee.property?.type !== 'Identifier' ||
- node.callee.property.name !== 'deleteProperty'
- )
- return
- const firstArg = node.arguments?.[0]
- if (firstArg?.type !== 'Identifier' || firstArg.name !== 'globalThis') return
- context.report({
- node,
- message:
- 'Do not mutate globalThis outside tests; isolate platform state behind a boundary.'
- })
- }
- }
- }
-} satisfies RuleDefinition
-
-const noTsSuppressionComments = {
- meta: {
- docs: {
- description: 'Disallow TypeScript suppression comments; fix types instead'
- }
- },
- create(context) {
- return {
- Program() {
- const comments = context.sourceCode.getAllComments?.() ?? []
- for (const comment of comments) {
- if (!/@ts-(?:ignore|expect-error|nocheck|check)\b/.test(comment.value)) continue
- context.report({
- node: comment,
- message:
- 'Do not use TypeScript suppression comments; fix the type or add a typed helper.'
- })
- }
- }
- }
- }
-} satisfies RuleDefinition
-
const noCoreBrowserGlobals = {
meta: {
docs: {
@@ -456,11 +313,6 @@ const maxCompositionRootLines = {
export {
noDirectStorageAccess,
- noBroadDoubleCast,
- noUnknownRecordDoubleCast,
- noFunctionType,
- noReflectDeleteGlobalThisOutsideTests,
- noTsSuppressionComments,
noCoreBrowserGlobals,
noZoomInSceneDrawing,
noDirectGraphEmitterSubscriptions,
diff --git a/tools/checks/lint/src/rules/structure.ts b/tools/checks/lint/src/rules/structure.ts
index 79ef8f9b3..0bf350f81 100644
--- a/tools/checks/lint/src/rules/structure.ts
+++ b/tools/checks/lint/src/rules/structure.ts
@@ -160,108 +160,6 @@ const noComponentRootSiblingFolder = {
}
} satisfies RuleDefinition
-const noUselessPassThroughWrappers = {
- meta: {
- docs: {
- description:
- 'Disallow functions that only return another function call with the same arguments'
- }
- },
- create(context) {
- function paramNames(params: readonly TSESTree.Parameter[]): string[] | null {
- const names: string[] = []
- for (const param of params ?? []) {
- if (param.type !== 'Identifier') return null
- names.push(param.name)
- }
- return names
- }
-
- function returnedCall(
- body: TSESTree.BlockStatement | TSESTree.Expression
- ): TSESTree.CallExpression | null {
- if (!body) return null
- if (body.type === 'CallExpression') return body
- if (body.type !== 'BlockStatement') return null
- const statements = body.body?.filter((statement) => statement.type !== 'EmptyStatement') ?? []
- if (statements.length !== 1) return null
- const statement = statements[0]
- if (statement.type !== 'ReturnStatement') return null
- return statement.argument?.type === 'CallExpression' ? statement.argument : null
- }
-
- function calleeName(callee: TSESTree.CallExpression['callee']): string | null {
- return callee?.type === 'Identifier' ? callee.name : null
- }
-
- function isSameArgumentForwarding(
- args: readonly TSESTree.CallExpressionArgument[],
- params: readonly string[]
- ): boolean {
- if (args?.length !== params.length) return false
- return args.every((arg, index) => arg.type === 'Identifier' && arg.name === params[index])
- }
-
- function check(
- node: TSESTree.Node,
- name: string,
- params: readonly TSESTree.Parameter[],
- body: TSESTree.BlockStatement | TSESTree.Expression
- ) {
- const names = paramNames(params)
- if (!names) return
- const call = returnedCall(body)
- if (!call || !isSameArgumentForwarding(call.arguments, names)) return
- const target = calleeName(call.callee)
- if (!target || target === name) return
- context.report({
- node,
- message: `Remove pass-through wrapper '${name}'. Call '${target}' directly or give the wrapper real domain logic.`
- })
- }
-
- return {
- FunctionDeclaration(node) {
- if (!node.id?.name) return
- check(node, node.id.name, node.params, node.body)
- },
- VariableDeclarator(node) {
- if (node.id?.type !== 'Identifier') return
- const init = node.init
- if (
- !init ||
- (init.type !== 'ArrowFunctionExpression' && init.type !== 'FunctionExpression')
- )
- return
- check(node, node.id.name, init.params, init.body)
- }
- }
- }
-} satisfies RuleDefinition
-
-const noFunctionAliasImports = {
- meta: {
- docs: {
- description: 'Disallow import aliases ending in Fn for facade delegation'
- }
- },
- create(context) {
- return {
- ImportSpecifier(node) {
- if (!node.imported || !node.local) return
- if (node.imported.type !== 'Identifier' || node.local.type !== 'Identifier') return
- if (node.imported.name === node.local.name) return
- if (!node.local.name.endsWith('Fn')) return
- context.report({
- node,
- message:
- 'Avoid aliasing imports as *Fn. Use a namespace import or give the exported helper a clearer domain name.'
- })
- }
- }
- }
-} satisfies RuleDefinition
-
const noDirectOpenPencilBrowserStore = {
meta: {
docs: {
@@ -338,37 +236,13 @@ const noTopLevelPrefixedTestFiles = createProgramFilenameRule({
}
})
-const noSiblingDomainPrefixedFiles = createProgramFilenameRule({
- description: 'Disallow files that repeat an existing sibling domain folder in the filename',
- check(file) {
- const match = file.match(/^(.*\/)([^/]+?)(?:\.test|\.spec)?\.(?:ts|tsx|vue)$/)
- if (!match) return false
-
- const [, dir, name] = match
- const parts = name.split('-')
- if (parts.length < 2) return false
-
- const prefix = parts[0]
- // Suffixes describe control kinds (page-list, color-input), not necessarily ownership.
- let domain: string | null = null
- if (existsSync(`${dir}${prefix}`)) domain = prefix
- if (!domain) return false
-
- const filename = file.slice(dir.length)
- return `Move '${filename}' under the existing '${domain}/' folder instead of repeating the domain in the filename.`
- }
-})
-
export {
vueComponentFilePascalCase,
componentNamespaceCasing,
nonComponentSourceDirectoriesKebabCase,
noComponentRootSiblingFolder,
- noUselessPassThroughWrappers,
- noFunctionAliasImports,
noDirectOpenPencilBrowserStore,
noDirectOpenPencilWindowInternals,
noBunGlobalsInCli,
- noTopLevelPrefixedTestFiles,
- noSiblingDomainPrefixedFiles
+ noTopLevelPrefixedTestFiles
}
diff --git a/tools/checks/lint/src/rules/typescript.ts b/tools/checks/lint/src/rules/typescript.ts
index ee09c9b81..9ce9c54ab 100644
--- a/tools/checks/lint/src/rules/typescript.ts
+++ b/tools/checks/lint/src/rules/typescript.ts
@@ -1,212 +1,13 @@
import type { RuleDefinition } from '#lint/support/types.ts'
import type { TSESTree } from '@typescript-eslint/utils'
-import { compact } from 'es-toolkit/array'
-type TypeNode = TSESTree.TypeNode
-
-function typeParameterNodes(node: TSESTree.TSTypeReference): TypeNode[] {
- return node.typeArguments?.params ?? []
-}
-
-function isRecordStringUnknownType(node: TypeNode | null | undefined): boolean {
- if (node?.type !== 'TSTypeReference') return false
- if (node.typeName?.type !== 'Identifier' || node.typeName.name !== 'Record') return false
- const params = typeParameterNodes(node)
- return params[0]?.type === 'TSStringKeyword' && params[1]?.type === 'TSUnknownKeyword'
-}
-
-function hasASTChild(
- node: unknown,
- predicate: (node: TypeNode) => boolean,
- seen = new WeakSet<object>()
-): boolean {
- if (!node || typeof node !== 'object') return false
- if (seen.has(node)) return false
- seen.add(node)
- if (predicate(node as TypeNode)) return true
-
- for (const [key, value] of Object.entries(node)) {
- if (key === 'parent' || key === 'range' || key === 'loc') continue
- if (Array.isArray(value)) {
- if (value.some((child) => hasASTChild(child, predicate, seen))) return true
- } else if (value && typeof value === 'object' && hasASTChild(value, predicate, seen)) {
- return true
- }
- }
- return false
-}
-
-function containsRecordStringUnknownType(node: TypeNode | null | undefined): boolean {
- if (isRecordStringUnknownType(node)) return true
- if (node?.type === 'TSArrayType') return isRecordStringUnknownType(node.elementType)
- if (node?.type === 'TSUnionType')
- return node.types?.some(containsRecordStringUnknownType) ?? false
- return false
-}
-
-function isUnknownArrayType(node: TypeNode | null | undefined): boolean {
- return node?.type === 'TSArrayType' && node.elementType?.type === 'TSUnknownKeyword'
-}
-
-function hasInlineUnknownArrayProperty(node: TypeNode): boolean {
- if (node?.type !== 'TSTypeLiteral') return false
- return (node.members ?? []).some((member) => {
- if (member.type !== 'TSPropertySignature') return false
- const typeNode = member.typeAnnotation?.typeAnnotation
- return isUnknownArrayType(typeNode)
- })
-}
-
-function containsInlineUnknownObjectType(node: TypeNode): boolean {
- return hasASTChild(node, hasInlineUnknownArrayProperty)
-}
-
-const noBroadUnknownTypeAssertions = {
- meta: {
- docs: {
- description:
- 'Disallow broad unknown object type assertions. Add a named domain type or a type guard instead.'
- }
- },
- create(context) {
- function check(node: TSESTree.TSAsExpression | TSESTree.TSTypeAssertion) {
- if (containsRecordStringUnknownType(node.typeAnnotation)) {
- context.report({
- node,
- message:
- 'Do not cast to Record<string, unknown>. Add a named domain type or a type guard.'
- })
- return
- }
- if (containsInlineUnknownObjectType(node.typeAnnotation)) {
- context.report({
- node,
- message: 'Do not cast to an inline unknown object shape. Add a named domain type.'
- })
- }
- }
-
- return {
- TSAsExpression: check,
- TSTypeAssertion: check
- }
- }
-} satisfies RuleDefinition
-
-function typeNameText(node: TSESTree.EntityName | null | undefined): string {
- if (!node) return 'unknown'
- if (node.type === 'Identifier') return node.name
- if (node.type === 'TSQualifiedName')
- return `${typeNameText(node.left)}.${typeNameText(node.right)}`
- return node.type
+function isRecordStringUnknownType(node: TSESTree.TypeNode): boolean {
+ if (node.type !== 'TSTypeReference') return false
+ if (node.typeName.type !== 'Identifier' || node.typeName.name !== 'Record') return false
+ const [key, value] = node.typeArguments?.params ?? []
+ return key?.type === 'TSStringKeyword' && value?.type === 'TSUnknownKeyword'
}
-function parameterType(parameter: TSESTree.Parameter): string {
- const value = parameter.type === 'TSParameterProperty' ? parameter.parameter : parameter
- return canonicalType('typeAnnotation' in value ? value.typeAnnotation?.typeAnnotation : null)
-}
-
-function canonicalType(node: TypeNode | null | undefined): string {
- if (!node) return 'unknown'
- switch (node.type) {
- case 'TSStringKeyword':
- return 'string'
- case 'TSNumberKeyword':
- return 'number'
- case 'TSBooleanKeyword':
- return 'boolean'
- case 'TSUnknownKeyword':
- return 'unknown'
- case 'TSNullKeyword':
- return 'null'
- case 'TSUndefinedKeyword':
- return 'undefined'
- case 'TSLiteralType':
- return `literal:${'value' in node.literal ? node.literal.value : node.literal.type}`
- case 'TSArrayType':
- return `array<${canonicalType(node.elementType)}>`
- case 'TSTypeReference': {
- const params = typeParameterNodes(node).map(canonicalType).join(',')
- return `ref:${typeNameText(node.typeName)}<${params}>`
- }
- case 'TSUnionType':
- return `union<${node.types.map(canonicalType).sort().join('|')}>`
- case 'TSTypeLiteral':
- return `object{${canonicalMembers(node.members)}}`
- case 'TSFunctionType': {
- const parameters = node.params.map(parameterType).join(',')
- return `function<${parameters}=>${canonicalType(node.returnType?.typeAnnotation)}>`
- }
- default:
- return node.type
- }
-}
-
-function propertyKeyName(key: TSESTree.PropertyName): string | null {
- if (key?.type === 'Identifier') return key.name
- if (key?.type === 'Literal') return String(key.value)
- return null
-}
-
-function canonicalMember(member: TSESTree.TypeElement): string | null {
- if (member.type === 'TSIndexSignature') {
- const parameter = member.parameters?.[0]
- const param = parameter?.type === 'TSParameterProperty' ? parameter.parameter : parameter
- const keyType = param && 'typeAnnotation' in param ? param.typeAnnotation?.typeAnnotation : null
- return `index:${canonicalType(keyType)}:${canonicalType(member.typeAnnotation?.typeAnnotation)}`
- }
- if (member.type !== 'TSPropertySignature') return null
- const name = propertyKeyName(member.key)
- if (!name) return null
- const optional = member.optional ? '?' : ''
- return `prop:${name}${optional}:${canonicalType(member.typeAnnotation?.typeAnnotation)}`
-}
-
-function canonicalMembers(members: readonly TSESTree.TypeElement[] | undefined): string {
- return compact((members ?? []).map(canonicalMember))
- .sort()
- .join(';')
-}
-
-function namedTypeShape(
- node: TSESTree.TSInterfaceDeclaration | TSESTree.TSTypeAliasDeclaration
-): string | null {
- if (node.type === 'TSInterfaceDeclaration') return canonicalMembers(node.body?.body)
- if (node.type === 'TSTypeAliasDeclaration' && node.typeAnnotation?.type === 'TSTypeLiteral') {
- return canonicalMembers(node.typeAnnotation.members)
- }
- return null
-}
-
-const noDuplicateTypeShapes = {
- meta: {
- docs: {
- description: 'Disallow duplicate local object type/interface shapes in one file'
- }
- },
- create(context) {
- const seen = new Map()
- return {
- 'TSInterfaceDeclaration, TSTypeAliasDeclaration'(node) {
- const shape = namedTypeShape(node)
- if (!shape) return
- const memberCount = shape ? compact(shape.split(';')).length : 0
- if (memberCount < 2) return
- const first = seen.get(shape)
- if (!first) {
- seen.set(shape, node)
- return
- }
- context.report({
- node,
- message:
- 'Duplicate object type shape. Reuse the existing named type instead of redeclaring the same members.'
- })
- }
- }
- }
-} satisfies RuleDefinition
-
const noLocalJsonObjectAliases = {
meta: {
docs: {
@@ -228,28 +29,4 @@ const noLocalJsonObjectAliases = {
}
} satisfies RuleDefinition
-const noImportTypeAnnotations = {
- meta: {
- docs: {
- description: 'Disallow inline import() type annotations — use top-level import type instead'
- }
- },
- create(context) {
- return {
- TSImportType(node) {
- context.report({
- node,
- message:
- 'Use a top-level import type instead of an inline import() type annotation. Dynamic imports are only for runtime lazy loading.'
- })
- }
- }
- }
-} satisfies RuleDefinition
-
-export {
- noBroadUnknownTypeAssertions,
- noDuplicateTypeShapes,
- noLocalJsonObjectAliases,
- noImportTypeAnnotations
-}
+export { noLocalJsonObjectAliases }
diff --git a/tools/checks/lint/src/support/scope.ts b/tools/checks/lint/src/support/scope.ts
deleted file mode 100644
index 32a43ea74..000000000
--- a/tools/checks/lint/src/support/scope.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { ESTree, Scope, SourceCode, Variable } from '@oxlint/plugins'
-
-/** Resolve an identifier to its binding by walking lexical scopes upward. */
-export function resolveVariable(
- sourceCode: SourceCode,
- identifier: Extract<ESTree.Node, { type: 'Identifier' }>
-): Variable | null {
- let scope: Scope | null = sourceCode.getScope(identifier)
- while (scope !== null) {
- const variable = scope.set.get(identifier.name)
- if (variable !== undefined) return variable
- scope = scope.upper
- }
- return null
-}
diff --git a/tools/checks/lint/tests/deep-paths.test.ts b/tools/checks/lint/tests/deep-paths.test.ts
deleted file mode 100644
index a9b13599e..000000000
--- a/tools/checks/lint/tests/deep-paths.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import { lint, ruleDiagnostics } from './helpers/lint.ts'
-
-const rule = 'no-deep-parent-relative-paths'
-const rules = { [`open-pencil/${rule}`]: 'error' }
-// A template that climbs one level and then names a folder, assembled so it stays source text.
-const oneLevelTemplate = ['join(import.meta.dir, `../', '$', "{folder}`, '..', 'assets')"].join('')
-
-describe('no-deep-parent-relative-paths', () => {
- test.each([
- "new URL('../../fixtures/a.fig', import.meta.url)",
- 'new URL(`../../fixtures/a.fig`, import.meta.url)',
- "resolve(import.meta.dir, '../../../tests/fixtures')",
- "join(import.meta.dirname, '..', '..', 'assets')",
- "path.resolve(import.meta.dir, '../..')",
- "join(import.meta.dir, '..\\\\..\\\\assets')",
- "join(dirname(fileURLToPath(import.meta.url)), '../../fixtures')"
- ])('rejects %s', async (source) => {
- expect(ruleDiagnostics(await lint(source, rules), rule)).toHaveLength(1)
- })
-
- test.each([
- "new URL('../fixtures/a.fig', import.meta.url)",
- "new URL('./worker.ts', import.meta.url)",
- "join(import.meta.dir, '..', 'fixtures')",
- "credentialRef('../../other-app', 'api-key')",
- "resolve(root, '../../somewhere')",
- "join(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures')",
- oneLevelTemplate
- ])('accepts %s', async (source) => {
- expect(ruleDiagnostics(await lint(source, rules), rule)).toHaveLength(0)
- })
-})
diff --git a/tools/checks/lint/tests/plugin.test.ts b/tools/checks/lint/tests/plugin.test.ts
index bd52243a6..8166e76e8 100644
--- a/tools/checks/lint/tests/plugin.test.ts
+++ b/tools/checks/lint/tests/plugin.test.ts
@@ -1,10 +1,7 @@
-import { afterEach, describe, expect, test } from 'bun:test'
-import { mkdir, mkdtemp, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
+import { describe, expect, test } from 'bun:test'
import { join } from 'node:path'
import type lintPlugin from '#lint/plugin.ts'
-import { noSiblingDomainPrefixedFiles } from '#lint/rules/structure.ts'
import {
noHardcodedTipLabelsInVue,
noNativeTitleAttributesInVue,
@@ -16,9 +13,7 @@ import { AST_NODE_TYPES, type TSESTree } from '@typescript-eslint/utils'
import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'
-import { lint, lintFiles, ruleDiagnostics } from './helpers/lint.ts'
-
-const temporaryDirectories: string[] = []
+import { lintFiles, ruleDiagnostics } from './helpers/lint.ts'
const unavailable = (member: string) => () => {
throw new Error(`${member} is not available in the filename-only harness`)
@@ -49,7 +44,6 @@ function emptyProgram(): TSESTree.Program {
/** Rules the filename-only harness below can drive without a parsed AST. */
const harnessRules = {
- 'no-sibling-domain-prefixed-files': noSiblingDomainPrefixedFiles,
'no-native-title-attributes-in-vue': noNativeTitleAttributesInVue,
'no-hardcoded-tip-labels-in-vue': noHardcodedTipLabelsInVue,
'no-raw-svg-in-app-vue-templates': noRawSvgInAppVueTemplates
@@ -76,18 +70,6 @@ async function runRule(
return reports
}
-test('domain naming uses ownership prefixes, not control-kind suffixes', async () => {
- const directory = await mkdtemp(join(tmpdir(), 'open-pencil-domains-'))
- temporaryDirectories.push(directory)
- await mkdir(join(directory, 'list'))
- expect(
- await runRule('no-sibling-domain-prefixed-files', '', join(directory, 'page-list.ts'))
- ).toBe(0)
- expect(
- await runRule('no-sibling-domain-prefixed-files', '', join(directory, 'list-actions.ts'))
- ).toBe(1)
-})
-
test('storage rule permits data keys but rejects storage access', async () => {
const rule = 'no-direct-storage-access'
const cases = {
@@ -109,67 +91,10 @@ test('storage rule permits data keys but rejects storage access', async () => {
}
})
-afterEach(async () => {
- await Promise.all(
- temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true }))
- )
-})
-
-describe('no-conditional-object-spreads', () => {
- const rule = 'no-conditional-object-spreads'
- const rules = { [`open-pencil/${rule}`]: 'error' }
-
- test('accepts a simple one-property projection', async () => {
- const diagnostics = await lint(
- 'export const result = { ...(enabled ? { value: 1 } : {}) }',
- rules
- )
- expect(ruleDiagnostics(diagnostics, rule)).toHaveLength(0)
- })
-
- test('reports a multi-property conditional projection', async () => {
- const diagnostics = await lint(
- 'export const result = { ...(enabled ? { value: 1, label: "yes" } : {}) }',
- rules
- )
- expect(ruleDiagnostics(diagnostics, rule)).toHaveLength(1)
- })
-
- test('reports multiple conditional projections in one object', async () => {
- const diagnostics = await lint(
- 'export const result = { ...(first ? { a: 1 } : {}), ...(second ? { b: 2 } : {}) }',
- rules
- )
- expect(ruleDiagnostics(diagnostics, rule)).toHaveLength(2)
- })
-})
-
-describe('AST-backed rules', () => {
- test('recognizes Record<string, unknown> from the TypeScript AST', async () => {
- const rule = 'no-unknown-record-double-cast'
- const diagnostics = await lint(
- 'export const result = value as unknown as Record< string, unknown >',
- { [`open-pencil/${rule}`]: 'error' }
- )
- expect(ruleDiagnostics(diagnostics, rule)).toHaveLength(1)
- })
-
- test('keeps distinct callback signatures out of duplicate type diagnostics', async () => {
- const rule = 'no-duplicate-type-shapes'
- const diagnostics = await lint(
- [
- 'interface First { handler: (value: string) => number; enabled: boolean }',
- 'interface Second { handler: (value: number) => number; enabled: boolean }'
- ].join('\n'),
- { [`open-pencil/${rule}`]: 'error' }
- )
- expect(ruleDiagnostics(diagnostics, rule)).toHaveLength(0)
- })
-
+describe('Vue template rules', () => {
test('recognizes native title attributes from the Vue template AST', async () => {
- const rule = 'no-native-title-attributes-in-vue'
const reports = await runRule(
- rule,
+ 'no-native-title-attributes-in-vue',
'<template><button title="Save">Save</button></template>',
'/repo/src/components/SaveButton.vue'
)
@@ -225,10 +150,12 @@ describe('path support', () => {
})
describe('plugin entrypoint', () => {
- test('loads all custom rules through the compatibility entrypoint', async () => {
+ test("loads this repository's rules and the published plugin's as one plugin", async () => {
const pluginPath = join(await resolveWorkspaceRoot(import.meta.dir), 'lint/plugin.js')
const module = (await import(pluginPath)) as { default: typeof lintPlugin }
- expect(Object.keys(module.default.rules)).toContain('no-conditional-object-spreads')
- expect(Object.keys(module.default.rules).length).toBeGreaterThan(60)
+ const rules = Object.keys(module.default.rules)
+ expect(module.default.meta.name).toBe('open-pencil')
+ expect(rules).toContain('no-conditional-object-spreads')
+ expect(rules).toContain('no-direct-storage-access')
})
})
diff --git a/tools/checks/package-quality/src/smoke/scenarios.ts b/tools/checks/package-quality/src/smoke/scenarios.ts
index 6a33a5748..2f56523d7 100644
--- a/tools/checks/package-quality/src/smoke/scenarios.ts
+++ b/tools/checks/package-quality/src/smoke/scenarios.ts
@@ -64,6 +64,10 @@ export const runtimeScenarios: RuntimeScenario[] = [
name: 'DOM/CSS JSX runtime',
code: "const { jsx, jsxToDesignDocument } = await import('@open-pencil/dom-css/jsx-runtime'); const document = await jsxToDesignDocument(jsx('section', { class: 'card', style: { width: '120px' }, children: 'OpenPencil' })); const node = document.children[0]; if (node?.type !== 'element' || node.inlineStyle?.width !== '120px') throw new Error('DOM/CSS JSX runtime failed')"
},
+ {
+ name: 'Oxlint plugin',
+ code: "const { default: plugin } = await import('@open-pencil/oxlint-plugin'); if (plugin.meta.name !== 'open-pencil' || Object.keys(plugin.rules).length < 28 || !plugin.rules['no-unvalidated-json-parse']?.meta) throw new Error('Oxlint plugin smoke failed')"
+ },
{
name: 'Cloud contract',
code: "const { CLOUD_AI_TOKEN_AUDIENCE, aiWalletSchema } = await import('@open-pencil/cloud/contract'); const { safeParse } = await import('valibot'); if (CLOUD_AI_TOKEN_AUDIENCE !== 'openpencil-ai' || !safeParse(aiWalletSchema, { balance: 5, buckets: [] }).success) throw new Error('Cloud contract smoke failed')"
diff --git a/tools/dev/unit-tests/tests/shards.test.ts b/tools/dev/unit-tests/tests/shards.test.ts
index cb43a1780..8bc5513c2 100644
--- a/tools/dev/unit-tests/tests/shards.test.ts
+++ b/tools/dev/unit-tests/tests/shards.test.ts
@@ -13,7 +13,12 @@ import {
const REPO_ROOT = await resolveWorkspaceRoot(import.meta.dir)
// Packages whose tests run in their own CI job instead of the unit shards.
-const OWN_SUITES = ['packages/harness/', 'packages/feedback/', 'packages/cloud/']
+const OWN_SUITES = [
+ 'packages/harness/',
+ 'packages/feedback/',
+ 'packages/cloud/',
+ 'packages/oxlint-plugin/'
+]
async function discover(pattern: string): Promise<string[]> {
return Array.fromAsync(new Bun.Glob(pattern).scan({ cwd: REPO_ROOT }))
diff --git a/tsconfig.tests.json b/tsconfig.tests.json
index e85821e98..19de6e09e 100644
--- a/tsconfig.tests.json
+++ b/tsconfig.tests.json
@@ -141,6 +141,12 @@
],
"#cloud-tests/*": [
"./packages/cloud/tests/*"
+ ],
+ "#oxlint-plugin/*": [
+ "./packages/oxlint-plugin/src/*"
+ ],
+ "#oxlint-plugin-tests/*": [
+ "./packages/oxlint-plugin/tests/*"
]
},
"types": [