Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(native): experimental canary-only @astryxdesign/native package (#7796)

Cindy Zhang50456d81bfcf
diff --git a/packages/native/README.md b/packages/native/README.md
new file mode 100644
index 0000000000..c49d4f0376
--- /dev/null
+++ b/packages/native/README.md
@@ -0,0 +1,121 @@
+# @astryxdesign/native
+
+> **Experimental. Canary only.** This package is published only under the
+> `@canary` dist-tag and is never released as a stable version. Its APIs change
+> without notice. Nothing here is supported for production apps.
+
+`@astryxdesign/native` is where Astryx experiments with native platforms
+(iOS, Android, macOS, Windows) under AST-082 (Native-first surfaces). The
+experiment compares ways of building Astryx components on each platform and
+measures them against the same scorecard, so the decision for each platform
+rests on evidence.
+
+## What is here today
+
+| Part | Path | What it does |
+| -------------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Contracts | `src/contract/` | Reads a core component's documentation and splits its props into a portable **core contract** and a **web-only** part, with a reason for each web-only prop. Checks prop names against Swift and Kotlin keywords and platform toolkit names. |
+| Platform types | `@astryxdesign/native/components` | TypeScript props per platform, chosen by type-resolution condition: `ios`, `android`, `macos`, `windows`, or `shared` for the core contract only. |
+| Swift binding | `apple/` | A Swift package with props generated from the same contracts. iOS and macOS props sit behind `#if os(...)`. |
+| Native theme | `defineNativeTheme` | Durable theme intent (`material: 'opaque' \| 'translucent'`) plus platform entries scoped by OS version, such as Liquid Glass from iOS 26. Never sets tokens. |
+| Icons | `NATIVE_ICON_DEFAULTS` | Astryx's built-in icon names mapped to SF Symbols on Apple platforms and Material Symbols on Android. |
+
+Only `Selector` has native additions so far. React Native and Android bindings
+are not built yet; see [the experiment matrix](#experiment-matrix).
+
+```ts
+// tsconfig.json for an iOS app: "customConditions": ["ios"]
+import type {SelectorProps} from '@astryxdesign/native/components';
+
+const props: SelectorProps = {
+ label: 'Shipping',
+ options: [{value: 'standard', label: 'Standard'}],
+ menuStyle: 'pullDown', // iOS-only prop; an Android build rejects it
+};
+```
+
+## Working on it
+
+```sh
+pnpm -F @astryxdesign/native build # dist/, including platform types
+pnpm -F @astryxdesign/native generate:apple # regenerate apple/Sources/.../Generated
+pnpm vitest run --project node packages/native
+```
+
+Generated Swift is committed so a Swift package can pin a commit. A test fails
+when it drifts from the contracts.
+
+Boundaries, checked by `pnpm check:package-boundaries`:
+
+- `@astryxdesign/core` never imports this package.
+- This package's source never imports core. It reads core's documentation
+ files as data at build time.
+
+## Experiment matrix
+
+Every arm runs the same subjects on the same devices and is scored against a
+**reference**: the same screens hand-built with the platform toolkit (SwiftUI,
+Jetpack Compose, WinUI).
+
+| Arm | How components are built | iOS | Android | macOS | Windows |
+| ------------------------- | ---------------------------------------------------------------------------------------- | --- | ------- | ----- | ------- |
+| A. Pure native | Platform views (SwiftUI, Compose, WinUI) on generated contracts | ✓ | ✓ | ✓ | ✓ |
+| B. React Native | React Native components; desktop through `react-native-macos` and `react-native-windows` | ✓ | ✓ | ✓ | ✓ |
+| C. Shared logic core | Component logic in TypeScript running in Hermes, driving platform views | ✓ | ✓ | ✓ | — |
+| D. Web on native | Web React components through a native renderer, such as Expo's experimental fork | ✓ | ✓ | — | — |
+| E. Web in a desktop shell | Astryx's web components unchanged inside Electron | — | — | ✓ | ✓ |
+
+Arms D and E are measured but cannot become required runtimes as written:
+arm D depends on a third-party fork and arm E on Electron, a third-party
+runtime (AST-082 FR13). Arm E is the baseline for how far plain web gets on
+desktop.
+
+### Test subjects
+
+Templates come first because their web version is a known reference for
+content and states.
+
+1. **Wave 1:** `checkout-wizard` (forms, stepper, pickers, validation, keyboard),
+ `table-inbox` (long list, row actions, search, compose sheet), `dashboard`
+ (charts, tables, scrolling).
+2. **Wave 2:** `settings`, `kanban-board`, `ai-chat`, `product-detail`.
+3. **Component flows:** Selector, text entry, dialog and sheet, list with row
+ actions.
+
+Each subject has one scripted interaction that every arm replays.
+
+Visual scores come from real screens. Every scripted step is captured as a
+screenshot on the device, every behavior (sheet open and dismiss, navigation
+transitions, gestures, scrolling, press feedback, keyboard) as a short video or
+GIF, and every scenario as a recording, for each arm, the
+reference, and the web version, in light and dark and at the largest text size.
+Reviewers compare captures side by side with arm names hidden, and pixel checks
+read colors and sizes from the captures, never from source.
+
+### Metrics
+
+| Area | Measure | How | Unit |
+| --------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
+| Gate | Required runtimes | Dependency manifest against FR13 | pass/fail |
+| Gate | Screen-reader parity | VoiceOver, TalkBack, Narrator task script | pass/fail |
+| Gate | Completeness | Every subject renders every state | pass/fail |
+| Experience | Platform feel | Blind reviewer rating of captured screens and recordings against the reference, plus a platform-conventions checklist | score, % of checklist |
+| Experience | Behavior and motion | Blind reviewer rating of behavior videos against the reference: timing, easing, gesture response, interruptibility | score per behavior |
+| Experience | Time to adopt a new OS feature | Days from OS release to shipping it in the arm (for example, Liquid Glass) | days |
+| Performance | Startup to first content | Release build, cold start, median of runs | ms |
+| Performance | Smoothness | Dropped frames during the scripted interaction | % frames |
+| Performance | Input latency | Touch or key to visible response | ms |
+| Performance | Memory and size | Peak memory during the script; app download size | MB |
+| Maintenance | Change cost | Time to ship one real Astryx change on the arm (a new prop, a new token) | hours |
+| Developer speed | Iteration | Edit to visible on device | seconds |
+| Developer speed | Sharing | Share of app code reused across platforms | % lines |
+| Design | Brand preservation | Blind designer review of whether the brand is recognizable from the web version while the screen still feels native, plus pixel checks on the captures for the theme's color, type, shape, spacing, and icons | score, % token checks |
+| Fidelity | Match to web | Content and states matching the web template | % checks |
+
+### Judging
+
+1. An arm that fails a gate is out for that platform.
+2. The remaining arms are compared per platform, each measure relative to the
+ reference on the same device.
+3. Whether the measures are weighted into one score or ranked side by side is
+ not decided yet.
diff --git a/packages/native/apple/.gitignore b/packages/native/apple/.gitignore
new file mode 100644
index 0000000000..2d9f16e2d2
--- /dev/null
+++ b/packages/native/apple/.gitignore
@@ -0,0 +1,2 @@
+.build/
+.swiftpm/
diff --git a/packages/native/apple/Package.swift b/packages/native/apple/Package.swift
new file mode 100644
index 0000000000..4b7137dc14
--- /dev/null
+++ b/packages/native/apple/Package.swift
@@ -0,0 +1,18 @@
+// swift-tools-version: 6.0
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// Experimental Astryx for Apple platforms (AST-082). The contract types under
+// Sources/AstryxNative/Generated are generated by `pnpm generate:apple`; do not
+// edit them by hand.
+
+import PackageDescription
+
+let package = Package(
+ name: "AstryxNative",
+ platforms: [.iOS(.v17), .macOS(.v14)],
+ products: [.library(name: "AstryxNative", targets: ["AstryxNative"])],
+ targets: [
+ .target(name: "AstryxNative", path: "Sources/AstryxNative"),
+ .testTarget(name: "AstryxNativeTests", dependencies: ["AstryxNative"], path: "Tests/AstryxNativeTests"),
+ ]
+)
diff --git a/packages/native/apple/Sources/AstryxNative/Generated/AstryxBase.swift b/packages/native/apple/Sources/AstryxNative/Generated/AstryxBase.swift
new file mode 100644
index 0000000000..732a8225a4
--- /dev/null
+++ b/packages/native/apple/Sources/AstryxNative/Generated/AstryxBase.swift
@@ -0,0 +1,12 @@
+// Generated by @astryxdesign/native. Do not edit.
+public enum AstryxBaseTarget: String, Sendable { case root, trigger, control, container }
+
+/// Base props shared by every platform (AST-082 FR7).
+public struct AstryxBaseProps: Equatable, Sendable {
+ public var id: String?
+ public var isHidden: Bool?
+ public init(id: String? = nil, isHidden: Bool? = nil) {
+ self.id = id
+ self.isHidden = isHidden
+ }
+}
diff --git a/packages/native/apple/Sources/AstryxNative/Generated/Selector.swift b/packages/native/apple/Sources/AstryxNative/Generated/Selector.swift
new file mode 100644
index 0000000000..af4655836d
--- /dev/null
+++ b/packages/native/apple/Sources/AstryxNative/Generated/Selector.swift
@@ -0,0 +1,159 @@
+// Generated by @astryxdesign/native. Do not edit.
+public struct SelectorOption: Equatable, Sendable {
+ public var value: String
+ public var label: String?
+ public var disabled: Bool?
+ public init(value: String, label: String? = nil, disabled: Bool? = nil) {
+ self.value = value
+ self.label = label
+ self.disabled = disabled
+ }
+}
+public enum SelectorSize: String, CaseIterable, Sendable {
+ case sm = "sm"
+ case md = "md"
+ case lg = "lg"
+}
+public enum SelectorVariant: String, CaseIterable, Sendable {
+ case input = "input"
+ case secondary = "secondary"
+ case ghost = "ghost"
+}
+public enum SelectorStatusType: String, CaseIterable, Sendable {
+ case error = "error"
+ case warning = "warning"
+ case success = "success"
+}
+public struct SelectorStatus: Equatable, Sendable {
+ public var type: SelectorStatusType
+ public var message: String?
+ public init(type: SelectorStatusType, message: String? = nil) {
+ self.type = type
+ self.message = message
+ }
+}
+public enum SelectorStatusVariant: String, CaseIterable, Sendable {
+ case attached = "attached"
+ case detached = "detached"
+ case tooltip = "tooltip"
+}
+public enum SelectorIndicatorPosition: String, CaseIterable, Sendable {
+ case start = "start"
+ case end = "end"
+}
+#if os(iOS)
+public enum SelectorMenuStyle: String, CaseIterable, Sendable {
+ case popUp = "popUp"
+ case pullDown = "pullDown"
+}
+public struct SelectorProps {
+ /// Base props attach to this part on every platform.
+ public static let baseTarget: AstryxBaseTarget = .trigger
+ public var base: AstryxBaseProps
+ public var label: String
+ public var options: [SelectorOption]
+ public var value: String?
+ public var onChange: ((String) -> Void)?
+ public var hasClear: Bool?
+ public var hasSearch: Bool?
+ public var searchPlaceholder: String?
+ public var placeholder: String?
+ public var size: SelectorSize?
+ public var variant: SelectorVariant?
+ public var isDisabled: Bool?
+ public var isReadOnly: Bool?
+ public var disabledMessage: String?
+ public var isLabelHidden: Bool?
+ public var description: String?
+ public var isOptional: Bool?
+ public var isRequired: Bool?
+ public var status: SelectorStatus?
+ public var statusVariant: SelectorStatusVariant?
+ public var indicatorPosition: SelectorIndicatorPosition?
+ public var isLoading: Bool?
+ public var menuStyle: SelectorMenuStyle?
+ public init(label: String, options: [SelectorOption], value: String? = nil, onChange: ((String) -> Void)? = nil, hasClear: Bool? = nil, hasSearch: Bool? = nil, searchPlaceholder: String? = nil, placeholder: String? = nil, size: SelectorSize? = nil, variant: SelectorVariant? = nil, isDisabled: Bool? = nil, isReadOnly: Bool? = nil, disabledMessage: String? = nil, isLabelHidden: Bool? = nil, description: String? = nil, isOptional: Bool? = nil, isRequired: Bool? = nil, status: SelectorStatus? = nil, statusVariant: SelectorStatusVariant? = nil, indicatorPosition: SelectorIndicatorPosition? = nil, isLoading: Bool? = nil, menuStyle: SelectorMenuStyle? = nil, base: AstryxBaseProps = AstryxBaseProps()) {
+ self.label = label
+ self.options = options
+ self.value = value
+ self.onChange = onChange
+ self.hasClear = hasClear
+ self.hasSearch = hasSearch
+ self.searchPlaceholder = searchPlaceholder
+ self.placeholder = placeholder
+ self.size = size
+ self.variant = variant
+ self.isDisabled = isDisabled
+ self.isReadOnly = isReadOnly
+ self.disabledMessage = disabledMessage
+ self.isLabelHidden = isLabelHidden
+ self.description = description
+ self.isOptional = isOptional
+ self.isRequired = isRequired
+ self.status = status
+ self.statusVariant = statusVariant
+ self.indicatorPosition = indicatorPosition
+ self.isLoading = isLoading
+ self.menuStyle = menuStyle
+ self.base = base
+ }
+}
+#endif
+#if os(macOS)
+public enum SelectorMenuStyle: String, CaseIterable, Sendable {
+ case popUp = "popUp"
+ case pullDown = "pullDown"
+}
+public struct SelectorProps {
+ /// Base props attach to this part on every platform.
+ public static let baseTarget: AstryxBaseTarget = .trigger
+ public var base: AstryxBaseProps
+ public var label: String
+ public var options: [SelectorOption]
+ public var value: String?
+ public var onChange: ((String) -> Void)?
+ public var hasClear: Bool?
+ public var hasSearch: Bool?
+ public var searchPlaceholder: String?
+ public var placeholder: String?
+ public var size: SelectorSize?
+ public var variant: SelectorVariant?
+ public var isDisabled: Bool?
+ public var isReadOnly: Bool?
+ public var disabledMessage: String?
+ public var isLabelHidden: Bool?
+ public var description: String?
+ public var isOptional: Bool?
+ public var isRequired: Bool?
+ public var status: SelectorStatus?
+ public var statusVariant: SelectorStatusVariant?
+ public var indicatorPosition: SelectorIndicatorPosition?
+ public var isLoading: Bool?
+ public var menuStyle: SelectorMenuStyle?
+ public init(label: String, options: [SelectorOption], value: String? = nil, onChange: ((String) -> Void)? = nil, hasClear: Bool? = nil, hasSearch: Bool? = nil, searchPlaceholder: String? = nil, placeholder: String? = nil, size: SelectorSize? = nil, variant: SelectorVariant? = nil, isDisabled: Bool? = nil, isReadOnly: Bool? = nil, disabledMessage: String? = nil, isLabelHidden: Bool? = nil, description: String? = nil, isOptional: Bool? = nil, isRequired: Bool? = nil, status: SelectorStatus? = nil, statusVariant: SelectorStatusVariant? = nil, indicatorPosition: SelectorIndicatorPosition? = nil, isLoading: Bool? = nil, menuStyle: SelectorMenuStyle? = nil, base: AstryxBaseProps = AstryxBaseProps()) {
+ self.label = label
+ self.options = options
+ self.value = value
+ self.onChange = onChange
+ self.hasClear = hasClear
+ self.hasSearch = hasSearch
+ self.searchPlaceholder = searchPlaceholder
+ self.placeholder = placeholder
+ self.size = size
+ self.variant = variant
+ self.isDisabled = isDisabled
+ self.isReadOnly = isReadOnly
+ self.disabledMessage = disabledMessage
+ self.isLabelHidden = isLabelHidden
+ self.description = description
+ self.isOptional = isOptional
+ self.isRequired = isRequired
+ self.status = status
+ self.statusVariant = statusVariant
+ self.indicatorPosition = indicatorPosition
+ self.isLoading = isLoading
+ self.menuStyle = menuStyle
+ self.base = base
+ }
+}
+#endif
diff --git a/packages/native/apple/Tests/AstryxNativeTests/SelectorPropsTests.swift b/packages/native/apple/Tests/AstryxNativeTests/SelectorPropsTests.swift
new file mode 100644
index 0000000000..a4e21be0ae
--- /dev/null
+++ b/packages/native/apple/Tests/AstryxNativeTests/SelectorPropsTests.swift
@@ -0,0 +1,17 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import Testing
+@testable import AstryxNative
+
+@Test func selectorCoreAndPlatformProps() {
+ let props = SelectorProps(
+ label: "Shipping",
+ options: [SelectorOption(value: "std", label: "Standard")],
+ onChange: { _ in },
+ menuStyle: .pullDown,
+ base: AstryxBaseProps(id: "shipping")
+ )
+ #expect(props.label == "Shipping")
+ #expect(props.menuStyle == .pullDown)
+ #expect(SelectorProps.baseTarget == .trigger)
+}
diff --git a/packages/native/package.json b/packages/native/package.json
new file mode 100644
index 0000000000..43231a6ed1
--- /dev/null
+++ b/packages/native/package.json
@@ -0,0 +1,80 @@
+{
+ "name": "@astryxdesign/native",
+ "version": "0.1.0",
+ "private": true,
+ "description": "Experimental native platforms for Astryx (iOS, Android, macOS, Windows) — published to npm only under the @canary dist-tag; never released as a stable (latest) version.",
+ "author": "Meta Open Source",
+ "license": "MIT",
+ "homepage": "https://github.com/facebook/astryx#readme",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/facebook/astryx.git",
+ "directory": "packages/native"
+ },
+ "bugs": {
+ "url": "https://github.com/facebook/astryx/issues"
+ },
+ "keywords": [
+ "astryx",
+ "native",
+ "experimental",
+ "design-system"
+ ],
+ "astryx": {
+ "canaryOnly": true,
+ "_comment": "Published ONLY to the @canary dist-tag (see .github/workflows/release.yml). Never published as a stable `latest` release. `private: true` is intentional and must stay — it is npm's hard guarantee against an accidental stable publish."
+ },
+ "type": "module",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "sideEffects": false,
+ "files": [
+ "dist",
+ "src",
+ "apple",
+ "README.md"
+ ],
+ "exports": {
+ ".": {
+ "source": "./src/index.ts",
+ "types": "./dist/index.d.ts",
+ "default": "./dist/index.js"
+ },
+ "./components": {
+ "ios": {
+ "types": "./dist/types/ios.d.ts"
+ },
+ "android": {
+ "types": "./dist/types/android.d.ts"
+ },
+ "macos": {
+ "types": "./dist/types/macos.d.ts"
+ },
+ "windows": {
+ "types": "./dist/types/windows.d.ts"
+ },
+ "shared": {
+ "types": "./dist/types/shared.d.ts"
+ },
+ "types": "./dist/types/shared.d.ts"
+ },
+ "./contract": {
+ "source": "./src/contract/index.ts",
+ "types": "./dist/contract/index.d.ts",
+ "default": "./dist/contract/index.js"
+ }
+ },
+ "scripts": {
+ "prepack": "pnpm build",
+ "build": "node ../../scripts/clean-dist.mjs && tsc --project tsconfig.build.json && node scripts/generate.mjs --types",
+ "generate:apple": "pnpm build && node scripts/generate.mjs --apple",
+ "test": "vitest run --root ../.. packages/native",
+ "typecheck": "tsc --project tsconfig.json --noEmit"
+ },
+ "peerDependencies": {
+ "@astryxdesign/core": "0.7.2"
+ },
+ "devDependencies": {
+ "@astryxdesign/core": "workspace:*"
+ }
+}
diff --git a/packages/native/scripts/core-docs.d.mts b/packages/native/scripts/core-docs.d.mts
new file mode 100644
index 0000000000..f019f0649d
--- /dev/null
+++ b/packages/native/scripts/core-docs.d.mts
@@ -0,0 +1,7 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {ComponentDocLike} from '../src/contract/fromComponentDoc.js';
+
+export declare const CORE_ROOT: string;
+export declare function loadCoreDoc(name: string): Promise<ComponentDocLike>;
+export declare function readCoreIconNames(): string[];
diff --git a/packages/native/scripts/core-docs.mjs b/packages/native/scripts/core-docs.mjs
new file mode 100644
index 0000000000..57791085a4
--- /dev/null
+++ b/packages/native/scripts/core-docs.mjs
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file scripts/core-docs.mjs
+ * @input A core component name
+ * @output That component's documentation, read from the installed core package
+ * @position Build-time loader shared by the generator and the tests. Reads
+ * core's published documentation files as data (AST-082 FR16)
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+
+const PACKAGE_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..',
+);
+export const CORE_ROOT = path.join(
+ PACKAGE_ROOT,
+ 'node_modules',
+ '@astryxdesign',
+ 'core',
+);
+
+/** @param {string} name */
+export async function loadCoreDoc(name) {
+ const file = path.join(CORE_ROOT, 'src', name, `${name}.doc.mjs`);
+ if (!fs.existsSync(file)) {
+ throw new Error(
+ `No core documentation for "${name}" at ${file}; run pnpm install`,
+ );
+ }
+ const mod = await import(pathToFileURL(file).href);
+ return mod.docs;
+}
+
+/** Core's built-in icon names, read from its icon registry source. */
+export function readCoreIconNames() {
+ const source = fs.readFileSync(
+ path.join(CORE_ROOT, 'src', 'Icon', 'globalIconRegistry.tsx'),
+ 'utf8',
+ );
+ const union = /export type IconName =([\s\S]*?);/.exec(source);
+ if (!union) throw new Error('Could not find the IconName union in core');
+ return [...union[1].matchAll(/'([^']+)'/g)].map(match => match[1]);
+}
diff --git a/packages/native/scripts/generate.mjs b/packages/native/scripts/generate.mjs
new file mode 100644
index 0000000000..78f78bb8a1
--- /dev/null
+++ b/packages/native/scripts/generate.mjs
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file scripts/generate.mjs
+ * @input Built contract tools (dist/) and core documentation
+ * @output --types: dist/types/*.d.ts. --apple: apple/Sources/AstryxNative/Generated/*.swift
+ * @position Run by `build` and `generate:apple`; the Swift output is committed
+ * and a test fails when it drifts from the contracts
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {loadCoreDoc} from './core-docs.mjs';
+
+const PACKAGE_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..',
+);
+const APPLE_GENERATED = path.join(
+ PACKAGE_ROOT,
+ 'apple',
+ 'Sources',
+ 'AstryxNative',
+ 'Generated',
+);
+
+const args = new Set(process.argv.slice(2));
+if (!args.has('--types') && !args.has('--apple')) {
+ console.error('Usage: node scripts/generate.mjs [--types] [--apple]');
+ process.exit(1);
+}
+
+const {buildContracts, generateTypeScript, generateSwift} = await import(
+ pathToFileURL(path.join(PACKAGE_ROOT, 'dist', 'contract', 'index.js')).href
+);
+const {contracts, warnings} = await buildContracts(loadCoreDoc);
+for (const warning of warnings) console.warn(`warning: ${warning.message}`);
+
+function writeAll(dir, files) {
+ fs.mkdirSync(dir, {recursive: true});
+ for (const [name, contents] of Object.entries(files)) {
+ fs.writeFileSync(path.join(dir, name), contents);
+ }
+ console.log(
+ `wrote ${Object.keys(files).length} files to ${path.relative(PACKAGE_ROOT, dir)}`,
+ );
+}
+
+if (args.has('--types'))
+ writeAll(
+ path.join(PACKAGE_ROOT, 'dist', 'types'),
+ generateTypeScript(contracts),
+ );
+if (args.has('--apple')) writeAll(APPLE_GENERATED, generateSwift(contracts));
diff --git a/packages/native/src/components/Selector.ts b/packages/native/src/components/Selector.ts
new file mode 100644
index 0000000000..17b7e730ab
--- /dev/null
+++ b/packages/native/src/components/Selector.ts
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file components/Selector.ts
+ * @input None
+ * @output What @astryxdesign/native adds to the core Selector contract
+ * @position Native additions read by fromComponentDoc together with core's
+ * Selector documentation
+ */
+
+import type {NativeAdditions} from '../contract/fromComponentDoc.js';
+
+export const selector: NativeAdditions = {
+ name: 'Selector',
+ baseTarget: 'trigger',
+ typeNames: {SelectorOption: 'SelectorOption'},
+ types: {
+ // The portable part of core's option data. Its rich description, icon,
+ // and secondary control are web-only until typed slots exist.
+ SelectorOption: {
+ value: {type: {kind: 'string'}},
+ label: {type: {kind: 'string'}, optional: true},
+ disabled: {type: {kind: 'boolean'}, optional: true},
+ },
+ },
+ webOnly: {
+ presentation:
+ 'web presentation choice; native platforms use their own control (FR11)',
+ },
+ platforms: {
+ ios: {
+ menuStyle: {
+ type: {kind: 'enum', values: ['popUp', 'pullDown']},
+ optional: true,
+ },
+ },
+ macos: {
+ menuStyle: {
+ type: {kind: 'enum', values: ['popUp', 'pullDown']},
+ optional: true,
+ },
+ },
+ android: {
+ menuStyle: {
+ type: {kind: 'enum', values: ['dropdown', 'bottomSheet']},
+ optional: true,
+ },
+ },
+ },
+};
diff --git a/packages/native/src/components/index.ts b/packages/native/src/components/index.ts
new file mode 100644
index 0000000000..6952949c09
--- /dev/null
+++ b/packages/native/src/components/index.ts
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file components/index.ts
+ * @input None
+ * @output Every component the native package adds to, by core component name
+ * @position The generator walks this list; each entry pairs with core's
+ * `<Name>/<Name>.doc.mjs`
+ */
+
+import type {NativeAdditions} from '../contract/fromComponentDoc.js';
+import {selector} from './Selector.js';
+
+export const NATIVE_COMPONENTS: readonly NativeAdditions[] = [selector];
diff --git a/packages/native/src/contract/contracts.test.ts b/packages/native/src/contract/contracts.test.ts
new file mode 100644
index 0000000000..d601ae0153
--- /dev/null
+++ b/packages/native/src/contract/contracts.test.ts
@@ -0,0 +1,150 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import ts from 'typescript';
+import {describe, expect, it} from 'vitest';
+import {loadCoreDoc} from '../../scripts/core-docs.mjs';
+import {
+ buildContracts,
+ checkContract,
+ generateSwift,
+ generateTypeScript,
+} from './index.js';
+import type {ComponentContract} from './types.js';
+
+const PACKAGE_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../..',
+);
+const APPLE_GENERATED = path.join(
+ PACKAGE_ROOT,
+ 'apple/Sources/AstryxNative/Generated',
+);
+
+describe('native contracts', () => {
+ it('splits core Selector documentation into a portable core and a web part', async () => {
+ const {contracts} = await buildContracts(loadCoreDoc);
+ const selector = contracts.find(contract => contract.name === 'Selector');
+ expect(selector).toBeDefined();
+ expect(Object.keys(selector!.core)).toEqual(
+ expect.arrayContaining([
+ 'label',
+ 'options',
+ 'value',
+ 'onChange',
+ 'isDisabled',
+ 'status',
+ ]),
+ );
+ const web = new Map(
+ selector!.webOnly.map(prop => [prop.name, prop.reason]),
+ );
+ expect(web.get('renderOption')).toContain('render function');
+ expect(web.get('emptyText')).toContain('typed slot');
+ expect(web.get('onClick')).toContain('DOM event');
+ expect(web.get('presentation')).toContain(
+ 'native platforms use their own control',
+ );
+ expect(selector!.core).not.toHaveProperty('controlXstyle');
+ });
+
+ it('reports naming and portability errors', () => {
+ const bad: ComponentContract = {
+ name: 'Bad',
+ baseTarget: 'root',
+ types: {},
+ core: {
+ as: {type: {kind: 'string'}},
+ style: {type: {kind: 'string'}},
+ item: {type: {kind: 'named', name: 'Missing'}},
+ },
+ platforms: {
+ ios: {item: {type: {kind: 'string'}}, var: {type: {kind: 'boolean'}}},
+ },
+ webOnly: [],
+ };
+ const rules = checkContract(bad).map(issue => issue.rule);
+ expect(rules).toEqual(
+ expect.arrayContaining([
+ 'name-keyword',
+ 'name-toolkit',
+ 'platform-shadows-core',
+ 'unknown-type',
+ ]),
+ );
+ });
+
+ it('keeps the committed Swift binding in sync with the contracts', async () => {
+ const {contracts} = await buildContracts(loadCoreDoc);
+ for (const [name, contents] of Object.entries(generateSwift(contracts))) {
+ const committed = fs.readFileSync(
+ path.join(APPLE_GENERATED, name),
+ 'utf8',
+ );
+ expect(
+ committed,
+ `${name} is stale; run pnpm -F @astryxdesign/native generate:apple`,
+ ).toBe(contents);
+ }
+ });
+
+ it('exposes each platform only its own props through type-resolution conditions', async () => {
+ const {contracts} = await buildContracts(loadCoreDoc);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-native-types-'));
+ const pkg = path.join(dir, 'node_modules/@astryxdesign/native');
+ fs.mkdirSync(path.join(pkg, 'types'), {recursive: true});
+ for (const [name, contents] of Object.entries(
+ generateTypeScript(contracts),
+ )) {
+ fs.writeFileSync(path.join(pkg, 'types', name), contents);
+ }
+ const manifest = JSON.parse(
+ fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'),
+ );
+ const exportsMap = JSON.stringify(
+ manifest.exports['./components'],
+ ).replaceAll('./dist/types/', './types/');
+ fs.writeFileSync(
+ path.join(pkg, 'package.json'),
+ JSON.stringify({
+ name: '@astryxdesign/native',
+ type: 'module',
+ exports: {'./components': JSON.parse(exportsMap)},
+ }),
+ );
+ const usage = (menuStyle: string) =>
+ "import type {SelectorProps} from '@astryxdesign/native/components';\n" +
+ `export const props: SelectorProps = {label: 'Shipping', options: [], menuStyle: '${menuStyle}'};\n`;
+
+ const errorsFor = (condition: string | null, source: string) => {
+ const file = path.join(dir, `${condition ?? 'none'}.ts`);
+ fs.writeFileSync(file, source);
+ const program = ts.createProgram([file], {
+ strict: true,
+ noEmit: true,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ customConditions: condition ? [condition] : [],
+ types: [],
+ });
+ return ts
+ .getPreEmitDiagnostics(program)
+ .map(d => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
+ };
+
+ expect(errorsFor('ios', usage('pullDown'))).toEqual([]);
+ expect(errorsFor('android', usage('bottomSheet'))).toEqual([]);
+ expect(errorsFor('android', usage('pullDown')).join('\n')).toContain(
+ 'pullDown',
+ );
+ expect(errorsFor('shared', usage('pullDown')).join('\n')).toContain(
+ 'menuStyle',
+ );
+ expect(errorsFor(null, usage('pullDown')).join('\n')).toContain(
+ 'menuStyle',
+ );
+ });
+});
diff --git a/packages/native/src/contract/fromComponentDoc.ts b/packages/native/src/contract/fromComponentDoc.ts
new file mode 100644
index 0000000000..1e85851999
--- /dev/null
+++ b/packages/native/src/contract/fromComponentDoc.ts
@@ -0,0 +1,131 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contract/fromComponentDoc.ts
+ * @input A component's documentation (.doc.mjs) plus the native additions for it
+ * @output A component contract: the portable core, native platform props, and the
+ * web-only props with reasons
+ * @position Turns core documentation into the contract the generators consume.
+ * Reads documentation as data at build time; never imports core at run time
+ * (AST-082 FR16)
+ */
+
+import {parseDocType} from './parseDocType.js';
+import {coreNameProblem} from './rules.js';
+import type {
+ BaseTarget,
+ ComponentContract,
+ PropMap,
+ PropSpec,
+ WebOnlyProp,
+} from './types.js';
+import type {NativePlatform} from '../platforms.js';
+
+/** The subset of a ComponentDoc this reader needs. */
+export interface ComponentDocLike {
+ readonly name: string;
+ readonly props?: ReadonlyArray<{
+ readonly name: string;
+ readonly type?: unknown;
+ readonly required?: boolean;
+ readonly description?: unknown;
+ }>;
+}
+
+/** What the native package adds to one core component. */
+export interface NativeAdditions {
+ readonly name: string;
+ readonly baseTarget: BaseTarget;
+ /**
+ * Portable definitions for named types the documentation references. Fields
+ * the web type has that are not portable are left out on purpose.
+ */
+ readonly types?: Readonly<Record<string, PropMap>>;
+ /** Documented types renamed to a native definition, e.g. `SelectorOption[]`. */
+ readonly typeNames?: Readonly<Record<string, string>>;
+ readonly platforms?: Readonly<Partial<Record<NativePlatform, PropMap>>>;
+ /**
+ * Portable-typed props that still belong to the web contract, with the
+ * reason, such as a web presentation heuristic a native platform replaces.
+ */
+ readonly webOnly?: Readonly<Record<string, string>>;
+}
+
+export function fromComponentDoc(
+ doc: ComponentDocLike,
+ additions: NativeAdditions,
+): ComponentContract {
+ const core: Record<string, PropSpec> = {};
+ const webOnly: WebOnlyProp[] = [];
+ const types = additions.types ?? {};
+
+ for (const prop of doc.props ?? []) {
+ const declaredWebOnly = additions.webOnly?.[prop.name];
+ if (declaredWebOnly) {
+ webOnly.push({name: prop.name, reason: declaredWebOnly});
+ continue;
+ }
+ if (
+ /(?:Xstyle|XStyle|ClassName|Style)$/.test(prop.name) ||
+ prop.name === 'xstyle'
+ ) {
+ webOnly.push({name: prop.name, reason: 'web styling input'});
+ continue;
+ }
+ if (prop.name.startsWith('html') || prop.name.startsWith('aria-')) {
+ webOnly.push({name: prop.name, reason: 'HTML attribute'});
+ continue;
+ }
+ const parsed = parseDocType(String(prop.type ?? ''));
+ if (!parsed.ok) {
+ webOnly.push({name: prop.name, reason: parsed.reason});
+ continue;
+ }
+ // A portable type can still carry a name another platform owns.
+ const nameProblem = coreNameProblem(prop.name);
+ if (nameProblem) {
+ webOnly.push({name: prop.name, reason: nameProblem});
+ continue;
+ }
+ let type = parsed.type;
+ const renamed = (name: string) => additions.typeNames?.[name] ?? name;
+ if (type.kind === 'named') {
+ type = {kind: 'named', name: renamed(type.name)};
+ }
+ if (type.kind === 'array' && type.of.kind === 'named') {
+ type = {kind: 'array', of: {kind: 'named', name: renamed(type.of.name)}};
+ }
+ if (type.kind === 'named' && !(type.name in types)) {
+ webOnly.push({
+ name: prop.name,
+ reason: `type "${type.name}" has no portable definition yet`,
+ });
+ continue;
+ }
+ if (
+ type.kind === 'array' &&
+ type.of.kind === 'named' &&
+ !(type.of.name in types)
+ ) {
+ webOnly.push({
+ name: prop.name,
+ reason: `type "${type.of.name}" has no portable definition yet`,
+ });
+ continue;
+ }
+ core[prop.name] = {
+ type,
+ optional: prop.required !== true,
+ ...(typeof prop.description === 'string' ? {doc: prop.description} : {}),
+ };
+ }
+
+ return {
+ name: additions.name,
+ baseTarget: additions.baseTarget,
+ types,
+ core,
+ platforms: additions.platforms ?? {},
+ webOnly,
+ };
+}
diff --git a/packages/native/src/contract/generateSwift.ts b/packages/native/src/contract/generateSwift.ts
new file mode 100644
index 0000000000..5dcc6a2280
--- /dev/null
+++ b/packages/native/src/contract/generateSwift.ts
@@ -0,0 +1,170 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contract/generateSwift.ts
+ * @input Component contracts
+ * @output Swift sources for the Apple platforms: shared base props and one file
+ * per component, with the iOS and macOS contracts behind `#if os(...)`
+ * @position Produces the Swift binding (AST-082 FR5). Generated files are
+ * committed under apple/ so a Swift package can pin a commit
+ */
+
+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 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;
+
+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, 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, 'Equatable, Sendable'));
+ return name;
+ }
+ case 'fn':
+ return `(${type.args.map((arg, i) => this.type(owner, `${prop}Arg${i}`, arg)).join(', ')}) -> Void`;
+ 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');
+ }
+}
+
+function componentFile(contract: ComponentContract): string {
+ const shared = new SwiftWriter();
+ const typeDecls = Object.entries(contract.types).map(([name, fields]) =>
+ shared.struct(name, fields, 'Equatable, Sendable'),
+ );
+ // 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 fields = writer.fields(contract.name, {...contract.core, ...extra});
+ // 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].join('\n')}\n#endif`;
+ });
+
+ return (
+ HEADER + [...typeDecls, ...shared.decls, ...variants].join('\n') + '\n'
+ );
+}
+
+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, 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';
+
+/** 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};
+ for (const contract of contracts) {
+ files[`${contract.name}.swift`] = componentFile(contract);
+ }
+ return files;
+}
diff --git a/packages/native/src/contract/generateTypeScript.ts b/packages/native/src/contract/generateTypeScript.ts
new file mode 100644
index 0000000000..df8e43bb93
--- /dev/null
+++ b/packages/native/src/contract/generateTypeScript.ts
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contract/generateTypeScript.ts
+ * @input Component contracts
+ * @output Declaration files: core.d.ts, one per native platform, and shared.d.ts
+ * @position Produces the platform-scoped types (AST-082 FR5, FR6). The package
+ * exports map selects one file per type-resolution condition
+ */
+
+import {NATIVE_PLATFORMS, type NativePlatform} from '../platforms.js';
+import type {ComponentContract, PropMap, PropType} from './types.js';
+
+const HEADER = '// Generated by @astryxdesign/native. Do not edit.\n';
+
+function tsType(type: PropType): string {
+ switch (type.kind) {
+ case 'string':
+ case 'number':
+ case 'boolean':
+ return type.kind;
+ case 'enum':
+ return type.values.map(value => `'${value}'`).join(' | ');
+ case 'array': {
+ const inner = tsType(type.of);
+ return `ReadonlyArray<${inner}>`;
+ }
+ case 'record':
+ return `{${members(type.fields, ' ')}}`;
+ case 'fn':
+ return `(${type.args.map((arg, i) => `arg${i}: ${tsType(arg)}`).join(', ')}) => void`;
+ case 'named':
+ return type.name;
+ }
+}
+
+function key(name: string): string {
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : `'${name}'`;
+}
+
+function members(props: PropMap, separator = '\n '): string {
+ return Object.entries(props)
+ .map(
+ ([name, spec]) =>
+ `${key(name)}${spec.optional ? '?' : ''}: ${tsType(spec.type)};`,
+ )
+ .join(separator);
+}
+
+function coreFile(contracts: readonly ComponentContract[]): string {
+ const types = new Map<string, PropMap>();
+ for (const contract of contracts) {
+ for (const [name, fields] of Object.entries(contract.types)) {
+ types.set(name, fields);
+ }
+ }
+ const typeDecls = [...types].map(
+ ([name, fields]) => `export interface ${name} {\n ${members(fields)}\n}`,
+ );
+ const props = contracts.map(
+ contract =>
+ `/** Core contract. Base props attach to the ${contract.baseTarget}. */\n` +
+ `export interface ${contract.name}CoreProps extends AstryxSharedBaseProps {\n ${members(contract.core)}\n}`,
+ );
+ return (
+ HEADER +
+ '/** Base props shared by every platform (AST-082 FR7). */\n' +
+ 'export interface AstryxSharedBaseProps {\n id?: string;\n isHidden?: boolean;\n}\n' +
+ [...typeDecls, ...props].join('\n') +
+ '\n'
+ );
+}
+
+function reExports(contracts: readonly ComponentContract[]): string {
+ const names = new Set<string>(['AstryxSharedBaseProps']);
+ for (const contract of contracts) {
+ Object.keys(contract.types).forEach(name => names.add(name));
+ names.add(`${contract.name}CoreProps`);
+ }
+ return `export type {${[...names].join(', ')}} from './core.js';\n`;
+}
+
+function platformFile(
+ contracts: readonly ComponentContract[],
+ platform: NativePlatform | null,
+): string {
+ const imports = `import type {${contracts.map(c => `${c.name}CoreProps`).join(', ')}} from './core.js';\n`;
+ const components = contracts.map(contract => {
+ const extra = platform ? (contract.platforms[platform] ?? {}) : {};
+ const body = Object.keys(extra).length > 0 ? `\n ${members(extra)}\n` : '';
+ const scope = platform
+ ? `core contract plus the ${platform} contract`
+ : 'core contract only';
+ return (
+ `/** ${contract.name} props: ${scope}. */\n` +
+ `export interface ${contract.name}Props extends ${contract.name}CoreProps {${body}}\n` +
+ `export declare function ${contract.name}(props: ${contract.name}Props): unknown;`
+ );
+ });
+ return HEADER + imports + reExports(contracts) + components.join('\n') + '\n';
+}
+
+/** Returns file name to contents, relative to the types output folder. */
+export function generateTypeScript(
+ contracts: readonly ComponentContract[],
+): Record<string, string> {
+ const files: Record<string, string> = {
+ 'core.d.ts': coreFile(contracts),
+ 'shared.d.ts': platformFile(contracts, null),
+ };
+ for (const platform of NATIVE_PLATFORMS) {
+ files[`${platform}.d.ts`] = platformFile(contracts, platform);
+ }
+ return files;
+}
diff --git a/packages/native/src/contract/index.ts b/packages/native/src/contract/index.ts
new file mode 100644
index 0000000000..41dd49823b
--- /dev/null
+++ b/packages/native/src/contract/index.ts
@@ -0,0 +1,53 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contract/index.ts
+ * @input Core component documentation, supplied by the caller
+ * @output Contracts for every native component, checked, plus the generators
+ * @position Build-time entry (`@astryxdesign/native/contract`). Reads core
+ * documentation as data; nothing here runs in an app
+ */
+
+import {NATIVE_COMPONENTS} from '../components/index.js';
+import {fromComponentDoc, type ComponentDocLike} from './fromComponentDoc.js';
+import {checkContract, type ContractIssue} from './rules.js';
+import type {ComponentContract} from './types.js';
+
+export {fromComponentDoc} from './fromComponentDoc.js';
+export type {ComponentDocLike, NativeAdditions} from './fromComponentDoc.js';
+export {generateSwift} from './generateSwift.js';
+export {generateTypeScript} from './generateTypeScript.js';
+export {parseDocType} from './parseDocType.js';
+export {checkContract, coreNameProblem} from './rules.js';
+export type {ContractIssue} from './rules.js';
+export type * from './types.js';
+
+/** Loads one core component's documentation by component name. */
+export type ComponentDocLoader = (name: string) => Promise<ComponentDocLike>;
+
+export interface BuiltContracts {
+ readonly contracts: readonly ComponentContract[];
+ readonly warnings: readonly ContractIssue[];
+}
+
+/** Builds and checks every native component contract; throws on any error. */
+export async function buildContracts(
+ loadDoc: ComponentDocLoader,
+): Promise<BuiltContracts> {
+ const contracts: ComponentContract[] = [];
+ const warnings: ContractIssue[] = [];
+ const errors: ContractIssue[] = [];
+ for (const additions of NATIVE_COMPONENTS) {
+ const contract = fromComponentDoc(await loadDoc(additions.name), additions);
+ for (const issue of checkContract(contract)) {
+ (issue.level === 'error' ? errors : warnings).push(issue);
+ }
+ contracts.push(contract);
+ }
+ if (errors.length > 0) {
+ throw new Error(
+ `Native contracts are invalid:\n${errors.map(e => ` ${e.message}`).join('\n')}`,
+ );
+ }
+ return {contracts, warnings};
+}
diff --git a/packages/native/src/contract/names.ts b/packages/native/src/contract/names.ts
new file mode 100644
index 0000000000..46bd361ec8
--- /dev/null
+++ b/packages/native/src/contract/names.ts
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contract/names.ts
+ * @input None
+ * @output Name lists the AST-082 FR8 rules check against
+ * @position Data for contract/rules.ts and contract/fromComponentDoc.ts
+ */
+
+export const SWIFT_KEYWORDS: ReadonlySet<string> = new Set(
+ (
+ 'associatedtype class deinit enum extension fileprivate func import init inout ' +
+ 'internal let open operator private precedencegroup protocol public rethrows ' +
+ 'static struct subscript typealias var break case catch continue default defer ' +
+ 'do else fallthrough for guard if in repeat return throw switch where while Any ' +
+ 'as await false is nil self Self super throws true try'
+ ).split(' '),
+);
+
+export const KOTLIN_KEYWORDS: ReadonlySet<string> = new Set(
+ (
+ 'as break class continue do else false for fun if in interface is null object ' +
+ 'package return super this throw true try typealias typeof val var when while'
+ ).split(' '),
+);
+
+/**
+ * Names each platform toolkit already uses with its own meaning. A core prop
+ * must not take one of them unless Astryx reclaims it (RECLAIMED).
+ */
+export const TOOLKIT_NAMES: Readonly<Record<string, ReadonlySet<string>>> = {
+ web: new Set([
+ 'children',
+ 'className',
+ 'style',
+ 'title',
+ 'hidden',
+ 'role',
+ 'tabIndex',
+ 'dir',
+ 'slot',
+ 'is',
+ 'key',
+ 'ref',
+ 'onChange',
+ 'color',
+ 'content',
+ ]),
+ reactNative: new Set([
+ 'style',
+ 'testID',
+ 'nativeID',
+ 'onPress',
+ 'onLongPress',
+ 'onLayout',
+ 'accessibilityLabel',
+ 'accessibilityHint',
+ 'accessibilityRole',
+ 'accessibilityState',
+ 'accessible',
+ 'hitSlop',
+ 'pointerEvents',
+ 'disabled',
+ 'editable',
+ 'numberOfLines',
+ 'onChangeText',
+ 'selectable',
+ ]),
+ swiftUI: new Set([
+ 'body',
+ 'disabled',
+ 'hidden',
+ 'opacity',
+ 'frame',
+ 'tint',
+ 'font',
+ 'background',
+ 'overlay',
+ 'accessibilityLabel',
+ 'accessibilityHint',
+ 'accessibilityIdentifier',
+ ]),
+ compose: new Set([
+ 'modifier',
+ 'enabled',
+ 'onClick',
+ 'colors',
+ 'testTag',
+ 'contentDescription',
+ ]),
+};
+
+/**
+ * Web names Astryx deliberately takes over for a component-owned concept
+ * (AST-082 FR8). The platform's own meaning is removed from that component's
+ * base props.
+ */
+export const RECLAIMED: ReadonlySet<string> = new Set([
+ 'onChange',
+ 'title',
+ 'color',
+ 'content',
+]);
diff --git a/packages/native/src/contract/parseDocType.test.ts b/packages/native/src/contract/parseDocType.test.ts
new file mode 100644
index 0000000000..7eb8bfa14b
--- /dev/null
+++ b/packages/native/src/contract/parseDocType.test.ts
@@ -0,0 +1,52 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {parseDocType} from './parseDocType.js';
+
+describe('parseDocType', () => {
+ it('reads portable forms', () => {
+ expect(parseDocType('string')).toEqual({ok: true, type: {kind: 'string'}});
+ expect(parseDocType("'sm' | 'md' | 'lg'")).toEqual({
+ ok: true,
+ type: {kind: 'enum', values: ['sm', 'md', 'lg']},
+ });
+ expect(parseDocType('SelectorOption[]')).toEqual({
+ ok: true,
+ type: {kind: 'array', of: {kind: 'named', name: 'SelectorOption'}},
+ });
+ expect(parseDocType('(value: string) => void')).toEqual({
+ ok: true,
+ type: {kind: 'fn', args: [{kind: 'string'}]},
+ });
+ expect(
+ parseDocType("{type: 'error' | 'warning', message?: string}"),
+ ).toEqual({
+ ok: true,
+ type: {
+ kind: 'record',
+ fields: {
+ type: {
+ type: {kind: 'enum', values: ['error', 'warning']},
+ optional: false,
+ },
+ message: {type: {kind: 'string'}, optional: true},
+ },
+ },
+ });
+ });
+
+ it.each([
+ ['ReactNode', 'free-form content'],
+ ['IconType | ReactNode', 'web icon component'],
+ ['(option: SelectorOptionData) => ReactNode', 'render function'],
+ ['(event: MouseEvent) => void', 'DOM event'],
+ ['StyleXStyles', 'web styling input'],
+ ['number | string', 'union of different kinds'],
+ ])('keeps %s out of the core', (type, reason) => {
+ const parsed = parseDocType(type);
+ expect(parsed.ok).toBe(false);
+ if (!parsed.ok) {
+ expect(parsed.reason).toContain(reason);
+ }
+ });
+});
diff --git a/packages/native/src/contract/parseDocType.ts b/packages/native/src/contract/parseDocType.ts
new file mode 100644
index 0000000000..f589b158c1
--- /dev/null
+++ b/packages/native/src/contract/parseDocType.ts
@@ -0,0 +1,211 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contract/parseDocType.ts
+ * @input A prop's type string as a component's .doc.mjs documents it
+ * @output A portable PropType, or the reason the type has no portable form
+ * @position Reads core documentation into the contract model (AST-082 FR4)
+ */
+
+import type {PropSpec, PropType} from './types.js';
+
+export type ParsedType =
+ | {readonly ok: true; readonly type: PropType}
+ | {readonly ok: false; readonly reason: string};
+
+/** Web-only types, keyed by name, with the reason each has no native form. */
+const WEB_ONLY_TYPES: Readonly<Record<string, string>> = {
+ ReactNode: 'free-form content; use a typed slot in the core',
+ ReactElement: 'free-form content; use a typed slot in the core',
+ 'JSX.Element': 'free-form content; use a typed slot in the core',
+ StyleXStyles: 'web styling input',
+ CSSProperties: 'web styling input',
+ SizeValue: 'CSS length',
+ IconType: 'web icon component; native icons use shared icon names',
+ ElementType: 'web element choice',
+ ComponentType: 'web component reference',
+ LinkComponentType: 'web link component',
+ AriaRole: 'web accessibility attribute',
+ MouseEvent: 'DOM event',
+ FocusEvent: 'DOM event',
+ KeyboardEvent: 'DOM event',
+ PointerEvent: 'DOM event',
+ ChangeEvent: 'DOM event',
+ DragEvent: 'DOM event',
+ ClipboardEvent: 'DOM event',
+};
+
+const ok = (type: PropType): ParsedType => ({ok: true, type});
+const no = (reason: string): ParsedType => ({ok: false, reason});
+
+/** Splits on a separator at bracket depth zero, ignoring quoted text. */
+function splitTop(text: string, separator: string): string[] {
+ const parts: string[] = [];
+ let depth = 0;
+ let quote: string | null = null;
+ let start = 0;
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+ if (quote) {
+ if (ch === quote) {
+ quote = null;
+ }
+ continue;
+ }
+ if (ch === "'" || ch === '"') {
+ quote = ch;
+ } else if (text.startsWith('=>', i)) {
+ // An arrow is not a closing angle bracket.
+ if (depth === 0 && separator === '=>') {
+ parts.push(text.slice(start, i));
+ start = i + 2;
+ }
+ i += 1;
+ } else if ('([{<'.includes(ch)) {
+ depth++;
+ } else if (')]}>'.includes(ch)) {
+ depth--;
+ } else if (depth === 0 && text.startsWith(separator, i)) {
+ parts.push(text.slice(start, i));
+ start = i + separator.length;
+ i += separator.length - 1;
+ }
+ }
+ parts.push(text.slice(start));
+ return parts.map(part => part.trim()).filter(part => part.length > 0);
+}
+
+/** True when the first `(` closes at the last character, as in `(A | B)`. */
+function isWrappedInParens(text: string): boolean {
+ if (!text.startsWith('(') || !text.endsWith(')')) {
+ return false;
+ }
+ let depth = 0;
+ for (let i = 0; i < text.length; i++) {
+ if (text[i] === '(') {
+ depth++;
+ } else if (text[i] === ')') {
+ depth--;
+ }
+ if (depth === 0 && i < text.length - 1) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function stripOuterParens(text: string): string {
+ let t = text.trim();
+ while (isWrappedInParens(t)) {
+ t = t.slice(1, -1).trim();
+ }
+ return t;
+}
+
+function parseRecord(body: string): ParsedType {
+ const fields: Record<string, PropSpec> = {};
+ for (const member of splitTop(body, ',').flatMap(part =>
+ splitTop(part, ';'),
+ )) {
+ const match = /^([A-Za-z_$][\w$]*)(\?)?\s*:\s*([\s\S]+)$/.exec(member);
+ if (!match) {
+ return no(`record member "${member}" is not a plain field`);
+ }
+ const parsed = parseDocType(match[3]);
+ if (!parsed.ok) {
+ return no(`field "${match[1]}": ${parsed.reason}`);
+ }
+ fields[match[1]] = {type: parsed.type, optional: match[2] === '?'};
+ }
+ return ok({kind: 'record', fields});
+}
+
+function parseFunction(text: string): ParsedType | null {
+ const arrow = splitTop(text, '=>');
+ if (arrow.length !== 2 || !arrow[0].startsWith('(')) {
+ return null;
+ }
+ const returns = arrow[1].trim();
+ if (returns !== 'void') {
+ return no(
+ /React|ReactNode|JSX/.test(returns)
+ ? 'render function; it returns web UI'
+ : 'callback returns a value; only void callbacks are portable today',
+ );
+ }
+ const params = arrow[0].slice(1, -1).trim();
+ const args: PropType[] = [];
+ for (const param of params ? splitTop(params, ',') : []) {
+ const match = /^([A-Za-z_$][\w$]*)\??\s*:\s*([\s\S]+)$/.exec(param);
+ const parsed = parseDocType(match ? match[2] : param);
+ if (!parsed.ok) {
+ return no(`callback argument: ${parsed.reason}`);
+ }
+ args.push(parsed.type);
+ }
+ return ok({kind: 'fn', args});
+}
+
+/**
+ * Parses a documented type string. Supported portable forms: `string`,
+ * `number`, `boolean`, closed string unions, arrays, plain object literals,
+ * callbacks with portable arguments, and named types. A union of different
+ * kinds has no Swift or Kotlin form.
+ */
+export function parseDocType(raw: string): ParsedType {
+ const text = stripOuterParens(raw.replace(/\s+/g, ' ').trim());
+ if (text === '') {
+ return no('no documented type');
+ }
+
+ const fn = parseFunction(text);
+ if (fn) {
+ return fn;
+ }
+
+ const members = splitTop(text, '|').filter(
+ m => m !== 'undefined' && m !== 'null',
+ );
+ if (members.length > 1) {
+ if (members.every(m => /^'[^']*'$/.test(m))) {
+ return ok({kind: 'enum', values: members.map(m => m.slice(1, -1))});
+ }
+ const webOnly = members.find(m => WEB_ONLY_TYPES[m] != null);
+ if (webOnly) {
+ return no(WEB_ONLY_TYPES[webOnly]);
+ }
+ return no('a union of different kinds has no Swift or Kotlin form');
+ }
+ const t = members[0] ?? '';
+
+ if (t === 'string' || t === 'number' || t === 'boolean') {
+ return ok({kind: t});
+ }
+ if (/^'[^']*'$/.test(t)) {
+ return ok({kind: 'enum', values: [t.slice(1, -1)]});
+ }
+ if (WEB_ONLY_TYPES[t] != null) {
+ return no(WEB_ONLY_TYPES[t]);
+ }
+
+ const generic = /^(?:Readonly)?Array<([\s\S]+)>$/.exec(t);
+ if (t.endsWith('[]') || generic) {
+ const inner = parseDocType(generic ? generic[1] : t.slice(0, -2));
+ return inner.ok
+ ? ok({kind: 'array', of: inner.type})
+ : no(`array item: ${inner.reason}`);
+ }
+ if (t.startsWith('{') && t.endsWith('}')) {
+ return parseRecord(t.slice(1, -1));
+ }
+ if (
+ /^(?:React\.)?(?:Ref|RefObject|MutableRefObject)</.test(t) ||
+ /^HTML\w*Element$/.test(t)
+ ) {
+ return no('web element reference');
+ }
+ if (/^[A-Z][\w$]*$/.test(t)) {
+ return ok({kind: 'named', name: t});
+ }
+ return no(`unsupported type "${t}"`);
+}
diff --git a/packages/native/src/contract/rules.ts b/packages/native/src/contract/rules.ts
new file mode 100644
index 0000000000..16f601f911
--- /dev/null
+++ b/packages/native/src/contract/rules.ts
@@ -0,0 +1,132 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contract/rules.ts
+ * @input A component contract
+ * @output Naming and portability issues under AST-082 FR4 and FR8
+ * @position Run by the generator before it writes any binding; an error stops
+ * generation
+ */
+
+import {NATIVE_PLATFORMS} from '../platforms.js';
+import {
+ KOTLIN_KEYWORDS,
+ RECLAIMED,
+ SWIFT_KEYWORDS,
+ TOOLKIT_NAMES,
+} from './names.js';
+import type {ComponentContract, PropMap, PropType} from './types.js';
+
+export interface ContractIssue {
+ readonly level: 'error' | 'warning';
+ readonly rule:
+ | 'core-is-portable'
+ | 'name-keyword'
+ | 'name-toolkit'
+ | 'platform-shadows-core'
+ | 'same-name-different-meaning'
+ | 'unknown-type';
+ readonly message: string;
+}
+
+/** Why a core prop name is not allowed, or null when it is. */
+export function coreNameProblem(name: string): string | null {
+ if (SWIFT_KEYWORDS.has(name)) {
+ return `"${name}" is a Swift keyword`;
+ }
+ if (KOTLIN_KEYWORDS.has(name)) {
+ return `"${name}" is a Kotlin keyword`;
+ }
+ if (RECLAIMED.has(name)) {
+ return null;
+ }
+ for (const [toolkit, names] of Object.entries(TOOLKIT_NAMES)) {
+ if (names.has(name)) {
+ return `"${name}" already means something else in ${toolkit}`;
+ }
+ }
+ return null;
+}
+
+function namedTypesIn(type: PropType, into: Set<string>): Set<string> {
+ if (type.kind === 'named') {
+ into.add(type.name);
+ } else if (type.kind === 'array') {
+ namedTypesIn(type.of, into);
+ } else if (type.kind === 'fn') {
+ type.args.forEach(arg => namedTypesIn(arg, into));
+ } else if (type.kind === 'record') {
+ Object.values(type.fields).forEach(field => namedTypesIn(field.type, into));
+ }
+ return into;
+}
+
+export function checkContract(contract: ComponentContract): ContractIssue[] {
+ const issues: ContractIssue[] = [];
+ const add = (
+ level: ContractIssue['level'],
+ rule: ContractIssue['rule'],
+ message: string,
+ ) => issues.push({level, rule, message: `${contract.name}: ${message}`});
+
+ const referenced = new Set<string>();
+ const collect = (props: PropMap) =>
+ Object.values(props).forEach(spec => namedTypesIn(spec.type, referenced));
+
+ for (const name of Object.keys(contract.core)) {
+ const problem = coreNameProblem(name);
+ if (problem) {
+ add(
+ 'error',
+ SWIFT_KEYWORDS.has(name) || KOTLIN_KEYWORDS.has(name)
+ ? 'name-keyword'
+ : 'name-toolkit',
+ `core prop ${problem}`,
+ );
+ }
+ }
+ collect(contract.core);
+
+ const seen = new Map<string, {platform: string; type: string}>();
+ for (const platform of NATIVE_PLATFORMS) {
+ const props = contract.platforms[platform] ?? {};
+ collect(props);
+ for (const [name, spec] of Object.entries(props)) {
+ if (name in contract.core) {
+ add(
+ 'error',
+ 'platform-shadows-core',
+ `${platform} prop "${name}" reuses a core prop name`,
+ );
+ }
+ if (SWIFT_KEYWORDS.has(name) || KOTLIN_KEYWORDS.has(name)) {
+ add(
+ 'error',
+ 'name-keyword',
+ `${platform} prop "${name}" is a Swift or Kotlin keyword`,
+ );
+ }
+ const type = JSON.stringify(spec.type);
+ const earlier = seen.get(name);
+ if (earlier && earlier.type !== type) {
+ add(
+ 'warning',
+ 'same-name-different-meaning',
+ `"${name}" has different values on ${earlier.platform} and ${platform}; ` +
+ 'allowed in platform-scoped types, never in a merged type',
+ );
+ }
+ if (!earlier) {
+ seen.set(name, {platform, type});
+ }
+ }
+ }
+
+ Object.values(contract.types).forEach(collect);
+ for (const name of referenced) {
+ if (!(name in contract.types)) {
+ add('error', 'unknown-type', `type "${name}" has no definition`);
+ }
+ }
+ return issues;
+}
diff --git a/packages/native/src/contract/types.ts b/packages/native/src/contract/types.ts
new file mode 100644
index 0000000000..b47ed20820
--- /dev/null
+++ b/packages/native/src/contract/types.ts
@@ -0,0 +1,52 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contract/types.ts
+ * @input None (pure type definitions)
+ * @output The contract model: portable prop types, prop specs, and component contracts
+ * @position Foundation of the contract generator; parseDocType produces these,
+ * generators consume them
+ */
+
+import type {NativePlatform} from '../platforms.js';
+
+/** A prop type every supported platform language can express (AST-082 FR4). */
+export type PropType =
+ | {kind: 'string'}
+ | {kind: 'number'}
+ | {kind: 'boolean'}
+ | {kind: 'enum'; values: readonly string[]}
+ | {kind: 'array'; of: PropType}
+ | {kind: 'record'; fields: Readonly<Record<string, PropSpec>>}
+ | {kind: 'fn'; args: readonly PropType[]}
+ | {kind: 'named'; name: string};
+
+export interface PropSpec {
+ readonly type: PropType;
+ readonly optional?: boolean;
+ readonly doc?: string;
+}
+
+export type PropMap = Readonly<Record<string, PropSpec>>;
+
+/** The part of a component its base props attach to (AST-082 FR7). */
+export type BaseTarget = 'root' | 'trigger' | 'control' | 'container';
+
+/** A web prop left out of the core contract, with the reason. */
+export interface WebOnlyProp {
+ readonly name: string;
+ readonly reason: string;
+}
+
+export interface ComponentContract {
+ readonly name: string;
+ readonly baseTarget: BaseTarget;
+ /** Named record types the contract references, such as an option shape. */
+ readonly types: Readonly<Record<string, PropMap>>;
+ /** Shared on every platform that offers the component. */
+ readonly core: PropMap;
+ /** Added per native platform; never removes or renames a core prop. */
+ readonly platforms: Readonly<Partial<Record<NativePlatform, PropMap>>>;
+ /** Core-doc props that stay in the web contract. */
+ readonly webOnly: readonly WebOnlyProp[];
+}
diff --git a/packages/native/src/icons/defaults.test.ts b/packages/native/src/icons/defaults.test.ts
new file mode 100644
index 0000000000..ff07d67152
--- /dev/null
+++ b/packages/native/src/icons/defaults.test.ts
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import {execFileSync} from 'node:child_process';
+import {describe, expect, it} from 'vitest';
+import {readCoreIconNames} from '../../scripts/core-docs.mjs';
+import {
+ BUILTIN_ICON_NAMES,
+ NATIVE_ICON_DEFAULTS,
+ SF_SYMBOL_NAMES,
+} from './defaults.js';
+
+// The system's SF Symbols catalog; present on macOS only.
+const SF_CATALOG =
+ '/System/Library/CoreServices/CoreGlyphs.bundle/Contents/Resources/name_availability.plist';
+
+describe('native icon defaults', () => {
+ it("lists exactly core's built-in icon names", () => {
+ expect([...BUILTIN_ICON_NAMES].sort()).toEqual(readCoreIconNames().sort());
+ });
+
+ it('gives every built-in name a default on each supported platform', () => {
+ for (const platform of ['ios', 'macos', 'android'] as const) {
+ expect(Object.keys(NATIVE_ICON_DEFAULTS[platform]).sort()).toEqual(
+ [...BUILTIN_ICON_NAMES].sort(),
+ );
+ }
+ });
+
+ it.skipIf(!fs.existsSync(SF_CATALOG))(
+ 'names only SF Symbols the system has',
+ () => {
+ const json = execFileSync(
+ 'plutil',
+ ['-convert', 'json', '-o', '-', SF_CATALOG],
+ {
+ maxBuffer: 16 * 1024 * 1024,
+ },
+ ).toString();
+ const symbols = JSON.parse(json).symbols as Record<string, string>;
+ const missing = Object.values(SF_SYMBOL_NAMES).filter(
+ name => symbols[name] == null,
+ );
+ expect(missing).toEqual([]);
+ },
+ );
+});
diff --git a/packages/native/src/icons/defaults.ts b/packages/native/src/icons/defaults.ts
new file mode 100644
index 0000000000..6282790861
--- /dev/null
+++ b/packages/native/src/icons/defaults.ts
@@ -0,0 +1,136 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file icons/defaults.ts
+ * @input None
+ * @output Shared icon names and each native platform's default system symbol
+ * @position Native icon defaults (AST-082 FR17, DEC-10). An icon the app or
+ * theme defines replaces these
+ */
+
+import type {PlatformIcon} from '../theme/defineNativeTheme.js';
+
+/**
+ * Astryx's built-in icon names. Until core's portable entry carries them,
+ * a test keeps this list equal to core's `IconName` union.
+ */
+export const BUILTIN_ICON_NAMES = [
+ 'close',
+ 'chevronDown',
+ 'chevronLeft',
+ 'chevronRight',
+ 'chevronsLeft',
+ 'chevronsRight',
+ 'check',
+ 'success',
+ 'error',
+ 'warning',
+ 'info',
+ 'calendar',
+ 'clock',
+ 'externalLink',
+ 'menu',
+ 'moreHorizontal',
+ 'search',
+ 'upload',
+ 'arrowUp',
+ 'arrowDown',
+ 'arrowsUpDown',
+ 'funnel',
+ 'eyeSlash',
+ 'viewColumns',
+ 'copy',
+ 'checkDouble',
+ 'wrench',
+ 'stop',
+ 'microphone',
+] as const;
+
+export type BuiltinIconName = (typeof BUILTIN_ICON_NAMES)[number];
+
+/** SF Symbols, shared by iOS and macOS. */
+const SF_SYMBOLS: Record<BuiltinIconName, string> = {
+ close: 'xmark',
+ chevronDown: 'chevron.down',
+ chevronLeft: 'chevron.left',
+ chevronRight: 'chevron.right',
+ chevronsLeft: 'chevron.left.2',
+ chevronsRight: 'chevron.right.2',
+ check: 'checkmark',
+ success: 'checkmark.circle.fill',
+ error: 'exclamationmark.circle.fill',
+ warning: 'exclamationmark.triangle.fill',
+ info: 'info.circle.fill',
+ calendar: 'calendar',
+ clock: 'clock',
+ externalLink: 'arrow.up.right.square',
+ menu: 'line.3.horizontal',
+ moreHorizontal: 'ellipsis',
+ search: 'magnifyingglass',
+ upload: 'square.and.arrow.up',
+ arrowUp: 'arrow.up',
+ arrowDown: 'arrow.down',
+ arrowsUpDown: 'arrow.up.arrow.down',
+ funnel: 'line.3.horizontal.decrease',
+ eyeSlash: 'eye.slash',
+ viewColumns: 'rectangle.split.3x1',
+ copy: 'doc.on.doc',
+ checkDouble: 'checkmark.message',
+ wrench: 'wrench.adjustable',
+ stop: 'stop.fill',
+ microphone: 'mic',
+};
+
+/** Material Symbols names for Android. */
+const MATERIAL_SYMBOLS: Record<BuiltinIconName, string> = {
+ close: 'close',
+ chevronDown: 'expand_more',
+ chevronLeft: 'chevron_left',
+ chevronRight: 'chevron_right',
+ chevronsLeft: 'keyboard_double_arrow_left',
+ chevronsRight: 'keyboard_double_arrow_right',
+ check: 'check',
+ success: 'check_circle',
+ error: 'error',
+ warning: 'warning',
+ info: 'info',
+ calendar: 'calendar_today',
+ clock: 'schedule',
+ externalLink: 'open_in_new',
+ menu: 'menu',
+ moreHorizontal: 'more_horiz',
+ search: 'search',
+ upload: 'upload',
+ arrowUp: 'arrow_upward',
+ arrowDown: 'arrow_downward',
+ arrowsUpDown: 'swap_vert',
+ funnel: 'filter_alt',
+ eyeSlash: 'visibility_off',
+ viewColumns: 'view_column',
+ copy: 'content_copy',
+ checkDouble: 'done_all',
+ wrench: 'build',
+ stop: 'stop',
+ microphone: 'mic',
+};
+
+const mapIcons = (
+ names: Record<BuiltinIconName, string>,
+ make: (name: string) => PlatformIcon,
+): Record<BuiltinIconName, PlatformIcon> =>
+ Object.fromEntries(
+ BUILTIN_ICON_NAMES.map(name => [name, make(names[name])]),
+ ) as Record<BuiltinIconName, PlatformIcon>;
+
+/**
+ * Default icons per native platform. Windows has no map yet, so it is not a
+ * supported platform for icons (FR17).
+ */
+export const NATIVE_ICON_DEFAULTS = {
+ ios: mapIcons(SF_SYMBOLS, systemName => ({systemName})),
+ macos: mapIcons(SF_SYMBOLS, systemName => ({systemName})),
+ android: mapIcons(MATERIAL_SYMBOLS, materialSymbol => ({materialSymbol})),
+} as const;
+
+export const SF_SYMBOL_NAMES: Readonly<Record<BuiltinIconName, string>> =
+ SF_SYMBOLS;
diff --git a/packages/native/src/index.ts b/packages/native/src/index.ts
new file mode 100644
index 0000000000..33227c0e83
--- /dev/null
+++ b/packages/native/src/index.ts
@@ -0,0 +1,35 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file index.ts
+ * @input None
+ * @output The run-time API of @astryxdesign/native: platforms, native theme
+ * configuration, and native icon defaults
+ * @position Package root. Experimental and canary-only (AST-082 FR15); component
+ * types live at `@astryxdesign/native/components`
+ */
+
+export {
+ NATIVE_PLATFORMS,
+ SHARED_CONDITION,
+ isNativePlatform,
+} from './platforms.js';
+export type {NativePlatform} from './platforms.js';
+export {
+ compareVersions,
+ defineNativeTheme,
+ resolveNativeTheme,
+} from './theme/defineNativeTheme.js';
+export type {
+ DefineNativeThemeOptions,
+ DurableMaterial,
+ NativeTheme,
+ NativeThemeConfig,
+ PlatformEntry,
+ PlatformIcon,
+ PlatformVocabulary,
+ PortableThemeLike,
+ ResolvedNativeTheme,
+} from './theme/defineNativeTheme.js';
+export {BUILTIN_ICON_NAMES, NATIVE_ICON_DEFAULTS} from './icons/defaults.js';
+export type {BuiltinIconName} from './icons/defaults.js';
diff --git a/packages/native/src/platforms.ts b/packages/native/src/platforms.ts
new file mode 100644
index 0000000000..7c816e6e06
--- /dev/null
+++ b/packages/native/src/platforms.ts
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file platforms.ts
+ * @input None
+ * @output The native platform names shared by contracts, types, themes, and icons
+ * @position Foundation; every other module keys platform data by these names
+ */
+
+/** Native platforms, in the order AST-082 lists them. */
+export const NATIVE_PLATFORMS = ['ios', 'android', 'macos', 'windows'] as const;
+
+export type NativePlatform = (typeof NATIVE_PLATFORMS)[number];
+
+/** Type-resolution condition that exposes only core contracts (AST-082 FR6). */
+export const SHARED_CONDITION = 'shared';
+
+export function isNativePlatform(value: string): value is NativePlatform {
+ return (NATIVE_PLATFORMS as readonly string[]).includes(value);
+}
diff --git a/packages/native/src/theme/defineNativeTheme.test.ts b/packages/native/src/theme/defineNativeTheme.test.ts
new file mode 100644
index 0000000000..53584c2dbc
--- /dev/null
+++ b/packages/native/src/theme/defineNativeTheme.test.ts
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it, vi} from 'vitest';
+import {
+ compareVersions,
+ defineNativeTheme,
+ resolveNativeTheme,
+} from './defineNativeTheme.js';
+
+const theme = {name: 'brand', tokens: {'--color-accent': '#0064e0'}};
+
+describe('defineNativeTheme', () => {
+ it('scopes a version-specific material and resolves it per OS version', () => {
+ const native = defineNativeTheme(
+ theme,
+ {
+ material: 'translucent',
+ platforms: {
+ ios: [{minVersion: '26', material: 'liquidGlass'}],
+ android: [{material: 'opaque'}],
+ },
+ },
+ {onReport: () => {}},
+ );
+ expect(
+ resolveNativeTheme(native, {platform: 'ios', osVersion: '26.1'}).material,
+ ).toBe('liquidGlass');
+ expect(
+ resolveNativeTheme(native, {platform: 'ios', osVersion: '18.6'}).material,
+ ).toBe('translucent');
+ expect(
+ resolveNativeTheme(native, {platform: 'android', osVersion: '16'})
+ .material,
+ ).toBe('opaque');
+ expect(
+ resolveNativeTheme(native, {platform: 'windows', osVersion: '11'})
+ .material,
+ ).toBe('translucent');
+ });
+
+ it('rejects a platform feature outside the versions that have it', () => {
+ expect(() =>
+ defineNativeTheme(
+ theme,
+ {platforms: {ios: [{material: 'liquidGlass'}]}},
+ {onReport: () => {}},
+ ),
+ ).toThrow(/liquidGlass.*minVersion: '26'/);
+ });
+
+ it('reports web-only theme parts and keeps only the portable part', () => {
+ const report = vi.fn();
+ const webTheme = {
+ ...theme,
+ components: {Button: {root: {}}},
+ icons: {},
+ __onDark: {x: 1},
+ };
+ const native = defineNativeTheme(webTheme, {}, {onReport: report});
+ expect(report.mock.calls.map(call => String(call[0]))).toEqual([
+ expect.stringContaining('"components" is web-only'),
+ expect.stringContaining('"onDark" is web-only'),
+ ]);
+ expect(native.theme).toEqual(theme);
+ });
+
+ it('extends another native theme: durable members merge, platform lists replace', () => {
+ const base = defineNativeTheme(theme, {
+ material: 'opaque',
+ platforms: {android: [{material: 'translucent'}]},
+ });
+ const child = defineNativeTheme(
+ theme,
+ {platforms: {ios: [{material: 'opaque'}]}},
+ {extends: base},
+ );
+ expect(child.config.material).toBe('opaque');
+ expect(child.config.platforms?.android).toEqual([
+ {material: 'translucent'},
+ ]);
+ expect(child.config.platforms?.ios).toEqual([{material: 'opaque'}]);
+ });
+
+ it('compares dotted versions numerically', () => {
+ expect(compareVersions('26', '26.0.1')).toBeLessThan(0);
+ expect(compareVersions('10.15', '10.9')).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/native/src/theme/defineNativeTheme.ts b/packages/native/src/theme/defineNativeTheme.ts
new file mode 100644
index 0000000000..b287ff572c
--- /dev/null
+++ b/packages/native/src/theme/defineNativeTheme.ts
@@ -0,0 +1,224 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file theme/defineNativeTheme.ts
+ * @input A defined theme (its portable part) and native theme configuration
+ * @output A native theme, and its resolution for one platform and OS version
+ * @position Native theme configuration (AST-082 FR10, FR18). Builds on the
+ * defined theme without changing it and never sets tokens
+ */
+
+import {NATIVE_PLATFORMS, type NativePlatform} from '../platforms.js';
+
+/**
+ * The portable part of a defined theme (AST-082 FR18). A core `DefinedTheme`
+ * satisfies it structurally, so native never imports core to accept one.
+ */
+export interface PortableThemeLike {
+ readonly name: string;
+ readonly tokens: Readonly<Record<string, string>>;
+ readonly localTokens?: Readonly<Record<string, string>>;
+}
+
+/** Durable outcomes a person sees; no platform feature names (DEC-5). */
+export type DurableMaterial = 'opaque' | 'translucent';
+
+export interface PlatformVocabulary {
+ ios: {material: DurableMaterial | 'liquidGlass'};
+ macos: {material: DurableMaterial | 'liquidGlass'};
+ android: {material: DurableMaterial};
+ windows: {material: DurableMaterial | 'mica' | 'acrylic'};
+}
+
+/** Platform icon reference, as data (AST-082 FR17). */
+export type PlatformIcon =
+ {readonly systemName: string} | {readonly materialSymbol: string};
+
+export type PlatformEntry<P extends NativePlatform> = Partial<
+ PlatformVocabulary[P]
+> & {
+ readonly minVersion?: string;
+ readonly maxVersion?: string;
+ /** Overrides for this platform's theme targets, keyed by target. */
+ readonly components?: Readonly<
+ Record<string, Readonly<Record<string, string | number>>>
+ >;
+ readonly icons?: Readonly<Record<string, PlatformIcon>>;
+};
+
+export interface NativeThemeConfig {
+ readonly material?: DurableMaterial;
+ readonly platforms?: {
+ readonly [P in NativePlatform]?: ReadonlyArray<PlatformEntry<P>>;
+ };
+}
+
+export interface NativeTheme {
+ readonly theme: PortableThemeLike;
+ readonly config: NativeThemeConfig;
+}
+
+export interface DefineNativeThemeOptions {
+ /** Native theme to extend: durable members merge, platform entry lists replace. */
+ readonly extends?: NativeTheme;
+ /** Receives each report; defaults to console.warn outside production. */
+ readonly onReport?: (message: string) => void;
+}
+
+/** Platform terms that exist only from a given OS version. */
+const FEATURE_FLOORS: Readonly<
+ Record<string, Readonly<Record<string, string>>>
+> = {
+ ios: {liquidGlass: '26'},
+ macos: {liquidGlass: '26'},
+ windows: {mica: '11'},
+};
+
+/** Web-only parts of a defined theme that have no native meaning (FR18). */
+const WEB_PARTS = [
+ 'components',
+ 'icons',
+ 'indicators',
+ '__onDark',
+ '__onLight',
+ '__adaptations',
+];
+
+export function compareVersions(a: string, b: string): number {
+ const pa = a.split('.').map(Number);
+ const pb = b.split('.').map(Number);
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
+ if (diff !== 0) {
+ return diff;
+ }
+ }
+ return 0;
+}
+
+function hasContent(value: unknown): boolean {
+ if (value == null) {
+ return false;
+ }
+ if (Array.isArray(value)) {
+ return value.length > 0;
+ }
+ if (typeof value === 'object') {
+ return Object.keys(value).length > 0;
+ }
+ return true;
+}
+
+function validate(config: NativeThemeConfig): string[] {
+ const errors: string[] = [];
+ for (const platform of NATIVE_PLATFORMS) {
+ for (const entry of config.platforms?.[platform] ?? []) {
+ const material = (entry as {material?: string}).material;
+ const floor = material ? FEATURE_FLOORS[platform]?.[material] : undefined;
+ if (
+ floor &&
+ (entry.minVersion == null ||
+ compareVersions(entry.minVersion, floor) < 0)
+ ) {
+ errors.push(
+ `${platform} material "${material}" exists only from ${platform} ${floor}; ` +
+ `scope its entry with minVersion: '${floor}' or later`,
+ );
+ }
+ if (
+ entry.minVersion &&
+ entry.maxVersion &&
+ compareVersions(entry.minVersion, entry.maxVersion) > 0
+ ) {
+ errors.push(`${platform} entry has minVersion above maxVersion`);
+ }
+ }
+ }
+ return errors;
+}
+
+export function defineNativeTheme(
+ theme: PortableThemeLike,
+ config: NativeThemeConfig,
+ options: DefineNativeThemeOptions = {},
+): NativeTheme {
+ const merged: NativeThemeConfig = options.extends
+ ? {
+ ...options.extends.config,
+ ...config,
+ platforms: {...options.extends.config.platforms, ...config.platforms},
+ }
+ : config;
+
+ const errors = validate(merged);
+ if (errors.length > 0) {
+ throw new Error(`defineNativeTheme(${theme.name}): ${errors.join('; ')}`);
+ }
+
+ const report =
+ options.onReport ??
+ ((message: string) => {
+ const env =
+ typeof process === 'undefined' ? undefined : process.env?.NODE_ENV;
+ if (env !== 'production') {
+ console.warn(message);
+ }
+ });
+ const received = theme as unknown as Record<string, unknown>;
+ for (const part of WEB_PARTS) {
+ if (hasContent(received[part])) {
+ report(
+ `defineNativeTheme(${theme.name}): "${part.replace(/^__/, '')}" is web-only and has ` +
+ 'no native meaning; use native platform entries instead',
+ );
+ }
+ }
+
+ const portable: PortableThemeLike = {
+ name: theme.name,
+ tokens: theme.tokens,
+ ...(theme.localTokens ? {localTokens: theme.localTokens} : {}),
+ };
+ return {theme: portable, config: merged};
+}
+
+export interface ResolvedNativeTheme {
+ readonly material?: string;
+ readonly components: Readonly<
+ Record<string, Readonly<Record<string, string | number>>>
+ >;
+ readonly icons: Readonly<Record<string, PlatformIcon>>;
+}
+
+/** Applies durable intent, then each matching platform entry in order. */
+export function resolveNativeTheme(
+ nativeTheme: NativeTheme,
+ target: {readonly platform: NativePlatform; readonly osVersion: string},
+): ResolvedNativeTheme {
+ let resolved: ResolvedNativeTheme = {
+ ...(nativeTheme.config.material
+ ? {material: nativeTheme.config.material}
+ : {}),
+ components: {},
+ icons: {},
+ };
+ const entries = (nativeTheme.config.platforms?.[target.platform] ??
+ []) as ReadonlyArray<PlatformEntry<NativePlatform>>;
+ for (const entry of entries) {
+ if (
+ entry.minVersion &&
+ compareVersions(target.osVersion, entry.minVersion) < 0
+ ) {
+ continue;
+ }
+ if (
+ entry.maxVersion &&
+ compareVersions(target.osVersion, entry.maxVersion) > 0
+ ) {
+ continue;
+ }
+ const {minVersion: _min, maxVersion: _max, ...members} = entry;
+ resolved = {...resolved, ...members};
+ }
+ return resolved;
+}
diff --git a/packages/native/tsconfig.build.json b/packages/native/tsconfig.build.json
new file mode 100644
index 0000000000..c85d2a5027
--- /dev/null
+++ b/packages/native/tsconfig.build.json
@@ -0,0 +1,11 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": false
+ },
+ "include": ["src"],
+ "exclude": ["src/**/*.test.ts"]
+}
diff --git a/packages/native/tsconfig.json b/packages/native/tsconfig.json
new file mode 100644
index 0000000000..01135cf8ff
--- /dev/null
+++ b/packages/native/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "lib": ["ES2022"],
+ "types": ["node"]
+ },
+ "include": ["src"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 89e9290999..9da9f3664e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -959,6 +959,12 @@ importers:
specifier: 17.0.0
version: 17.0.0([email protected])
+ packages/native:
+ devDependencies:
+ '@astryxdesign/core':
+ specifier: workspace:*
+ version: link:../core
+
packages/richtext:
dependencies:
'@astryxdesign/core':
diff --git a/scripts/check-package-boundaries.js b/scripts/check-package-boundaries.js
index 325ef92533..3949a6db9c 100644
--- a/scripts/check-package-boundaries.js
+++ b/scripts/check-package-boundaries.js
@@ -1,13 +1,16 @@
#!/usr/bin/env node
// Copyright (c) Meta Platforms, Inc. and affiliates.
-
/**
* Package Boundary Check
*
* Keeps package-specific APIs out of the core package. Core should expose
* primitive XDS building blocks; shell/common wrappers belong in their owning
* package so consumers do not get parallel implementations.
+ *
+ * Also keeps core and the experimental native package apart (AST-082 FR14,
+ * FR16): core never imports @astryxdesign/native, and native's source never
+ * imports core. Native reads core's documentation as data at build time.
*/
const fs = require('node:fs');
@@ -15,14 +18,16 @@ const path = require('node:path');
const ROOT = path.resolve(__dirname, '..');
const CORE_SRC = path.join(ROOT, 'packages/core/src');
+const NATIVE_SRC = path.join(ROOT, 'packages/native/src');
+const IMPORT_SPECIFIER = /\b(?:from|import|require)\s*\(?\s*['"]([^'"]+)['"]/g;
const violations = [];
-function walk(dir) {
+function walk(dir, check = checkFile) {
for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
- walk(fullPath);
+ walk(fullPath, check);
continue;
}
@@ -30,7 +35,31 @@ function walk(dir) {
continue;
}
- checkFile(fullPath);
+ check(fullPath);
+ }
+}
+
+function importsOf(filePath) {
+ const content = fs.readFileSync(filePath, 'utf8');
+ return [...content.matchAll(IMPORT_SPECIFIER)].map(match => match[1]);
+}
+
+function checkNativeBoundary(filePath, forbidden, message) {
+ const relPath = path.relative(ROOT, filePath);
+ for (const specifier of importsOf(filePath)) {
+ const resolved = specifier.startsWith('.')
+ ? path.relative(ROOT, path.resolve(path.dirname(filePath), specifier))
+ : specifier;
+ if (
+ forbidden.some(
+ prefix => resolved === prefix || resolved.startsWith(`${prefix}/`),
+ )
+ ) {
+ violations.push({
+ file: relPath,
+ message: `${message} (imports "${specifier}")`,
+ });
+ }
}
}
@@ -41,7 +70,8 @@ function checkFile(filePath) {
if (/^XDSCommon[A-Z]/.test(basename)) {
violations.push({
file: relPath,
- message: 'XDSCommon* files belong in the common package, not @astryxdesign/core.',
+ message:
+ 'XDSCommon* files belong in the common package, not @astryxdesign/core.',
});
}
@@ -63,6 +93,22 @@ function checkFile(filePath) {
}
walk(CORE_SRC);
+walk(CORE_SRC, filePath =>
+ checkNativeBoundary(
+ filePath,
+ ['@astryxdesign/native', 'packages/native'],
+ '@astryxdesign/core must never import @astryxdesign/native.',
+ ),
+);
+if (fs.existsSync(NATIVE_SRC)) {
+ walk(NATIVE_SRC, filePath =>
+ checkNativeBoundary(
+ filePath,
+ ['@astryxdesign/core', 'packages/core'],
+ '@astryxdesign/native source must not import core; read core documentation at build time instead.',
+ ),
+ );
+}
if (violations.length === 0) {
console.log('Package boundaries are clean.');