Skip to content

API Reference

All public exports from ts-archunit, organized by category.

Entry Points

ExportSignatureDescription
projectproject(tsConfigPath: string): ArchProjectLoad a TypeScript project. Cached per path.
modulesmodules(p: ArchProject): ModuleRuleBuilderRule builder for source files (imports/dependencies).
classesclasses(p: ArchProject): ClassRuleBuilderRule builder for class declarations.
functionsfunctions(p: ArchProject): FunctionRuleBuilderRule builder for functions, arrow functions, class methods.
typestypes(p: ArchProject): TypeRuleBuilderRule builder for interfaces and type aliases.
slicesslices(p: ArchProject): SliceRuleBuilderRule builder for file groupings (cycles, layers).
callscalls(p: ArchProject): CallRuleBuilderRule builder for call expressions.
withinwithin(sel: CallRuleBuilder): ScopedContextScoped rule builder for callback functions inside matched calls.

Rule Builders

ExportDescription
RuleBuilderBase rule builder class.
TerminalBuilderBase terminal builder class (slices, smells, cross-layer).
ModuleRuleBuilderBuilder returned by modules().
ClassRuleBuilderBuilder returned by classes().
FunctionRuleBuilderBuilder returned by functions().
TypeRuleBuilderBuilder returned by types().
SliceRuleBuilderBuilder returned by slices().
CallRuleBuilderBuilder returned by calls().
ScopedFunctionRuleBuilderBuilder returned by within().functions().

Rule Builder Methods

Chain methods available on all rule builders (RuleBuilder, SliceRuleBuilder).

MethodSignatureDescription
.excluding().excluding(...patterns: (string | RegExp)[])Permanently suppress violations matching element name (e.g., 'MyService.doWork'), file path, or message. Strings use exact match; regex uses .test(). Warns on unused patterns.
.because().because(reason: string)Attach a human-readable rationale to the rule.
.rule().rule(metadata: RuleMetadata)Attach rich metadata (id, because, suggestion, docs).
.check().check(options?: CheckOptions)Execute rule; throw on violations.
.warn().warn(options?: CheckOptions)Execute rule; log violations without throwing.
.severity().severity(level: 'error' | 'warn')Execute with the given severity.
.violations().violations(): ArchViolation[]Execute rule, return violations without throwing. For programmatic access and presets.
.describeRule().describeRule(): RuleDescriptionReturn rule metadata without executing. Used by explain command.

Exclusion Comments

ExportSignatureDescription
parseExclusionCommentsparseExclusionComments(source: string, file: string): ParseResultParse // ts-archunit-exclude comments from source text.
isExcludedByCommentisExcludedByComment(violation: ArchViolation, comments: ExclusionComment[]): booleanCheck if a violation is covered by an exclusion comment.

Types

ExportKindDescription
ExclusionCommenttypeParsed exclusion comment with ruleId, reason, file, line, isBlock, endLine.
ExclusionWarningtypeWarning about a malformed exclusion comment.
ParseResulttypeResult of parsing: { exclusions, warnings }.

Identity Predicates

Available on all entry points via .that().

ExportSignatureDescription
haveNameMatchinghaveNameMatching(re: RegExp)Name matches regex.
haveNameStartingWithhaveNameStartingWith(s: string)Name starts with string.
haveNameEndingWithhaveNameEndingWith(s: string)Name ends with string.
resideInFileresideInFile(glob: string)File path matches glob.
resideInFolderresideInFolder(glob: string)Folder path matches glob.
areExportedareExportedElement is exported.
areNotExportedareNotExportedElement is not exported.

Module Predicates

ExportSignatureDescription
importFromimportFrom(...globs) or importFrom(globs[], options)Module imports from files matching glob. Options: { ignoreTypeImports }.
predicateNotImportFromnotImportFrom(...globs) or notImportFrom(globs[], options)Module does not import from files matching glob. Options: { ignoreTypeImports }.
exportSymbolNamedexportSymbolNamed(name: string)Module exports a symbol with the name.
havePathMatchinghavePathMatching(re: RegExp)Module file path matches regex.

Class Predicates

ExportSignatureDescription
extendextend(name: string)Class extends the named base class.
implementimplement(name: string)Class implements the named interface.
haveDecoratorhaveDecorator(name: string)Class has the named decorator.
haveDecoratorMatchinghaveDecoratorMatching(re: RegExp)Class has a decorator matching regex.
areAbstractareAbstractClass is abstract.
classHaveMethodNamedhaveMethodNamed(name: string)Class has a method with the name.
haveMethodMatchinghaveMethodMatching(re: RegExp)Class has a method matching regex.
havePropertyNamedhavePropertyNamed(name: string)Class has a property with the name.

Function Predicates

ExportSignatureDescription
areAsyncareAsyncFunction is async.
areNotAsyncareNotAsyncFunction is not async.
arePublicarePublic()Function/method is public (standalone always match).
areProtectedareProtected()Method is protected.
arePrivatearePrivate()Method is private.
haveParameterCounthaveParameterCount(n: number)Function has exactly n parameters.
haveParameterCountGreaterThanhaveParameterCountGreaterThan(n: number)Function has more than n parameters.
haveParameterCountLessThanhaveParameterCountLessThan(n: number)Function has fewer than n parameters.
haveParameterNamedhaveParameterNamed(name: string)Function has a parameter with the name.
haveReturnTypehaveReturnType(type: string)Function has the given return type.
haveRestParameterhaveRestParameter()Function has a ...args rest parameter.
haveOptionalParameterhaveOptionalParameter()Function has an optional or default-valued parameter.
haveParameterOfTypehaveParameterOfType(i: number, m: TypeMatcher)Parameter at index i matches the TypeMatcher.
haveParameterNameMatchinghaveParameterNameMatching(re: RegExp)Function has a parameter name matching regex.

Type Predicates

ExportSignatureDescription
areInterfacesareInterfacesType is an interface.
areTypeAliasesareTypeAliasesType is a type alias.
havePropertyhaveProperty(name: string)Type has a property with the name.
havePropertyOfTypehavePropertyOfType(name: string, re: RegExp)Property exists with type matching regex.
extendTypeextendType(name: string)Interface extends the named type.

Call Predicates

ExportSignatureDescription
onObjectonObject(name: string)Call is on the named object (e.g., app). Supports nested: router.route.
withMethodwithMethod(nameOrRegex: string | RegExp)Call method matches exact name or regex pattern.
withArgMatchingwithArgMatching(index: number, pattern: string | RegExp)Argument at index matches regex or exact string.
withStringArgwithStringArg(index: number, glob: string)String literal argument at index matches glob pattern.

Structural Conditions

ExportSignatureDescription
notExistnotExist()No elements should match the predicates.
beExportedbeExported()All matched elements should be exported.
conditionResideInFileresideInFile(glob: string)All elements should reside in matching files.
conditionResideInFolderresideInFolder(glob: string)All elements should reside in matching folders.
conditionHaveNameMatchinghaveNameMatching(re: RegExp)All elements should have names matching regex.

Class Conditions

ExportSignatureDescription
shouldExtendshouldExtend(name: string)Class must extend the named base class.
shouldImplementshouldImplement(name: string)Class must implement the named interface.
shouldHaveMethodNamedshouldHaveMethodNamed(name: string)Class must have a method with the name.
shouldNotHaveMethodMatchingshouldNotHaveMethodMatching(re: RegExp)Class must not have methods matching regex.
classAcceptParameterOfTypeacceptParameterOfType(matcher: TypeMatcher)At least one param (ctor/method/setter) matches type.
classNotAcceptParameterOfTypenotAcceptParameterOfType(matcher: TypeMatcher)No param (ctor/method/setter) matches type.

Function Conditions

ExportSignatureDescription
functionNotExistnotExist()No functions should match.
functionBeExportedbeExported()Function must be exported.
functionBeAsyncbeAsync()Function must be async.
functionHaveNameMatchinghaveNameMatching(re: RegExp)Function name must match regex.
functionHaveReturnTypeMatchinghaveReturnTypeMatching(matcher: TypeMatcher)Return type must satisfy TypeMatcher.
functionAcceptParameterOfTypeacceptParameterOfType(matcher: TypeMatcher)At least one parameter matches TypeMatcher.
functionNotAcceptParameterOfTypenotAcceptParameterOfType(matcher: TypeMatcher)No parameter matches TypeMatcher.

Dependency Conditions

ExportSignatureDescription
onlyImportFromonlyImportFrom(...globs) or (globs[], options)Module may only import from listed paths. Options: { ignoreTypeImports }.
conditionNotImportFromnotImportFrom(...globs) or (globs[], options)Module must not import from listed paths. Options: { ignoreTypeImports }.
onlyHaveTypeImportsFromonlyHaveTypeImportsFrom(...globs: string[])Imports from matching paths must use import type.
notHaveAliasedImportsnotHaveAliasedImports()No named import may use an alias (import { x as y }).

Body Analysis Matchers

ExportSignatureDescription
callcall(target: string | RegExp)Match function/method call expressions.
newExprnewExpr(target: string | RegExp)Match constructor invocations (new ...).
accessaccess(target: string | RegExp)Match property access expressions.
propertyproperty(name: string | RegExp, value?: boolean | number | string | RegExp)Match property assignments by name and optional value.
expressionexpression(target: string | RegExp)Match any expression by text.

Body Analysis Conditions

ExportSignatureDescription
classContainclassContain(matcher: ExpressionMatcher)Class methods must contain expression.
classNotContainclassNotContain(matcher: ExpressionMatcher)Class methods must not contain expression.
classUseInsteadOfclassUseInsteadOf(banned, replacement)Ban expression in class, suggest replacement.
functionContainfunctionContain(matcher: ExpressionMatcher)Function body must contain expression.
functionNotContainfunctionNotContain(matcher: ExpressionMatcher)Function body must not contain expression.
functionUseInsteadOffunctionUseInsteadOf(banned, replacement)Ban expression in function, suggest replacement.
functionNotHaveEmptyBodyfunctionNotHaveEmptyBody()Function must have at least one statement.
classNotHaveEmptyBodyclassNotHaveEmptyBody()Class must have at least one member.
moduleContainmoduleContain(matcher, options?)Module must contain expression.
moduleNotContainmoduleNotContain(matcher, options?)Module must not contain expression.
moduleUseInsteadOfmoduleUseInsteadOf(banned, replacement, opts?)Ban expression in module, suggest replacement.

Export Conditions

ExportSignatureDescription
notHaveDefaultExportnotHaveDefaultExport()Module must not have a default export.
haveDefaultExporthaveDefaultExport()Module must have a default export.
haveMaxExportshaveMaxExports(max: number)Module must have at most max named exports.

Reverse Dependency Conditions

ExportSignatureDescription
onlyBeImportedViaonlyBeImportedVia(...globs)All importers must match at least one glob.
beImportedbeImported()Module must be imported by at least one other file.
haveNoUnusedExportshaveNoUnusedExports()Every named export must be referenced by another file.

Property Conditions

ExportSignatureDescription
conditionHavePropertyNamedhavePropertyNamed(...names: string[])All named properties must exist.
conditionNotHavePropertyNamednotHavePropertyNamed(...names: string[])None of the named properties may exist.
conditionHavePropertyMatchinghavePropertyMatching(pattern: RegExp)At least one property name matches regex.
conditionNotHavePropertyMatchingnotHavePropertyMatching(pattern: RegExp)No property name matches regex.
haveOnlyReadonlyPropertieshaveOnlyReadonlyProperties()All properties must be readonly.
maxPropertiesmaxProperties(max: number)Property count must not exceed max.

Type-Level Conditions

ExportSignatureDescription
havePropertyTypehavePropertyType(name: string, matcher: TypeMatcher)Property must match the type matcher.

Type Matchers

ExportSignatureDescription
isStringisString(): TypeMatcherType is string.
isNumberisNumber(): TypeMatcherType is number.
isBooleanisBoolean(): TypeMatcherType is boolean.
isUnionOfLiteralsisUnionOfLiterals(): TypeMatcherType is a union of literal types.
isStringLiteralisStringLiteral(): TypeMatcherType is a string literal.
arrayOfarrayOf(matcher: TypeMatcher): TypeMatcherType is an array whose element matches.
matchingmatching(re: RegExp): TypeMatcherType text matches regex.
exactlyexactly(text: string): TypeMatcherType text matches exactly.

Slice Conditions

ExportSignatureDescription
beFreeOfCyclesbeFreeOfCycles()No circular dependencies between slices.
respectLayerOrderrespectLayerOrder(...layers: string[])Dependencies follow declared layer order.
notDependOnnotDependOn(slice: string)No slice depends on the named slice.

Call Conditions

ExportSignatureDescription
callHaveCallbackContaininghaveCallbackContaining(matcher: ExpressionMatcher)At least one callback argument must contain the matched expression.
callNotHaveCallbackContainingnotHaveCallbackContaining(matcher: ExpressionMatcher)No callback argument may contain the matched expression.
callNotExistnotExist()The filtered call set must be empty.
haveArgumentWithPropertyhaveArgumentWithProperty(...names: string[])At least one object literal arg has ALL named properties.
notHaveArgumentWithPropertynotHaveArgumentWithProperty(...names: string[])No object literal arg has ANY of the named properties.
callHaveArgumentContaininghaveArgumentContaining(matcher: ExpressionMatcher)At least one argument subtree must contain the matched expression.
callNotHaveArgumentContainingnotHaveArgumentContaining(matcher: ExpressionMatcher)No argument subtree may contain the matched expression.

See Call Rules for usage examples.

Pattern Templates

ExportSignatureDescription
definePatterndefinePattern(name: string, opts: { returnShape: Record<string, PropertyConstraint> }): ArchPatternDefine a return type shape pattern.
followPatternfollowPattern(pattern: ArchPattern): Condition<ArchFunction>Condition: function return type must match the pattern. Unwraps Promise<T>.
PropertyConstraintstring | TypeMatcherstring = regex on type text, 'T[]' = any array, TypeMatcher = programmatic.
ArchPatterntypePattern with name and returnShape.

See Pattern Templates for usage examples.

Smell Detectors

ExportSignatureDescription
smells.duplicateBodiessmells.duplicateBodies(p: ArchProject): DuplicateBodiesBuilderDetect functions with structurally similar AST bodies.
smells.inconsistentSiblingssmells.inconsistentSiblings(p: ArchProject): InconsistentSiblingsBuilderDetect sibling files missing a majority pattern.
SmellBuilderclassBase builder: inFolder, minLines, ignoreTests, ignorePaths, groupByFolder, because, warn, check.
DuplicateBodiesBuilderclassExtends SmellBuilder. Adds withMinSimilarity(n).
InconsistentSiblingsBuilderclassExtends SmellBuilder. Adds forPattern(matcher).
buildFingerprintbuildFingerprint(node: Node): FingerprintBuild an AST fingerprint (kinds, calls, nodeCount) from a body node.
computeSimilaritycomputeSimilarity(a: Fingerprint, b: Fingerprint): numberLCS-based similarity between two fingerprints, normalized to [0,1].

See Smell Detection for usage examples.

Cross-Layer Validation

ExportSignatureDescription
crossLayercrossLayer(p: ArchProject): CrossLayerBuilderEntry point for cross-layer consistency rules.
CrossLayerBuilderclassBuilder: .layer(name, glob) (2+ required) then .mapping(fn).
MappedCrossLayerBuilderclassAfter .mapping(): provides .forEachPair().
PairConditionBuilderclassAfter .forEachPair(): provides .should(condition).
PairFinalBuilderclassTerminal: .because(), .rule(), .check(), .warn(), .severity().
haveMatchingCounterparthaveMatchingCounterpart(layers: Layer[]): PairConditionEvery left-layer file must have a counterpart in the right layer.
haveConsistentExportshaveConsistentExports(extractLeft, extractRight): PairConditionEvery exported symbol in left file must appear in right file.
satisfyPairConditionsatisfyPairCondition(desc: string, fn: (pair: LayerPair) => Violation | null): PairConditionCustom inline pair condition.

See Cross-Layer Validation for usage examples.

Extension API

ExportSignatureDescription
definePredicatedefinePredicate<T>(desc, fn): Predicate<T>Create a custom predicate.
defineConditiondefineCondition<T>(desc, fn): Condition<T>Create a custom condition.
andand(...inputs): Predicate | TypeMatcherCombine with AND. Accepts predicates or type matchers.
oror(...inputs): Predicate | TypeMatcherCombine with OR. Accepts predicates or type matchers.
notnot(input): Predicate | TypeMatcherNegate. Accepts a predicate or type matcher.

Utilities

ExportSignatureDescription
createViolationcreateViolation(node, msg, ctx): ArchViolationCreate a violation from a ts-morph node.
getElementNamegetElementName(node): stringGet the name of a ts-morph node.
getElementFilegetElementFile(node): stringGet the file path of a ts-morph node.
getElementLinegetElementLine(node): numberGet the line number of a ts-morph node.
generateCodeFramegenerateCodeFrame(source, line, opts?): stringGenerate a code frame snippet.
formatViolationsformatViolations(violations, opts?): stringFormat violations for terminal output.
formatViolationsPlainformatViolationsPlain(violations): stringFormat violations as plain text.
formatViolationsJsonformatViolationsJson(violations): stringFormat violations as JSON.
formatViolationsGitHubformatViolationsGitHub(violations): stringFormat violations as GitHub Actions annotations.
detectFormatdetectFormat(): OutputFormatAuto-detect output format from environment.
isCIisCI(): booleanTrue if running in a CI environment.
ArchRuleErrorclassError thrown by .check() on violations.
isTypeOnlyImportisTypeOnlyImport(decl: ImportDeclaration): booleanCheck if an import is purely type-only.

Check Options

ExportSignatureDescription
withBaselinewithBaseline(path: string): BaselineLoad a baseline file for gradual adoption.
generateBaselinegenerateBaseline(violations, path): voidWrite a baseline file from current violations.
collectViolationscollectViolations(...rules): ArchViolation[]Collect violations from multiple rules.
diffAwarediffAware(base: string): DiffFilterOnly report violations in changed files.
BaselineclassBaseline instance for filtering known violations.
DiffFilterclassDiff filter instance.

ArchFunction Model

ExportSignatureDescription
collectFunctionscollectFunctions(sourceFiles): ArchFunction[]Collect all functions from source files.
fromFunctionDeclarationfromFunctionDeclaration(node): ArchFunctionWrap a function declaration.
fromArrowVariableDeclarationfromArrowVariableDeclaration(node): ArchFunctionWrap an arrow function variable.
fromMethodDeclarationfromMethodDeclaration(node): ArchFunctionWrap a class method declaration.

Callback Extraction

ExportSignatureDescription
extractCallbacksextractCallbacks(calls): ExtractedCallback[]Extract callback functions from call expressions.

Scoped Rules

ExportSignatureDescription
withinwithin(sel): ScopedContextCreate scoped rules from call selections.
ScopedFunctionRuleBuilderclassBuilder for function rules within a scope.

Metrics

ExportSignatureDescription
cyclomaticComplexitycyclomaticComplexity(body: Node | undefined): numberCalculate McCabe cyclomatic complexity for a function body.
linesOfCodelinesOfCode(node: Node): numberCount span lines (start to end, inclusive).
haveCyclomaticComplexityhaveCyclomaticComplexity(opts): Predicate<ClassDeclaration>Predicate: class has a method with complexity > threshold.
haveComplexityhaveComplexity(opts): Predicate<ArchFunction>Predicate: function has complexity > threshold.
haveMoreLinesThanhaveMoreLinesThan(n): Predicate<ClassDeclaration>Predicate: class spans more than n lines.
haveMoreFunctionLinesThanhaveMoreFunctionLinesThan(n): Predicate<ArchFunction>Predicate: function spans more than n lines.
haveMoreMethodsThanhaveMoreMethodsThan(n): Predicate<ClassDeclaration>Predicate: class has more than n methods.

CLI

ExportSignatureDescription
defineConfigdefineConfig(config: CliConfig): CliConfigDefine CLI configuration file.
resetProjectCacheresetProjectCache(): voidClear the project singleton cache. Used by watch mode and tests.

Types (TypeScript)

ExportKindDescription
ArchProjecttypeLoaded TypeScript project.
PredicatetypePredicate interface.
ConditiontypeCondition interface.
ConditionContexttypeContext passed to condition evaluators.
ArchViolationtypeViolation model.
RuleMetadatatypeRule metadata (id, because, suggestion, docs).
RuleDescriptiontypeStructured rule description returned by .describeRule().
CheckOptionstypeOptions for .check().
OutputFormattypeOutput format ('terminal' | 'github' | 'json').
FormatOptionstypeOptions for formatting functions.
CodeFrameOptionstypeOptions for generateCodeFrame().
ExpressionMatchertypeMatcher returned by call(), newExpr(), etc.
TypeMatchertypeMatcher used with havePropertyType().
TypeDeclarationtypeUnion of interface and type alias declarations.
ArchFunctiontypeUnified function/arrow/method model.
ArchCalltypeModel for matched call expressions.
SlicetypeA named group of source files.
SliceDefinitiontypeInput to assignedFrom().
NamedtypeElement with a name.
LocatedtypeElement with a file location.
ExportabletypeElement that can be exported.
BaselineEntrytypeSingle entry in a baseline file.
BaselineFiletypeStructure of the baseline JSON file.
LayertypeLayer definition for cross-layer validation.
LayerPairtypePair of elements from two layers.
PairConditiontypeCondition for cross-layer pairs.
ArchPatterntypePattern template definition.
PropertyConstrainttypeProperty type constraint in a pattern.
FingerprinttypeAST fingerprint for similarity detection.
ScopedContexttypeContext returned by within().
ExtractedCallbacktypeCallback extracted from a call expression.
PropertyBearingNodetypeUnion of interface, type alias, and class declarations.
ImportOptionstypeOptions for import conditions/predicates ({ ignoreTypeImports }).
CliConfigtypeCLI configuration object.

GraphQL Extension (ts-archunit/graphql)

Requires the optional graphql peer dependency.

Entry Points

ExportSignatureDescription
schemaschema(p: ArchProject | string, glob: string): SchemaRuleBuilderRule builder for .graphql schema files.
schemaFromSDLschemaFromSDL(sdl: string, path?): SchemaRuleBuilderRule builder from raw SDL string.
resolversresolvers(p: ArchProject, glob: string): ResolverRuleBuilderRule builder for resolver TypeScript files.

Schema Predicates

ExportSignatureDescription
queriesqueriesSelect Query type fields.
mutationsmutationsSelect Mutation type fields.
typesNamedtypesNamed(re: RegExp)Select types matching regex.
returnListOfreturnListOf(re: RegExp)Select fields returning a list of matching type.

Schema Conditions

ExportSignatureDescription
haveFieldshaveFields(...names: string[])Type must have the named fields.
acceptArgsacceptArgs(...names: string[])Field must accept the named arguments.
haveMatchingResolverhaveMatchingResolver(resolverGlob: string)Schema field has a matching resolver file.

Resolver Predicates

ExportSignatureDescription
resolveFieldReturningresolveFieldReturning(re: RegExp)Resolver resolves a field returning matching type.

Schema Loader

ExportSignatureDescription
loadSchemaFromGlobloadSchemaFromGlob(root, glob): LoadedSchemaLoad schema from glob pattern.
loadSchemaFromSDLloadSchemaFromSDL(sdl, path?): LoadedSchemaLoad schema from SDL string.
isGraphQLAvailableisGraphQLAvailable(): booleanCheck if the graphql package is installed.

Builders

ExportDescription
SchemaRuleBuilderBuilder for schema architecture rules.
ResolverRuleBuilderBuilder for resolver architecture rules.

Types

ExportKindDescription
SchemaElementtypeElement in a GraphQL schema.
LoadedSchematypeLoaded and parsed GraphQL schema.
GraphQLSchemaLiketypeSchema interface.
GraphQLObjectTypeLiketypeObject type interface.
GraphQLFieldLiketypeField interface.
GraphQLArgumentLiketypeArgument interface.
GraphQLTypeLiketypeType interface.

Presets (ts-archunit/presets)

Parameterized architecture rule bundles that generate multiple coordinated rules from a single function call.

ExportSignatureDescription
layeredArchitecturelayeredArchitecture(p, options): voidLayer ordering, cycles, isolation, restricted packages.
dataLayerIsolationdataLayerIsolation(p, options): voidBase class extension and typed error enforcement.
strictBoundariesstrictBoundaries(p, options): voidNo cycles, no cross-boundary imports, shared isolation.
dispatchRuledispatchRule(builder, ruleId, severity, overrides): V[]Run a single rule within a preset with severity control.
throwIfViolationsthrowIfViolations(violations): voidThrow aggregated ArchRuleError if violations exist.
validateOverridesvalidateOverrides(overrides, knownIds): voidWarn on unrecognized override keys.

See Architecture Presets for full configuration options.

Standard Rules (Sub-Path Imports)

ts-archunit/rules/typescript

ExportDescription
noAnyProperties()Class properties must not be typed as any.
noTypeAssertions()Method bodies must not contain as type assertions (allows as const).
noNonNullAssertions()Method bodies must not contain non-null assertions (!).

ts-archunit/rules/security

ExportTargetDescription
noEval()classesNo eval() calls in class methods.
noFunctionConstructor()classesNo new Function() constructor.
noConsoleLog()classesNo console.log calls.
noProcessEnv()classesNo direct process.env access.
noConsole()classesNo console access at all (log, warn, error, etc).
noJsonParse()classesNo JSON.parse calls.
functionNoEval()functionsNo eval() calls in functions.
functionNoFunctionConstructor()functionsNo new Function() in functions.
functionNoProcessEnv()functionsNo process.env access in functions.
functionNoConsoleLog()functionsNo console.log in functions.
functionNoConsole()functionsNo console access in functions.
functionNoJsonParse()functionsNo JSON.parse in functions.
moduleNoEval()modulesNo eval() anywhere in module.
moduleNoProcessEnv()modulesNo process.env anywhere in module.
moduleNoConsoleLog()modulesNo console.log anywhere in module.

ts-archunit/rules/errors

ExportTargetDescription
noGenericErrors()classesNo new Error() -- use typed domain errors.
noTypeErrors()classesNo new TypeError().
functionNoGenericErrors()functionsNo new Error() in functions.
functionNoTypeErrors()functionsNo new TypeError() in functions.

ts-archunit/rules/naming

ExportDescription
mustMatchName(re: RegExp)Class name must match regex.
mustNotEndWith(suffix: string)Class name must not end with suffix.

ts-archunit/rules/dependencies

ExportDescription
onlyDependOn(...globs)Module may only import from listed paths.
mustNotDependOn(...globs)Module must not import from listed paths.
typeOnlyFrom(...globs)Imports from listed paths must use import type.

ts-archunit/rules/architecture

ExportTargetDescription
mustCall(pattern)functionsFunction body must contain a call matching the regex.
classMustCall(pattern)classesAt least one class method must contain a matching call.

ts-archunit/rules/hygiene

ExportTargetDescription
noDeadModules()modulesModule must be imported by at least one other file.
noUnusedExports()modulesEvery named export must be referenced by another file.
noStubComments(pattern?)functionsNo TODO/FIXME/HACK/STUB comments in function body.
noEmptyBodies()functionsFunctions must have at least one statement.

ts-archunit/rules/metrics

ExportDescription
maxCyclomaticComplexity(n)No method/constructor/getter/setter exceeds complexity n.
maxClassLines(n)Class spans no more than n lines.
maxMethodLines(n)No method/constructor/getter/setter exceeds n lines.
maxMethods(n)Class has no more than n methods.
maxParameters(n)No method/constructor has more than n parameters.
maxFunctionComplexity(n)Function complexity does not exceed n.
maxFunctionLines(n)Function spans no more than n lines.
maxFunctionParameters(n)Function has no more than n parameters.

Released under the MIT License.