Skip to content

Latest commit

 

History

History
750 lines (569 loc) · 23.8 KB

attributes.md

File metadata and controls

750 lines (569 loc) · 23.8 KB

Attribute Reference

Most Metano attributes live in the Metano.Annotations namespace. Import it once per file:

using Metano.Annotations;

TypeScript-only attributes live in Metano.Annotations.TypeScript:

using Metano.Annotations.TypeScript;

This page is the complete reference — every attribute, what it does, and when to use it.

Type selection

[Transpile]

Marks a single type for transpilation. Without this (and without [assembly: TranspileAssembly]), a type is ignored even if it's public.

[Transpile]
public record User(string Name, string Email);

[assembly: TranspileAssembly]

Assembly-level attribute. Transpiles every public type in the assembly by default. Individual types can opt out with [Ignore].

[assembly: TranspileAssembly]

Use this when most of your types should cross to TypeScript — less boilerplate than marking each type individually.

Internal types that transpiled code uses are transpiled too (#770): a non-public type referenced from a transpiled signature or body (directly or through another such type) gets its own module, imported where it is used, but no barrel re-exports it, so it stays out of the package's public surface (package.json#exports) and out of every consumer's imports. An internal type nothing transpiled references is not emitted. A reference to a type that still cannot be emitted (a file-local type), or a friend package's ([InternalsVisibleTo]) reference to a non-public type of a Metano package, reports MS0002; [Ignore] keeps winning and its references keep reporting MS0013.

Naming

[Name("x")]

Overrides the name emitted in the TypeScript output. Works on types, methods, constructor overloads, properties, fields, and enum members.

[Name("USD")] USDollar,

[Name("api")]
public void CallApi() { /* … */ }

[Name("snake_case_name")]
public string OriginalCamelCase { get; set; }

On one overload of an overloaded constructor, method, operator or module function, [Name] pins only the overload's generated suffix (spec 013 FR-005): the dispatcher keeps the C# name, and the other overloads are named by the usual rules.

public Money(string text) { /* … */ }        // Money.fromText, Money.byMoneyText

[Name("cents")]
public Money(int value) { /* … */ }          // Money.fromCents, Money.byMoneyCents

[Name("cents")]
public Money Add(int value) => /* … */;      // money.addCents, beside the dispatcher money.add

The value must start with an ASCII letter or _ and contain only ASCII letters, digits and _; otherwise MS0003 is reported and the generated suffix is kept. Two overloads pinned to the same suffix also report MS0003. An override or an interface implementation always takes the suffix of the member it overrides or implements, so put [Name] there; a different [Name] on the implementer is ignored with an MS0003 warning. A conversion operator has no C# name, so its [Name] still names it, and [Name] on a constructor that is not overloaded has no effect (an MS0003 warning). The Dart target pins the same suffixes. The whole naming rule is in Overloads.

[Ignore]

Marks a type or member as .NET-only. Ignored symbols do not emit for the selected target, and transpilable code may not reference ignored types in signatures or bodies. If a generated surface mentions an ignored type, the compiler reports MS0013. Every position a type can be spelled in raises: parameters, return types, fields, properties, events, generic constraints and type arguments, delegate signatures, plus anything inside the body of an emitted member, a field/property/event initializer, a parameter default, or a constructor-initializer argument — locals, new, casts, is/as, every kind of pattern (o is IgnoredType x, IgnoredType { }, switch arms, case labels), catch declarations, local functions, explicitly typed lambda parameters, foreach variables, default(T), and typeof. A property's type is reported once, not again for its accessors. Reading or calling an [Ignore] member from transpilable code raises too. Bodies the compiler does not emit (static constructors, explicit interface implementations, custom event add/remove accessors) are not scanned.

Four cases are exempt, because nothing from them reaches the generated code:

  • Base-list interfaces. An interface ignored for the active target ([Ignore], or [Ignore(TargetLanguage.X)] when emitting X) and listed in a transpilable type's base list is erased from implements (classes, records, structs) or extends (interfaces) in every target it is ignored for; a [Ignore(TargetLanguage.Dart)] interface stays in the TypeScript output. The erased interface is replaced by its own base interfaces that are not ignored (recursively, without duplicates), so class Person : IDotNetOnly with IDotNetOnly : IKept still implements IKept. Its members stay on the type as ordinary members; its explicit implementations (string IDotNetOnly.Tag) are dropped, since they are only reachable through the erased interface. Only the interface itself is erased: an [Ignore] type used as a type argument of a kept base interface (IHolder<DotNetOnly>) still reports MS0013.
  • Attribute applications. Attributes are never emitted, so [Ignore] types referenced inside an attribute — typically [JsonConverter(typeof(MyConverter<T>))], or an [Ignore] attribute class itself — are allowed on types, members, and parameters. The exception is an attribute the compiler reads to produce output: [JsonSerializable(typeof(T))] makes the JSON serializer context emit a type spec for T, so an [Ignore] T still reports MS0013. typeof(IgnoredType) in an ordinary expression still reports too.
  • nameof. nameof(IgnoredType) and nameof(IgnoredType.Member) fold to a string constant, so the type never reaches the output.
  • Source-generator output. Code produced by source generators (for example the System.Text.Json *.g.cs files) is not user-authored and is not scanned. The list of generated files comes from the build workspace; a user file named *.g.cs is still scanned. This only exempts the code from MS0013: it does not stop emission, so a member or type a source generator adds to a transpilable partial type may still be emitted.
[Ignore]
public interface IWorkspaceText<TSelf> where TSelf : IWorkspaceText<TSelf>
{
    static abstract TSelf From(string value);
}

[Ignore]
public sealed class WorkspaceTextJsonConverter<T> : JsonConverter<T>
    where T : IWorkspaceText<T> { /* … */ }

// No MS0013: the interface is erased and the attribute is not emitted, so the
// TypeScript output is the same as without either of them.
[Branded]
[JsonConverter(typeof(WorkspaceTextJsonConverter<WorkspaceText>))]
public readonly record struct WorkspaceText(string Value) : IWorkspaceText<WorkspaceText>
{
    public static WorkspaceText From(string value) => new(value.Trim());
}

Use [Ignore] for implementation-only C# types or members that should stay out of generated targets. For ambient JavaScript/runtime declarations, prefer the TypeScript-only [External] attribute or [Import], depending on whether the symbol comes from a global/runtime surface or an npm package.

[Ignore]
public sealed class EfCoreOnlyProjection { }

public class User
{
    public string Name { get; set; }

    [Ignore]
    public string InternalDebugInfo { get; set; } // not emitted
}

The attribute is target-aware:

[Ignore(TargetLanguage.Dart)]
public sealed class TypeScriptOnlyWidget { }

The parameterless form applies to every target. [Ignore(TargetLanguage.Dart)] suppresses only the Dart backend while leaving TypeScript emission unchanged.

Output shaping

[StringEnum]

Emits the enum as a string union (via a const object + type alias) instead of a numeric TypeScript enum. Recommended for most enums — more idiomatic in TypeScript and plays nicely with JSON.

[StringEnum]
public enum Priority
{
    Low,
    [Name("medium")] Medium,
    High,
}

Becomes:

export const Priority = {
  Low: "Low",
  Medium: "medium",
  High: "High",
} as const;
export type Priority = (typeof Priority)[keyof typeof Priority];

[Branded] — branded primitives

Struct with a single primitive field → branded type with zero runtime overhead. Perfect for strongly-typed IDs.

[Branded]
public readonly record struct UserId(string Value)
{
    public static UserId New() => new(Guid.NewGuid().ToString("N"));
}

Becomes:

export type UserId = string & { readonly __brand: "UserId" };
function UserId$create(value: string): UserId { return value as UserId; }
function UserId$new_(): UserId { return crypto.randomUUID().replace(/-/g, "") as UserId; }
export const UserId = { create: UserId$create, new_: UserId$new_ } as const;

At runtime UserId is literally a string — no wrapper object. But the type system prevents you from passing a plain string where a UserId is expected.

[InlineWrapper] is still supported with the same behavior for existing code, but new code should prefer [Branded].

[JsonFactory] — validating branded JSON reads

On the one static method of a [Branded] / [InlineWrapper] type that validates its input (From): the generated JsonSerializerContext descriptor calls it (create: Title.from) instead of the non-validating create, so the C# validation also runs on JSON input. TypeScript-only; an invalid factory is error MS0034. See Validating branded types.

[PlainObject] — record → interface

Emits a record or class as a TypeScript interface instead of a class. No equals, no hashCode, no with, no constructor call site lowering.

Useful for DTOs that flow through JSON.stringify/parse or HTTP boundaries.

[PlainObject]
public record CreateUserDto(string Name, string Email);

Becomes:

export interface CreateUserDto {
  name: string;
  email: string;
}

And at call sites, new CreateUserDto("Alice", "a@example.com") becomes { name: "Alice", email: "a@example.com" }.

[NoContainer]

Applied to a static class: instead of emitting a class, each method becomes a top-level exported function in the generated target module, and member access drops the class qualifier at call sites.

[NoContainer]
public static class MathHelpers
{
    public static int Square(int x) => x * x;
    public static int Cube(int x) => x * x * x;
}

Becomes:

export function square(x: number): number {
  return x * x;
}

export function cube(x: number): number {
  return x * x * x;
}

No MathHelpers class in the output — just loose functions. Idiomatic in JS modules.

[ExportedAsModule] is obsolete and kept temporarily for existing callers. New code should use [NoContainer]. [Module] is accepted as an alias for the same module-shaping intent, but [NoContainer] is the clearest spelling when the class is purely a compile-time container.

[ObjectArgs]

Lowers a method, constructor, or class API so the TypeScript surface receives a single object argument. Each C# parameter becomes a property on the object type; optional C# parameters become optional properties.

This is useful for UI and interop APIs that conventionally take props objects.

[ObjectArgs]
public static Widget Column(int gap = 0, Widget[] children) =>
    new ColumnWidget(gap, children);

A call such as Column(gap: 12, children: items) emits as:

column({ gap: 12, children: items })

On a constructor, the runtime constructor stays positional and a static create({ ... }) factory takes the object; call sites become T.create({ ... }). A positional record or primary constructor takes the attribute through [method: ObjectArgs]; a type-level [ObjectArgs] applies to the type's only constructor (several constructors report MS0001). Arguments are listed in the order the source evaluates them; a params parameter becomes items?: T[] defaulting to []. TypeScript only: Dart keeps positional construction.

Not supported (each reports MS0001, no factory, positional constructions): abstract types, [PlainObject] types, a type declaring a static create, constructor overloading, and a derived type whose factory would not be compatible with its base factory (the base must be non-generic and every base key must appear in the derived arguments with the same type and requiredness).

[Transpile]
[method: ObjectArgs]
public record Point(int X, int Y = 2);

new Point(1); // Point.create({ x: 1 })

[GenerateGuard]

Generates a TypeScript type guard function isTypeName(value: unknown): value is TypeName next to the type. Validates structure at runtime.

[Transpile, GenerateGuard]
public record Money(decimal Amount, string Currency);

Emits both the Money class AND:

export function isMoney(value: unknown): value is Money {
  return (
    value instanceof Money ||
    (typeof value === "object" && value !== null &&
      "amount" in value && value.amount instanceof Decimal &&
      "currency" in value && typeof value.currency === "string")
  );
}

Guards are auto-imported wherever they're needed (e.g., in generated overload dispatchers).

[EmitInFile("name")]

Co-locates multiple types in a single .ts file. Types in the same C# namespace with the same EmitInFile("foo") name share foo.ts.

[PlainObject, EmitInFile("todos")]
public record StoredTodo(string Id, TodoItem Item);

[PlainObject, EmitInFile("todos")]
public record CreateTodoDto(string Title, Priority Priority);

[EmitInFile("todos")]
public class TodoStore { /* … */ }

All three land in todos.ts. Consumers that import any of them get import { … } from "…/todos" automatically.

[Inline]

Marks a static readonly field, static expression-bodied property, or static single-expression method for use-site inlining. The declaration itself does not emit as a top-level export.

[Inline]
public static int Twice(int value) => value * 2;

[Inline(InlineMode.Substitute)] performs direct parameter substitution. The default InlineMode.Materialize emits a small inline function shape so arguments are evaluated once.

[Constant]

Requires a field or call-site argument to be known at compile time. Invalid uses report MS0014.

public static HtmlTag Tag([Constant] string name) =>
    throw new NotSupportedException();

[Constant]
public const string Section = "section";

Module-level features

[ModuleEntryPoint]

Applied to a static method. The method body becomes top-level code in the generated TypeScript module — no function wrapper. Useful for app bootstrap code.

[NoContainer]
public static class Program
{
    [ModuleEntryPoint]
    public static void Main()
    {
        var app = new Hono();
        app.Get("/", c => c.Text("hello"));
    }
}

Becomes:

const app = new Hono();
app.get("/", (c) => c.text("hello"));

[ExportVarFromBody("name", AsDefault = true)]

Combines with [ModuleEntryPoint] to promote a local variable to a module export (optionally export default). The attribute names the C# local; the export uses the local's emitted name, so a PascalCase local is exported under its camelCased form (var App → export default app;).

[NoContainer]
public static class Program
{
    [ModuleEntryPoint, ExportVarFromBody("app", AsDefault = true)]
    public static void Main()
    {
        var app = new Hono();
        // … wire routes
    }
}

Becomes:

const app = new Hono();
// … routes

export default app;

Delegates and call-site binding

[This]

Marks the first parameter of a delegate or inlinable method as the JavaScript this receiver. The parameter is removed from the emitted argument list and reintroduced as a TypeScript this: annotation.

public delegate void MouseListener([This] Element self, MouseEvent ev);

Becomes:

export type MouseListener = (this: Element, ev: MouseEvent) => void;

The attribute is target-agnostic, but only targets with JS-style rebinding use it today. Invalid placement reports MS0018.

External bindings

[Import(name, from, Version = "^x.y.z", AsDefault = false)]

Declares a type that's provided by an external npm package, not by your C# code. The transpiler emits import { Name } from "package-name" wherever this type is used, and adds the package to the generated package.json#dependencies.

[Import(name: "Hono", from: "hono", Version = "^4.6.0")]
public class Hono
{
    [Name("get")]
    public void Get(string path, Func<IHonoContext, IHonoContext> handler) =>
        throw new NotSupportedException();
}

Set AsDefault = true for default imports (import Foo from "package").

[assembly: ExportFromBcl(typeof(BclType), FromPackage = "npm-pkg", ExportedName = "TsName", Version = "^x.y.z")]

Assembly-level mapping from a .NET BCL type to an npm package. Used by the Metano package itself to wire up default mappings like decimal → Decimal from metano-runtime/system/decimal (decimal.js configured for System.Decimal).

[assembly: ExportFromBcl(
    typeof(decimal),
    FromPackage = "decimal.js",
    ExportedName = "Decimal",
    Version = "^10.6.0")]

FromPackage may also be a module specifier inside a package. The shipped exception mappings use one per class, so a program imports only the exception modules it uses, and an exception type mapped this way constructs, extends, names and tests the exported class (see the Exceptions section of bcl-mappings.md):

[assembly: ExportFromBcl(
    typeof(InvalidOperationException),
    ExportedName = "InvalidOperationException",
    FromPackage = "metano-runtime/system/exceptions/invalid-operation-exception")]

[Emit("$0.foo($1, $2)")]

Inlines JavaScript at the call site, with $0 = the receiver and $1, $2, … = arguments. Escape hatch for when you need a specific JS idiom that isn't worth modeling in C#.

[Emit("$0.replace(/-/g, \"\")")]
public static string StripDashes(this string value) =>
    throw new NotSupportedException();

At the call site text.StripDashes() emits text.replace(/-/g, "").

$Type stands for the type the method is declared on, by its own exported name (never a using alias of it), and imports it. A type name written in the template text is not imported:

public static class Fmt
{
    [Emit("$Type.make($0)")]
    public static string Make(int value) => throw new NotSupportedException();
}

Fmt.Make(1) emits Fmt.make(1) and imports Fmt from its module (or package). [MapMethod] / [MapProperty] templates use the same placeholder (new $Type(parseDecimalText($0))).

[ImportAlias]

Pins the local name used for an imported type in the generated file. Declare it on a C# file-scoped carrier class.

[ImportAlias(typeof(Column), "ColumnWidget", Target = TargetLanguage.TypeScript)]
file class TsAliases;

Bulk aliasing is also supported:

[ImportAlias(Suffix = "Widget", Types = [typeof(Row), typeof(Text)])]
file class TsAliases;

Precedence is [ImportAlias] > C# using X = Y > automatic collision aliasing

canonical name.

TypeScript-specific attributes

These attributes require:

using Metano.Annotations.TypeScript;

[Optional]

Marks a nullable parameter or property as optional-presence in TypeScript: name?: T | null instead of the default present nullable value name: T | null.

public record SearchRequest([Optional] string? Query);

The C# type must be nullable. Applying [Optional] to a non-nullable type reports MS0010.

[External]

Declares a TypeScript runtime-provided symbol. External symbols emit no .ts file, but transpilable code may still reference them. This is the right choice for DOM shapes, Hono-style context interfaces, abstract ambient classes, and runtime globals provided by another declaration file or package.

[External] accepts static classes, abstract classes, interfaces, structs, and members. Concrete non-static classes are rejected with MS0012, because Metano cannot both erase the declaration and preserve instance implementation.

Static member access stays class-qualified:

[External]
public static class Js
{
    [Name("document")]
    public static Document Document => throw new NotSupportedException();
}

Js.Document emits as Js.document. Add [NoContainer] to the same static class when you intentionally want the qualifier erased.

Use [External] for ambient/runtime symbols. Use [Import] for npm package symbols.

[Discriminator("FieldName")]

Marks the discriminator field for generated TypeScript guards. The field must exist, be non-nullable, and use a [StringEnum] type.

[GenerateGuard]
[Discriminator(nameof(Kind))]
public interface Shape
{
    ShapeKind Kind { get; }
}

Invalid discriminator setup reports MS0011.

Cross-project packaging

[assembly: EmitPackage("name", Version = "^x.y.z")]

Declares the npm package name for this assembly's transpiled output. Used by cross-project resolution: when another project references this assembly, imports resolve to "name/subpath" instead of a relative "./….js" file import.

[assembly: TranspileAssembly]
[assembly: EmitPackage("@acme/domain", Version = "^1.0.0")]

The Version field is optional — if omitted, the consumer uses workspace:* for monorepo siblings or the assembly's Identity.Version.

The optional SubpathRoot names the namespace prefix the package name stands for. It is stripped from the package.json#exports keys and from consumers' imports (on-disk layout and the relative internal imports are unchanged):

[assembly: EmitPackage("@video-studio/domain", SubpathRoot = "VideoStudio.Domain")]
// VideoStudio.Domain.Episodes → import { Episode } from "@video-studio/domain/episodes"
// VideoStudio.Domain          → import { Clock } from "@video-studio/domain"

Matching is by whole namespace segment (VideoStudio.DomainEvents keeps its full path). An invalid value reports MS0029; two barrels claiming the same key (including the --namespace-barrels root barrel vs. types in the root namespace, both on .) report MS0030. See Cross-Project References.

Declarative BCL mappings

[assembly: MapMethod(typeof(T), "MethodName", JsMethod = "jsName")]

Maps a .NET BCL method to a JS method. Used by the Metano assembly to define things like List<T>.Add → push, List<T>.Contains → includes.

[assembly: MapMethod(typeof(List<>), nameof(List<int>.Add), JsMethod = "push")]

Alternative: JsTemplate for full control:

[assembly: MapMethod(
    typeof(Enumerable),
    nameof(Enumerable.Where),
    WrapReceiver = "Enumerable.from",
    JsTemplate = "$this.where($0)")]

Placeholders:

  • $this — the receiver
  • $0, $1, … — arguments
  • $T0, $T1, … — generic type arguments

A template imports what it prints: a type argument only through its $T<n>, the receiver only through $this. A template without $this that names the receiver's type as an identifier (new Decimal(parseDecimalText($0)) for decimal.Parse) gets a value import of that type's canonical exported name, never a using alias of it; any other name a template uses must come from RuntimeImports.

[assembly: MapProperty(typeof(T), "PropertyName", JsProperty = "jsName")]

Same idea for properties.

[assembly: MapProperty(typeof(List<>), nameof(List<int>.Count), JsProperty = "length")]

See also