@happyvertical/smrt-fields

中文文档
0.62.1发布于 2026/11/17MITTypeScriptES Module近 30 天下载 1.5万

Layered field policy store and resolver (defaults, visibility tiers, help text) for SMRT objects

原始使用文档
文档目录9 节
  1. Install
  2. Define a safe code seed
  3. Resolve on the server
  4. Use policy-aware Svelte forms
  5. Administration and personal settings
  6. Important behavior
  7. Usage learning
  8. Feature recipe
  9. Example application

@happyvertical/smrt-fields

@happyvertical/smrt-fields lets an application adjust an object's form defaults, labels, help, order, visibility, and locks without changing the object's source. Policies layer organization and personal choices over the code-authored field definition.

For the complete application and operator guide, see the field policy guide.

Install

pnpm add @happyvertical/smrt-fields

The package includes @happyvertical/smrt-users because policy writes and operator actions use its permission and tenant context services.

Define a safe code seed

The decorated model remains the definition of a field. Use its description and ui hints to supply a useful first form before any policy row exists.

import { field, SmrtObject, smrt } from '@happyvertical/smrt-core';

@smrt({ packageName: '@acme/billing' })
export class Invoice extends SmrtObject {
  @field({
    required: true,
    description: 'Shown on the customer invoice.',
    ui: { basic: true, group: 'billing', order: 1 },
  })
  title = '';

  @field({ ui: { basic: false, group: 'billing', order: 2 } })
  internalNotes = '';
}

If no field has ui.basic: true, fields start in the basic view. Once at least one field is marked basic, unmarked fields start advanced. group and order are code-owned hints; locked: true seeds a lock that can prevent a personal override. widget ('textarea' | 'currency' | 'email' | 'url' | 'phone') is a presentation hint for the input, validated against the field type at build time (every widget needs a text field; currency picks an ISO 4217 code such as 'USD', it is not for money amounts).

Resolve on the server

Use the resolver in trusted server code when rendering SSR or applying a server-owned workflow. It merges code → app → tenant ancestry → user.

import { resolveFieldPolicy } from '@happyvertical/smrt-fields';

const policy = await resolveFieldPolicy(
  '@acme/billing:Invoice',
  { tenantId: requestTenant.id, userId: session.user.id, db },
);

const title = policy.fields.title;

The client-facing generated resolveBatch action derives the tenant and user from the authenticated request context. Do not accept those identifiers from a browser request. It returns only fields that are safe to expose; sensitive, transient, and read-permission-gated fields are omitted.

Use policy-aware Svelte forms

For a custom form, provide a resolved policy with FieldPolicyProvider and wrap each input in PolicyField. The wrapper applies visibility, labels, help, and new-record defaults while preserving your markup and input component.

<script lang="ts">
  import {
    FieldPolicyProvider,
    PolicyField,
  } from '@happyvertical/smrt-fields/svelte';

  let { policy, invoice = $bindable({}) } = $props();
</script>

<FieldPolicyProvider {policy}>
  <PolicyField name="title">
    <input id="title" bind:value={invoice.title} />
  </PolicyField>
</FieldPolicyProvider>

For generated forms, register the application's generated collection definitions once in an ObjectFormSourceRegistry, place it in an ObjectFormSourceProvider, then render an ObjectForm by canonical objectRef. The registry validates both the generated field definition and the resolveBatch response before rendering. See the guide for the complete setup, including field-specific input renderers and policy-aware tables.

Administration and personal settings

Use FieldPolicyGearProvider with an adapter to the generated getEditorState, create, update, and delete actions. It derives identity on the server; adapter methods intentionally do not accept tenant or user ids. Use FieldPolicyGearButton or showPolicyGear on ObjectForm to expose the editor.

For a settings destination, the server builds data with buildFieldPolicySettingsCatalog() and the browser renders it through FieldPolicyControlPanel. Hosts supply route, transport, confirmation, and AdminShell adapters. fieldPolicyControlPanelNavItem() and registerFieldPolicyFocusTool() are structural seams, so Fields does not take a dependency on a particular application shell.

fields.policy.manage permits app and tenant administration. fields.policy.personalize permits only the current user's personal choices. The host must still establish a trusted authenticated principal context and enforce the route permission before rendering an operator destination.

Important behavior

  • A policy row is sparse: null means inherit the lower layer. Delete a row to reset that scope completely.
  • defaultValue is the JSON-encoded wire channel. Server code with a plain value should use defaultValueRaw or setDefaultValue().
  • Required fields cannot be hidden or moved to advanced without a usable resolved default. Resolution forces a required, default-less field back to basic as a safety net.
  • App and tenant rows may lock a field. While the resolved organization policy is locked, personal writes are rejected and old personal rows do not apply.
  • Defaults are rejected for sensitive, transient, and read-permission-gated fields. Reference defaults must use a valid UUID unless that reference declares a text id type.

Usage learning

Optional usage capture records bounded, aggregated submissions from authenticated tenant members and turns qualified patterns into administrator-reviewed tenant-policy suggestions. It never auto-applies a suggestion. ObjectForm reports only after its host confirms persistence; browser values transit only for low-cardinality boolean and reference fields, and telemetry failures never affect the saved submit.

Operators enable the dormant maintenance and suggestion schedules explicitly with ensureFieldUsageLearningSchedules({ db }). The learning loop retains aggregates and uses conservative thresholds; its accepted/dismissed suggestion queue is restricted to fields.policy.manage. See the field policy guide for the capture, privacy, retention, and schedule contract.

Feature recipe

The package declares one feature recipe, fields.form-customization (FormCustomizationRecipe), with end-user help in src/form-customization.recipe.md. Its management screen is the settings-panel surface @happyvertical/smrt-fields/svelte#FieldPolicyControlPanel; the host still supplies the settings catalog shell and the generated-client adapter described above. The recipe declares runtime: 'server': the package root entry still imports node-only helpers (#3618), while the /svelte components only render a policy that was resolved on the server.

Example application

The field-policy walkthrough in the now-archived smrt-saas-starter (pinned pull request, s-m-r-t 0.40.61) showed the owner/admin controls and the member-facing personal form flow in a working application. smrt-start is the current template.

版本与发布记录

@happyvertical/smrt-fields 共发布 220 个版本,首次发布于 2026/08/06;过去 12 个月发布了 220 个版本。

版本发布日期距今
0.62.1latest2026/11/17今天
0.62.02026/11/17今天
0.61.62026/11/161 天前
0.61.52026/11/161 天前
0.61.42026/11/161 天前
0.61.32026/11/152 天前

关于 @happyvertical/smrt-fields 的常见问题

@happyvertical/smrt-fields 是什么?

Layered field policy store and resolver (defaults, visibility tiers, help text) for SMRT objects

如何安装 @happyvertical/smrt-fields?

在项目目录运行 npm install @happyvertical/smrt-fields,或使用 pnpm add / yarn add / bun add。

@happyvertical/smrt-fields 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@happyvertical/smrt-fields 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@happyvertical/smrt-fields 可以商用吗?

@happyvertical/smrt-fields 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@happyvertical/smrt-fields 的下载量有多少?

根据 npm 官方下载统计,@happyvertical/smrt-fields 在 2026/10/17 – 2026/11/15 这 30 天内被下载 14,705 次,日均约 490 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@happyvertical/smrt-fields 还在维护吗?

最新版本 0.62.1 发布于 2026/11/17(今天);至今共发布 220 个版本,其中过去 12 个月发布了 220 个;首次发布于 2026/08/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。