Back to Skills
expo/skillsCheck passed

SKILL DETAIL

expo-migrate-module

expo/skills/expo-migrate-module

This skill is used to migrate an existing Apple/Swift Expo native module from the Expo Modules API 1.0 definition DSL to the 2.0 macro API (sometimes called v2) while preserving its JavaScript and TypeScript contract. Use it when converting or incrementally adopting @ExpoModule, @JS, @Event, @SharedObject, or @Record in an existing module. Do not use it for creating a new module, general Expo SDK upgrades, or Android/Kotlin migrations. The skill provides a detailed workflow including establishing the contract, verifying the available 2.0 surface, applying the migration, verifying behavior, and handling missing 2.0 equivalents. It emphasizes preserving JS-visible names, optionality, event names, and queue semantics, and supports mixed mode where some members remain in the 1.0 DSL while others migrate to 2.0. The skill also guides on reporting blocked issues and submitting feedback.

Installs · 269View source

Installation

npx skills add https://github.com/expo/skills --skill expo-migrate-module

Skill files

SKILL.md

Last synced · Oct 23, 2026

agents/openai.yaml›
interface:
  display_name: "Migrate Expo Module"
  short_description: "Migrate Swift Expo modules from 1.0 DSL to 2.0"
  default_prompt: "Use $expo-migrate-module to migrate this Expo module's Swift implementation from the 1.0 definition DSL to the 2.0 macro API without changing its JavaScript contract."
references/compatibility.md›
# Expo Modules API 2.0 Compatibility Checks

The Expo Modules API 2.0 design and implementation evolve across the macros plugin and `expo-modules-core`. Verify the checked-out dependency instead of relying on an SDK-number claim.

## Find the actual declarations

Locate `ExpoModulesMacros.swift` in the target repository or installed dependencies (use your search tool, or portable shell commands - do not assume `rg` is installed):

```bash
find . -name 'ExpoModulesMacros.swift' -not -path '*/node_modules/.cache/*'
```

Inspect the declarations that the user's source can import:

```bash
grep -nE 'public macro (ExpoModule|JS|Event|SharedObject|Record|Union|ViewProps|ExpoView)' <path-to-ExpoModulesMacros.swift>
```

A declaration proves only that Swift recognizes the attribute, not that the code the macro generates will compile and run against the installed core.

## Check paired core support

The macros plugin and core can drift independently, so a successful macro expansion does not prove the generated code links or is called at runtime.

> The symbol names in this section are macro internals, for your own verification only. Never print them in the conversation, name them in your report, or write them into the migrated module's source. Report a capability by its macro (`@JS static`, `@Event(sync:)`) and by observable JS behavior. See the reporting rule in `SKILL.md`.

**Fast pre-check.** Search core for the hooks the generated code calls, to rule out an unsupported capability before you write any Swift:

```bash
grep -rnE '_decorateModule|_decorateSharedObject|_constructSharedObject|_jsName|EventEmitter|emitSync|StaticProperty|AnyViewProps|PropsDiff|_updateViewProps|didCreate|__expo_onStartListeningToEvent|decodeAnyDictionary|decodeAnyArray|JSOptions|UnionCaseMismatch' <expo-modules-core>
```

An absent hook is strong evidence the capability is unavailable. A present one is weaker: it proves the symbol exists, not that its signature matches what the plugin generates or that core ever calls it.

**Confirm by compiling.** Write the smallest `@JS` member that uses the capability, build the module target against the checked-out core, and read the diagnostics:

- The build succeeds: the capability is supported end to end.
- The macro reports an error or warning: the plugin itself rejects the construct. The diagnostic names the supported alternative.
- Expansion succeeds but linking fails on an undefined symbol: the plugin is ahead of core. Keep the member in the 1.0 DSL.

Then exercise the member from the example app or a test, because a binding can link and still never be invoked.

## Capability gates

Treat these as independent capabilities. Confirm each by compiling a minimal member that uses it, then calling it from JS:

| Capability | Macro surface | Core hook to grep (internal) | Confirm by |
| --- | --- | --- | --- |
| Module functions/properties | `@ExpoModule`, `@JS` | `_decorateModule` and its call site | calling the function and reading the property from JS |
| Module name | `@ExpoModule("Name")` | `_jsName` and the name lookup that reads it | resolving the module under its expected JS name |
| Records | `@Record` | coding conformances and field decode/encode | round-tripping a record argument and a record return value |
| Async events | `@Event` | `EventEmitter` on modules and shared objects | receiving an emitted event through the module's JS listener |
| Shared-object instances | `@SharedObject`, `@JS` | `_decorateSharedObject(prototype:)`, construction hook | constructing one from JS and calling an instance member |
| Shared-object static members | `@JS static` | `_decorateSharedObject(constructor:)`, distinct from the `prototype:` overload | calling the member on the JS class itself, not an instance |
| Synchronous events | `@Event(sync:)` | `emitSync` overloads | observing the listener run before the emit call returns |
| Task-returning functions | `@JS` returning `Task` | `JavaScriptEncodable` for `Task` (encode-only) | awaiting the returned promise in JS |
| Views | `@ViewProps`, `@ExpoView` | `AnyViewProps`, `PropsDiff`, `_updateViewProps` | rendering the view and updating every prop from JS |
| Module lifecycle methods | lifecycle members on the module class | `AnyModule` requirements and holder call sites | observing each hook fire |
| Free-form `Any` arguments | `@JS` with `Any`, `[Any]`, `[String: Any]` | `decodeAny`, `decodeAnyArray`, `decodeAnyDictionary` | building it, then passing a JS object through |
| Off-JS-thread async start | `@JS(.concurrent)` | `JSOptions` and the options-taking `@JS` overload (plugin `0.10.0`) | the `@JS` declaration accepting an options argument |
| Typed N-case unions | `@Union` | `Union` macro declaration and `UnionCaseMismatch` (plugin `0.10.0`) | round-tripping each case through the JS boundary |
| Autolinked `@ExpoModule` discovery | none, it is a build-time step | none, `scan-modules` plus the autolinking consumer | the module loading without an `expo-module.config.json` entry |

If a capability cannot be confirmed, keep that item in the 1.0 DSL.

## Known migration hazards

Use this only as a warning list; checked-out source wins.

- Async threading changed architecturally, not just syntactically: a 2.0 `async` member starts on the JS thread and leaves it at the first suspension point, where a 1.0 `AsyncFunction` never ran there. A verbatim migration can move blocking work onto the JS thread with no signature change. `@JS(.concurrent)` (plugin `0.10.0`) restores the 1.0 behavior, but needs a paired `JSOptions` type and a second `@JS` overload in core. See the threading table in `references/migration-map.md`.
- Same-JS-name `@JS` overload grouping/dispatch was designed but not built; duplicate bindings could silently overwrite each other.
- `@Union` landed in plugin `0.10.0`, but needs the paired `Union` macro declaration and `UnionCaseMismatch` exception in core. Decoding is first-match in case-declaration order, so preserving a 1.0 `Either`'s type order is part of the contract. See the unions section in `references/migration-map.md`.
- Decode errors lacked the 1.0 argument-index wrapper. This affects diagnostics rather than call semantics, but tests asserting exact messages may fail.
- `@ViewProps` had only an initial pure-macro slice; the UIKit typed props runtime and `@ExpoView` contract were still gated on core.
- `@Event(sync: true)` macro generation existed, but core `emitSync` was still required.
- Default asynchronous `@Event` was supported after core added `EventEmitter` to modules and shared objects.
- `@JS` functions/properties, range-based arity, default/optional-aware calls, `@Record` field synthesis, async `@JavaScriptActor`, and shared-object decoration had landed in the macros work.
- Shared-object `@JS static`/`class` members bind onto the constructor object through a `constructor:`-labeled decoration hook, separate from the `prototype:` one used for instance members. The plugin has emitted this binding since `v0.7.0`, but core shipped the `prototype:` overload well ahead of it, so a static member can expand and then fail to link. Instance support does not imply static support. Keep `StaticFunction`/`StaticAsyncFunction` entries in the 1.0 `Class(...)` block until the `constructor:` overload is present.
- Async `@JS` bindings are two-phase: arguments decode synchronously before the asynchronous boundary, and return values encode on the JS thread. A 1.0 async function whose argument decoding had side effects ordered after the hop can therefore observe a different order.

## Landed in the macros plugin since 0.8.0

Free-form `Any` arguments and `scan-modules` shipped in `0.9.0`, both covered below. `@JS(.concurrent)` (see the threading section in `references/migration-map.md`) and `@Union` (see the unions section) shipped in `0.10.0`.

All four are macro-side only. The plugin generates the code, but each needs a paired declaration or runtime hook in `expo-modules-core`, and core has been the lagging half throughout. A plugin version number therefore tells you nothing about whether a feature is usable. Check the checked-out core, per the capability gates above.

### Free-form `Any` arguments in `@JS` (plugin `0.9.0`)

`Any`, `[Any]`, and `[String: Any]` are accepted as **argument** types and decode through dedicated entry points instead of the type's own `.decode`:

Free-form is decode-only, so the position where the type appears decides whether it is allowed:

- **argument** (function, constructor, setter): compiles, with a warning steering you to `[String: JavaScriptValue]`
- **return type**: compile error
- **property**: compile error, because its getter always encodes

Optional (`[String: Any]?`) and nested (`[String: [String: Any]]`) spellings are unsupported.

These bindings decode through `JavaScriptValue.decodeAny`, `decodeAnyArray`, and `decodeAnyDictionary`. Core shipped the macro side first, so where those methods are absent the member expands and then fails to link. Confirm by building one minimal free-form argument against the checked-out core before migrating any others.

Prefer `[String: JavaScriptValue]` when you can change the Swift signature without changing the JS contract. A 1.0 DSL function taking a loosely typed dictionary is often expressible that way, and it is the alternative the macro's own warning points to.

### `scan-modules` for autolinked module discovery (plugin `0.9.0`)

The scanner CLI merged into the shipped `ExpoModulesMacros-tool` binary, so one executable serves both the compiler plugin protocol (no arguments) and a CLI:

```bash
ExpoModulesMacros-tool scan-modules --platform iOS --define DEBUG ios/
```

Its JSON output is versioned and reports each detected module's access level. It evaluates `#if` conditions against `--platform` and repeatable `--define`, answers `canImport` for a curated set of Apple SDK frameworks, and prunes `node_modules` along with test and example directories (`Tests`, `UITests`, `__tests__`, `__mocks__`, `example`, `examples`, `e2e`).

The intent is that `expo-modules-autolinking` detects `@ExpoModule` classes automatically, replacing the `expo-module.config.json` module list. **The scanner shipped ahead of that consumer**, so until autolinking actually calls it, discovery is not active. Consequences for a migration:

- Keep the module's existing `expo-module.config.json` declarations, and verify they are correct before you finish. Listing every module class under `apple.modules` is a 1.0 requirement that still applies on SDK 57; 2.0 does not lift it. The entries are bare Swift class names with no compile-time link to the class, so a rename during migration silently detaches the module: it builds, and then is absent at runtime. SDK 58 adds auto-discovery, at which point these entries can be removed.
- A migrated `@ExpoModule` class must be `public` or `open` to be linkable from the app target. The scanner reports each class's access level so inaccessible ones can be skipped with a diagnostic.
- Product sources kept under a pruned directory name are invisible to the scanner. A package in that layout stays on `expo-module.config.json`, which opts it out of scanning.
- You can run `scan-modules` yourself as a migration check: it lists which classes the macro attribute is actually detected on, which catches an `@ExpoModule` that landed in a conditional block or a non-public class.

## Integration verification

Use the target project's own commands. A robust sequence is:

1. Run macro/unit tests if working inside the macros package.
2. Compile the migrated native module against the paired core checkout.
3. Re-run CocoaPods installation when plugin dependencies or injection changed.
4. Restart Xcode after swapping a macro plugin binary; cleaning DerivedData alone may not reload it.
5. Build the example app and execute existing JS/TS behavior tests.

Do not report a migration complete based only on textual expansion tests.
references/example.md›
# Worked Example: Full Module Migration

This walks a single small module from the 1.0 DSL through mixed mode to a fully migrated 2.0 form. Every per-member rule lives in `migration-map.md`; this shows how they compose and how mixed mode is an intermediate state, not a failure.

The module below is representative: a name, a sync function, two async functions (one that suspends, one that blocks), a settable property, a constant, an event with observing hooks, and a record.

## Starting point: 1.0 DSL

```swift
import ExpoModulesCore

@Record
struct DownloadOptions {
  var url: URL              // required
  var retries: Int = 3      // omittable, default 3
  var label: String?        // omittable and nullable
}

public final class DownloaderModule: Module {
  private var volume: Double = 1

  public func definition() -> ModuleDefinition {
    Name("Downloader")

    Events("onProgress")

    OnStartObserving {
      self.beginProgressUpdates()
    }

    OnStopObserving {
      self.stopProgressUpdates()
    }

    Constant("buildInfo") { computeBuildInfo() }

    Function("clamp") { (value: Double) -> Double in
      return min(max(value, 0), 1)
    }

    Property("volume") { self.volume }
      .set { self.volume = $0 }

    AsyncFunction("download") { (options: DownloadOptions) -> String in
      return try await self.performDownload(options)
    }

    AsyncFunction("clearCache") {
      try FileManager.default.removeItem(at: self.cacheDirectory)
    }
  }

  private func report(percent: Double) {
    sendEvent("onProgress", ["percent": percent])
  }
}
```

The observable contract to preserve:

| Member | JS name | Contract |
| --- | --- | --- |
| Module | `Downloader` | `requireNativeModule("Downloader")` |
| `clamp` | `clamp` | sync, 1 arg, returns number |
| `volume` | `volume` | read/write number |
| `buildInfo` | `buildInfo` | read-only constant |
| `download` | `download` | async, 1 record arg, returns string |
| `clearCache` | `clearCache` | async, no args, blocking work runs off the JS thread |
| `onProgress` | `onProgress` | event, payload `{ percent }` |
| observing hooks | n/a | progress updates start/stop with the listener count |
| `DownloadOptions` | n/a | `url` required; `retries` default 3; `label` nullable |

## Intermediate: mixed mode

Suppose the checked-out core supports everything used above: `@ExpoModule`, `@JS` functions/properties/constants, async `@JavaScriptActor`, `@Record`, default async `@Event`, and the module lifecycle hooks. One member is still blocked, by semantics rather than support: `clearCache` has a body that blocks and never suspends, and a 1.0 `AsyncFunction` runs it on a background queue automatically, while a 2.0 async member starts on the JS actor. Migrating it as-is would move blocking I/O onto the JS thread, so it stays in the DSL.

The record migrates first because it is a pure data type and the function that consumes it depends on it. Its shape is already correct, so migration is just verifying each field decodes: `url`, `retries`, `label` all map cleanly, so `@Record` stays as-is (it was already using the macro here).

```swift
import ExpoModulesCore

@Record
struct DownloadOptions {
  var url: URL
  var retries: Int = 3
  var label: String?
}

@ExpoModule("Downloader")
public final class DownloaderModule: Module {
  // Explicit wire name: default @Event would strip "on" and emit "progress".
  @Event("onProgress")
  var onProgress: (ProgressEvent) -> Void

  @JS("clamp")
  func clamp(value: Double) -> Double {
    return min(max(value, 0), 1)
  }

  // Stored var -> JS getter + setter, matching the 1.0 get/set pair.
  @JS
  var volume: Double = 1

  // A let is a natural constant: read-only from JS.
  @JS
  let buildInfo = computeBuildInfo()

  @JS
  func download(options: DownloadOptions) async throws -> String {
    return try await performDownload(options)
  }

  // override: the hooks are inherited from the Module base class.
  override func didStartListening(event: String) {
    beginProgressUpdates()
  }

  override func didStopListening(event: String) {
    stopProgressUpdates()
  }

  // Kept on the DSL: the body blocks without suspending, and a 2.0 async
  // member would start it on the JS actor instead of a background queue.
  public func definition() -> ModuleDefinition {
    AsyncFunction("clearCache") {
      try FileManager.default.removeItem(at: self.cacheDirectory)
    }
  }

  private func report(percent: Double) {
    onProgress(ProgressEvent(percent: percent))
  }
}

@Record
struct ProgressEvent {
  var percent: Double
}
```

Notes on the choices, each traceable to `migration-map.md`:

- `Name("Downloader")` moved into `@ExpoModule("Downloader")`; the custom name is carried explicitly, never dropped.
- `@Event("onProgress")` uses the explicit wire name to avoid the `on`-stripping default; the untyped dictionary became a typed `ProgressEvent`.
- The duplicate `private var volume` field was removed once `@JS var volume` became the single source of truth. Watch for this: a 1.0 backing field plus a migrated `@JS var` of the same name is a double-declaration.
- `Constant("buildInfo")` became `@JS let buildInfo`. Evaluation moves from the lazy 1.0 closure to module initialization, acceptable here because `computeBuildInfo()` is cheap; an expensive value would keep lazy storage behind a getter-only computed `@JS var`.
- `OnStartObserving`/`OnStopObserving` became the `didStartListening(event:)`/`didStopListening(event:)` hooks, with `override` because the class inherits `Module`. The 1.0 hooks were module-wide, so the event argument is ignored.
- `definition()` remains but now holds only the queue-sensitive `clearCache`. It is not deleted because it is non-empty.

## Fully migrated (after explicitly moving the blocking work off the JS actor)

The DSL entry for `clearCache` was the semantics-preserving default. To finish the migration, replace the implicit background queue with an explicit hop so the blocking work still never runs on the JS thread, then delete the empty `definition()`.

```swift
import ExpoModulesCore

@Record
struct DownloadOptions {
  var url: URL
  var retries: Int = 3
  var label: String?
}

@Record
struct ProgressEvent {
  var percent: Double
}

@ExpoModule("Downloader")
public final class DownloaderModule: Module {
  @Event("onProgress")
  var onProgress: (ProgressEvent) -> Void

  @JS("clamp")
  func clamp(value: Double) -> Double {
    return min(max(value, 0), 1)
  }

  @JS
  var volume: Double = 1

  @JS
  let buildInfo = computeBuildInfo()

  @JS
  func download(options: DownloadOptions) async throws -> String {
    return try await performDownload(options)
  }

  @JS
  func clearCache() async throws {
    // Explicit hop: the body blocks, so it must not run on the JS actor.
    try await Task.detached {
      try FileManager.default.removeItem(at: self.cacheDirectory)
    }.value
  }

  override func didStartListening(event: String) {
    beginProgressUpdates()
  }

  override func didStopListening(event: String) {
    stopProgressUpdates()
  }

  private func report(percent: Double) {
    onProgress(ProgressEvent(percent: percent))
  }
}
```

`definition()` is gone only because it was empty and `@ExpoModule("Downloader")` preserves the resolved name. If any member had stayed blocked or unverified, the mixed-mode form above is the correct place to stop, not a broken end state.
references/migration-map.md›
# 1.0 to 2.0 Migration Map

Use this reference while editing. Preserve behavior first; macro adoption is secondary.

## Module and naming

Convert the module class and remove `Name(...)` only when the paired core reads the macro-synthesized name:

```swift
// 1.0
public final class CameraModule: Module {
  public func definition() -> ModuleDefinition {
    Name("Camera")
  }
}

// 2.0
@ExpoModule("Camera")
public final class CameraModule: Module {}
```

Always carry a custom 1.0 name into `@ExpoModule("...")`. A stale `Name(...)` can override or conflict with the 2.0 name depending on the core revision. In mixed mode, remove `Name(...)` only after verifying that the module still resolves under its expected JS name.

## Functions

Move a DSL closure into a real method and use `@JS("wireName")` when the Swift method name is different:

```swift
// 1.0
Function("sum") { (a: Double, b: Double) -> Double in
  return a + b
}

// 2.0
@JS("sum")
func add(a: Double, b: Double) -> Double {
  return a + b
}
```

Preserve:

- the JS name
- positional arity
- optional arguments and Swift defaults
- thrown errors and return type
- whether the result is synchronous or a Promise

Do not migrate functions that resolve to the same JS name unless the checked-out macro has overload grouping and collision diagnostics. Older 2.0 implementations install one property per declaration, so the last overload silently wins.

Reject or keep in DSL any unsupported signature such as variadics, `inout`, unresolved generics, or closure parameters without verified callback support. A `Promise` parameter is also unsupported; refactor it as described under Async functions.

### Async functions

A `Promise` parameter is not supported in a `@JS` signature; 2.0 drops the trailing-`Promise` argument entirely. A Promise-returning function has three shapes in 2.0. Pick by how the underlying work produces its result.

**1. Standard `async` method.** The common case. Swift `async` maps to a JS Promise:

```swift
// 1.0
AsyncFunction("load") { (url: URL) -> String in
  return try loadSynchronously(url)
}

// 2.0
@JS
func load(url: URL) async throws -> String {
  return try await loadResource(url)
}
```

**2. Checked continuation.** When the result arrives through a delegate or completion handler that fires once, wrap it with `withCheckedThrowingContinuation` (or `withCheckedContinuation` for non-throwing callbacks, or an `AsyncStream` for repeated values). This is the usual refactor for a 1.0 `AsyncFunction` that took a trailing `Promise` instance:

```swift
// 1.0
AsyncFunction("start") { (promise: Promise) in
  scanner.start(
    onSuccess: { result in promise.resolve(result) },
    onFailure: { error in promise.reject(error) }
  )
}

// 2.0
@JS
func start() async throws -> ScanResult {
  return try await withCheckedThrowingContinuation { continuation in
    scanner.start(
      onSuccess: { result in continuation.resume(returning: result) },
      onFailure: { error in continuation.resume(throwing: error) }
    )
  }
}
```

Resume the continuation exactly once on every path. If the callback API cannot guarantee that, or the refactor is otherwise unsafe, keep the function on the DSL instead of forcing it.

**3. Synchronous method returning a `Task`.** The `Task` encodes to a promise that settles with its result. Use it when the work is naturally a `Task`, or when a promise is needed as a value nested inside another encoded result rather than as the function's own return:

```swift
// 2.0
@JS
func download(url: URL) -> Task<DownloadResult, any Error> {
  return Task {
    try await self.downloader.download(url)
  }
}
```

This shape requires the `JavaScriptEncodable` conformance for `Task` in the checked-out core (encode-only; a JS promise does not decode back into a `Task`). Verify it exists before using this shape; prefer shape 1 or 2 when it is absent.

#### Threading: the architectural difference

This is the highest-risk part of an async migration, because the code compiles and the JS signature is unchanged while the work moves onto a different thread.

The two versions schedule async work from opposite starting points:

| | 1.0 `AsyncFunction` | 2.0 `async` `@JS` |
| --- | --- | --- |
| Where the body starts | off the JS thread, from the first statement | on the JS thread |
| When it leaves the JS thread | never runs there | at the first real suspension point |
| A body with no `await` | still runs off the JS thread | runs entirely on the JS thread |

A 2.0 async member is `@JavaScriptActor`-isolated and stays on the JS thread until it actually suspends. So the dangerous case is a function marked `async` whose body never awaits anything, or awaits only after doing substantial work. In 1.0 that body was off the JS thread from the start; migrated verbatim to 2.0, it now blocks the JS thread for its full duration. Nothing in the JS contract reveals this: the function still returns a promise.

Audit every `AsyncFunction` you migrate for what the body does before its first `await`:

- No `await` at all, or synchronous work ahead of the first `await`: the work is on the JS thread. Treat it as a regression unless the body is trivial.
- Blocking I/O, file or database access, image or crypto work, or an unbounded loop: never leave this on the JS actor.
- `.runOnQueue(...)` in 1.0: the queue was the contract. See the continuation pattern below.

To restore the 1.0 behavior, use the `@JS` macro's `.concurrent` option (macros plugin `0.10.0`):

```swift
// Body runs off the JS thread, like a 1.0 AsyncFunction.
@JS(.concurrent)
func process(input: String) async throws -> String {
  return try self.processor.process(input)
}

// The option is variadic, so it combines with an explicit JS name.
@JS("doWork", .concurrent)
func performWork() async throws {}
```

Only the body moves. Arguments are still decoded on the JS thread and the result is still encoded back on it, so `.concurrent` changes execution, not the JS contract. This makes it the preferred fix for a migrated function that relied on 1.0 background execution: the intent is explicit and the body stays as written.

Two constraints:

- `.concurrent` is valid only on an `async` function. On anything else it is diagnosed on the `@JS` attribute.
- You must still write `async` yourself. The macro cannot add it, but the diagnostic for a synchronous function carries a fix-it that inserts it.

**Check availability first.** The plugin side shipped in `0.10.0`, but this also needs a `JSOptions` type and a second `@JS` overload in core, because the options-only spelling cannot reuse the unlabeled JS-name slot. Core has lagged the plugin on every 2.0 feature so far, and where it still declares `@JS(_ jsName: String? = nil)` alone, `@JS(.concurrent)` does not compile. Read the checked-out declaration:

```bash
grep -rn 'public macro JS' <expo-modules-core>
```

If it takes only a name, use the explicit patterns below instead.

For a queue-pinned function, or when `.concurrent` is unavailable, prefer restructuring the work onto the Swift Concurrency model (structured concurrency, an actor, or a detached task for blocking work). When that is not feasible because the queue itself is the contract, for example a library that must be called from one serial queue, convert to an `async` method that dispatches to that queue inside a checked continuation:

```swift
// 1.0
AsyncFunction("process") { (input: String) -> String in
  return try self.processor.process(input)
}
.runOnQueue(processingQueue)

// 2.0
@JS
func process(input: String) async throws -> String {
  return try await withCheckedThrowingContinuation { continuation in
    processingQueue.async {
      do {
        continuation.resume(returning: try self.processor.process(input))
      } catch {
        continuation.resume(throwing: error)
      }
    }
  }
}
```

## Properties and constants

Map a getter to a getter-only `@JS var`; map a getter/setter pair to a settable stored or computed `@JS var`:

```swift
// 1.0
Property("volume") { self.volume }
  .set { self.volume = $0 }

// 2.0
@JS
var volume: Double = 1
```

Access control does not define JS mutability. Verify whether the declaration is syntactically settable; a stored `var` normally produces a JS setter.

Map a 1.0 `Constant` to a `@JS let`; a `let` property is a natural constant and produces a read-only JS property:

```swift
// 1.0
Constant("apiVersion") { 3 }

// 2.0
@JS
let apiVersion = 3
```

Evaluation timing shifts: a 1.0 `Constant` closure runs lazily, while a `let` initializes with the module instance. When the value is expensive and must stay deferred, keep private lazy storage and expose a getter-only computed property (a `var` with a `{ }` getter body and no storage of its own), not a stored `lazy var`:

```swift
private lazy var cachedInfo = computeInfo()

@JS
var info: Info {  // computed: recomputes nothing, just returns the cached value
  return cachedInfo
}
```

Do not expose a cached value as a settable `lazy @JS var`.

## Events

Replace `Events(...)` plus `sendEvent(...)` with a typed function property:

```swift
@Record
struct ProgressEvent {
  var percent: Double
}

// Explicit string preserves the old wire name.
@Event("onProgress")
var onProgress: (ProgressEvent) -> Void

func report(percent: Double) {
  onProgress(ProgressEvent(percent: percent))
}
```

The default `@Event` wire name strips a leading `on` and decapitalizes the remainder: Swift `onProgress` emits `progress`. 1.0 modules commonly expose `onProgress`. During migration, pass the original wire name explicitly unless an intentional JS breaking change was approved.

Use `() -> Void` for no-payload events. For payloads, create or reuse a `JavaScriptEncodable` type instead of preserving an untyped dictionary. Migrate `OnStartObserving` and `OnStopObserving` to the `didStartListening(event:)`/`didStopListening(event:)` lifecycle hooks (see Views and lifecycle).

Default `@Event` dispatch schedules onto the JS thread and is callable from other isolation contexts. Do not use `sync: true` unless core provides the matching `emitSync` overloads.

## Shared objects

Move instance behavior from a `Class(...)` block onto the `SharedObject` subclass:

```swift
// 2.0
@SharedObject
final class Download: SharedObject {
  @JS
  init(url: URL) {
    self.url = url
  }

  @JS
  func pause() {}

  @JS
  var progress: Double { currentProgress }
}

@ExpoModule(classes: [Download.self])
final class DownloadModule: Module {}
```

Drop the leading owner argument used by instance DSL closures; use `self` in the real instance method. Preserve constructor arity and JS member names.

Migrate only when the checked-out core supplies the shared-object decoration and construction hooks. Never create both a 1.0 `Class(...)` entry and a 2.0 registration for the same class without confirming that core intentionally merges them.

Static members belong to shared objects, not modules: a module is exported to JS as an instance, so Swift `static` members on a `Module` class are not useful there. Keep module-level values as instance `@JS` members.

#### Static members

A static member installs on the JS class object itself, so JS reaches it as `Download.supportedSchemes()`, not through an instance. The 1.0 DSL has dedicated components for this: `StaticFunction` and `StaticAsyncFunction`. Unlike `Function`, they do not receive the instance as their first argument. There is no static *property* component in 1.0, so a static value was exposed as a `StaticFunction` returning it.

```swift
// 1.0
Class(Download.self) {
  Constructor { (url: URL) in Download(url: url) }

  // Instance function: receives the owner as its first argument.
  Function("pause") { (download: Download) in
    download.pause()
  }

  // Static: no owner argument, callable as Download.supportedSchemes()
  StaticFunction("supportedSchemes") { () -> [String] in
    Download.supportedSchemes
  }
}
```

```swift
// 2.0
@SharedObject
final class Download: SharedObject {
  @JS
  init(url: URL) { self.url = url }

  @JS
  func pause() {}

  @JS
  static func supportedSchemes() -> [String] {
    return Self.schemes
  }
}
```

`StaticFunction` and `StaticAsyncFunction` both collapse into a `static` (or `class`) Swift declaration, with `async` carrying the distinction, exactly as `Function`/`AsyncFunction` do for instance members. Because 1.0 had no static property component, a `StaticFunction` that only returns a stored value can become a `@JS static var` in 2.0. That changes the JS contract from a call to a property access, so do it only when the user asks; a syntax migration keeps it a function.

What decides whether any of this works is the binding path: instance members bind onto the class prototype, while `static`/`class` members bind onto the constructor object through a separate, `constructor:`-labeled decoration hook. The two are independent capabilities.

**Support status.** The macros plugin has emitted the `constructor:` binding since `0.7.0`, but core shipped the `prototype:` overload well ahead of it. Where only `prototype:` is declared, a `@JS static` member expands and then fails to link. Verify before migrating any static member:

```bash
grep -rn '_decorateSharedObject' <expo-modules-core>
```

If only the `prototype:` overload is declared, keep every `StaticFunction`/`StaticAsyncFunction` entry in the 1.0 `Class(...)` block. Mixed mode is the expected outcome here: migrate the constructor and instance members, leave the static entries on the DSL, and say in the handoff that static members stayed behind because the installed core does not bind them yet.

Static functions and static properties travel this same path, so neither is available ahead of the other. When the hook is present, confirm it by calling the member on the JS class rather than on an instance; an instance-side test passes whether or not static binding works.

## Records

Attach `@Record`, remove field wrappers, and encode requiredness in the declaration:

```swift
@Record
struct Options {
  var source: URL       // required
  var retries: Int = 3  // omittable; default applies
  var label: String?    // omittable and nullable
}
```

Rules:

- non-optional with no default: required
- any property with a default: omittable
- optional type: omittable and nullable

Preserve the 1.0 contract exactly. For example, migrate `@Field var source: URL? = nil` to `var source: URL?`, not to `var source: URL`, unless the user approved a breaking change.

Every stored property is part of the 2.0 record surface. If the old type contains stored bookkeeping that was not a 1.0 field, move it out of the record or leave the type on 1.0; there is no field opt-out. Verify that each field supports the required `JavaScriptDecodable`/`JavaScriptEncodable` direction.

## Unions

`@Union` (macros plugin `0.10.0`) is the typed, N-case alternative to 1.0's `Either` types. It applies to a non-generic `enum` whose every case carries exactly one associated value:

```swift
// 1.0: JS `string | SourceOptions`, unwrapped by probing each side.
@JS
func load(_ source: Either<String, SourceOptions>) throws {
  if let text: String = source.get() {
    load(url: URL(string: text))
  } else if let options: SourceOptions = source.get() {
    load(url: options.url, headers: options.headers)
  }
}
```

```swift
// 2.0: the same JS type, as a named enum.
@Union
enum Source {
  case text(String)
  case options(SourceOptions)   // a @Record
}

@JS
func load(_ source: Source) throws {
  switch source {               // exhaustive; each payload keeps its static type
  case .text(let text):
    load(url: URL(string: text))
  case .options(let options):
    load(url: options.url, headers: options.headers)
  }
}
```

The JS-visible type is unchanged: case order defines the accepted alternatives, so `Either<String, SourceOptions>` maps to cases in that same order. Decoding tries each case's payload in declaration order and the first match wins, which matters for overlapping types (`Int`/`Double`, `URL`/`String`): keep the 1.0 `Either` order, since reordering silently changes which case a given JS value lands in.

Besides `switch`, a value unwraps by payload type without naming the case, which is the closest analogue to 1.0's `get()`:

```swift
let text = try source.as(String.self)              // throws on a mismatch
let options = try? source.as(SourceOptions.self)   // SourceOptions?
```

A type the union does not carry is a compile error, not a runtime `nil`. A mismatch on a held value throws, where 1.0's `get()` returned `nil`, so a migrated probe chain must become a `switch` or a `try?`.

Constraints, each a compile error: a generic enum, no cases, a case with no payload or more than one, a default value on the payload, and two cases with the identical payload spelling.

**Check availability first.** The plugin side shipped in `0.10.0`, but this also needs the `Union` macro declaration and the `UnionCaseMismatch` exception in core:

```bash
grep -rn 'public macro Union\|UnionCaseMismatch' <expo-modules-core>
```

Keep `Either` types on the 1.0 DSL until both exist in the target. Treat adopting `@Union` as an API-shape change to raise with the user rather than a mechanical step: it renames nothing in JS, but it does restructure Swift call sites.

## Views and lifecycle

Views are not covered by 2.0 yet. Keep UIKit `View`, `Prop`, view `Events`, and `OnViewDidUpdateProps` DSL entries on 1.0. Macro declarations or expansion tests alone do not prove the runtime update path exists.

The planned shape is a class marked `@ExpoView` whose props and event callbacks are declared once in a typed `@ViewProps` struct, instead of split between the native view and a hand-written JS prop type. Until that lands complete, a module with views migrates its non-view members and keeps the view on the DSL. That is a normal mixed-mode result, not a failed migration.

Module lifecycle is core-owned rather than macro-generated. The DSL components map to hook methods with no-op defaults:

| 1.0 | 2.0 |
| --- | --- |
| `OnCreate` | `didCreate()` |
| `OnDestroy` | `willDestroy()` |
| `OnStartObserving` | `didStartListening(event:)` |
| `OnStopObserving` | `didStopListening(event:)` |

Rules:

- Use the `override` keyword when the class inherits `Module`/`BaseModule`; define the hooks directly (no `override`) when the conformance comes only from `@ExpoModule`. Hooks added only in a subclass of a macro module are not called; keep them on the class that declares the conformance.
- The listening hooks receive the event name. A module-wide 1.0 `OnStartObserving` ignores the argument; a per-event `OnStartObserving("name")` becomes a comparison on it.
- `didCreate()` runs after the module is registered, slightly later than 1.0 `OnCreate`, which fires before registration; `willDestroy()` runs at holder teardown. Verify nothing depends on the earlier timing before migrating `OnCreate`.
- DSL lifecycle components can remain during an incremental migration and each fires exactly once, but do not implement a DSL component and its hook for the same behavior, or the work runs twice.

There is no 2.0 replacement for every lifecycle component; for example, retain app-context teardown handling when no matching hook exists.

## Mixed mode

`@ExpoModule` may coexist with a non-empty `definition()` when the paired core supports merging the two surfaces. Keep only unsupported entries in the DSL and avoid duplicate names across macro and DSL registrations.

Before deleting `definition()`, verify that it contains no:

- views or view events
- lifecycle or app-context listeners
- queue-pinned functions
- `StaticFunction`/`StaticAsyncFunction` entries, unless core declares the `constructor:` decoration hook

## Contract checklist

For every migrated member compare before and after:

| Concern | Must remain stable |
| --- | --- |
| Module | registration name and `requireNativeModule` key |
| Function | JS name, accepted arity, omitted/default behavior, sync/Promise result |
| Property | JS name, read/write behavior, evaluation/caching |
| Event | listener string, payload shape, timing |
| Record | field names, requiredness, nullability, defaults |
| Shared object | constructor shape, prototype vs constructor placement, identity |
| Execution | JS actor, main actor, background queue, ordering |
SKILL.md›
---
name: expo-migrate-module
description: Migrate an existing Apple/Swift Expo native module from the Expo Modules API 1.0 definition DSL to the 2.0 macro API (sometimes called v2) while preserving its JavaScript and TypeScript contract. Use when converting or incrementally adopting @ExpoModule, @JS, @Event, @SharedObject, or @Record in an existing module. Do not use for creating a new module, general Expo SDK upgrades, or Android/Kotlin migrations.
version: 1.0.0
license: MIT
---

# Migrate an Expo Module

Migrate the Swift side of an existing Expo module without changing its observable JS API. Treat the current JS/TypeScript surface and tests as the compatibility contract. Leave Kotlin on the 1.0 DSL unless the user explicitly expands the task.

## Prerequisite

Use `expo` `57.0.21` or newer. Earlier `57.x` versions can compile the macros but lack many of the 2.0 features and performance optimizations, so do not target them. Before editing, check the target's installed version (`expo` in `package.json`/lockfile, or `npm ls expo`). If it is older, stop and tell the user to upgrade first.

Check the example app's own `package.json` too, not only the module root. The example app is the integration surface you build and launch in step 4, so it needs the same floor.

This is a floor, not a guarantee: the exact macro and core surface still varies within `57.x`, so step 2 must still verify the checked-out source.

SDK 57 ships the macros as **experimental and undocumented**, with the official beta in SDK 58. The API can still change under you. Say this to the user before a large migration, and prefer incremental mixed mode over converting a module wholesale.

## References

- Read `references/migration-map.md` before changing source. It contains the 1.0-to-2.0 mappings, semantic traps, and mixed-mode rules.
- Read `references/example.md` for a full before/after walkthrough of one module through mixed mode to a complete migration. Consult it when you need to see how the per-member rules compose.
- Read `references/compatibility.md` when the checked-out `expo-modules-core` version or branch is not known to support every requested macro. It explains how to verify the actual compile-time and runtime surface instead of guessing from a version number, and lists what the macros plugin gained through `0.10.0`.

## Workflow

### 1. Establish the contract

Inspect repository instructions and the worktree before editing. Locate the Swift module classes, records, shared objects, native views, JS/TS bindings, tests, example app, podspec, `expo-module.config.json`, and installed or checked-out `expo-modules-core`.

Inventory every exported item before rewriting it:

- module and shared-object JS names
- function names, arity, labels, defaults, nullability, sync/async behavior, errors, and queue/thread semantics (note which `AsyncFunction` bodies do blocking or long-running work, and any `.runOnQueue(...)`)
- property names, mutability, and constant caching behavior
- event wire names and payload shapes
- record field names, defaults, requiredness, and nullability
- shared-object constructors and instance/static placement (`Function` vs `StaticFunction`/`StaticAsyncFunction`)
- lifecycle hooks and views

Use the TypeScript declarations and JS call sites to resolve ambiguity. Do not silently "improve" requiredness, rename an event, or change sync behavior during a syntax migration.

### 2. Verify the available 2.0 surface

Inspect the macro declarations and matching core hooks in the dependency actually used by the target. Do not assume that all items in the 2.0 design are present because one macro compiles.

Classify each 1.0 item as:

- **Migrate:** both its macro and required core runtime support exist.
- **Keep in DSL:** mixed mode preserves it safely, or 2.0 lacks an equivalent.
- **Blocked:** migration would alter the JS contract or requires unavailable runtime support.

Prefer an incremental mixed-mode result over speculative generated code. Keep `definition()` for any remaining DSL elements; delete it only when it is empty and the resolved module name is preserved by `@ExpoModule`.

### 3. Apply the migration

Migrate one semantic group at a time: module naming, functions, properties/constants, events, shared objects, then records. Keep the diff narrow.

Follow these invariants:

- Preserve every existing JS-visible name explicitly when Swift naming rules or macro defaults differ.
- Keep original optional/default behavior. An optional 1.0 record field must not become required merely because 2.0 can express required fields.
- Do not migrate same-JS-name overloads unless the checked-out macro groups and dispatches them.
- Preserve async threading behavior. A 1.0 `AsyncFunction` body ran off the JS thread; a 2.0 `async` `@JS` member starts on it and leaves only at the first `await`. A body that never awaits therefore blocks the JS thread, with no change to the JS signature. Audit what runs before the first `await`, and never leave blocking I/O on the JS actor. Fix with `@JS(.concurrent)`, or restructure onto Swift Concurrency or a continuation. Queue-pinned functions get the same treatment. See the threading section in `references/migration-map.md`.
- Verify core support before migrating views, unions, synchronous events, shared-object static members, or free-form `Any` arguments. The macros plugin has shipped ahead of core on every one of these, so check the checked-out core rather than a plugin version, and leave unsupported members on the 1.0 DSL. `references/compatibility.md` has the per-capability checks.
- Keep `expo-module.config.json` listing every module class under `apple.modules`. The entries are bare Swift class names, so renaming a class during migration detaches the module silently: it builds, then is absent at runtime. A migrated class must also stay `public` or `open`. SDK 58's auto-discovery is what retires these entries.
- Do not change Kotlin, JS wrappers, or public `.d.ts` files unless the user requested an API change.
- Never write macro-generated symbols into the module's source. The macro emits them; hand-writing or overriding them is not part of a migration.

After each group, search for old DSL entries and call sites that should have moved. Avoid broad formatting or unrelated cleanup.

### When a 2.0 equivalent is missing or a group fails

When step 2 classified an item as **Blocked**, or a migrated group fails to build or breaks the contract, do not force it. Stop on that group and:

1. **Ask the user how to proceed** for that item, with two options:
   - **Co-exist:** keep the item in the 1.0 `definition()` DSL alongside the migrated `@ExpoModule` (mixed mode) and continue with the other groups.
   - **Revert:** back out the group's edits, leaving it untouched on 1.0, and move on.

   Default to co-existence when mixed mode is verified safe, since it preserves the most progress. Revert when the half-applied change left the module in a non-building state and cannot be salvaged incrementally.

2. **Open a tracking issue on `expo/expo`** noting the functionality that 2.0 does not yet cover, so the gap is recorded rather than silently worked around. Use `gh issue create --repo expo/expo` and confirm with the user before posting (per repo conventions, do not post outward-facing comments without approval). Include:
   - the 1.0 member and its JS contract
   - the specific macro or core hook that is missing (cite the evidence gap from `references/compatibility.md`)
   - the `expo-modules-core` version/branch checked out

   Reference the issue in the handoff so the remaining DSL entry is traceable to a known limitation.

Keep going with the groups that do migrate cleanly; one blocked member does not block the rest.

### 4. Verify behavior

Run the narrowest available checks first, then the real integration surface:

1. Build or type-check the Apple module against the target `expo-modules-core`.
2. Run native unit tests and JS/TS tests.
3. Build and launch the example app when the repository provides one.
4. Confirm `expo-module.config.json` still names every module class under `apple.modules`, matching the Swift class names as they now stand. A stale entry builds clean and fails only at runtime, so the example app must actually resolve the module, not merely compile.
5. Compare the final exported surface with the inventory from step 1.
6. Search for stale `Name`, migrated `Function`/`AsyncFunction`/`StaticFunction`/`StaticAsyncFunction`/`Property`/`Constant`/`Events` entries, old `sendEvent` calls, `@Field`, and duplicate registrations. Search the source you wrote, not macro expansion output.

Expansion tests alone are insufficient: generated macro code can look correct while failing to link or run against a mismatched core. If dependencies changed or macro plugin flags are missing, reinstall JS dependencies as appropriate, run the repository's CocoaPods installation workflow, and restart Xcode before diagnosing plugin communication failures.

## Handoff

Never print macro-generated or core-internal symbol names to the user. `references/compatibility.md` cites them so you can grep for them, but they are implementation details that change between plugin revisions, and they are noise in a report. Name a capability by its macro (`@JS static`, `@Event(sync:)`) and by observable JS behavior. Say "the installed core does not support decoding free-form dictionary arguments yet", not the name of the missing method. The exception is a tracking issue on `expo/expo`, where the specific missing hook is the point.

Report:

- which members moved to 2.0
- which members intentionally remain in the 1.0 DSL and why
- any compatibility-sensitive choices, especially event names, record requiredness, constants, and queues
- the commands run and any verification not completed

## Submitting Feedback
If you encounter errors, misleading or outdated information in this skill, report it so Expo can improve:
```bash
npx --yes @expo/agent-cli@latest feedback --category skills --subject "expo-migrate-module" "<actionable feedback>"
```
Only submit when you have something specific and actionable to report. Include as much relevant context as possible.
If an agent repeatedly fails at an Expo task or the user has to step in, submit a brief report of the task, expected result, and what went wrong using `--category evals` and the relevant Expo package or command as `--subject`.