An open source design system that's fully customizable and agent ready
TypeScript
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
* @file contract/generateSwift.ts
* @input Component contracts
* @output Swift sources for the Apple platforms: shared base props, the wire
* (AstryxNode, AstryxAction), and one file per component with the iOS and
* macOS contracts behind `#if os(...)`
* @position Produces the Swift binding (AST-082 FR5). Each component gets
* `<Name>Props`, the contract a SwiftUI view takes, and `<Name>Node`, the
* same contract as JSON a TypeScript core sends (arm C), which turns into
* props whose callbacks send `AstryxAction`s back. Generated files are
* committed under apple/ so a Swift package can pin a commit
*/
import {BUILTIN_ICON_NAMES} from '../icons/defaults.js';
import {SWIFT_KEYWORDS} from './names.js';
import type {ComponentContract, PropMap, PropType} from './types.js';
const HEADER = '// Generated by @astryxdesign/native. Do not edit.\n';
const APPLE_PLATFORMS = [
{platform: 'ios', condition: 'os(iOS)'},
{platform: 'macos', condition: 'os(macOS)'},
] as const;
const RECORD_CONFORMANCES = 'Equatable, Codable, Sendable';
const camel = (text: string) =>
text.replace(/[-_ ]+([a-zA-Z0-9])/g, (_, ch: string) => ch.toUpperCase());
const pascal = (text: string) =>
camel(text).replace(/^./, ch => ch.toUpperCase());
const ident = (name: string) =>
SWIFT_KEYWORDS.has(name) ? `\`${name}\`` : name;
/** `1` → `v1`, `0.5` → `v0_5`, `-1` → `vMinus1`. */
function numberCaseName(value: number): string {
return `v${String(value).replace('-', 'Minus').replace('.', '_')}`;
}
function caseName(value: string): string {
const name = camel(value.replace(/[^A-Za-z0-9_-]/g, '-'));
return ident(/^[0-9]/.test(name) ? `v${name}` : name || 'empty');
}
/** Collects nested declarations (enums, structs) while rendering types. */
class SwiftWriter {
readonly decls: string[] = [];
type(owner: string, prop: string, type: PropType): string {
switch (type.kind) {
case 'string':
return 'String';
case 'number':
return 'Double';
case 'boolean':
return 'Bool';
case 'enum': {
const name = `${owner}${pascal(prop)}`;
const cases = type.values.map(
value => ` case ${caseName(value)} = "${value}"`,
);
this.decls.push(
`public enum ${name}: String, CaseIterable, Codable, Sendable {\n${cases.join('\n')}\n}`,
);
return name;
}
case 'numberEnum': {
const name = `${owner}${pascal(prop)}`;
const raw = type.values.every(Number.isInteger) ? 'Int' : 'Double';
const cases = type.values.map(
value => ` case ${numberCaseName(value)} = ${value}`,
);
this.decls.push(
`public enum ${name}: ${raw}, CaseIterable, Codable, Sendable {\n${cases.join('\n')}\n}`,
);
return name;
}
case 'array':
return `[${this.type(owner, prop, type.of)}]`;
case 'record': {
const name = `${owner}${pascal(prop)}`;
this.decls.push(this.struct(name, type.fields, RECORD_CONFORMANCES));
return name;
}
case 'fn':
return `(${type.args.map((arg, i) => this.type(owner, `${prop}Arg${i}`, arg)).join(', ')}) -> Void`;
case 'content':
return '[AstryxNode]';
case 'icon':
return 'IconName';
case 'textOrBoolean': {
const name = `${owner}${pascal(prop)}`;
this.decls.push(
[
`/// Words or a switch: \`.on\` is the component's own words, \`.off\` none,`,
`/// \`.text\` the given words. On the wire it is the web value, a string or a Bool.`,
`public enum ${name}: Equatable, Codable, Sendable, ExpressibleByStringLiteral, ExpressibleByBooleanLiteral {`,
' case on',
' case off',
' case text(String)',
' public init(stringLiteral value: String) { self = .text(value) }',
' public init(booleanLiteral value: Bool) { self = value ? .on : .off }',
' public init(from decoder: any Decoder) throws {',
' let container = try decoder.singleValueContainer()',
' if let value = try? container.decode(Bool.self) { self = value ? .on : .off }',
' else { self = .text(try container.decode(String.self)) }',
' }',
' public func encode(to encoder: any Encoder) throws {',
' var container = encoder.singleValueContainer()',
' switch self {',
' case .on: try container.encode(true)',
' case .off: try container.encode(false)',
' case .text(let value): try container.encode(value)',
' }',
' }',
'}',
].join('\n'),
);
return name;
}
case 'named':
return type.name;
}
}
fields(
owner: string,
props: PropMap,
): Array<{name: string; decl: string; param: string; assign: string}> {
return Object.entries(props).map(([name, spec]) => {
const base = this.type(owner, name, spec.type);
const optional = spec.type.kind === 'fn' ? `(${base})?` : `${base}?`;
const swiftType = spec.optional ? optional : base;
return {
name,
decl: ` public var ${ident(name)}: ${swiftType}`,
param: `${name}: ${spec.type.kind === 'fn' && !spec.optional ? `@escaping ${swiftType}` : swiftType}${spec.optional ? ' = nil' : ''}`,
assign: ` self.${name} = ${ident(name)}`,
};
});
}
struct(
name: string,
props: PropMap,
conformances: string | null,
extra: string[] = [],
): string {
const fields = this.fields(name, props);
const head = conformances
? `public struct ${name}: ${conformances} {`
: `public struct ${name} {`;
return [
head,
...extra,
...fields.map(field => field.decl),
` public init(${fields.map(field => field.param).join(', ')}) {`,
...fields.map(field => field.assign),
' }',
'}',
].join('\n');
}
}
/** Props without content slots: a SwiftUI view takes content as a builder. */
function withoutContent(props: PropMap): PropMap {
return Object.fromEntries(
Object.entries(props).filter(([, spec]) => spec.type.kind !== 'content'),
);
}
function withoutCallbacks(props: PropMap): PropMap {
return Object.fromEntries(
Object.entries(props).filter(([, spec]) => spec.type.kind !== 'fn'),
);
}
/** `<Name>Node`: the component as JSON from a TypeScript core (arm C). */
function nodeStruct(
writer: SwiftWriter,
contract: ComponentContract,
props: PropMap,
): string {
const name = contract.name;
const data = writer.fields(name, withoutCallbacks(props));
const callbacks = Object.entries(props).filter(
([, spec]) => spec.type.kind === 'fn',
);
// Each callback the core listens to (`events`) sends an action with the
// callback's arguments; one it does not listen to stays nil.
const binding = Object.entries(withoutContent(props)).map(([prop, spec]) => {
if (spec.type.kind !== 'fn') {
return ` ${prop}: props.${ident(prop)}`;
}
const params = spec.type.args.map((_, i) => `arg${i}`);
const values = params.map(param => `AstryxValue(${param})`).join(', ');
const closure = `{ ${params.length > 0 ? `${params.join(', ')} in ` : ''}send(AstryxAction(key: key, component: "${name}", event: "${prop}", args: [${values}])) }`;
return spec.optional
? ` ${prop}: listens("${prop}") ? ${closure} : nil`
: ` ${prop}: ${closure}`;
});
return [
`public struct ${name}Node: Decodable, Equatable, Sendable {`,
` public struct Props: Decodable, Equatable, Sendable {`,
...data.map(field => ` ${field.decl}`),
' }',
' public let key: String',
' public let base: AstryxBaseProps?',
' public let props: Props',
` /// The callbacks the core listens to, by prop name.`,
' public let events: [String]?',
'',
` public func listens(_ event: String) -> Bool { events?.contains(event) ?? false }`,
'',
` /// The contract a ${name} view takes; its callbacks send actions to the core.`,
` public func viewProps(send: @escaping @Sendable (AstryxAction) -> Void) -> ${name}Props {`,
...(callbacks.length > 0 ? [' let key = self.key'] : []),
` return ${name}Props(`,
[...binding, ' base: base ?? AstryxBaseProps()'].join(',\n'),
' )',
' }',
'}',
].join('\n');
}
function componentFile(contract: ComponentContract): string {
const shared = new SwiftWriter();
const typeDecls = Object.entries(contract.types).map(([name, fields]) =>
shared.struct(name, fields, RECORD_CONFORMANCES),
);
// Core enums and records are declared once, outside the platform blocks.
shared.fields(`${contract.name}`, contract.core);
const variants = APPLE_PLATFORMS.map(({platform, condition}) => {
const writer = new SwiftWriter();
const extra = contract.platforms[platform] ?? {};
const all = {...contract.core, ...extra};
const fields = writer.fields(contract.name, withoutContent(all));
const node = nodeStruct(writer, contract, all);
// Core-prop declarations already live outside the platform blocks; keep
// only the declarations this platform's own props need.
writer.decls.length = 0;
writer.fields(contract.name, extra);
const struct = [
`public struct ${contract.name}Props {`,
` /// Base props attach to this part on every platform.`,
` public static let baseTarget: AstryxBaseTarget = .${contract.baseTarget}`,
' public var base: AstryxBaseProps',
...fields.map(field => field.decl),
` public init(${[...fields.map(field => field.param), 'base: AstryxBaseProps = AstryxBaseProps()'].join(', ')}) {`,
...fields.map(field => field.assign),
' self.base = base',
' }',
'}',
].join('\n');
return `#if ${condition}\n${[...writer.decls, struct, node].join('\n')}\n#endif`;
});
return (
HEADER + [...typeDecls, ...shared.decls, ...variants].join('\n') + '\n'
);
}
/** `AstryxNode`: one case per component, decoded by its `component` name. */
function nodeFile(contracts: readonly ComponentContract[]): string {
const caseOf = (name: string) =>
camel(name.replace(/^./, ch => ch.toLowerCase()));
return (
HEADER +
[
'import Foundation',
'',
'#if os(iOS) || os(macOS)',
'/// One Astryx component in a tree a TypeScript core sends, by its `component` name.',
'/// A node this binding cannot read decodes as `unsupported`: an unknown component,',
'/// or a known one with a value its enums lack or a required prop missing. An older',
"/// app then keeps drawing the rest of a newer core's tree.",
'public enum AstryxNode: Decodable, Equatable, Sendable {',
...contracts.map(c => ` case ${ident(caseOf(c.name))}(${c.name}Node)`),
' case unsupported(component: String, key: String)',
'',
' public var key: String {',
' switch self {',
...contracts.map(
c => ` case .${ident(caseOf(c.name))}(let node): return node.key`,
),
' case .unsupported(_, let key): return key',
' }',
' }',
'',
' private enum Keys: String, CodingKey { case component, key }',
'',
' public init(from decoder: any Decoder) throws {',
' let container = try decoder.container(keyedBy: Keys.self)',
' let component = try container.decode(String.self, forKey: .component)',
' let key = try container.decode(String.self, forKey: .key)',
' do {',
' switch component {',
...contracts.map(
c =>
` case "${c.name}": self = .${ident(caseOf(c.name))}(try ${c.name}Node(from: decoder))`,
),
' default: self = .unsupported(component: component, key: key)',
' }',
' } catch {',
' self = .unsupported(component: component, key: key)',
' }',
' }',
'}',
'#endif',
].join('\n') +
'\n'
);
}
const WIRE_FILE =
HEADER +
`import Foundation
/// A JSON value: a portable callback argument on its way to the core.
public enum AstryxValue: Codable, Equatable, Sendable {
case null
case bool(Bool)
case number(Double)
case string(String)
case array([AstryxValue])
case object([String: AstryxValue])
/// Any portable value (a contract's strings, numbers, enums, and records) as JSON.
public init<T: Encodable>(_ value: T) {
guard let data = try? JSONEncoder().encode(value),
let decoded = try? JSONDecoder().decode(AstryxValue.self, from: data) else {
self = .null
return
}
self = decoded
}
public init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() { self = .null }
else if let value = try? container.decode(Bool.self) { self = .bool(value) }
else if let value = try? container.decode(Double.self) { self = .number(value) }
else if let value = try? container.decode(String.self) { self = .string(value) }
else if let value = try? container.decode([AstryxValue].self) { self = .array(value) }
else { self = .object(try container.decode([String: AstryxValue].self)) }
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .null: try container.encodeNil()
case .bool(let value): try container.encode(value)
case .number(let value): try container.encode(value)
case .string(let value): try container.encode(value)
case .array(let value): try container.encode(value)
case .object(let value): try container.encode(value)
}
}
}
/// A callback a view called: which node, which prop, and its arguments.
public struct AstryxAction: Codable, Equatable, Sendable {
public let key: String
public let component: String
public let event: String
public let args: [AstryxValue]
public init(key: String, component: String, event: String, args: [AstryxValue]) {
self.key = key
self.component = component
self.event = event
self.args = args
}
/// The JSON the core receives.
public var json: String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
guard let data = try? encoder.encode(self) else { return "{}" }
return String(decoding: data, as: UTF8.self)
}
}
`;
const BASE_FILE =
HEADER +
[
'public enum AstryxBaseTarget: String, Sendable { case root, trigger, control, container }',
'',
'/// Base props shared by every platform (AST-082 FR7).',
'public struct AstryxBaseProps: Equatable, Codable, Sendable {',
' public var id: String?',
' public var isHidden: Bool?',
' public init(id: String? = nil, isHidden: Bool? = nil) {',
' self.id = id',
' self.isHidden = isHidden',
' }',
'}',
].join('\n') +
'\n';
/**
* `IconName`: a shared icon name (AST-082 FR17), string-backed so a
* registered `<library>:<name>` name is valid too, with every built-in name
* as a static member.
*/
function iconNameFile(): string {
return (
HEADER +
[
'/// A shared icon name (AST-082 FR17): a built-in name, or a registered',
'/// `<library>:<name>` name. A view draws the image the theme or the platform',
'/// maps it to.',
'public struct IconName: RawRepresentable, ExpressibleByStringLiteral, Hashable, Codable, Sendable {',
' public let rawValue: String',
' public init(rawValue: String) { self.rawValue = rawValue }',
' public init(stringLiteral value: String) { self.rawValue = value }',
' public init(from decoder: any Decoder) throws {',
' self.rawValue = try decoder.singleValueContainer().decode(String.self)',
' }',
' public func encode(to encoder: any Encoder) throws {',
' var container = encoder.singleValueContainer()',
' try container.encode(rawValue)',
' }',
' /// Every built-in name, in the order AST-082 FR17 lists them.',
` public static let builtIn: [IconName] = [${BUILTIN_ICON_NAMES.map(name => `.${ident(name)}`).join(', ')}]`,
...BUILTIN_ICON_NAMES.map(
name => ` public static let ${ident(name)}: IconName = "${name}"`,
),
'}',
].join('\n') +
'\n'
);
}
/** Returns file name to contents, relative to the generated Swift folder. */
export function generateSwift(
contracts: readonly ComponentContract[],
): Record<string, string> {
const files: Record<string, string> = {
'AstryxBase.swift': BASE_FILE,
'AstryxNode.swift': nodeFile(contracts),
'AstryxWire.swift': WIRE_FILE,
'IconName.swift': iconNameFile(),
};
for (const contract of contracts) {
files[`${contract.name}.swift`] = componentFile(contract);
}
return files;
}