Skip to content

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

chore: prefer es-toolkit helpers and lint the mechanical cases (#898)

Danila Poyarkovc8d68acc9efb
diff --git a/AGENTS.md b/AGENTS.md
index 5af9fdaf0..7789bc53e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -55,7 +55,8 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun
- Non-component folders and files use lowercase or kebab-case except standard entrypoints (`README.md`, `AGENTS.md`, `index.ts`). Component domains use kebab-case folders; Vue files stay PascalCase and component composables camelCase. Do not add new PascalCase app folders or root-level base controls; migrate old ones when touched.
- No `any`, non-null assertions, or `Math.random()`; use precise types, guards, and `crypto.getRandomValues()` — through `randomHex`, `randomInt`, and `randomIndex` from `@open-pencil/scene-graph/random` rather than new copies. New component property IDs come from `createComponentPropertyId()`, and graph entity IDs from the `SceneGraph`'s generator (`createNode`, `createCollection`, `createMode`).
- Valibot for first-party runtime validation. Keep Zod only where an upstream dependency requires it; never maintain parallel first-party schemas in both.
-- Use existing dependencies before writing utilities: `culori` for color conversion, `es-toolkit` for focused helpers (without replacing clear native code), VueUse for browser, event, focus, clipboard, storage, and timer behavior (one-shot rAF or service-owned timers are fine when clearer), `dedent` for multiline prompt composition and embedded examples. Keep substantial prompt prose in the owning Markdown source and compose it.
+- Use existing dependencies before writing utilities: `culori` for color conversion, VueUse for browser, event, focus, clipboard, storage, and timer behavior (one-shot rAF or service-owned timers are fine when clearer), `dedent` for multiline prompt composition and embedded examples. Keep substantial prompt prose in the owning Markdown source and compose it.
+- Reach for `es-toolkit` before hand-writing a collection or object helper: `uniq`/`uniqBy` over `Set` round trips, `compact` over `filter(Boolean)`, `groupBy`/`keyBy`/`partition`/`countBy` over accumulator loops, `pick`/`omit`/`mapValues`/`mapKeys` over rewriting `Object.entries`, `isEmptyObject`/`isEqual` over manual checks. Keep native code where it is a single clear call (`map`, `some`, `Object.fromEntries` of a direct mapping) or on a measured hot path such as per-frame rendering and layout. `open-pencil/prefer-es-toolkit` enforces the `uniq` and `compact` cases.
- Use `js-base64` directly for Base64: `fromUint8Array`/`toUint8Array` for bytes, `encode`/`decode` for text, and `isValid` before decoding input from outside (clipboard, imported files, tool arguments). Do not wrap it or use `atob`, `btoa`, or `Buffer` Base64 conversions; `open-pencil/no-hand-rolled-base64` enforces this.
- Parse JSON from outside the process (clipboard, files, network, storage, tool arguments) with `v.safeParse(v.pipe(v.string(), v.parseJson(), Schema), text)`, so malformed JSON and a wrong shape fail the same way. Never assert a type on a `JSON.parse` or `.json()` result other than `unknown`; `open-pencil/no-unvalidated-json-parse` enforces this in source, tests, and tooling.
- Browser-shipped code targets the supported browser baseline in `src/app/shell/support/baseline.ts`: TypeScript `lib` stays ES2023 and `compat/compat` rejects missing Web APIs; Node-only packages (`cli`, `mcp`, `harness`) are exempt. Details in `src/AGENTS.md` (Browser baseline).
diff --git a/bun.lock b/bun.lock
index 8f73cd3be..4c0f2a136 100644
--- a/bun.lock
+++ b/bun.lock
@@ -381,6 +381,7 @@
"@open-pencil/design-jsx": "workspace:*",
"@open-pencil/scene-graph": "workspace:*",
"@valibot/to-json-schema": "^1.8.0",
+ "es-toolkit": "^1.52.0",
"hono": "^4.13.13",
"js-base64": "^3.9.3",
"package-manager-detector": "^1.8.0",
@@ -432,6 +433,7 @@
"@open-pencil/scene-graph": "workspace:*",
"@tanstack/vue-table": "^8.21.3",
"@vueuse/core": "^14.4.0",
+ "es-toolkit": "^1.52.0",
"fuse.js": "^7.5.0",
"nanostores": "^1.5.4",
"reka-ui": "^2.10.5",
@@ -472,9 +474,15 @@
},
"tools/checks/i18n": {
"name": "@open-pencil/i18n-tools",
+ "dependencies": {
+ "es-toolkit": "^1.52.0",
+ },
},
"tools/checks/lint": {
"name": "@open-pencil/lint-tools",
+ "dependencies": {
+ "es-toolkit": "^1.52.0",
+ },
"devDependencies": {
"@open-pencil/package-artifacts-tools": "workspace:*",
},
@@ -499,6 +507,9 @@
},
"tools/checks/type-shapes": {
"name": "@open-pencil/type-shapes-tools",
+ "dependencies": {
+ "es-toolkit": "^1.52.0",
+ },
},
"tools/ci/images": {
"name": "@open-pencil/ci-images-tools",
@@ -525,6 +536,7 @@
"name": "@open-pencil/unit-tests-tools",
"dependencies": {
"@open-pencil/package-artifacts-tools": "workspace:*",
+ "es-toolkit": "^1.52.0",
},
},
"tools/generate/authoring-reference": {
@@ -556,6 +568,9 @@
},
"tools/generate/tauri-menu": {
"name": "@open-pencil/tauri-menu-tools",
+ "dependencies": {
+ "es-toolkit": "^1.52.0",
+ },
"devDependencies": {
"@open-pencil/package-artifacts-tools": "workspace:*",
"@open-pencil/vue": "workspace:*",
diff --git a/oxlint.json b/oxlint.json
index 004735b10..a45e5fd19 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -420,11 +420,18 @@
"no-loop-func": "error",
"typescript/no-dynamic-delete": "error",
"open-pencil/no-hand-rolled-base64": "error",
+ "open-pencil/prefer-es-toolkit": "error",
"open-pencil/no-module-mocking": "error",
"open-pencil/no-reduce-accumulator-copy": "error",
"open-pencil/no-widen-then-assert": "error"
},
"overrides": [
+ {
+ "files": ["tools/ci/policy/src/**/*.ts"],
+ "rules": {
+ "open-pencil/prefer-es-toolkit": "off"
+ }
+ },
{
"files": ["tools/checks/lint/src/rules/quality/widen-then-assert.ts"],
"rules": {
diff --git a/packages/core/src/editor/guides.ts b/packages/core/src/editor/guides.ts
index 10f91ab7e..6306c9d4a 100644
--- a/packages/core/src/editor/guides.ts
+++ b/packages/core/src/editor/guides.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit/array'
+
import type { CanvasGuide } from '@open-pencil/scene-graph/guides'
import type { EditorContext } from './types'
@@ -13,7 +15,7 @@ function replaceGuides(ctx: EditorContext, ownerId: string, guides: CanvasGuide[
const node = ctx.graph.getNode(ownerId)
if (!node) return
ctx.graph.updateNode(ownerId, { guides: structuredClone(guides) })
- node.source.editedFields = [...new Set([...node.source.editedFields, 'guides'])]
+ node.source.editedFields = uniq([...node.source.editedFields, 'guides'])
ctx.emitEditorEvent('guides:changed', ownerId, structuredClone(guides))
ctx.requestRender()
}
diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.ts
index 10dbac767..b22c6be9d 100644
--- a/packages/core/src/figma-api/components.ts
+++ b/packages/core/src/figma-api/components.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit/array'
+
import type {
ComponentPropertyReferenceField,
ComponentPropertyDefinition,
@@ -76,7 +78,7 @@ export function exposeInstanceSwap(
)
)
throw new Error('Candidates must be COMPONENT or COMPONENT_SET nodes')
- const candidateIds = [...new Set(candidateNodes.map((node) => node.id))]
+ const candidateIds = uniq(candidateNodes.map((node) => node.id))
if (candidateIds.length !== candidateNodes.length) throw new Error('Candidates must be distinct')
const host = findPropertyHost(graph, slotNodes[0].parentId)
if (!host) throw new Error('Instance must be nested inside a COMPONENT or COMPONENT_SET')
diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.ts
index 453617ec9..d90ef3707 100644
--- a/packages/core/src/io/formats/svg/paths.ts
+++ b/packages/core/src/io/formats/svg/paths.ts
@@ -1,3 +1,5 @@
+import { compact } from 'es-toolkit/array'
+
import type {
SceneNode,
VectorNetwork,
@@ -251,7 +253,7 @@ export function roundedRectPath(node: SceneNode): string {
br = Math.min(br, w / 2, h / 2)
bl = Math.min(bl, w / 2, h / 2)
- return [
+ return compact([
`M${round(tl)} 0`,
`L${round(w - tr)} 0`,
tr > 0 ? `A${round(tr)} ${round(tr)} 0 0 1 ${round(w)} ${round(tr)}` : '',
@@ -262,9 +264,7 @@ export function roundedRectPath(node: SceneNode): string {
`L0 ${round(tl)}`,
tl > 0 ? `A${round(tl)} ${round(tl)} 0 0 1 ${round(tl)} 0` : '',
'Z'
- ]
- .filter(Boolean)
- .join('')
+ ]).join('')
}
export function arcPath(node: SceneNode): string {
diff --git a/packages/core/src/lint/utils.ts b/packages/core/src/lint/utils.ts
index 90965e763..c4687084f 100644
--- a/packages/core/src/lint/utils.ts
+++ b/packages/core/src/lint/utils.ts
@@ -1,3 +1,4 @@
+import { compact } from 'es-toolkit/array'
export function isDefaultName(name: string): boolean {
return /^(Frame|Rectangle|Ellipse|Line|Text|Group|Vector|Polygon|Star|Section|Component|Instance|Slice)\s*\d*$/i.test(
name
@@ -10,12 +11,13 @@ export function isDefaultName(name: string): boolean {
* `button`, `2`, and "Rectangle" does not contain `cta`.
*/
export function nameWords(name: string): string[] {
- return name
- .replaceAll(/([a-z\d])([A-Z])/g, '$1 $2')
- .replaceAll(/([a-z])(\d)/gi, '$1 $2')
- .toLowerCase()
- .split(/[^a-z\d]+/)
- .filter(Boolean)
+ return compact(
+ name
+ .replaceAll(/([a-z\d])([A-Z])/g, '$1 $2')
+ .replaceAll(/([a-z])(\d)/gi, '$1 $2')
+ .toLowerCase()
+ .split(/[^a-z\d]+/)
+ )
}
export function isMultipleOf(value: number, base: number, tolerance = 0.01): boolean {
diff --git a/packages/core/src/vector/vectorize/svg/transform.ts b/packages/core/src/vector/vectorize/svg/transform.ts
index c7c25e13a..a9717a5ad 100644
--- a/packages/core/src/vector/vectorize/svg/transform.ts
+++ b/packages/core/src/vector/vectorize/svg/transform.ts
@@ -1,3 +1,4 @@
+import { compact } from 'es-toolkit/array'
import svgpath from 'svgpath'
import type { Rect, Size, Vector } from '@open-pencil/scene-graph/primitives'
@@ -31,7 +32,7 @@ export function resolveSVGViewportMapping(
const value =
parseSVGDocument(svg)?.documentElement?.getAttribute('preserveAspectRatio')?.trim() ?? ''
- const tokens = value.split(/\s+/).filter(Boolean)
+ const tokens = compact(value.split(/\s+/))
if (tokens.includes('none')) return { space, scaleX, scaleY, offsetX: 0, offsetY: 0 }
const align = tokens.find((token) => token.startsWith('x')) ?? 'xMidYMid'
diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.ts
index cc9b93f90..159dfb672 100644
--- a/packages/design-jsx/src/export/index.ts
+++ b/packages/design-jsx/src/export/index.ts
@@ -1,3 +1,5 @@
+import { compact } from 'es-toolkit/array'
+
import { jsx, type SyntaxNode } from '@open-pencil/emit'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
@@ -126,13 +128,12 @@ export function selectionToJSXWithLayers(
graph: SceneGraph
): DesignJSXWithLayers {
const layerIds: string[] = []
- const code = nodeIds
- .map((id) => {
+ const code = compact(
+ nodeIds.map((id) => {
const node = graph.getNode(id)
const syntax = node ? nodeToJSX(node, graph, 0, layerIds) : null
return syntax ? jsx.printJSX(syntax) : ''
})
- .filter(Boolean)
- .join('\n\n')
+ ).join('\n\n')
return { code, layerIds }
}
diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.ts
index 1f6064ee5..8c2706983 100644
--- a/packages/design-jsx/src/renderer.ts
+++ b/packages/design-jsx/src/renderer.ts
@@ -1,3 +1,5 @@
+import { compact } from 'es-toolkit/array'
+
import {
createComponentPropertyId,
setInstanceOverride,
@@ -284,10 +286,7 @@ function renderSVGNode<Artwork>(
}
function parseVariantValues(name: string): Record<string, string> {
- const entries = name
- .split(',')
- .map((part) => part.trim())
- .filter(Boolean)
+ const entries = compact(name.split(',').map((part) => part.trim()))
const values: Record<string, string> = {}
for (const entry of entries) {
const [key = '', ...rest] = entry.split('=')
diff --git a/packages/dom-css/src/export/storybook/groups.ts b/packages/dom-css/src/export/storybook/groups.ts
index a60f19406..90dd25af7 100644
--- a/packages/dom-css/src/export/storybook/groups.ts
+++ b/packages/dom-css/src/export/storybook/groups.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit/array'
+
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'
@@ -49,9 +51,7 @@ function componentSetGroup(graph: SceneGraph, page: SceneNode, set: SceneNode):
}))
const props = definitions.map((def, index) => ({
name: def.name,
- options: [
- ...new Set([...(def.variantOptions ?? []), ...variants.map((v) => v.values[index] ?? '')])
- ]
+ options: uniq([...(def.variantOptions ?? []), ...variants.map((v) => v.values[index] ?? '')])
}))
return distinctVariants({
page,
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index 9fc56c08b..90df75c1d 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -69,6 +69,7 @@
"@open-pencil/design-jsx": "workspace:*",
"@open-pencil/scene-graph": "workspace:*",
"@valibot/to-json-schema": "^1.8.0",
+ "es-toolkit": "^1.52.0",
"hono": "^4.13.13",
"js-base64": "^3.9.3",
"package-manager-detector": "^1.8.0",
diff --git a/packages/mcp/src/tool/output.ts b/packages/mcp/src/tool/output.ts
index 6087bd6bc..2a3ed3a89 100644
--- a/packages/mcp/src/tool/output.ts
+++ b/packages/mcp/src/tool/output.ts
@@ -1,6 +1,7 @@
import { lstat, mkdir, readlink, realpath, writeFile } from 'node:fs/promises'
import { dirname, basename, isAbsolute, join, parse, resolve, sep as osSep } from 'node:path'
+import { compact } from 'es-toolkit/array'
import { toUint8Array } from 'js-base64'
import { ok } from '#mcp/result'
@@ -55,7 +56,7 @@ async function resolveRealAncestor(
*/
async function assertNoSymlinksInRemainder(realAncestor: string, remainder: string): Promise<void> {
if (!remainder) return
- const segments = remainder.split(osSep).filter(Boolean)
+ const segments = compact(remainder.split(osSep))
let current = realAncestor
for (const seg of segments) {
current = join(current, seg)
diff --git a/packages/mcp/src/tool/policy.ts b/packages/mcp/src/tool/policy.ts
index dbaac1d30..60368ad01 100644
--- a/packages/mcp/src/tool/policy.ts
+++ b/packages/mcp/src/tool/policy.ts
@@ -1,15 +1,10 @@
+import { compact, uniq } from 'es-toolkit/array'
+
import type { ToolDescriptor, ToolPolicy } from '#mcp/tool/metadata'
export function parseDisabledTools(value: string | undefined): string[] {
if (!value) return []
- return [
- ...new Set(
- value
- .split(',')
- .map((name) => name.trim())
- .filter(Boolean)
- )
- ]
+ return uniq(compact(value.split(',').map((name) => name.trim())))
}
export function isToolEnabled(descriptor: ToolDescriptor, policy: ToolPolicy): boolean {
diff --git a/packages/scene-graph/src/mutation-impact.ts b/packages/scene-graph/src/mutation-impact.ts
index 2d8c38ff2..0c91fa547 100644
--- a/packages/scene-graph/src/mutation-impact.ts
+++ b/packages/scene-graph/src/mutation-impact.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit/array'
+
import type { SceneGraph } from './index'
export interface SceneMutationImpact {
@@ -64,7 +66,5 @@ export async function collectSceneMutation<T>(
}
export function mutationLayoutScopeIds(impact: SceneMutationImpact): string[] {
- return [
- ...new Set([...impact.changedNodeIds, ...impact.previousParentIds, ...impact.currentParentIds])
- ]
+ return uniq([...impact.changedNodeIds, ...impact.previousParentIds, ...impact.currentParentIds])
}
diff --git a/packages/vue/package.json b/packages/vue/package.json
index 8505f9fb4..aa86dc6a6 100644
--- a/packages/vue/package.json
+++ b/packages/vue/package.json
@@ -48,6 +48,7 @@
"@open-pencil/scene-graph": "workspace:*",
"@tanstack/vue-table": "^8.21.3",
"@vueuse/core": "^14.4.0",
+ "es-toolkit": "^1.52.0",
"fuse.js": "^7.5.0",
"nanostores": "^1.5.4",
"reka-ui": "^2.10.5"
diff --git a/packages/vue/src/controls/stroke/helpers.ts b/packages/vue/src/controls/stroke/helpers.ts
index 07aa08b07..f42871c73 100644
--- a/packages/vue/src/controls/stroke/helpers.ts
+++ b/packages/vue/src/controls/stroke/helpers.ts
@@ -1,3 +1,4 @@
+import { compact } from 'es-toolkit/array'
import { computed, type ComputedRef, type Ref } from 'vue'
import { BLACK } from '@open-pencil/core/constants'
@@ -153,7 +154,7 @@ export function currentSides(activeNode: SceneNode | null): StrokeSides {
borderLeftWeight: l
} = activeNode
const active = [t > 0, r > 0, b > 0, l > 0]
- const count = active.filter(Boolean).length
+ const count = compact(active).length
if (count === 4 && t === r && r === b && b === l) return 'ALL'
if (count === 1) {
if (t > 0) return 'TOP'
diff --git a/packages/vue/src/editor/commands/shortcut.ts b/packages/vue/src/editor/commands/shortcut.ts
index 244bc7413..9bd66befa 100644
--- a/packages/vue/src/editor/commands/shortcut.ts
+++ b/packages/vue/src/editor/commands/shortcut.ts
@@ -1,3 +1,4 @@
+import { compact } from 'es-toolkit/array'
export type ShortcutPlatform = 'mac' | 'windows' | 'linux'
const MODIFIER_DISPLAY: Record<ShortcutPlatform, Record<string, string>> = {
@@ -44,7 +45,7 @@ export function formatShortcut(
return shortcut
.split(' ')
.map((combo) => {
- const parts = combo.split('+').filter(Boolean)
+ const parts = compact(combo.split('+'))
const modifiers = parts.filter((part) => part in MODIFIER_DISPLAY[platform])
const keys = parts.filter((part) => !(part in MODIFIER_DISPLAY[platform]))
const formattedModifiers = sortModifiers(modifiers, platform).map(
diff --git a/src/app/ai/models/catalog/index.ts b/src/app/ai/models/catalog/index.ts
index c94f4bd28..c15c6300e 100644
--- a/src/app/ai/models/catalog/index.ts
+++ b/src/app/ai/models/catalog/index.ts
@@ -1,3 +1,4 @@
+import { uniq } from 'es-toolkit/array'
import * as v from 'valibot'
import { AI_PROVIDERS } from '@open-pencil/core/constants'
@@ -124,14 +125,12 @@ function modelIDCandidates(providerKey: string, modelID: string): string[] {
const unprefixed = modelID.startsWith(`${providerKey}/`)
? modelID.slice(providerKey.length + 1)
: modelID
- return [
- ...new Set([
- modelID,
- unprefixed,
- unprefixed.replace(/-\d{8}$/, ''),
- unprefixed.replace(/:[a-z0-9-]+$/, '')
- ])
- ]
+ return uniq([
+ modelID,
+ unprefixed,
+ unprefixed.replace(/-\d{8}$/, ''),
+ unprefixed.replace(/:[a-z0-9-]+$/, '')
+ ])
}
function curatedProviderModels(providerID: AIProviderID): ModelOption[] {
diff --git a/src/app/ai/tools/changes/capture.ts b/src/app/ai/tools/changes/capture.ts
index fe1fe3a71..ff0d94326 100644
--- a/src/app/ai/tools/changes/capture.ts
+++ b/src/app/ai/tools/changes/capture.ts
@@ -1,4 +1,5 @@
import { diffLines, type ChangeObject } from 'diff'
+import { compact } from 'es-toolkit/array'
import { graphFromPageSnapshot, type PageSnapshot } from '@open-pencil/core/editor'
import { diffPageLayersJSX } from '@open-pencil/core/tools'
@@ -16,7 +17,7 @@ const MAX_JSX_LENGTH = 40_000
const CLIP_CONTEXT = 2_000
function joinJSX(sources: string[]): string {
- return sources.filter(Boolean).join('\n\n')
+ return compact(sources).join('\n\n')
}
function lineStart(text: string, index: number): number {
diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.ts
index 971203d96..f6708ca68 100644
--- a/src/app/automation/mcp/spawn.ts
+++ b/src/app/automation/mcp/spawn.ts
@@ -1,4 +1,5 @@
import { promiseTimeout } from '@vueuse/core'
+import { compact } from 'es-toolkit/array'
import * as v from 'valibot'
import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'
@@ -512,9 +513,11 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSer
`MCP server exited before startup completed (code ${earlyExit.code ?? 'null'}, signal ${earlyExit.signal ?? 'null'})${details ? `: ${details}` : '.'}`,
mcpFailure(
'exited',
- [`code=${earlyExit.code ?? 'null'}`, `signal=${earlyExit.signal ?? 'null'}`, details]
- .filter(Boolean)
- .join(' ')
+ compact([
+ `code=${earlyExit.code ?? 'null'}`,
+ `signal=${earlyExit.signal ?? 'null'}`,
+ details
+ ]).join(' ')
)
)
)
diff --git a/src/app/diagnostics/settings/recent.ts b/src/app/diagnostics/settings/recent.ts
index f2e3014c1..6eec5eb97 100644
--- a/src/app/diagnostics/settings/recent.ts
+++ b/src/app/diagnostics/settings/recent.ts
@@ -1,4 +1,5 @@
import { tryOnScopeDispose } from '@vueuse/core'
+import { uniq } from 'es-toolkit/array'
import { computed, ref, shallowRef, watch } from 'vue'
import {
@@ -36,7 +37,7 @@ export function useRecentDiagnostics(
if (!disposed && request === version) events.value = listed
}
- const categories = computed(() => [...new Set(events.value.map((event) => event.category))])
+ const categories = computed(() => uniq(events.value.map((event) => event.category)))
const matching = computed(() =>
events.value.filter(
(event) =>
diff --git a/src/app/editor/pages/palette.ts b/src/app/editor/pages/palette.ts
index f345aae43..cc1fc28fa 100644
--- a/src/app/editor/pages/palette.ts
+++ b/src/app/editor/pages/palette.ts
@@ -29,7 +29,7 @@ function pageItem(
return {
id: `page:${page.id}`,
label: page.name,
- description: [note, people].filter(Boolean).join(' · ') || undefined,
+ description: compact([note, people]).join(' · ') || undefined,
icon: IconFile,
onSelect: () => void store.switchPage(page.id),
...extra
diff --git a/src/app/integrations/storage/s3/cors.ts b/src/app/integrations/storage/s3/cors.ts
index 492e849e7..38f21f982 100644
--- a/src/app/integrations/storage/s3/cors.ts
+++ b/src/app/integrations/storage/s3/cors.ts
@@ -1,3 +1,5 @@
+import { compact } from 'es-toolkit/array'
+
import { IS_BROWSER, WEB_APP_ORIGIN } from '@/constants'
/** Origins OpenPencil may run from when calling S3 from the browser. */
@@ -22,7 +24,7 @@ export function collectCloudCORSOrigins(extra?: string | null): string[] {
if (IS_BROWSER && window.location.origin) {
set.add(window.location.origin)
}
- return [...set].filter(Boolean).sort()
+ return compact([...set]).sort()
}
function escapeXML(value: string): string {
diff --git a/src/app/integrations/storage/settings/use.ts b/src/app/integrations/storage/settings/use.ts
index c34fbadb4..63fe061c9 100644
--- a/src/app/integrations/storage/settings/use.ts
+++ b/src/app/integrations/storage/settings/use.ts
@@ -1,5 +1,5 @@
import { tryOnMounted, tryOnScopeDispose } from '@vueuse/core'
-import { isEqual } from 'es-toolkit'
+import { isEqual, uniq } from 'es-toolkit'
import { computed, ref, watch, type Ref } from 'vue'
import {
@@ -107,7 +107,7 @@ export function useStorageSettings(
function clearCredential(field: string) {
if (busy.value || !provider.value.credentialFields.some((item) => item.id === field)) return
credentialDrafts.value = { ...credentialDrafts.value, [field]: '' }
- cleared.value = [...new Set([...cleared.value, field])]
+ cleared.value = uniq([...cleared.value, field])
}
async function save(): Promise<SettingsSaveResult> {
diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.ts
index 78986c6a2..de16a151a 100644
--- a/src/app/shell/menu/files.ts
+++ b/src/app/shell/menu/files.ts
@@ -1,4 +1,5 @@
import { useFileDialog } from '@vueuse/core'
+import { uniq } from 'es-toolkit/array'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
@@ -18,12 +19,10 @@ import { IS_BROWSER } from '@/constants'
const io = new IORegistry(BUILTIN_IO_FORMATS)
const DOM_DOCUMENT_EXTENSIONS = ['html', 'htm', 'xhtml'] as const
-const READABLE_DOCUMENT_EXTENSIONS = [
- ...new Set([
- ...io.listReadableFormats().flatMap((format) => format.extensions),
- ...DOM_DOCUMENT_EXTENSIONS
- ])
-]
+const READABLE_DOCUMENT_EXTENSIONS = uniq([
+ ...io.listReadableFormats().flatMap((format) => format.extensions),
+ ...DOM_DOCUMENT_EXTENSIONS
+])
const DESIGN_FILE_ACCEPT = READABLE_DOCUMENT_EXTENSIONS.map((extension) => `.${extension}`).join(
','
)
diff --git a/src/components/chat/ChatProfileSelect.vue b/src/components/chat/ChatProfileSelect.vue
index 7eedc67a3..5166c5863 100644
--- a/src/components/chat/ChatProfileSelect.vue
+++ b/src/components/chat/ChatProfileSelect.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { compact } from 'es-toolkit/array'
import {
SelectContent,
SelectGroup,
@@ -51,7 +52,7 @@ function profileMetadata(profile: AIModelProfile): string {
const provider = AI_PROVIDERS.find((candidate) => candidate.id === connection?.providerID)
const modelID = profile.customModelID || profile.modelID
const modelName = provider?.models.find((model) => model.id === modelID)?.name || modelID
- return [modelName, provider?.name ?? connection?.providerID].filter(Boolean).join(' · ')
+ return compact([modelName, provider?.name ?? connection?.providerID]).join(' · ')
}
function manageModels(): void {
diff --git a/src/components/design-check/IssueMarkerTooltip.vue b/src/components/design-check/IssueMarkerTooltip.vue
index 6c8567ea7..5775feba8 100644
--- a/src/components/design-check/IssueMarkerTooltip.vue
+++ b/src/components/design-check/IssueMarkerTooltip.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { compact } from 'es-toolkit/array'
import {
TooltipContent,
TooltipPortal,
@@ -72,7 +73,7 @@ const items = computed(() =>
id: issue.id,
severity: issue.severity,
title: ruleTitle(issue.ruleId, messages.value),
- detail: [layer, detail].filter(Boolean).join(' · ')
+ detail: compact([layer, detail]).join(' · ')
}
})
)
diff --git a/src/components/design-check/PageIssueBadge.vue b/src/components/design-check/PageIssueBadge.vue
index ea2ed8fde..239954045 100644
--- a/src/components/design-check/PageIssueBadge.vue
+++ b/src/components/design-check/PageIssueBadge.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { compact } from 'es-toolkit/array'
import { computed } from 'vue'
import { useDesignCheckMessages } from '@open-pencil/vue'
@@ -20,12 +21,10 @@ const total = computed(() => errors.value + warnings.value)
const severity = computed(() => (errors.value > 0 ? 'error' : 'warning'))
const styles = computed(() => pageIssueBadge({ severity: severity.value }))
const label = computed(() =>
- [
+ compact([
errors.value > 0 ? `${messages.value.errors}: ${errors.value}` : null,
warnings.value > 0 ? `${messages.value.warnings}: ${warnings.value}` : null
- ]
- .filter(Boolean)
- .join(', ')
+ ]).join(', ')
)
</script>
diff --git a/src/components/settings/mcp/MCPFailureAlert.vue b/src/components/settings/mcp/MCPFailureAlert.vue
index b4a8f0040..4f20c0365 100644
--- a/src/components/settings/mcp/MCPFailureAlert.vue
+++ b/src/components/settings/mcp/MCPFailureAlert.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
+import { compact } from 'es-toolkit/array'
import { computed, ref } from 'vue'
import { useAutomationMessages } from '@open-pencil/vue'
@@ -73,9 +74,10 @@ const detail = computed(() =>
)
async function copyDetails(): Promise<void> {
- const payload = [`code=${failure.code}`, failure.detail ? `detail=${failure.detail}` : null]
- .filter(Boolean)
- .join('\n')
+ const payload = compact([
+ `code=${failure.code}`,
+ failure.detail ? `detail=${failure.detail}` : null
+ ]).join('\n')
// VueUse falls back to a legacy write and never rejects, so awaiting the write
// is what keeps the confirmation honest.
await copy(payload)
diff --git a/src/components/settings/provider/ProviderSettingsField.vue b/src/components/settings/provider/ProviderSettingsField.vue
index 2fdfff750..0fb9c6433 100644
--- a/src/components/settings/provider/ProviderSettingsField.vue
+++ b/src/components/settings/provider/ProviderSettingsField.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { compact } from 'es-toolkit/array'
import { computed, useId } from 'vue'
import AppButton from '@/components/ui/button/AppButton.vue'
@@ -20,9 +21,8 @@ const control = computed(() => ({
id: inputID.value,
'aria-invalid': Boolean(error),
'aria-describedby':
- [error && `${inputID.value}-error`, hint && `${inputID.value}-hint`]
- .filter(Boolean)
- .join(' ') || undefined,
+ compact([error && `${inputID.value}-error`, hint && `${inputID.value}-hint`]).join(' ') ||
+ undefined,
state: error ? ('invalid' as const) : ('idle' as const)
}))
diff --git a/src/components/ui/binding/BindingPill.vue b/src/components/ui/binding/BindingPill.vue
index 968b966fa..5ae3e83cb 100644
--- a/src/components/ui/binding/BindingPill.vue
+++ b/src/components/ui/binding/BindingPill.vue
@@ -1,4 +1,5 @@
<script lang="ts">
+import { compact } from 'es-toolkit/array'
import type { HTMLAttributes } from 'vue'
import type { BindingFieldUI } from './ui'
@@ -33,7 +34,7 @@ const {
const styles = computed(() =>
useBindingFieldUI(
{ state: unresolved ? 'unresolved' : 'bound', disabled, derived },
- { ...ui, pill: [ui?.pill, normalizeClass(className)].filter(Boolean).join(' ') }
+ { ...ui, pill: compact([ui?.pill, normalizeClass(className)]).join(' ') }
)
)
diff --git a/src/components/ui/binding/BindingTrigger.vue b/src/components/ui/binding/BindingTrigger.vue
index c03cbfafe..9c052d715 100644
--- a/src/components/ui/binding/BindingTrigger.vue
+++ b/src/components/ui/binding/BindingTrigger.vue
@@ -1,4 +1,5 @@
<script lang="ts">
+import { compact } from 'es-toolkit/array'
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
@@ -38,7 +39,7 @@ const {
const styles = computed(() =>
useBindingFieldUI(
{ state, open, disabled, derived },
- { ...ui, trigger: [ui?.trigger, normalizeClass(className)].filter(Boolean).join(' ') }
+ { ...ui, trigger: compact([ui?.trigger, normalizeClass(className)]).join(' ') }
)
)
diff --git a/src/components/ui/button/AppButton.vue b/src/components/ui/button/AppButton.vue
index f444857e8..76e4650da 100644
--- a/src/components/ui/button/AppButton.vue
+++ b/src/components/ui/button/AppButton.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { compact } from 'es-toolkit/array'
import { computed, normalizeClass, useAttrs, type HTMLAttributes } from 'vue'
import {
@@ -40,7 +41,7 @@ const styles = computed(() =>
variant,
size,
shape,
- ui: { ...ui, base: [ui?.base, normalizeClass(className)].filter(Boolean).join(' ') }
+ ui: { ...ui, base: compact([ui?.base, normalizeClass(className)]).join(' ') }
})
)
const isDisabled = computed(() => disabled || loading)
diff --git a/tests/e2e/layers/panel.spec.ts b/tests/e2e/layers/panel.spec.ts
index d7e1ccf68..011dc4b3c 100644
--- a/tests/e2e/layers/panel.spec.ts
+++ b/tests/e2e/layers/panel.spec.ts
@@ -34,7 +34,9 @@ async function getSceneTree(): Promise<SceneTreeNode> {
return {
name: node.name,
type: node.type,
- children: node.childIds.map((cid: string) => nodeTree(cid)).filter(Boolean)
+ children: node.childIds
+ .map((cid: string) => nodeTree(cid))
+ .filter((child): child is SceneTreeNode => child !== null)
}
}
const tree = nodeTree(store.state.currentPageId)
diff --git a/tests/engine/vue/controls/stroke.test.ts b/tests/engine/vue/controls/stroke.test.ts
index bf2a5d03a..a84225606 100644
--- a/tests/engine/vue/controls/stroke.test.ts
+++ b/tests/engine/vue/controls/stroke.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test'
+import { compact } from 'es-toolkit/array'
import { computed, ref } from 'vue'
import { createEditor } from '@open-pencil/core/editor'
@@ -58,9 +59,7 @@ describe('stroke geometry controls', () => {
const first = graph.createNode('RECTANGLE', pageId, { strokes: [{ ...DEFAULT_STROKE }] })
const second = graph.createNode('RECTANGLE', pageId, { strokes: [{ ...DEFAULT_STROKE }] })
const editor = createEditor({ graph })
- const nodes = computed(() =>
- [graph.getNode(first.id), graph.getNode(second.id)].filter(Boolean)
- )
+ const nodes = computed(() => compact([graph.getNode(first.id), graph.getNode(second.id)]))
const actions = createStrokeGeometryActions(editor, nodes)
actions.setCap('ROUND')
@@ -87,9 +86,7 @@ describe('stroke geometry controls', () => {
strokeMiterLimit: 8
})
const editor = createEditor({ graph })
- const nodes = computed(() =>
- [graph.getNode(first.id), graph.getNode(second.id)].filter(Boolean)
- )
+ const nodes = computed(() => compact([graph.getNode(first.id), graph.getNode(second.id)]))
const actions = createStrokeGeometryActions(editor, nodes)
actions.updateMiterLimit(12)
@@ -129,7 +126,7 @@ describe('setCap with per-vertex overrides', () => {
}
})
const editor = createEditor({ graph })
- const nodes = computed(() => [graph.getNode(vector.id)].filter(Boolean))
+ const nodes = computed(() => compact([graph.getNode(vector.id)]))
const actions = createStrokeGeometryActions(editor, nodes)
actions.setCap('ROUND')
@@ -199,7 +196,7 @@ describe('cap state with per-vertex overrides', () => {
}
})
const editor = createEditor({ graph })
- const nodes = computed(() => [graph.getNode(vector.id)].filter(Boolean))
+ const nodes = computed(() => compact([graph.getNode(vector.id)]))
const capState = () =>
createStrokeGeometryState({ nodes, merged: (key) => merged(nodes.value)(key) }).cap.value
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index 3299e9114..026917210 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -20,6 +20,7 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce
- `.github/workflows/ci.yml` and `heavy-tests.yml` define validation gates. PR CI always classifies changed paths through `tools/ci/policy/src/policy.ts`: root docs, package READMEs, every `AGENTS.md`, `packages/docs` Markdown and assets, and skill Markdown are docs-only; runtime prompt Markdown, executable examples, configuration, and unknown paths require code validation.
- Docs-only changes run documentation integrity and the docs build; everything else runs the full suites. The aggregate `CI result` gate requires successful classification and every applicable job; failures, cancellations, and unexpected skips cannot pass. Do not restore workflow-level path filtering on required CI.
- `commitlint.config.ts` enforces commit structure in the **Commit messages** job; the separate **PR title** workflow validates titles. Preserve the `Release vX.Y.Z` exception and product casing when changing rules; the known AI co-author check does not rewrite base history. Gate policy lives in `tools/ci/policy/src/policy.ts`.
+- `tools/ci/policy` runs right after Bun is set up, before any install, so it imports only Node built-ins; `oxlint.json` switches `open-pencil/prefer-es-toolkit` off there. Other CI tools install their workspace first, as `pr-review-guidance.yml` does through `.github/actions/setup-bun`.
- Required checks must also run on `merge_group`, the merge queue's event; read base and head from `merge_group.base_sha`/`head_sha` there (`ci.yml`, `pr-title.yml`).
- App and docs production workflows run on `v*` tags or `workflow_dispatch`, not ordinary `master` pushes. `build.yml` checks the tooling out under `.pipeline/` and runs `tools/release/release-packages` from there.
diff --git a/tools/checks/i18n/package.json b/tools/checks/i18n/package.json
index 9185588f3..c07a25631 100644
--- a/tools/checks/i18n/package.json
+++ b/tools/checks/i18n/package.json
@@ -4,5 +4,8 @@
"type": "module",
"scripts": {
"test": "bun test tests"
+ },
+ "dependencies": {
+ "es-toolkit": "^1.52.0"
}
}
diff --git a/tools/checks/i18n/src/check-locales.ts b/tools/checks/i18n/src/check-locales.ts
index e2e904341..4c4f5b335 100644
--- a/tools/checks/i18n/src/check-locales.ts
+++ b/tools/checks/i18n/src/check-locales.ts
@@ -2,6 +2,7 @@
import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
+import { compact } from 'es-toolkit/array'
import * as v from 'valibot'
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
@@ -73,16 +74,18 @@ const expectedLocaleDirs = new Map<TranslatedLocale, string>(
const baselineLocaleId = (locale: TranslatedLocale): string => LOCALE_DIR_NAMES[locale]
const expectedLocaleFiles = new Set(namespaces.map(localeFileName))
const translationBaseline = new Set(
- readFileSync(TRANSLATION_BASELINE_PATH, 'utf8')
- .split('\n')
- .map((line) => line.trim())
- .filter(Boolean)
+ compact(
+ readFileSync(TRANSLATION_BASELINE_PATH, 'utf8')
+ .split('\n')
+ .map((line) => line.trim())
+ )
)
const mixedScriptBaseline = new Set(
- readFileSync(MIXED_SCRIPT_BASELINE_PATH, 'utf8')
- .split('\n')
- .map((line) => line.trim())
- .filter(Boolean)
+ compact(
+ readFileSync(MIXED_SCRIPT_BASELINE_PATH, 'utf8')
+ .split('\n')
+ .map((line) => line.trim())
+ )
)
const observedIdentical = new Set<string>()
const observedMixedScript = new Set<string>()
diff --git a/tools/checks/lint/package.json b/tools/checks/lint/package.json
index c40197970..ebfd6acf8 100644
--- a/tools/checks/lint/package.json
+++ b/tools/checks/lint/package.json
@@ -8,6 +8,9 @@
"scripts": {
"test": "bun test tests"
},
+ "dependencies": {
+ "es-toolkit": "^1.52.0"
+ },
"devDependencies": {
"@open-pencil/package-artifacts-tools": "workspace:*"
}
diff --git a/tools/checks/lint/src/plugin.ts b/tools/checks/lint/src/plugin.ts
index e5c791b8d..4db9cd867 100644
--- a/tools/checks/lint/src/plugin.ts
+++ b/tools/checks/lint/src/plugin.ts
@@ -4,6 +4,7 @@ import {
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'
@@ -494,6 +495,7 @@ const plugin = {
'no-conditional-object-spreads': noConditionalObjectSpreads,
'no-hand-rolled-base64': noHandRolledBase64Rule,
'no-unvalidated-json-parse': noUnvalidatedJSONParseRule,
+ 'prefer-es-toolkit': preferEsToolkitRule,
'no-module-mocking': noModuleMockingRule,
'no-reduce-accumulator-copy': noReduceAccumulatorCopyRule,
'no-widen-then-assert': noWidenThenAssertRule,
diff --git a/tools/checks/lint/src/rules/quality/es-toolkit.ts b/tools/checks/lint/src/rules/quality/es-toolkit.ts
new file mode 100644
index 000000000..a950998a5
--- /dev/null
+++ b/tools/checks/lint/src/rules/quality/es-toolkit.ts
@@ -0,0 +1,134 @@
+import { resolveVariable } from '#lint/support/scope.ts'
+import { defineRule } from '@oxlint/plugins'
+import type { ESTree, SourceCode } from '@oxlint/plugins'
+
+/** Methods that always return a new array, so deduplicating their result needs no type check. */
+const ARRAY_RETURNING_METHODS = new Set([
+ 'concat',
+ 'filter',
+ 'flat',
+ 'flatMap',
+ 'map',
+ 'slice',
+ 'split',
+ 'toReversed',
+ 'toSorted',
+ 'toSpliced'
+])
+
+/** Methods that return an iterator, whose `filter` is not an array's and takes no `compact`. */
+const ITERATOR_RETURNING_METHODS = new Set(['entries', 'keys', 'matchAll', 'values'])
+
+/** Calls that serialize their callback into a browser page, away from the module's imports. */
+const SERIALIZED_CALLBACK_METHODS = new Set([
+ '$$eval',
+ '$eval',
+ 'addInitScript',
+ 'evaluate',
+ 'evaluateHandle',
+ '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
+ const variable = resolveVariable(sourceCode, node)
+ return variable === null || variable.defs.length === 0
+}
+
+/** An expression that is an array without type information: a literal or an array method's result. */
+function isArrayExpression(node: ESTree.Node | undefined): boolean {
+ if (!node) return false
+ return node.type === 'ArrayExpression' || isMethodCall(node, ARRAY_RETURNING_METHODS)
+}
+
+/** `new Set(array)` over an array, the first half of a deduplicating round trip. */
+function isSetOfArray(sourceCode: SourceCode, node: ESTree.Node | undefined): boolean {
+ return (
+ node?.type === 'NewExpression' &&
+ node.arguments.length === 1 &&
+ isGlobal(sourceCode, node.callee, 'Set') &&
+ isArrayExpression(node.arguments[0])
+ )
+}
+
+function isMethodCall(node: ESTree.Node, methods: ReadonlySet<string>): boolean {
+ if (node.type !== 'CallExpression' || node.callee.type !== 'MemberExpression') return false
+ const name = propertyName(node.callee)
+ return name !== null && methods.has(name)
+}
+
+/**
+ * Code inside a callback that Playwright serializes into the page, such as `page.evaluate`,
+ * where an es-toolkit import does not exist.
+ */
+function insideSerializedCallback(node: ESTree.Node): boolean {
+ for (let current: ESTree.Node | null = node; current; current = current.parent) {
+ const { parent } = current
+ const isCallback =
+ (current.type === 'ArrowFunctionExpression' || current.type === 'FunctionExpression') &&
+ parent?.type === 'CallExpression' &&
+ parent.arguments.includes(current)
+ if (isCallback && isMethodCall(parent, SERIALIZED_CALLBACK_METHODS)) return true
+ }
+ return false
+}
+
+/** Require es-toolkit's `uniq` and `compact` over their hand-written equivalents. */
+export const preferEsToolkitRule = defineRule({
+ meta: {
+ type: 'suggestion',
+ docs: {
+ description:
+ 'Prefer es-toolkit uniq and compact over Set round trips and filter(Boolean) on arrays.'
+ },
+ messages: {
+ uniq: 'Use uniq from es-toolkit instead of a Set round trip to deduplicate an array.',
+ compact: 'Use compact from es-toolkit instead of filter(Boolean); it also narrows the type.'
+ }
+ },
+ createOnce(context) {
+ return {
+ ArrayExpression(node) {
+ const [only] = node.elements
+ if (
+ node.elements.length === 1 &&
+ only?.type === 'SpreadElement' &&
+ isSetOfArray(context.sourceCode, only.argument) &&
+ !insideSerializedCallback(node)
+ )
+ context.report({ node, messageId: 'uniq' })
+ },
+ CallExpression(node) {
+ const { sourceCode } = context
+ if (node.callee.type !== 'MemberExpression' || insideSerializedCallback(node)) return
+ const name = propertyName(node.callee)
+ const [argument] = node.arguments
+ if (
+ name === 'from' &&
+ isGlobal(sourceCode, node.callee.object, 'Array') &&
+ node.arguments.length === 1 &&
+ isSetOfArray(sourceCode, argument)
+ ) {
+ context.report({ node, messageId: 'uniq' })
+ return
+ }
+ if (
+ name === 'filter' &&
+ node.arguments.length === 1 &&
+ argument &&
+ isGlobal(sourceCode, argument, 'Boolean') &&
+ !isMethodCall(node.callee.object, ITERATOR_RETURNING_METHODS)
+ )
+ context.report({ node, messageId: 'compact' })
+ }
+ }
+ }
+})
diff --git a/tools/checks/lint/src/rules/typescript.ts b/tools/checks/lint/src/rules/typescript.ts
index 27d208207..ee09c9b81 100644
--- a/tools/checks/lint/src/rules/typescript.ts
+++ b/tools/checks/lint/src/rules/typescript.ts
@@ -1,5 +1,6 @@
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
@@ -162,7 +163,9 @@ function canonicalMember(member: TSESTree.TypeElement): string | null {
}
function canonicalMembers(members: readonly TSESTree.TypeElement[] | undefined): string {
- return (members ?? []).map(canonicalMember).filter(Boolean).sort().join(';')
+ return compact((members ?? []).map(canonicalMember))
+ .sort()
+ .join(';')
}
function namedTypeShape(
@@ -187,7 +190,7 @@ const noDuplicateTypeShapes = {
'TSInterfaceDeclaration, TSTypeAliasDeclaration'(node) {
const shape = namedTypeShape(node)
if (!shape) return
- const memberCount = shape ? shape.split(';').filter(Boolean).length : 0
+ const memberCount = shape ? compact(shape.split(';')).length : 0
if (memberCount < 2) return
const first = seen.get(shape)
if (!first) {
diff --git a/tools/checks/lint/tests/es-toolkit.test.ts b/tools/checks/lint/tests/es-toolkit.test.ts
new file mode 100644
index 000000000..77b2b095c
--- /dev/null
+++ b/tools/checks/lint/tests/es-toolkit.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, test } from 'bun:test'
+
+import { lint, ruleDiagnostics } from './helpers/lint.ts'
+
+const rule = 'prefer-es-toolkit'
+const rules = { [`open-pencil/${rule}`]: 'error' }
+
+describe('prefer-es-toolkit', () => {
+ test.each([
+ '[...new Set(items.map((item) => item.id))]',
+ '[...new Set([...items, extra])]',
+ "Array.from(new Set(text.split(',')))",
+ 'items.filter(Boolean)'
+ ])('rejects %s', async (source) => {
+ expect(ruleDiagnostics(await lint(source, rules), rule)).toHaveLength(1)
+ })
+
+ test.each([
+ // A variable may hold a string or a Map's keys, which uniq does not take.
+ '[...new Set(items)]',
+ 'Array.from(new Set(items), (item) => item * 2)',
+ 'items.filter((item) => item > 0)',
+ // compact takes arrays, not iterators.
+ 'map.values().filter(Boolean)',
+ // Playwright runs these callbacks in the page, where imports do not exist.
+ 'page.evaluate(() => items.filter(Boolean))',
+ "page.$$eval('p', () => [...new Set(items.map((item) => item.id))])",
+ // A local Boolean or Set is not the global one.
+ 'const Boolean = (value) => value > 1; items.filter(Boolean)',
+ 'function dedupe(Set) { return [...new Set(items.map((item) => item.id))] }'
+ ])('accepts %s', async (source) => {
+ expect(ruleDiagnostics(await lint(source, rules), rule)).toHaveLength(0)
+ })
+})
diff --git a/tools/checks/package-quality/src/checks/run.ts b/tools/checks/package-quality/src/checks/run.ts
index d0dd03833..fd3120ba8 100644
--- a/tools/checks/package-quality/src/checks/run.ts
+++ b/tools/checks/package-quality/src/checks/run.ts
@@ -1,4 +1,4 @@
-import { mapAsync } from 'es-toolkit'
+import { compact, mapAsync } from 'es-toolkit'
import { CommandError, runCommand, type CommandRequest } from '@open-pencil/package-artifacts-tools'
@@ -16,7 +16,7 @@ export async function runPackageChecks(
return undefined
} catch (error) {
if (error instanceof CommandError) {
- return new Error([error.message, error.stdout, error.stderr].filter(Boolean).join('\n'))
+ return new Error(compact([error.message, error.stdout, error.stderr]).join('\n'))
}
return error instanceof Error ? error : new Error(String(error))
}
diff --git a/tools/checks/type-shapes/package.json b/tools/checks/type-shapes/package.json
index 9e1ad7718..3114f49dc 100644
--- a/tools/checks/type-shapes/package.json
+++ b/tools/checks/type-shapes/package.json
@@ -4,5 +4,8 @@
"type": "module",
"scripts": {
"test": "bun test tests"
+ },
+ "dependencies": {
+ "es-toolkit": "^1.52.0"
}
}
diff --git a/tools/checks/type-shapes/src/index.ts b/tools/checks/type-shapes/src/index.ts
index e11cc4d45..9413aaf63 100644
--- a/tools/checks/type-shapes/src/index.ts
+++ b/tools/checks/type-shapes/src/index.ts
@@ -1,3 +1,4 @@
+import { compact } from 'es-toolkit/array'
import ts from 'typescript'
import { discoverTypeShapeFiles } from './files'
@@ -77,7 +78,7 @@ for (const file of files) {
function visit(node: ts.Node) {
const collected = collectShape(node)
if (collected) {
- const memberCount = collected.shape.split(';').filter(Boolean).length
+ const memberCount = compact(collected.shape.split(';')).length
if (memberCount >= 2) {
const position = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))
const locations = shapes.get(collected.shape) ?? []
diff --git a/tools/dev/unit-tests/package.json b/tools/dev/unit-tests/package.json
index 56d9fbd07..5573e6686 100644
--- a/tools/dev/unit-tests/package.json
+++ b/tools/dev/unit-tests/package.json
@@ -9,6 +9,7 @@
"test": "bun test tests"
},
"dependencies": {
- "@open-pencil/package-artifacts-tools": "workspace:*"
+ "@open-pencil/package-artifacts-tools": "workspace:*",
+ "es-toolkit": "^1.52.0"
}
}
diff --git a/tools/dev/unit-tests/src/shards.ts b/tools/dev/unit-tests/src/shards.ts
index 1ee7e8d63..a9dae9b41 100644
--- a/tools/dev/unit-tests/src/shards.ts
+++ b/tools/dev/unit-tests/src/shards.ts
@@ -2,6 +2,8 @@ import { existsSync } from 'node:fs'
import { readdir } from 'node:fs/promises'
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
+import { uniq } from 'es-toolkit/array'
+
import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'
const REPO_ROOT = await resolveWorkspaceRoot(import.meta.dir)
@@ -116,7 +118,7 @@ export async function listHeavyUnitTests(group: UnitTestGroup = 'all'): Promise<
async function listTestFiles(paths: string[]): Promise<string[]> {
const files = await Promise.all(paths.map((path) => listTestFilesInPath(path)))
- return [...new Set(files.flat())].sort()
+ return uniq(files.flat()).sort()
}
async function listTestFilesInPath(path: string): Promise<string[]> {
diff --git a/tools/generate/tauri-menu/package.json b/tools/generate/tauri-menu/package.json
index f3799f4bf..ab7595992 100644
--- a/tools/generate/tauri-menu/package.json
+++ b/tools/generate/tauri-menu/package.json
@@ -5,6 +5,9 @@
"scripts": {
"test": "bun test tests"
},
+ "dependencies": {
+ "es-toolkit": "^1.52.0"
+ },
"devDependencies": {
"@open-pencil/package-artifacts-tools": "workspace:*",
"@open-pencil/vue": "workspace:*"
diff --git a/tools/generate/tauri-menu/src/menu.ts b/tools/generate/tauri-menu/src/menu.ts
index 8db53855d..760da433f 100644
--- a/tools/generate/tauri-menu/src/menu.ts
+++ b/tools/generate/tauri-menu/src/menu.ts
@@ -1,3 +1,5 @@
+import { compact } from 'es-toolkit/array'
+
import { editorCommandMetadata } from '@open-pencil/vue'
import { APP_MENU_APP_ITEMS, APP_MENU_SCHEMA } from '@/app/shell/menu/schema'
@@ -25,7 +27,7 @@ function cleanEntry(entry: AppMenuEntry): unknown | null {
label: entry.label,
accelerator: entryAccelerator(entry),
checkbox: entry.checkbox,
- sub: entry.sub?.map(cleanEntry).filter(Boolean)
+ sub: entry.sub ? compact(entry.sub.map(cleanEntry)) : undefined
}
}
@@ -33,12 +35,12 @@ function cleanGroup(group: AppMenuGroupSchema): unknown | null {
if (!isNativeVisible(group)) return null
return {
label: group.label,
- items: group.items.map(cleanEntry).filter(Boolean)
+ items: compact(group.items.map(cleanEntry))
}
}
export function renderMenu(): string {
- const menu = APP_MENU_SCHEMA.map(cleanGroup).filter(Boolean)
+ const menu = compact(APP_MENU_SCHEMA.map(cleanGroup))
return `${JSON.stringify(menu, null, 2)}\n`
}