Skip to content

Latest commit

 

History

History
292 lines (215 loc) · 70.2 KB

CLAUDE.md

File metadata and controls

292 lines (215 loc) · 70.2 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. Kept in sync with AGENTS.md — edit both together.

Project Overview

VEF Framework is a React 19 application framework published to npm under @vef-framework-react/* (with external consumers). It is a pnpm-workspace monorepo built on TypeScript and Vite. Backwards-incompatible changes affect downstream apps, so prefer additive changes and surface breaking ones explicitly.

Commands

Development

  • pnpm playground — Start the playground dev server
  • pnpm test — Run all tests
  • pnpm test:watch — Tests in watch mode
  • pnpm test:coverage — Coverage report (informational only; not a CI gate)
  • vitest run path/to/file.test.ts — Run a single test file

Quality (CI gates)

  • pnpm typecheck — Typecheck all packages
  • pnpm typecheck:<pkg> — Typecheck one package (core / components / hooks / shared / dev / starter / form-editor / approval / approval-flow-editor / calendar)
  • pnpm lint — ESLint --fix across the repo
  • eslint --fix <file> — Lint a single file

Build

  • pnpm build — Build all packages
  • pnpm build:<pkg> — Build one package (core / components / hooks / shared / dev / starter / calendar; plus build:playground)
  • pnpm clean — Clean all package build outputs
  • pnpm clean:modules — Drop all node_modules and pnpm-lock.yaml

Dependencies & Metadata

  • pnpm deps:check — Check inter-package dependency consistency
  • pnpm deps:check:apply — Apply recommended fixes
  • pnpm sync-meta — Sync package metadata across the monorepo

Release

Publishing is CI-triggered by pushing a v* tag (.github/workflows/release.yml) — not by a local pnpm pub. Flow:

  1. pnpm version:patch|minor|major — bump root + every package (--no-git-tag-version, so no commit/tag).
  2. Commit the bump as chore(release): vX.Y.Z.
  3. git tag -a vX.Y.Z -m vX.Y.Z — the tag must equal the root package.json version (CI hard-fails otherwise).
  4. git push --follow-tags — the v* tag fires release.yml: install --frozen-lockfile → tag/version check → typecheck → lint → test → build → pnpm publish → GitHub Release (notes via git-cliff from Conventional Commits).
  • Land feature commits before the chore(release) commit so git-cliff picks them up.
  • Don't publish with pnpm pub / pnpm release:* for a real release — they publish from your machine (local npm auth, skipping CI gates) and double-publish if combined with the tag flow; a published version can't be re-published.
  • A failed CI gate blocks the publish but the tag remains — delete the tag, fix, re-tag.
  • CI authenticates by npm trusted publishing (the job's OIDC token; no npm token secret exists). Each package's npm settings name coldsmirk/vef-framework-react / release.yml as its trusted publisher, and npm attaches provenance, which rejects a package.json without repository (keep url and directory). A new package needs its trusted publisher configured on npmjs.com before CI can publish it; npm offers that setting only once the package exists, so a new package's first version is published by hand.
  • If one package's publish fails mid-run (for example a transient Sigstore TLOG_CREATE_ENTRY_ERROR (409)), re-run the failed job: pnpm publish -r skips versions already on the registry.

Scripts: pnpm version:patch|minor|major (bump only) · pnpm release:patch|minor|major (local bump + build + publish, the non-CI path) · pnpm pub (local publish, no bump) · pnpm unpub (roll back, see scripts/unpublish.ts).

Architecture

Monorepo Layout

  • pnpm workspaces; inter-package deps use workspace:*
  • Source packages: packages/*. Demo app: playground/. Plugins: plugins/.
  • Build orchestration via pnpm --filter=./packages/* <cmd>
  • Source resolution: package exports include a "vef" condition pointing at src; the playground's Vite config and the Vitest config resolve through it (Vitest also via explicit src path aliases) to the unbuilt sources for HMR / fast tests without rebuilds.

Packages

Packages publish under @vef-framework-react/* as dual ESM/CJS with TypeScript declarations.

Package Purpose
core API client (TanStack Query + axios), HttpClient with BusinessError / token refresh, state utilities (Jotai / Zustand / XState), Immer, selector-based contexts, resumable chunked-upload Uploader, SSE client
components antd v6 + Emotion UI library (100+ components), TanStack Form integration, semantic color/scene system, custom motion/typography components
hooks Reusable React hook library (permission / event / code-set / upload / deep-compare / etc.)
shared Pure-function utilities (tree, chrono, color, equal, key, path, string, event, task, format)
starter Ready-to-use layouts and auth components on top of TanStack Router, plus the headless login flow (useLoginFlow) and single sign-on landing page
form-editor Visual form schema editor; linkage expressions are plain JavaScript via new Function. Published under @vef-framework-react/form-editor; treat exported APIs and schema shapes as external surface. Targets forms with 100s of fields.
approval-flow-editor Visual approval flow editor on @xyflow/react v12 (ReactFlow) + elkjs auto-layout (excluded from test scope — visual canvas)
approval-form-bridge Projection bridge from form-editor schemas to the Go approval form contract: projectFormSchema (one walk → backend FormDefinition + flow-editor formFields, conservation errors for unprojectable keyed fields), createApprovalRegistries (approval profile — no switch / button), validateApprovalSchema save gate, and its projection layer alone (validateApprovalProjection) for FormEditor's validate
calendar Work calendar year/month views and override management, reusable window-rule editing and summaries, and server-backed window previews and status indicators
approval Ready-to-use approval engine pages on the Go approval module: runtime pages (initiate / task center / my instances with the action-complete instance detail), management pages (flow list + full-screen designer wizard absorbing form-editor + approval-flow-editor, categories, delegations, admin console), ApprovalProvider host plugins (org pickers, option / lookup API catalog and FormServices, form globals), typed API layer mirroring the Go DTOs, and the progress-annotated flow-graph viewer
dev Shared ESLint / Stylelint / Commitlint configs, Vite plugins, TypeScript configs

Key Patterns

  • Business approval forms register a BusinessKindRenderer under ApprovalPlugins.businessKinds[kind]. Its StartForm and DetailView expose BusinessFormHandle.collect() on the supplied handle. Collect validates local input and returns the data for one start, resubmit, or process_task request. A missing renderer disables the action. The designer uses list_business_kinds for the field catalog, deploys business versions with JSON storage and an empty form schema, and checks conditions, personnel, field permissions and rollback options against the backend contract. Aggregate conditions use the projected or business form fields. Scalar conditions can also reference runtime globals. The wizard checks static title references at business kind selection or during ordinary form design.

  • Instance voiding uses the current flow policy and the detail's server-resolved actions. Direct voids require approval.instance.void and preview with admin.plan_void. The built-in approval.void_request renderer receives a voidTarget from the target detail, previews with my.plan_void, and submits through the ordinary start or resubmit action. A host can override this renderer in ApprovalPlugins.businessKinds. A target renderer can supply BusinessKindRenderer.VoidOptions({ value, onChange }). Changes to those options always fetch a fresh plan, including on returned requests. Renderers can call onAvailabilityChange(false, reason) to show why submission or resubmission is disabled. Read-only details show the live plan for pending requests and the recorded outcome for settled requests. Hidden fields are omitted, including the link when the target ID is hidden.

  • Host form documents may use a host format when the Go backend installs vef.ProvideApprovalFormSchemaParser. Supply a stable ApprovalPlugins.formSchemaAdapter that treats its input as immutable, returns native schemas unchanged and returns undefined for unsupported documents. useFormSchema(document) shares one result per object within the provider, including empty results. The public InstanceFormPanel, start drawer, personal and admin detail forms, and annotation field pickers and anchors use this resolution. Unsupported documents render the empty state. The query cache retains the wire document. The built-in flow designer edits native schemas directly.

  • Idempotent approval submissions accept an optional idempotencyKey on approval/instance.start and resubmit (at most 128 characters, scoped to the instance tenant). The built-in forms reuse a key when retrying the same submission and generate a fresh key for a new session or a changed payload. A replay returns the original instance in its current state for start and empty success for resubmit. Reusing a key with a different applicant, operation or submission returns 40041, shown inline. Hosts with their own forms supply the key. A business kind with its own command ID should use that ID as its idempotency key.

  • Approval annotations come from the viewer-specific detail. Use useAnnotations(detail), AnnotationList, AnnotationComposer, and AnnotationResponseComposer for inline business views. Draft saves and deletes use approval.annotation.write. A task decision publishes its drafts and an applicant resubmission publishes response drafts. A field filter can select a whole field, a row, a column, or a cell. Node audiences select approval and handle nodes.

  • Form field extras use the optional FormRenderer.renderFieldExtra({ key, type, label, row, column }) render prop. It runs for visible keyed fields after linkage and field permissions. A subform has one whole-field slot. Both layouts expose row and cell slots with zero-based row indices. Desktop tables also expose column-header slots. A column uses its template field key. Returning null keeps the original layout.

  • API Client (packages/core/src/api/client.ts) wraps HttpClient + QueryClient. createQueryFn injects an invocation-isolated AbortSignal; its factory runs once per query execution and must keep cross-request state or side effects outside the factory. createMutationFn reuses a handler for each HTTP error-feedback mode, passes mutation meta to that handler, and executeMutation() runs mutations imperatively.

  • CRUD reads take their filters in meta: every CRUD read (find_page / find_all / find_one / find_tree) decodes its search struct (crud.Sortable, an api.M) from the request's meta, beside the pagination, never from params, where the backend drops it as unmapped. Each package's API layer therefore folds the filters into meta (toCrudReadMeta in approval / cron / integration); sent as params, a find_one id would come back as an arbitrary row. Custom RPC actions are the opposite: their params structs embed api.P and read params.

  • HTTP errors split into BusinessError (API returned a non-OK business code; carries code / message / data) and network errors (axios errors for 4xx/5xx, timeouts).

  • Token refresh coordination (packages/core/src/http/client.ts): on a 401 with a configured tokenExpiredCode, HttpClient publishes one shared refresh promise. Concurrent new requests wait through request-scoped, abort-aware waiters and resume with the renewed token; canceling a waiter or the triggering 401 caller does not cancel the global refresh. After a successful refresh, a live triggering request retries with the renewed token; an automatic refresh failure calls onUnauthenticated once even if that caller was canceled. ensureTokenRefreshed(false) suppresses the callback only when it owns the refresh cycle.

  • Login flow (packages/starter/src/components/login/use-login-flow.ts): authentication is a loop, not a request — the backend answers a login with either a session or a challenge, and answering a challenge yields the same two outcomes again. useLoginFlow owns that loop headlessly (challenge cycle, error normalization, credential encryption, the store write, navigation), so <Login> and an application's own login screen are consumers rather than reimplementations. It never rejects — failures surface through error; the store write is not overridable (the route guards read it) while onAuthenticated replaces navigation and the welcome notification. The store write is also the success boundary: a failure after it (a rejecting onAuthenticated, a failed invalidation or navigation) goes to onError alone, never to error, which would otherwise render "登录失败" over an authenticated session on a form that can no longer accomplish anything. cancel is likewise ignored while pending: an answer already submitted will still be applied. A URL-supplied redirect is narrowed to a rooted internal path before navigation (redirectTo, being the application's own, is not) — on the single sign-on route the search is whatever the originating system appended. Establishing a session drops the previous identity's menus before the layout guard can read them. LoginChallengeOutlet is the shared renderer lookup, including the alert shown for a challenge type no renderer is registered for; it renders each renderer as an element with a per-type key, never by calling it — a plain call would run every renderer's hooks in the outlet's one hook list, so a chain such as department selection followed by a forced password change would crash on the second challenge. autoResolve answers selected challenges without presenting them, keyed by type and deliberately partial where the renderer registry is exhaustive: presenting a challenge is mandatory, answering one on the user's behalf is opt-in per type, so a second factor can never be resolved from ambient data. Each type is attempted once — a silent answer the server rejects falls through to the renderer instead of retrying, which would loop against the backend's brute-force guard.

  • Single sign-on (packages/starter/src/components/sso, createSsoRouteOptions): a trust-login handoff is an ordinary login carrying a one-time code instead of a password, so everything after the exchange is the shared login flow — challenge chain included, because the originating system authenticated the user but did not satisfy this application's login policy. useSsoLogin adds only what is specific to a handoff: reading it out of the URL (readHandoff, defaulting to the framework's app_id + code convention), spending it exactly once per mount, and clearing it from the address bar. Two details are load-bearing there. The clear happens before the exchange, not after: by the time the exchange settles the browser may already be on the destination, where rewriting the URL to its bare pathname would discard that page's own query and hash. And SsoLoginFlow.search is a snapshot taken at mount, because @tanstack/history patches history.replaceState — clearing the URL notifies the router and empties its live search, which a landing page or an auto-resolver still needs to read. status has a terminal state: a spent handoff that produced neither a session nor a pending challenge (the user cancelled, or the result carried nothing) reports failed, since the one-time code is gone and nothing can restart it. publicKey is accepted here too — a handoff meets the same password_change challenge a password login does, and without the key its renderer would submit the new password in clear text. The route deliberately has no beforeLoad bouncing an authenticated visitor: a handoff names the user it is for and may arrive at a tab signed in as somebody else, so it always exchanges and replaces the session. <SsoLogin> is a plain default page taking no slots; an application-specific screen is written over useSsoLogin and passed to createSsoRouteOptions as component. <SsoLogin> pairs onResolveChallenge with challengeRenderers the way <Login> does — renderers without a dispatcher put a challenge on screen whose submit button can never do anything. createLoginRouteOptions and createSsoRouteOptions are the same shape: each takes either the default page's props or a component replacing the page, as a discriminated union rather than an optional prop that would leave the others silently dead; the custom-page member forbids every default-page prop explicitly (Partial<Record<keyof …Props, never>>) because excess-property checking catches an inline literal but not a pre-built value, where the surplus props would be dropped in silence. The route keeps what no screen should restate — for login the redirect contract (defaulted and catch-guarded) and the already-authenticated guard, for single sign-on the pass-through search.

  • Path parameters: :paramName in the URL is substituted from params — /users/:id + { id: 123 } → /users/123.

  • Query remounts: VEF no longer enables experimental_prefetchInRender on its default QueryClient. An enabled query that failed before receiving data retries when its observer remounts. Hosts reading result.promise must migrate to useSuspenseQuery from @tanstack/react-query for Suspense or read the query observer's data for ordinary rendering and effects.

  • Inline HTTP errors: set meta.shouldShowErrorFeedback: false on the query or mutation whose UI displays every failure. Other callers of the same API keep global feedback by default. The API client applies skipErrorMessage: true to HTTP requests for that invocation; direct HTTP callers can set the same request option. This suppresses global warning and error messages for that request. Errors still reject, and token refresh, expired-login handling and access-denied callbacks still run.

  • Auth skip: set header X-Skip-Authentication: "1" to bypass Bearer injection for a single request.

  • Body encoding (packages/core/src/http/body-encoding.ts): legacy request-only encoding remains available through bodyEncoding: "base64" | "gzip+base64" on post/put (or defaultBodyEncoding), with "none" as a per-request opt-out; integration script saves use gzip+base64. Client-wide protectedBodyEncoding: { encoding: "aes-gcm+base64", key } is a separate mandatory bidirectional mode: every JSON request body is AES-GCM protected regardless of a legacy per-request override, every envelope/error response must carry the same X-Body-Encoding, and the response interceptor decrypts before business/error handling. Multipart/binary bodies remain native. The wire body is raw standard padded Base64 with no JSON wrapper: Base64(12-byte random nonce || ciphertext || 16-byte tag). Keep transformRequest: [body => body] for every pre-encoded request, because axios otherwise JSON-stringifies a base64 string under application/json and adds quotes. The Go backend also supports sm4-gcm+base64, but this browser package deliberately does not ship an SM4 implementation; AES-GCM is the supported interoperable path, run on Web Crypto where the runtime exposes crypto.subtle and on @noble/ciphers elsewhere: browsers expose crypto.subtle only in secure contexts, so a page served over plain HTTP would otherwise be unable to construct the client. Both produce identical bytes, and the nonce source getRandomValues is available in either context. Working over HTTP is not being secure over HTTP — a browser-held symmetric key is extractable, and without TLS anyone on the path reads it from the bundle — so HTTPS is still what provides confidentiality. client.node.test.ts pins wire and crypto interoperability against a real HTTP server; body-encoding.test.ts pins the portable cipher against Web Crypto with crypto.subtle hidden.

  • File preview bridge: the framework bundles no viewer library. components/file-preview defines the FilePreviewTarget / FilePreviewHandler contract; the app installs a preview host via FilePreviewProvider, and <Upload> (and everything built on it) dispatches non-image files to it as normalized targets (toFilePreviewTarget reads UploadedFileMeta — stamped by FileUpload on upload and by StoredFileUpload on hydrate). Images keep the built-in Image modal; without an accepting provider the framework warns and never navigates directly to a URL whose authentication requirements it cannot prove. Private files are fetched or downloaded by the host through HttpClient.requestFile(url) / HttpClient.download(url) (Bearer + 401 refresh + Content-Disposition filename). Reference integration: playground's @file-viewer/react host at playground/src/components/file-viewer-preview-host.tsx, mounted around the authenticated layout in pages/_layout/route.tsx (try it at sys/file-preview-demo); the viewer's renderer preset is registered by fileViewerRenderers() in playground/vite.config.ts.

  • Storage-backed upload fields: StoredFileUpload (components) is the controlled core — value in, value out, where the value is storage object keys: a single key string when maxCount is 1, an array otherwise, which is exactly what the Go approval.FieldUpload kind validates. It owns key hydration, the registry filename lookup, and that single-vs-multi shape, so every binding is a thin wrapper: UploadField binds it to TanStack form state, and the form designer's upload field (form-editor/components/upload-field, palette group date-file, projected to the approval upload kind by the bridge's KIND_BY_TYPE) binds it to the renderer's value/onChange props. The mobile registry reuses the same renderer deliberately — a file picker is a native OS surface, and omitting it would render "未知字段类型" instead of a working control.

  • State management: Jotai for atomic state, Zustand for stores (with createStore / createPersistedStore middleware stack in core/store), XState for complex machines (with useActor + selector in core/state-machine). Pick by complexity.

  • Forms: TanStack Form is wrapped by packages/components/src/form/* and surfaced through FormModal / FormDrawer / Crud.

  • Application-wide component defaults: ConfigProvider's components (in starter, App / ThemeConfigProvider) is a per-component whitelist, not a pass-through. defaultablePropKeys in components/config-provider/component-defaults.ts is the entire surface an application can default; ComponentDefaults is derived from it and resolveComponentDefaults picks by it at runtime, so the type and the enforcement cannot drift and a pre-built value cannot smuggle a non-whitelisted prop. A prop qualifies only when its right value depends on the business rather than the design system, stays correct wherever the framework itself renders the component, does not restyle it, and does not bypass a framework pipeline — so prefixCls, raw theme tokens, componentSize, variant, locale, overlay containers, and the modal / drawer / popover interaction conventions have no global entry point (a single instance may still pass a prop explicitly). Entries backed by an antd component route into antd's own ConfigProvider component config, because the re-exported antd components have no wrapper that could read a context; framework-owned components resolve theirs with useDefaultProps(name, props) — explicit non-undefined prop > application default > destructuring default, returning props itself when nothing is configured. A composite forwards undefined instead of baking in a default, so one entry covers everything built on the consumer; a composite that also reads the prop itself resolves it with the same entry (Crud resolves ProTable.rowKey for its delete bookkeeping). useFormLayout applies the Form entry to fields rendered outside a Form. Starter's theme store persists only the user's explicit picks (optional colorScheme, partial colors); defaultTheme fills the rest through context (useEffectiveColorScheme / useEffectiveThemeColors), so a changed application default reaches every user who never picked their own — seeding the store could not, since it hydrates at import time.

  • Linkage expressions: form-editor conditions, assignment expressions, and script actions are all plain JavaScript compiled through new Function (engine/linkage/default-evaluator.ts) with field / $form, $vars, $user, $node, $applicant, $globals, a Date $now, and (inside effect action sequences) $steps in scope; hosts swap in their own runtime via LinkageEvaluators. Structured DynamicValue slots support "literal", "reference" (dot-path reads without new Function), and "expression". Expression inputs are CodeMirror (CodeEditor from components) with completion off. approval-flow-editor condition expressions use the Go engine's own syntax — edited as plain text (no highlighting), validated and evaluated on the backend; its CONDITION_OPERATORS vocabulary lives in approval-flow-editor/src/types.ts, and the per-field operator compatibility table (getOperatorsForField / isOperatorValidForField in approval-flow-editor/src/shared/condition-operators.ts, distinguishing single-value select from multi-value select via FormFieldDefinition.isMultiple, set by the bridge and Go parser for checkbox-group, multi-select, and tree-multi-select, supporting ordering/emptiness on date and datetime, and limiting daterange to is_empty / is_not_empty) stays in lockstep with Go approval/condition.go (ConditionOperatorsForField / IsOperatorValidForField) and is enforced by both flow-validation.ts (condition_operator_not_allowed) and Go deploy validation (ValidateConditionFields, reported as approval.ErrInvalidFlowDesign). Date granularity (DateGranularity = "year" | "quarter" | "month" | "day", omitted = "day", shared format constants and strict parse/format helpers in @vef-framework-react/shared/utils/chrono.ts: YYYY, YYYY-Qn, YYYY-MM, YYYY-MM-DD) applies to date and daterange on PC, mobile, approval projection (FormFieldDefinition.granularity), and flow condition inputs, while datetime projects to its own datetime kind (YYYY-MM-DD HH:mm:ss).

  • Global context injection: FormRenderer's evaluationContext carries host runtime context into every expression, script, and — via a $-rooted sourceKey like $applicant.departmentId — visual leaf condition. The roots are one table, CONTEXT_SLOTS in engine/linkage/scope.ts ($vars / $user / $node / $applicant / $globals, plus $form for the values): the leaf resolver, the validator (an unknown root is source_scope_unknown), dependency tracking, and key renames all read it, and every path segment is read as an own property — a prototype member such as $user.constructor never resolves. $user is whoever views the form now; $applicant is the subject it is filled on behalf of — in a workflow the initiator — and is the same for every viewer of a record, which is why an approval form must never put the initiator in $user. $globals are read-only host attributes, unlike the schema's own writable $vars. The designer's contextSources (LinkageContextSource[]) declares those paths as system variables: the sidebar's 数据 tab lists them with design-time preview samples (laid over the host context in the preview only, never stored), and the condition builder offers them as a 系统变量 group. The approval package wires this end to end: InstanceFormPanel takes the instance's applicant and globals (the start form's from my.get_start_form, which resolves the applicant exactly as starting does, so $applicant reads identically at initiation and on every detail view), and the designer offers the four applicant attributes plus ApprovalPlugins.formGlobals. A host rendering its own designer uses ApprovalFormEditor, the design-time counterpart of InstanceFormPanel: FormEditor wired from ApprovalProvider with those system variables and the approval projection check (validateApprovalProjection) fixed, and registries, services, evaluators and the API and dictionary catalogs taken from the provider unless passed explicitly. Host globals reach a form only by opt-in: the Go resolver implements approval.FormGlobalsExposer naming the keys, and formGlobals must stay in lockstep with them. approval-flow-editor mirrors this with EditorPlugins.globalSubjects (FormFieldDefinition[]), layered between the built-in applicant subjects and form fields; the Go engine resolves them from Instance.Globals, a server-side snapshot supplied by the host's InstanceGlobalsResolver at instance start (never from the client request — globals steer routing). The two built-in applicant subjects are not reachable that way — the engine resolves them before globals, deliberately, since the same instance column also drives assignee resolution and the initiator check — so making them selectable rather than typed goes through EditorPlugins.pickers instead: applicantId takes the user picker and applicantDepartmentId the department one, for the operators that compare a whole id, degrading to free text where a picker is unwired.

  • Option hierarchy and tree select controls: FieldOption supports disabled, description, and nested children across all four option sources (static, ref, codeSet, remote), with tree-wide value uniqueness checked recursively (findDuplicateOptionValues over walkOptionTree). RemoteOptionMapping adds childrenKey (nested mode, default "children") and parentKey (flat-to-tree mode, taking precedence over childrenKey; missing/empty/self/cyclic parents become roots without looping), alongside disabledKey and descriptionKey (all active in mapRemoteResponseToOptions, with matching default placeholders in RemoteOptionSourceEditor). Runtime preserves full option trees: flat selection controls (select, multi-select, radio, checkbox-group) read top-level entries only through useTopLevelFieldOptions, while tree-select (scalar) and tree-multi-select (strict non-cascading multi-value array, columnType: "json") consume the full tree and support leafOnly (leafOnlyEntry, data-contract synced between matching tree twins, isolated from flat choice families). disabled options cannot be picked while already-stored values keep rendering; description renders as secondary muted text and participates in search. PC (OptionTreeSelect in render/parts/option-tree-select.tsx, shared across runtime controls, TypedLiteralInput, and canvas SampleCell) and mobile (MobileTreeSelectInput / MobileTreeMultiSelectInput) share filterOptionTree (retaining a matched node's entire subtree, with showSearch.filterTreeNode: false on PC) and useOptionTreeExpansion (recomputing initial expansion on open, async option arrival, and query change while keeping browse and search expansion isolated and never resetting on selection changes); under leafOnly, clicking a non-leaf node expands it on both PC (treeExpandAction="click") and mobile. OptionListEditor edits both flat and hierarchical lists through one pre-order row model keyed by stable ephemeral row IDs (reusing sortable-rows drag helpers in flat mode) so focus, open details, and collapse state follow logical rows across delete, move, indent, and outdent. Runtime value normalization, permission bridge, and approval projection share selectableOptionsForField (tree controls flatten in pre-order honoring leafOnly, flat controls and fixed-row subforms take top-level only), stripping disabled / description / children to plain { label, value } and carrying normalized childrenKey / parentKey in optionSource.mapping.

  • Remote option data sources: a RemoteDataSourceRequest carries resource / action / version plus params, and each parameter is a DynamicValue — the same { kind: "literal" } | { kind: "reference" } | { kind: "expression" } union linkage action values use, so one DynamicValueEditor serves both and the two cannot drift. References and expressions are evaluated by the form runtime before the request reaches the host service (engine/data-source-params.ts), so FormServices.request only ever sees plain data plus { signal } (and DataSourceProvider maps array or paginated .items payloads into FieldOption[] via mapRemoteResponseToOptions); the option cache is keyed on the resolved request, which is what makes a bound parameter changing re-fetch while an unrelated keystroke does not — cascading falls out of the cache key rather than needing its own channel. The values subscription is gated on schemaHasBoundParams, so a form that binds nothing keeps its selects out of the keystroke re-render path. Host services are not wired by default: FormRenderer and FormEditor take services (FormServices) as a prop and ApprovalProvider passes plugins.services through to the instance form and the designer — without services.request, every remote source resolves to [], which reads as "the framework never fetches" rather than as missing configuration. A host API catalog replaces hand-typed endpoints: FormEditor's dataSourceApis (DataSourceApi[], ApprovalPlugins.dataSourceApis in approval) makes the remote option-source editors lead with a picker; a pick copies the endpoint, mapping, and declared-parameter defaults into the schema, so the stored request stays self-contained and the runtime, the request service, and the bridge projection never need the catalog — a stored request is recognized as an API again by its endpoint (resource + action + version). Mappings are normalized (normalizeOptionMapping) wherever they are stored, resolved, or projected: a blank key means the default, but a mapper reading mapping.labelKey ?? "label" would take "" literally. Parameter names in the editor are draft-buffered and committed only when non-blank and unique, so a rename in progress can never collapse two rows into one record key. Evaluators are the opposite: they default through resolveLinkageEvaluators, and the param scope must resolve through it too — reading the host's raw overrides instead makes a bound parameter silently unresolvable on every form that does not override, while linkage expressions keep working. The approval projection carries the source through to the backend: projectFormSchema enumerates a static source (inline or via a ref) into options as before, and now emits an unresolvable one as ApprovalFormField.optionSource — the post-dereference { kind: "remote", request?, mapping? }, mirroring the Go FieldOptionSource. Params travel unevaluated, since neither the backend nor a list-rendering consumer holds form values to evaluate them against; the Go RemoteOptionRequest.HasBoundParams (true for both "reference" and "expression" params) tells a consumer whether one lookup can translate a whole column or the option set is per-row. It exists so a list view can render a stored value as its label instead of its raw value — the backend still validates against options alone, so a remote field accepts any submitted value and options_not_static keeps warning about exactly that.

  • Form action sequences (FormServices, commit, SequenceController): effect rules run ordered action sequences (runtime/action-executor.ts, with a synchronous fast-path for sync-only rules and a single finally settlement point so any throw still releases slots, busy counts, and submit gates) across api_call, select_record, set_fields, set_variable, refresh_data_source, alert, navigate, submit, and reset, returning a typed SequenceOutcome ("completed" | "stopped" | "aborted" | "failed"). They share one host FormServices interface (request, navigate, notify; notify defaults to framework toast messages; preview runs real request and maps navigate to a preview toast while the designer gates api_call / navigate on host serviceCapabilities, keeps already-stored unwired actions editable, and marks them 当前宿主不支持). Every step reads live environment state (disabled, $vars, evaluators, fieldPermissions, services, knownOptions) through one stable SequenceEnv rather than trigger-time snapshots. commit (FieldComponentConfig.commit: "entry" | "change", default "change") separates explicit completion from per-keystroke change: single-line text and number inputs commit on IME-safe Enter (guarding compositionstart..end, isComposing, key === "Process", and Safari's post-compositionend keyCode === 229; preventing outer form submit; number flushes its draft first) or dirty blur, textarea commits on dirty blur, and selection controls commit on user change; programmatic writes never fire commit or change. Event triggers accept an optional when guard (preserved across trigger switches via switchRuleTrigger, with control-specific commit hints); condition triggers carry rule-level retrigger: "edge" | "always". Earlier step outputs (output, minted rule-unique by default and propagated downstream on rename via renameStepOutputInRule) feed later actions via $steps.<name>[.path] (with per-action onError: "stop" | "continue"). select_record auto-selects 1 record, notifies + obeys whenNone ("stop" / "continue") on 0 records, and opens a picker on >1 records (PC Modal with framework Table inside a single ScrollArea, semantic <table> without role="option", scoped keyboard navigation with scrollIntoView({ block: "nearest" }), close-transition retention, and trigger-focus restoration; mobile Popup card list contained inside useMobileScopeContainer). SequenceController (runtime/sequence-controller.ts) enforces single-flight per (scope, ownerField, rule), staleness discard when re-resolved api_call inputs diverge on settle, aborts on supersede / external reset / unmount / subform row deletion (with live shifted-index prefix reads for surviving sibling rows; a reset action aborts other runs via abortOthers while continuing its own sequence), and a unified submit gate via polymorphic <Form component={FormSurface}> (no form-instance mutation) that coalesces concurrent external submits onto one Promise, cancels waiting submits on reset, releases a calling sequence's request gate via leaveSubmitGate() on submit (preventing multi-rule or recursive-lifecycle deadlocks), blocks submission quietly whenever beforeSubmit ends with any outcome other than "completed", keeps getSubmitValues() synchronous while exposing FormRendererApi.waitForPendingSequences() (awaited by InstanceDetailPanel's reject path before reading values), renders per-field busy indicators (useFieldBusy + <Spin size="small" /> in label / cell-status slots, never overlaid on control suffixes), and enforces disabled-form read-only rules (set_fields skipped; select_record / submit / reset halt the sequence). Every programmatic write passes through writeFieldValue / normalizeFieldValue (runtime/field-write.ts), guarded by the single isWritableTargetField predicate shared with validation and designer pickers, normalizing values to the exact shapes Go validateFormField accepts and clearing broken references. In the designer (editor/properties/entries/linkage/*), RuleListEditor renders field, container, and form-event rules as a compact two-line DataListRow list (trigger summary from trigger-summary.ts, single- or multi-step action summary from action-summary.ts, issue marker & count, hover/focus duplicate and delete; rows are memoized on primitive summaries and stable callbacks). Draft-modal lifecycle (monotonic session keys, editingId, close-transition mount retention, row-ref maps, and scroll+open diagnostic jumps) is shared through useDraftSession (editor/properties/use-draft-session.ts) across data sources, variables (useDataEntryEditor), and linkage rule lists. Clicking a row, 新建…规则, or a template opens one rule at a time in a single-layer 960px RuleDraftModal (DraftModal: structuredClone draft, dirty-close confirmation, single undo step on 确定, live draft diagnostics via useDraftRuleIssues, and rule-wide step-output draft validation/pruning/rename-apply helpers in step-output-drafts.ts that block 确定 and focus the offending step). useScopeFieldOptions and useFieldOptionsReferenceScope (editor/properties/scope-fields.ts) provide the single path shared by NodeReferenceScopeProvider, useLinkageEditorModel, and RuleDraftModal, subscribing to $vars only while a picker or open rule dialog is mounted so variable or unrelated scope edits never re-render closed rule rows. Inside the rule dialog, action sequences are drag-sortable, collapsible with plain-Chinese one-line summaries (single-step expanded, multi-step collapsed so a full pipeline fits on one screen), confirm before deleting a referenced step or moving a producer past its consumer, and edit all steps — including api_call, select_record, and set_fields — directly in place with no second modal on top. CatalogRemoteRequestEditor serves both remote option sources and api_call; ReferenceScopeProvider / ReferencePicker (editor/properties/reference-scope.tsx) is the single grouped candidate picker shared by ConditionEditor and DynamicValueEditor (fields, $vars.*, system variables, and earlier step outputs with api.fields inherited across select_record plus inline sub-path input for undeclared APIs); set_fields offers sortable mappings, target-typed literals (TypedLiteralInput), and "按名称匹配" (matchStepFieldsToTargets, which leaves the rule's own field out so a lookup that finds nothing never clears what was just typed); select_record offers declared-field column picking, drag-sorting, and live auto-inferred column previews (collectInferredSelectRecordColumns); and "查询并回填" (templates.ts) is offered as a pure rule factory only on writable leaf fields when serviceCapabilities.hasRequest is true. engine/linkage/action-descriptors.ts (ACTION_DESCRIPTORS, internal to the package) is the single traversal table shared by validation, key rename, reference pruning, date-literal checks/scrubs, clone/move remapping, and bound-parameter scanning, while engine/linkage/step-schema.ts holds the pure designer step analysis/matching helpers.

  • Data-dictionary option sources: a selection field can take its options from a host data dictionary — { kind: "codeSet", codeSet }, the fourth FieldOptionSource arm (数据字典 in the designer). There is deliberately no form-level list of dictionaries to maintain: FormRenderer (and the designer canvas) collect every key the presentation's fields read, subform templates and fixed-row subform sources included (collectCodeSets), and CodeSetProvider loads them in one batched call through codeSetQueryFn — the prop, else AppContext.codeSetQueryFn, under the same [queryFn.key, sortedKeys] query key useCodeSetQuery builds, so a dictionary the application already loaded is served from the TanStack cache. The load runs in a sibling that mounts only when there is a key and a query function, so a form reading no dictionary never needs a QueryClient (form-editor specs render without one). CodeSetProvider preserves nested children, disabled, and description from each loaded dictionary: flat selection controls and fixed-row subforms consume top-level entries only while tree-select and tree-multi-select consume the full hierarchy. PC table-variant subform cells render the exact same leaf field components (and per-row SubformRowController / DataSourceParamScopeProvider) as stacked subforms (with the canvas SampleCell also reading through useFieldOptions), so all four option sources (static, ref, remote, codeSet), bound parameters, and original option value types behave identically across layouts. The designer picks from the host catalog FormEditor.codeSets (ApprovalPlugins.codeSets; design-time only — the schema stores the key) or takes a typed key committed on blur, since every committed key is a dictionary the canvas loads. Approval projects it as optionSource: { kind: "codeSet", codeSet } (an unpicked one keeps its kind and drops the blank key, as Go's omitempty does), and unlike a remote source it is checked: the Go backend validates a submitted value against the dictionary through the host's mold.CodeSetLoader, so it raises no options_not_static warning.

  • Detail-table row modes (SubformRows): SubformBase.rows is a discriminated union ({ mode: "dynamic", min?, max?, addLabel? } | { mode: "fixed", source, itemKey, headerLabel?, headerWidth?, required? }; omitted rows is dynamic). Fixed-row subforms (also offered in the palette via the matrixTableDefinition preset with paletteId: "matrix-table" — a type: "subform" factory, not a second node type) model checklist/matrix tables whose rows come from any FieldOptionSource (static, ref, codeSet, or remote, edited through the shared OptionSourceEditor with bulk-paste support on static lists). Each row snapshots { value, label } under row[itemKey] (reserved inside the subform's key scope via collectScopeKeys and never included in columns or aggregate pickers). At runtime on PC, variant: "table" renders every template cell directly editable against the outer form (render/subform-table.tsx, sharing SubformRowController's per-row linkage, bound-parameter scope, memoization, and direct cell validation with stack, with no per-row edit/save/operation column): fixed rows prepend a read-only header column with no add/delete controls, while dynamic rows show a bottom add button (rows.addLabel, respecting max) and a compact trailing delete action when rows.length > min; PC stack and mobile render each row as a titled card in fixed mode with no add/delete controls. At runtime (useFixedSubformRows), non-empty stored defaultValues lock the subform to its stored snapshot (never calling useFieldOptions even when bound params change), while fresh fills resolve the source, rebuild rows on bound-param changes preserving surviving cells by value, and clear to [] on error so rows.required blocks submission. Approval projects fixed-row tables with ApprovalFormField.fixedRows (itemKey, optional headerLabel, and items XOR post-dereference source), mirroring Go formeditor parity fixtures; Go validates each source kind (static exact order/value/label, codeSet unique + dictionary membership, remote unique + shape) and materializes <itemKey>_value / <itemKey>_label TEXT NOT NULL columns under table storage.

  • Cross-device data-contract consistency: PC and mobile presentations may arrange different layout trees, but a keyed node (same value scope and key) binds one shared data contract. In form-editor, editing any data-contract property (key, granularity, validate, dataSource, leafOnly, columnType, number precision, upload maxCount, or subform rows mode / itemKey / source / required / dynamic min / max) via the store (setFieldKey, setDateGranularity, editField, updateBlock, backed by engine/schema/contract-sync.ts) propagates to its same-scope, same-key twin on the opposite presentation within the same undo step, while leaving purely presentational properties (label, placeholder, headerLabel, headerWidth, addLabel, variant, layout sizing, and template column trees) device-local and leaving absent twins untouched. At publish/deploy, both approval-form-bridge (contract-compare.ts) and Go internal/approval/formeditor (contract_compare.go) project both devices and structurally compare their data contracts (stripping display-only fields including label, placeholder, validation.message, fixedRows.headerLabel, and field/column order), reporting residual divergences with dedicated error codes (cross_device_kind_mismatch, cross_device_options_mismatch, cross_device_validation_mismatch, cross_device_storage_mismatch, cross_device_table_mismatch, cross_device_table_rows_mismatch) pinned by shared parity fixtures.

  • Designer diagnostics: one surface per editor. FormEditor's footer chip opens every issue — its own validateSchema plus the host's validate (SchemaValidator, called only for a schema free of structural errors; approval passes validateApprovalProjection) — with plain designer-Chinese linkage messages (engine/validation.ts), and each locatable one jumps directly to its node, 数据 entry modal, or exact linkage rule and action step (pendingLinkageFocus with ruleIndex switches to the 联动 tab or the 表单 tab for form events, opens that rule's dialog, and expands, scrolls to, and briefly highlights the step; omitting ruleIndex — as the 字段联动 overview does — lands on the field's 联动 tab or scrolls a container's linkage section into view without opening a dialog; editor/issue-location.ts names nodes through the shared nodeDisplayName / nodeDefinition helpers in engine/schema/walk.ts — label → key → field-registry definition name, mapping fixed-row subforms to the matrix-table preset 矩阵表格 — used consistently across outline, linkage overview, container properties/linkage, and diagnostics, e.g. 工号 · 规则 1 · 步骤 3(设置字段), 弹性布局 · 规则 1 · 步骤 1(调用接口), 数据源「…」, with the raw path kept as a tooltip; a host path that is a field-key chain such as lines.price locates the field). Node removal previews (engine/schema/removal-impact.ts + editor/remove-node-confirm.tsx) report both dropped rules and partial impacts (removed set_fields write items and cleared references on surviving rules, nodes, and data sources). The publish gate reads the same merged list. approval-flow-editor has the equivalent toolbar indicator, so the approval wizard renders no issue banners above either editor (they would eat canvas height) and only says, beside the disabled 下一步, why the step cannot advance.

  • Shared flows: Flow.isShared (the Go Flow.IsShared, set by CreateFlowParams.isShared and fixed at creation) offers a flow to every tenant, while Flow.tenantId stays the real tenant that owns and manages it; each instance runs in the tenant that started it. There is no reserved shared tenant and no shared category: a shared flow sits under one of its owner's categories, and a shared code is unique across every tenant's shared flows (ErrSharedFlowCodeExists, 40026), while a tenant flow of the same code replaces the shared one in its tenant. Tenancy splits by side. Self-service calls carry no tenant: a start runs in the tenant the caller acts in, so ApprovalInitiatePage / StartInstanceDrawer take no tenantId and the list shows exactly what a start accepts — the tenant's own flows plus the ones other tenants share — while the other my.* lists (task center, my instances) read the caller's own work in every tenant — cross-tenant views are the admin console's. Definitions are managed across tenants, gated by permission: ApprovalFlowPage / ApprovalCategoryPage's tenantId is the tenant the page manages, filtering its list (find_flows / find_tree list every tenant when it is omitted) and stamping what it creates; the backend never checks it against the caller's own tenant. find_flows lists the flows a tenant owns, its shared ones included; FlowSearch.includeShared adds other tenants' shared flows whose code the tenant has not taken — the flows a start by code finds there, which is what a host picker of a tenant's usable flows wants. The designer's basic step carries the 全局流程 switch (disabled once the flow exists), and the designer derives shared mode from it — flow.isShared when editing, the draft while creating — passing it as EditorPlugins.shared: a shared flow may route work to people of other tenants than the one that starts it, who act on it from their own (the backend's tenant guard lets the people a task or copy was routed to through; administration stays within the instance's tenant), so nothing is disabled or flagged for it. Users and departments belong to one tenant each, so with the host's ApprovalPlugins.tenants (TenantOption[], EditorPlugins.tenants) wired, an assignee or CC row picking them asks for the 机构 first and the picker is handed the pick as PickerProps.tenantId — disabled until one is chosen. The pick is stored as tenantId on the rule (designer-only: the backend keeps it with the definition and never reads it); changing the tenant clears the ids, switching a row between user and department keeps it, and roles and host catalogs are never per tenant. Without tenants a shared flow picks people through the plain pickers, and the node-admin and fallback-user lists are not tenant-aware yet. Categories never span tenants, so the designer's category picker, the category form's parent picker and the delegation picker all read the one tenant they are given.

  • Sortable lists: a dnd-kit sortable drag moves the rows' elements as it goes and puts them back only when it is canceled, so a list must end up rendered in the order left on screen. Commit a drop with core's moveSortableItem (form-editor rows: useSortableRows / reorderRows), never moveDragItem, which keeps the old order when the pointer is released off every row. Key rows by identity, never by position. An order that may be taken back — a confirm after the drop — is rendered first and asked about second, as ActionsEditor does, since React cannot put back rows it never moved.

  • Editor perf at scale: the form/flow editors target 100s of fields — keep per-keystroke render and per-frame drag cheap (structural sharing in packages/form-editor/src/engine/schema/mutate.ts, memoized canvas rows, and don't let $vars / expression-scope changes bust cell memo). Discrete-action tree walks (drop / duplicate) are not hot paths; don't pre-optimize them.

Build System

  • Vite for all packages via defineBuildConfig() (scripts/build-config.ts)
  • Auto-externalizes deps/peerDeps; Emotion CSS-in-JS transform; .d.ts via unplugin-dts
  • Requires Node 22+. pnpm version is auto-tracked from package.json#packageManager (CI uses pnpm/action-setup@v4).

Testing

Vitest 4 + jsdom + @testing-library/react. Test files: ./packages/**/*.test.{ts,tsx}. Global setup at ./scripts/test-setup.ts (browser-API mocks, localStorage polyfill, jsdom virtual-console filter). The root vitest.config.ts enables globals: true, so describe / it / beforeEach / expect / vi are available without imports.

Conventions below follow Testing Library, Kent C. Dodds' Testing Trophy, and the practices of React Aria / Radix / Mantine / TanStack. Existing specs are being aligned; new specs follow these from day one.

Philosophy

  • Test behavior, not implementation. Assert on what a caller observes, not internal state, private fields, or refactor-fragile structure.
  • Confidence over coverage. Prefer integration-level tests (render → interact → assert). Coverage is a side-effect of good tests.
  • One concept per it. Unrelated assertions belong in separate it blocks.
  • No flaky tests. No performance assertions, time-of-day logic, or real-clock setTimeout waits.

File Layout

Specs are colocated next to the source: <name>.test.ts(x) when the source is <name>.ts(x), or index.test.ts(x) when the source is index.ts(x). No __tests__/ directories.

Canonical Samples

Reach for these patterns before inventing new ones:

  • Pure utility — packages/shared/src/utils/tree.test.ts
  • Hook with apiClient injection — packages/hooks/src/use-has-fetching/index.test.ts (passes apiClient to renderHook, builds a queryFn via apiClient.createQueryFn)
  • Component (antd + permission) — packages/components/src/permission-gate/index.test.tsx
  • Component (form submit lifecycle) — packages/components/src/form-modal/index.test.tsx
  • Component (async UI gated by Promise.withResolvers) — packages/components/src/action-button/index.test.tsx (loading state under a deferred onClick)
  • vi.hoisted + vi.mock for a CJS package — packages/core/src/http/client.test.ts (axios)
  • vi.mock for a typed SDK module — packages/core/src/sse/client.test.ts
  • In-repo dependency mock at the package boundary — packages/components/src/file-upload/index.test.tsx (mocks core/Uploader)
  • Fake-driver scripted backend — packages/core/src/storage/uploader.test.ts
  • Manual defer<T>() for deterministic async ordering — packages/core/src/http/client.test.ts, packages/core/src/storage/uploader.test.ts

Imports & Wrappers

  • globals: true is on — new specs omit describe / it / expect / vi imports. Existing explicit imports are kept; do not bulk-rename old specs purely to drop them.
  • Component and hook specs go through the package's test-utils.tsx (packages/components/test-utils.tsx, packages/hooks/test-utils.tsx) — render / renderHook from that module install ConfigProvider / AppContextProvider / ApiClientProvider. Bypassing the wrapper makes antd and permission-aware code misfire.
  • Pull screen, waitFor, act, within, etc. from the same test-utils.tsx (it re-exports * from "@testing-library/react").
  • Specs that touch useApiClient / useMutation / useQuery pass apiClient to render / renderHook; the wrapper installs ApiClientProvider (which provides QueryClientProvider). Use createTestApiClient() for an isolated per-test instance — its default baseUrl is http://vef-test.invalid so any leaked real network call fails loudly.
  • packages/starter/test-utils.tsx differs from the others: it mounts what is under test as the only route of a router (renderRouterHook / renderInRouter), because RouterProvider renders a route tree rather than its children, so a Testing Library wrapper cannot host one. It renders under StrictMode on purpose — double-invoked effects are what a "run this once" guard has to survive. The default memory history never touches window.location, which also means it never writes there: anything asserting on the address bar must pass history: "browser", or the assertion holds regardless of what the code does.
  • Packages without a local test-utils.tsx (currently core, shared, and form-editor) import directly from @testing-library/react. They have no provider requirements — core/state-machine/index.test.ts, core/context/disabled.test.tsx, and core/context/context-selector.test.tsx are the canonical examples. packages/form-editor/test-utils.ts holds no wrapper either: its dragSortableRow runs a real dnd-kit drag in jsdom, which is how a spec sees the rows as a drag leaves them.

Structure & Queries

  • describe(module name) → optional describe("when <condition>") → it("<observable outcome>"). Descriptions read as sentences: it("renders the dialog"), it("throws when X is missing"). Do not prefix with "should" — third-person verb or imperative statement only.
  • Separate happy path, edge cases, and errors into distinct describe blocks.
  • One it per case — do not use it.each (it collapses semantically distinct cases under one description and obscures which row failed).
  • Prefer accessible queries: getByRole / findByRole > getByLabelText > getByText > getByTestId. See Testing Library priority.
  • queryBy* is only for absence assertions (expect(queryBy...).not.toBeInTheDocument()).
  • findBy* already waits — do not wrap it in waitFor.
  • Don't query by CSS class unless the class is a documented contract (e.g. vef-btn-loading).

Interactions & Async

  • userEvent only. Fresh userEvent.setup() per test. userEvent fires the full pointer/focus chain and flushes microtasks; fireEvent does not, which silently breaks antd popover / popconfirm transitions. The repo currently has zero fireEvent usage — even antd's hidden <Upload> input is driven by user.upload(input, file) (see packages/components/src/file-upload/index.test.tsx). If a new spec genuinely needs fireEvent, justify the exception in the PR description.
  • await findBy* for elements appearing async; await waitFor(() => expect(...)) for non-element state.
  • Promise.withResolvers() (or a hand-rolled defer<T>()) gates async flow under test (action-button, http/client, uploader).
  • Timer-driven code: vi.useFakeTimers() / vi.useRealTimers(); flush via vi.runAllTimers(), vi.runAllTimersAsync(), or vi.advanceTimersByTime(ms). Use vi.useFakeTimers({ shouldAdvanceTime: true }) when the code under test mixes a real await with fake intervals.
  • vi.spyOn(target, "method") over vi.fn whenever you want the original implementation to still run (e.g. silencing console.warn while observing calls — see silenceConsole in http/client.test.ts). Reach for vi.fn when constructing a replacement from scratch.
  • Never await new Promise(r => setTimeout(r, ms)) — it's flaky, slow, and not what user-visible behavior depends on. Use microtask flushes (await Promise.resolve()) for ordering and fake timers for delay-sensitive code.

Assertions

  • Plain expect().to* + jest-dom matchers (toBeInTheDocument, toHaveTextContent, toHaveAttribute, toBeDisabled, toHaveValue). No custom matchers.
  • Snapshot tests only for stable structural output (e.g. generated schema). Never for rendered DOM.

Mocking

  • Mock the network layer (axios / fetch / event-source) and side-effect entry points of third-party SDKs.
  • vi.hoisted is required when a vi.mock factory needs to reference an outer variable — Vitest hoists vi.mock to file-top, and vi.hoisted is the only legal way to share state with the factory. See http/client.test.ts.
  • Browser APIs (ResizeObserver, IntersectionObserver, matchMedia, localStorage) are already mocked globally in scripts/test-setup.ts — do not duplicate.
  • Do not mock internal modules. Test through the public API. The fake-driver pattern in uploader.test.ts is canonical: construct a typed fake of the boundary, script its responses, record calls for assertion.
  • A dependency from another in-repo package counts as a boundary — mocking it is fine when that dependency has its own thorough coverage (e.g. components/file-upload mocking core/Uploader).
  • Per-test mock isolation: the project does not run test.concurrent, so two patterns coexist legitimately:
    1. Boundary mocks created once (vi.hoisted instances, module-scoped vi.fn() like mockHasPermission in permission-gate) — cleared in beforeEach via mockClear() / mockReset(). Required for vi.mock factories; acceptable elsewhere.
    2. State-carrying fakes (call counters, captured payloads, in-memory queues like use-deep-memo's factoryCallCount) — must be re-created inside beforeEach. If a counter or buffer survives between tests, isolation is gone.
  • Reset shared state in afterEach via vi.restoreAllMocks() / vi.clearAllTimers().

Hooks

  • renderHook from the package's local test-utils.tsx. The legacy @testing-library/react-hooks is not used.
  • act wrapping is implicit for Testing-Library-triggered updates — wrap manually only when the React warning explicitly asks.
  • Read latest value via result.current at each assertion point. Don't destructure into a stale binding.

What Not to Test

  • Pure re-export modules: core/common, core/dnd, core/immer, core/motion, core/state
  • Pure antd pass-through components (no behavior beyond a wrapper)
  • Pure style / animation components
  • Excluded from coverage (existing specs still run in pnpm test): starter, dev, plugins, playground, and the visual canvas in approval-flow-editor. form-editor IS in test scope (heavily tested) — just without an aggregate threshold yet.
  • Generated artifacts (dist/, .d.ts)

Coverage & Process

  • Package-level thresholds enforced via vitest.config.ts for shared / hooks / core. Values reflect the measured baseline minus ~5% buffer; raised stage by stage as new specs land. components and form-editor are coverage-measured but have no aggregate threshold by design — tracked per-component/feature.
  • CI gates on pnpm typecheck && pnpm lint && pnpm test. pnpm test:coverage runs as an informational artifact only.
  • New components and hooks ship with a spec. Exceptions justified in the PR description.
  • When modifying any packages/{shared,hooks,core,components,form-editor}/** source, update the corresponding spec. Before renaming exports or changing prop types, search for specs asserting the old contract.
  • Use test: prefix for test-only commits (Conventional Commits, enforced by commitlint).

Conventions

Commit Messages

  • Single-line only. One Conventional Commits header (type(scope): subject); no blank line, no body — enforced by commitlint's body-empty/footer-empty rules (root commitlint.config.ts and @vef-framework-react/dev's defineCommitlintConfig). Pass exactly one -m (keep under ~100 chars). Flag breaking changes with the header ! (feat!:, feat(scope)!:) — the BREAKING CHANGE: footer is rejected. Extra rationale goes in the PR description or chat, never the commit body.
  • test: prefix marks test-only commits (commitlint-enforced).

Naming & Imports

  • Filenames: kebab-case. React components: PascalCase.
  • No leading-underscore identifiers (e.g. _handleSubmit). A _ prefix is reserved solely for intentionally-unused params/vars (the ESLint ^_ ignore pattern) — never as a naming style for real, used bindings.
  • Comments, JSDoc, and inline docs: English only.
  • When wrapping a same-named component from another package, alias the imported inner component as XxxInternal.
  • Imports sorted by perfectionist plugin: type imports first, then external, then internal (alphabetical within group).

TypeScript

  • Strict mode; TypeScript 6+. Avoid any — no-explicit-any is off (a convention, not lint-enforced), so prefer precise types / generics and narrow casts rather than reaching for any
  • Prefer interface over type for object shapes
  • Array types: T[] for simple, Array<T> for complex (array-simple rule)
  • Max 5 function parameters
  • Type safety is not negotiable: prefer an exhaustive switch (with assert-never / exhaustive()) over as / widening casts on discriminated unions — never loosen types with a cast where a switch type-checks.

React & JSX

  • No class components, no defaultProps, prefer hooks
  • No unnecessary useMemo / useCallback
  • JSX props sorted: key / ref first, then alphabetical, callbacks last

Formatting

@stylistic/eslint-plugin: 2-space indent, double quotes, semicolons, 120-char line width.

CSS Styling

  • Antd styles live in the antd CSS layer; VEF styles already have higher priority — don't use !important or && to override antd.
  • Use globalCssVars from @vef-framework-react/components for theme variables. Brand-coloured text and glyphs take colorPrimaryText, never colorPrimary, which is unreadable as text on dark surfaces; fills, borders and rings take colorPrimary.
  • Many CSS vars (colorText, colorBorder, colorBgContainer) auto-adapt to light/dark — no .dark overrides needed.
  • Use html.dark & only for properties that genuinely differ between themes (gradients, shadows, glass effects).

Tooling & Workflow

Git Hooks

  • Pre-commit (lint-staged): runs eslint --fix on staged .js / .ts / .tsx / .json / .md files
  • Pre-push (.husky/pre-push): runs pnpm typecheck && pnpm test before any push

CI

.github/workflows/test.yml runs on every PR and push to main:

  • Gating: pnpm typecheck → pnpm lint → pnpm test
  • Informational: pnpm test:coverage (uploaded as artifact but not gating)

.github/workflows/release.yml runs on a pushed v* tag — re-runs the gates, then pnpm publish and a GitHub Release (see Release).

Skills to Use

Every package is React 19 — apply these by default when writing or reviewing any component / hook (not only for big refactors):

  • /vercel-react-best-practices — performance & re-render patterns (memoization, derived state, effect deps, large lists)
  • /vercel-composition-patterns — component API design (compound components, avoid boolean-prop sprawl, lift state, React 19 APIs)
  • /ant-design — antd 6.x decision guide (component selection, theming/tokens, performance, CRUD / ProComponents); the UI layer is antd v6 + Emotion
  • /frontend-design — visual design, styling, UI aesthetics
  • /web-design-guidelines — UI code review (performance, forms, animations; accessibility is not prioritized for this project)
  • ReactFlow v12 (@xyflow/react) best practices when working in approval-flow-editor (its only consumer)
  • No tanstack-form skill exists — forms go through the @vef-framework-react/components form wrapper (packages/components/src/form/*)