@amritk/helpers

中文文档
0.26.0发布于 2026/10/23MITTypeScriptES Module构建来源已验证近 30 天下载 6万

Shared utilities for the mjst code generation ecosystem.

原始使用文档
文档目录9 节
  1. Overview
  2. Installation
  3. Modules
  4. Schema traversal
  5. Codegen utilities
  6. Runtime helpers (also copied into generated output)
  7. Usage
  8. Related packages
  9. License

@amritk/helpers

Shared schema-traversal and runtime helpers for the mjst code generation ecosystem.

status  version  license  JSON Schema  node  vibe coded


Overview

@amritk/helpers is the shared utility belt used by mjst's generators and by the runtime code those generators produce. Each helper is published as its own subpath export so consumers (and generated output) only pull in what they need — no barrel, no incidental dependencies.


Installation

npm install @amritk/helpers
# or
pnpm add @amritk/helpers
# or
yarn add @amritk/helpers
# or
bun add @amritk/helpers

Modules

Schema traversal

SubpathExportsPurpose
@amritk/helpers/extract-refsextractRefsCollect every $ref reachable from a schema.
@amritk/helpers/resolve-refresolveRefResolve a $ref — JSON Pointer, $anchor name, or URI — against a root schema.
@amritk/helpers/build-anchor-mapbuildAnchorMapBuild a map of $anchor / $dynamicAnchor name → JSON Pointer.
@amritk/helpers/build-dynamic-ref-mapbuildDynamicRefMapBuild a map of $dynamicAnchor → resolved location.
@amritk/helpers/resolve-dynamic-refsresolveDynamicRefsReplace $dynamicRef occurrences using the map above.
@amritk/helpers/assert-id-scopesassertIdScopesReject a document whose $id-scoped fragment ref resolves to nothing in its own resource.
@amritk/helpers/max-schema-depthMAX_SCHEMA_DEPTH, assertSchemaDepthThe nesting cap every recursive walker enforces.
@amritk/helpers/upgrade-draft07-schemaupgradeDraft07Schema, isDraft07SchemaUpgrade a Draft-07 schema to 2020-12.
@amritk/helpers/ref-to-filenamerefToFilename, toKebabCaseConvert a $ref to a stable filename.
@amritk/helpers/ref-to-namerefToNameConvert a $ref to a TypeScript identifier (PascalCase).
@amritk/helpers/walk-ref-graphwalkRefGraph, RefNodeThe shared $ref-graph traversal every generator runs: upgrades draft-07, resolves each ref, rewrites $dynamicRef, derives type/file names, and hands one pre-computed node per output file to a visit callback.
@amritk/helpers/build-resource-registrybuildResourceRegistry, ResourceRegistryRead a document's $id base-URI scopes once, expressed as JSON Pointers.
@amritk/helpers/normalize-ref-scopesnormalizeRefScopesRewrite every $ref / $dynamicRef to a plain root-relative JSON Pointer, applying the $id bases in scope.
@amritk/helpers/resolve-scoped-refresolveScopedRef, ScopedRefTargetWhere a $ref lands once the $id bases in scope are applied.
@amritk/helpers/graft-external-schemasgraftExternalSchemas, GraftedSchemaFold already-loaded external documents into the document being generated so cross-document refs resolve like local ones.
@amritk/helpers/prune-external-schemaspruneExternalSchemasDrop the grafted documents nothing references.
@amritk/helpers/extract-dynamic-anchor-defsextractDynamicAnchorDefsCollect a #/... ref for every subschema carrying a $dynamicAnchor.
@amritk/helpers/fold-nullablefoldNullableRewrite OpenAPI 3.0 nullable: true into a null member of type.
@amritk/helpers/referenced-conditionalreferencedConditionalThe if/then definition an allOf member's local $ref points at, so the type emitter and the import collectors agree on what gets inlined.
@amritk/helpers/derive-root-type-namederiveRootTypeNameTurn a schema title into a PascalCase root type name.
@amritk/helpers/read-keyreadKey, declaresKeyRead an author-chosen name ($defs entry, config key) off a map, treating inherited names such as __proto__ as absent.
@amritk/helpers/assign-keyassignKeyAssign a key on a rebuilt object without letting __proto__ reach the prototype setter.
@amritk/helpers/schema-guardsisSchemaObject, hasType, hasProperties, hasOneOf, hasAnyOf, hasAllOf, hasEnum, hasConst, hasPattern, hasFormat, hasDefault, hasExamples, hasRequired, hasItems, hasAdditionalProperties, hasMinLength, hasMaxLength, hasMinimum, hasMaximum, hasExclusiveMinimum, hasExclusiveMaximum, hasMultipleOf, hasMinItems, hasMaxItems, hasUniqueItems, hasMinProperties, hasMaxProperties, …Type-narrowing predicates for JSON Schema keywords.

Codegen utilities

SubpathExportsPurpose
@amritk/helpers/generate-type-definitiongenerateTypeDefinitionRender a TypeScript type from a schema node.
@amritk/helpers/mjst-extensionMJST_EXTENSION_KEY, MjstExtension, hasMjstHint, getMjstInstanceOf, getMjstPrimitive, getMjstBrand, getMjstDiscriminatorRead the x-mjst vendor hints (instanceOf, primitive, brand) a schema carries, and the message discriminator an AsyncAPI channel names.
@amritk/helpers/generate-index-barrelgenerateIndexBarrelRender the index.ts barrel that re-exports every generated file. A name starting with _ is for sibling files only and is left out.
@amritk/helpers/identifier-mentionsidentifierMentionsAsk whether emitted source names an identifier, ignoring comments, strings, and regex literals — decides which $ref imports a generated file keeps.
@amritk/helpers/get-default-valuegetDefaultValueThe fallback value (as source text) a parser or repairing validator substitutes for missing data: default > const > first enum > first usable examples entry > first union branch > pattern > type. default and examples are used only when they match the declared type.
@amritk/helpers/generate-default-from-patterngenerateDefaultFromPatternBuild a fallback string that is guaranteed to match a pattern (and length bounds), or null.
@amritk/helpers/unknown-keys-strategyUnknownKeysStrategy, UNKNOWN_KEYS_STRATEGIES, DEFAULT_UNKNOWN_KEYS, isUnknownKeysStrategyHow a generated fast path proves a closed object has no extra key: 'count-keys' (default) or 'count-enumerable'.
@amritk/helpers/escape-regex-patternescapeRegexPattern, regexFlagsFor, regexLiteralEmbed a JSON Schema pattern in a generated regex literal, validating it at generation time.
@amritk/helpers/quote-js-stringquoteJsStringQuote a string as a JS literal, escaping only when needed.
@amritk/helpers/multiple-of-checkmultipleOfPassExpr, multipleOfFailExprEmit a multipleOf check that agrees with the runtime interpreter.
@amritk/helpers/numeric-bound-checkboundPassExpr, boundFailExpr, boundOperatorEmit minimum / maximum / exclusive* checks that agree with the runtime interpreter.
@amritk/helpers/string-length-checkminLengthPassExpr, maxLengthPassExpr, …Emit minLength / maxLength checks that count code points, not UTF-16 units.
@amritk/helpers/unknown-key-checkunknownKeyCheck, INLINE_KEY_LIMITEmit an unknown-key sweep — inline comparisons for small key sets, a hoisted Set past the limit.
@amritk/helpers/parse-documentationparseDocumentation, ObjectDocumentationParse one section of the OpenAPI specification markdown (selected by a commentUrl fragment such as #info-object) into a title, description, and per-property descriptions.
@amritk/helpers/safe-accessorsafeAccessor, hasOwnCheck, missingCheck, safeKeyEmit a safe JS property-access expression (dot vs bracket notation, own-property guard for Object.prototype names).

Runtime helpers (also copied into generated output)

SubpathExportsPurpose
@amritk/helpers/coercion-runtimecoerceScalar, coerceUnion, valuesEqual, allUnique, everyItem, escapePointerThe validator's coercion and matching runtime, byte-identical to the copy in a validator build's validation-result.ts, for a coercing parser that has to agree with coerceX.
@amritk/helpers/is-objectisObjectNarrow unknown → Record<string, unknown>.
@amritk/helpers/has-refhasRefNarrow a value to an object carrying a string $ref.
@amritk/helpers/validate-arrayvalidateArrayValidate array shape and items.
@amritk/helpers/validate-recordvalidateRecordValidate record shape and additional properties.

Usage

import { resolveRef } from '@amritk/helpers/resolve-ref'
import { isObjectSchema, hasProperties } from '@amritk/helpers/schema-guards'

const node = resolveRef('#/$defs/info', rootSchema)

if (isObjectSchema(node) && hasProperties(node)) {
  for (const [name, property] of Object.entries(node.properties)) {
    // ...
  }
}

Most helpers have a colocated test file (*.test.ts) — read those for canonical examples.



License

MIT

版本与发布记录

@amritk/helpers 共发布 45 个版本,首次发布于 2026/05/12;过去 12 个月发布了 45 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.26.0latest2026/10/2314 天前
0.25.02026/10/1027 天前
0.24.02026/09/261 个月前
0.23.32026/09/241 个月前
0.23.22026/09/231 个月前
0.23.12026/09/221 个月前

关于 @amritk/helpers 的常见问题

@amritk/helpers 是什么?

Shared utilities for the mjst code generation ecosystem.

如何安装 @amritk/helpers?

在项目目录运行 npm install @amritk/helpers,或使用 pnpm add / yarn add / bun add。

@amritk/helpers 支持 TypeScript 吗?

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

@amritk/helpers 支持 ESM 还是 CommonJS?

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

@amritk/helpers 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@amritk/helpers 可以商用吗?

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

@amritk/helpers 的下载量有多少?

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

@amritk/helpers 还在维护吗?

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