expo-widgets 56.0.8 → 56.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -10,6 +10,27 @@
10
10
 
11
11
  ### 💡 Others
12
12
 
13
+ ## 56.0.10 — 2026-05-19
14
+
15
+ ### 💡 Others
16
+
17
+ - Validate/sanitize config-plugin inputs more comprehensively ([#45884](https://github.com/expo/expo/pull/45884) by [@kitten](https://github.com/kitten))
18
+
19
+ ## 56.0.9 — 2026-05-15
20
+
21
+ ### 🎉 New features
22
+
23
+ - Use shared JS runtime. ([#45781](https://github.com/expo/expo/pull/45781) by [@jakex7](https://github.com/jakex7))
24
+
25
+ ### 🐛 Bug fixes
26
+
27
+ - Fix Live Activity multiple evaluations. ([#45675](https://github.com/expo/expo/pull/45675) by [@nkopylov](https://github.com/nkopylov))
28
+ - Fix module precompile. ([#45715](https://github.com/expo/expo/pull/45715) by [@jakex7](https://github.com/jakex7))
29
+
30
+ ### 💡 Others
31
+
32
+ - Migrated to the single-payload `SharedObject.emit` API. ([#45596](https://github.com/expo/expo/pull/45596) by [@tsapeta](https://github.com/tsapeta))
33
+
13
34
  ## 56.0.8 — 2026-05-13
14
35
 
15
36
  ### 🎉 New features
@@ -66,7 +66,7 @@ final class LiveActivity: SharedObject {
66
66
  pushTokenObserverTask = Task {
67
67
  for await data in activity.pushTokenUpdates {
68
68
  let token = data.reduce("") { $0 + String(format: "%02x", $1) }
69
- emit(event: onTokenReceived, arguments: [
69
+ emit(event: onTokenReceived, payload: [
70
70
  "activityId": activity.id,
71
71
  "pushToken": token
72
72
  ])
@@ -58,19 +58,25 @@ struct WidgetUserInteraction: AppIntent {
58
58
 
59
59
  guard let timeline,
60
60
  let entryIndex,
61
+ timeline.indices.contains(entryIndex),
61
62
  let entry = timeline[entryIndex] as? [String: Any],
62
63
  let props = entry["props"] as? [String: Any],
63
- let context = createWidgetContext(layout: layout),
64
64
  let environmentData = environmentString?.data(using: .utf8),
65
65
  var environment = try? JSONSerialization.jsonObject(with: environmentData) as? [String: Any] else {
66
66
  return .result()
67
67
  }
68
68
  environment["target"] = target
69
69
 
70
- let result = context.objectForKeyedSubscript("__expoWidgetHandlePress")?.call(
71
- withArguments: [props, environment]
72
- )
73
- if let newProps = result?.toObject() as? [String: Any] {
70
+ let newProps: [String: Any]?
71
+ switch evaluateWidgetButtonPress(layout: layout, props: props, environment: environment) {
72
+ case .success(let result):
73
+ newProps = result
74
+ case .failure(let error):
75
+ print("[ExpoWidgets] Button press evaluation failed: \(error.message)")
76
+ newProps = nil
77
+ }
78
+
79
+ if let newProps {
74
80
  var newEntry = entry
75
81
  if let originalProps = entry["props"] as? [String: Any] {
76
82
  newEntry["props"] = originalProps.merging(newProps) { _, new in new }
@@ -33,41 +33,27 @@ public func evaluateLayout(
33
33
  props: [String: Any],
34
34
  environment: [String: Any]
35
35
  ) -> [String: Any] {
36
- guard let context = createWidgetContext(layout: layout) else {
37
- return createRedBox(message: "Could not create context for layout evaluation.")
36
+ switch evaluateWidgetLayout(layout: layout, props: props, environment: environment) {
37
+ case .success(let result):
38
+ return result
39
+ case .failure(let error):
40
+ print("[ExpoWidgets] Layout evaluation failed: \(error.message)")
41
+ return createRedBox(message: error.message)
38
42
  }
39
-
40
- let result = context.objectForKeyedSubscript("__expoWidgetRender")?.call(
41
- withArguments: [props, environment]
42
- )
43
- if let exception = context.exception {
44
- print("[ExpoWidgets] Layout evaluation failed: \(exception)")
45
- return createRedBox(message: exception.toString())
46
- }
47
- return result?.toObject() as? [String: Any] ?? createRedBox(message: "Expo widget render did not produce any results.")
48
43
  }
49
44
 
50
45
  func getLiveActivityNodes(forName name: String, props: String = "{}", environment: [String: Any]) -> [String: Any] {
51
46
  let layout = WidgetsStorage.getString(forKey: "__expo_widgets_live_activity_\(name)_layout") ?? ""
52
47
  let propsData = props.data(using: .utf8)
53
48
  let propsDict = propsData.flatMap { try? JSONSerialization.jsonObject(with: $0, options: []) as? [String: Any] } ?? [:]
54
- guard let context = createWidgetContext(layout: layout) else {
55
- return ["banner": createRedBox(message: "Could not create context for layout evaluation.")]
56
- }
57
49
 
58
- var widgetEnvironment = environment
59
- widgetEnvironment["timestamp"] = Int(Date.now.timeIntervalSince1970 * 1000)
60
-
61
- let result = context.objectForKeyedSubscript("__expoWidgetRender")?.call(
62
- withArguments: [propsDict, environment]
63
- )
64
-
65
- if let exception = context.exception {
66
- print("[ExpoWidgets] Layout evaluation failed: \(exception)")
67
- return ["banner": createRedBox(message: exception.toString())]
50
+ switch evaluateWidgetLayout(layout: layout, props: propsDict, environment: environment) {
51
+ case .success(let result):
52
+ return result
53
+ case .failure(let error):
54
+ print("[ExpoWidgets] Layout evaluation failed: \(error.message)")
55
+ return ["banner": createRedBox(message: error.message)]
68
56
  }
69
-
70
- return result?.toObject() as? [String: Any] ?? ["banner": createRedBox(message: "Expo widget render did not produce any results.")]
71
57
  }
72
58
 
73
59
  func getLiveActivityUrl(forName name: String) -> URL? {
@@ -24,27 +24,37 @@ public struct WidgetLiveActivity: Widget {
24
24
 
25
25
  public var body: some WidgetConfiguration {
26
26
  ActivityConfiguration(for: LiveActivityAttributes.self) { context in
27
- LiveActivityBannerView(context: context, environment: environment)
27
+ let nodes = getLiveActivityNodes(
28
+ forName: context.state.name,
29
+ props: context.state.props,
30
+ environment: environment
31
+ )
32
+ LiveActivityBannerView(context: context, nodes: nodes)
28
33
  } dynamicIsland: { context in
29
- DynamicIsland {
34
+ let nodes = getLiveActivityNodes(
35
+ forName: context.state.name,
36
+ props: context.state.props,
37
+ environment: environment
38
+ )
39
+ return DynamicIsland {
30
40
  DynamicIslandExpandedRegion(.center) {
31
- LiveActivitySectionView(context: context, environment: environment, sectionName: "expandedCenter")
41
+ LiveActivitySectionView(context: context, nodes: nodes, sectionName: "expandedCenter")
32
42
  }
33
43
  DynamicIslandExpandedRegion(.leading) {
34
- LiveActivitySectionView(context: context, environment: environment, sectionName: "expandedLeading")
44
+ LiveActivitySectionView(context: context, nodes: nodes, sectionName: "expandedLeading")
35
45
  }
36
46
  DynamicIslandExpandedRegion(.trailing) {
37
- LiveActivitySectionView(context: context, environment: environment, sectionName: "expandedTrailing")
47
+ LiveActivitySectionView(context: context, nodes: nodes, sectionName: "expandedTrailing")
38
48
  }
39
49
  DynamicIslandExpandedRegion(.bottom) {
40
- LiveActivitySectionView(context: context, environment: environment, sectionName: "expandedBottom")
50
+ LiveActivitySectionView(context: context, nodes: nodes, sectionName: "expandedBottom")
41
51
  }
42
52
  } compactLeading: {
43
- LiveActivitySectionView(context: context, environment: environment, sectionName: "compactLeading")
53
+ LiveActivitySectionView(context: context, nodes: nodes, sectionName: "compactLeading")
44
54
  } compactTrailing: {
45
- LiveActivitySectionView(context: context, environment: environment, sectionName: "compactTrailing")
55
+ LiveActivitySectionView(context: context, nodes: nodes, sectionName: "compactTrailing")
46
56
  } minimal: {
47
- LiveActivitySectionView(context: context, environment: environment, sectionName: "minimal")
57
+ LiveActivitySectionView(context: context, nodes: nodes, sectionName: "minimal")
48
58
  }
49
59
  .widgetURL(getLiveActivityUrl(forName: context.state.name))
50
60
  }
@@ -55,15 +65,10 @@ public struct WidgetLiveActivity: Widget {
55
65
  @available(iOS 16.1, *)
56
66
  private struct LiveActivitySectionView: View {
57
67
  let context: ActivityViewContext<LiveActivityAttributes>
58
- let environment: [String: Any]
68
+ let nodes: [String: Any]
59
69
  let sectionName: String
60
70
 
61
71
  var body: some View {
62
- let nodes = getLiveActivityNodes(
63
- forName: context.state.name,
64
- props: context.state.props,
65
- environment: environment
66
- )
67
72
  if let node = nodes[sectionName] as? [String: Any] {
68
73
  WidgetsDynamicView(name: context.activityID, kind: .liveActivity, node: node)
69
74
  } else {
@@ -75,14 +80,9 @@ private struct LiveActivitySectionView: View {
75
80
  @available(iOS 16.1, *)
76
81
  private struct LiveActivityBannerView: View {
77
82
  var context: ActivityViewContext<LiveActivityAttributes>
78
- let environment: [String: Any]
83
+ let nodes: [String: Any]
79
84
 
80
85
  var body: some View {
81
- let nodes = getLiveActivityNodes(
82
- forName: context.state.name,
83
- props: context.state.props,
84
- environment: environment
85
- )
86
86
  if #available(iOS 18.0, *) {
87
87
  LiveActivityBanner(context: context, nodes: nodes)
88
88
  } else if let node = nodes["banner"] as? [String: Any] {
@@ -0,0 +1,142 @@
1
+ import Foundation
2
+ import JavaScriptCore
3
+
4
+ struct WidgetJavaScriptError: Error {
5
+ let message: String
6
+ }
7
+
8
+ typealias WidgetJavaScriptResult<Value> = Result<Value, WidgetJavaScriptError>
9
+
10
+ private final class WidgetsJSRuntime {
11
+ static let shared = WidgetsJSRuntime()
12
+
13
+ private let lock = NSRecursiveLock()
14
+ private var context: JSContext?
15
+ private var bundleScript: String?
16
+ private var layoutCache: [String: JSValue] = [:]
17
+
18
+ private init() {}
19
+
20
+ func render(layout: String, props: [String: Any], environment: [String: Any]) -> WidgetJavaScriptResult<[String: Any]> {
21
+ call(layout: layout, functionName: "__expoWidgetRender", arguments: [props, environment]).flatMap { result in
22
+ guard let renderedNode = result?.toObject() as? [String: Any] else {
23
+ return .failure(WidgetJavaScriptError(message: "Expo widget render did not produce any results."))
24
+ }
25
+ return .success(renderedNode)
26
+ }
27
+ }
28
+
29
+ func handlePress(layout: String, props: [String: Any], environment: [String: Any]) -> WidgetJavaScriptResult<[String: Any]?> {
30
+ call(layout: layout, functionName: "__expoWidgetHandlePress", arguments: [props, environment])
31
+ .map { $0?.toObject() as? [String: Any] }
32
+ }
33
+
34
+ private func call(layout: String, functionName: String, arguments: [Any]) -> WidgetJavaScriptResult<JSValue?> {
35
+ lock.lock()
36
+ defer { lock.unlock() }
37
+
38
+ guard let context = getContext() else {
39
+ return .failure(WidgetJavaScriptError(message: "Could not create context for layout evaluation."))
40
+ }
41
+ guard let layoutValue = getLayoutValue(layout, in: context) else {
42
+ return .failure(WidgetJavaScriptError(message: contextExceptionMessage(context) ?? "Could not evaluate layout."))
43
+ }
44
+
45
+ context.exception = nil
46
+ context.setObject(layoutValue, forKeyedSubscript: "__expoWidgetLayout" as NSString)
47
+
48
+ let function = context.objectForKeyedSubscript(functionName)
49
+ guard let function, function.isObject else {
50
+ return .failure(WidgetJavaScriptError(message: "Expo widget runtime function \(functionName) is unavailable."))
51
+ }
52
+
53
+ let result = function.call(withArguments: arguments)
54
+ if let exceptionMessage = contextExceptionMessage(context) {
55
+ return .failure(WidgetJavaScriptError(message: exceptionMessage))
56
+ }
57
+ return .success(result)
58
+ }
59
+
60
+ private func getContext() -> JSContext? {
61
+ if let context {
62
+ return context
63
+ }
64
+
65
+ guard let context = JSContext() else {
66
+ return nil
67
+ }
68
+
69
+ guard let script = getBundleScript() else {
70
+ print("[ExpoWidgets] Missing ExpoWidgets.bundle")
71
+ return nil
72
+ }
73
+
74
+ context.evaluateScript(script)
75
+ if let exceptionMessage = contextExceptionMessage(context) {
76
+ print("[ExpoWidgets] Bundle evaluation failed: \(exceptionMessage)")
77
+ return nil
78
+ }
79
+
80
+ self.context = context
81
+ return context
82
+ }
83
+
84
+ private func getBundleScript() -> String? {
85
+ if let bundleScript {
86
+ return bundleScript
87
+ }
88
+
89
+ guard let bundleURL = Bundle.main.url(forResource: "ExpoWidgets", withExtension: "bundle"),
90
+ let bundle = Bundle(url: bundleURL),
91
+ let url = bundle.url(forResource: "ExpoWidgets", withExtension: "bundle"),
92
+ let script = try? String(contentsOf: url, encoding: .utf8) else {
93
+ return nil
94
+ }
95
+
96
+ bundleScript = script
97
+ return script
98
+ }
99
+
100
+ private func getLayoutValue(_ layout: String, in context: JSContext) -> JSValue? {
101
+ if let layoutValue = layoutCache[layout] {
102
+ return layoutValue
103
+ }
104
+
105
+ context.exception = nil
106
+ guard let layoutValue = context.evaluateScript("(\(layout))"),
107
+ !layoutValue.isUndefined else {
108
+ return nil
109
+ }
110
+ guard context.exception == nil else {
111
+ return nil
112
+ }
113
+
114
+ layoutCache[layout] = layoutValue
115
+ return layoutValue
116
+ }
117
+
118
+ private func contextExceptionMessage(_ context: JSContext) -> String? {
119
+ guard let exception = context.exception else {
120
+ return nil
121
+ }
122
+
123
+ context.exception = nil
124
+ return exception.toString() ?? "Unknown JavaScript exception."
125
+ }
126
+ }
127
+
128
+ func evaluateWidgetLayout(
129
+ layout: String,
130
+ props: [String: Any],
131
+ environment: [String: Any]
132
+ ) -> WidgetJavaScriptResult<[String: Any]> {
133
+ WidgetsJSRuntime.shared.render(layout: layout, props: props, environment: environment)
134
+ }
135
+
136
+ func evaluateWidgetButtonPress(
137
+ layout: String,
138
+ props: [String: Any],
139
+ environment: [String: Any]
140
+ ) -> WidgetJavaScriptResult<[String: Any]?> {
141
+ WidgetsJSRuntime.shared.handlePress(layout: layout, props: props, environment: environment)
142
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-widgets",
3
- "version": "56.0.8",
3
+ "version": "56.0.10",
4
4
  "description": "Widgets.",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -22,7 +22,7 @@
22
22
  "homepage": "https://docs.expo.dev/versions/latest/sdk/widgets/",
23
23
  "dependencies": {
24
24
  "@expo/plist": "^0.6.0",
25
- "@expo/ui": "~56.0.7"
25
+ "@expo/ui": "~56.0.9"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@expo/spawn-async": "^1.7.2",
@@ -30,7 +30,7 @@
30
30
  "@types/react": "~19.2.0",
31
31
  "react-native": "0.85.3",
32
32
  "resolve-workspace-root": "^2.0.0",
33
- "expo": "56.0.0-preview.11",
33
+ "expo": "56.0.0-preview.13",
34
34
  "expo-module-scripts": "56.0.2"
35
35
  },
36
36
  "peerDependencies": {
@@ -44,7 +44,7 @@
44
44
  "./scripts/xcode-build-bundle.sh"
45
45
  ]
46
46
  },
47
- "gitHead": "51c27fce31a5b3a877a4b05d832dabf4a99db5e1",
47
+ "gitHead": "290368bc41026449a05a4ebf991b85c3a2fb0e3a",
48
48
  "scripts": {
49
49
  "build": "expo-module build",
50
50
  "build:plugin": "expo-module build plugin",
@@ -40,31 +40,71 @@ const plist_1 = __importDefault(require("@expo/plist"));
40
40
  const config_plugins_1 = require("expo/config-plugins");
41
41
  const fs = __importStar(require("fs"));
42
42
  const path = __importStar(require("path"));
43
- const withWidgetSourceFiles = (config, { widgets, targetName, onFilesGenerated, groupIdentifier }) => (0, config_plugins_1.withDangerousMod)(config, [
44
- 'ios',
45
- async (config) => {
46
- const projectRoot = config.modRequest.platformProjectRoot;
47
- const targetDirectory = path.join(projectRoot, targetName);
48
- const existingInfoPlistPath = path.join(targetDirectory, 'Info.plist');
49
- const existingInfoPlist = fs.existsSync(existingInfoPlistPath)
50
- ? fs.readFileSync(existingInfoPlistPath, 'utf8')
51
- : null;
52
- if (fs.existsSync(targetDirectory)) {
53
- fs.rmSync(targetDirectory, { recursive: true, force: true });
43
+ const WidgetFamily_type_1 = require("./types/WidgetFamily.type");
44
+ const VALID_WIDGET_FAMILIES = new Set(Object.values(WidgetFamily_type_1.WidgetFamily));
45
+ function assertSwiftIdentifier(value, label) {
46
+ if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
47
+ throw new Error(`Invalid ${label} ${JSON.stringify(value)}: must be a Swift identifier.`);
48
+ }
49
+ }
50
+ function assertWidgetFamily(value) {
51
+ if (typeof value !== 'string' || !VALID_WIDGET_FAMILIES.has(value)) {
52
+ throw new Error(`Invalid supportedFamilies entry ${JSON.stringify(value)}: must be one of ${[...VALID_WIDGET_FAMILIES].join(', ')}.`);
53
+ }
54
+ }
55
+ function validateWidget(widget) {
56
+ assertSwiftIdentifier(widget.name, 'widget name');
57
+ for (const family of widget.supportedFamilies) {
58
+ assertWidgetFamily(family);
59
+ }
60
+ if (widget.configuration) {
61
+ for (const [paramName, param] of Object.entries(widget.configuration.parameters)) {
62
+ assertSwiftIdentifier(paramName, 'parameter name');
63
+ if (param.type === 'number' && typeof param.default !== 'number') {
64
+ throw new Error(`Invalid default for ${JSON.stringify(paramName)}: must be a number.`);
65
+ }
66
+ else if (param.type === 'boolean' && typeof param.default !== 'boolean') {
67
+ throw new Error(`Invalid default for ${JSON.stringify(paramName)}: must be a boolean.`);
68
+ }
69
+ else if (param.type === 'enum') {
70
+ assertSwiftIdentifier(param.default, `default for ${JSON.stringify(paramName)}`);
71
+ for (const value of param.values) {
72
+ assertSwiftIdentifier(value.value, `enum case for ${JSON.stringify(paramName)}`);
73
+ }
74
+ }
54
75
  }
55
- fs.mkdirSync(targetDirectory, { recursive: true });
56
- const entitlementsPath = path.join(targetDirectory, `${targetName}.entitlements`);
57
- const entitlementsContent = {
58
- 'com.apple.security.application-groups': [groupIdentifier],
59
- };
60
- fs.writeFileSync(entitlementsPath, plist_1.default.build(entitlementsContent));
61
- const infoPlistPath = createInfoPlist(groupIdentifier, targetDirectory, config.ios?.version ?? config.version ?? '1.0', config.ios?.buildNumber ?? '1', existingInfoPlist);
62
- const indexSwiftPath = createIndexSwift(widgets, targetDirectory);
63
- const widgetSwiftPaths = widgets.map((widget) => createWidgetSwift(widget, targetDirectory));
64
- onFilesGenerated([entitlementsPath, infoPlistPath, indexSwiftPath, ...widgetSwiftPaths]);
65
- return config;
66
- },
67
- ]);
76
+ }
77
+ }
78
+ const withWidgetSourceFiles = (config, { widgets, targetName, onFilesGenerated, groupIdentifier }) => {
79
+ for (const widget of widgets) {
80
+ validateWidget(widget);
81
+ }
82
+ return (0, config_plugins_1.withDangerousMod)(config, [
83
+ 'ios',
84
+ async (config) => {
85
+ const projectRoot = config.modRequest.platformProjectRoot;
86
+ const targetDirectory = path.join(projectRoot, targetName);
87
+ const existingInfoPlistPath = path.join(targetDirectory, 'Info.plist');
88
+ const existingInfoPlist = fs.existsSync(existingInfoPlistPath)
89
+ ? fs.readFileSync(existingInfoPlistPath, 'utf8')
90
+ : null;
91
+ if (fs.existsSync(targetDirectory)) {
92
+ fs.rmSync(targetDirectory, { recursive: true, force: true });
93
+ }
94
+ fs.mkdirSync(targetDirectory, { recursive: true });
95
+ const entitlementsPath = path.join(targetDirectory, `${targetName}.entitlements`);
96
+ const entitlementsContent = {
97
+ 'com.apple.security.application-groups': [groupIdentifier],
98
+ };
99
+ fs.writeFileSync(entitlementsPath, plist_1.default.build(entitlementsContent));
100
+ const infoPlistPath = createInfoPlist(groupIdentifier, targetDirectory, config.ios?.version ?? config.version ?? '1.0', config.ios?.buildNumber ?? '1', existingInfoPlist);
101
+ const indexSwiftPath = createIndexSwift(widgets, targetDirectory);
102
+ const widgetSwiftPaths = widgets.map((widget) => createWidgetSwift(widget, targetDirectory));
103
+ onFilesGenerated([entitlementsPath, infoPlistPath, indexSwiftPath, ...widgetSwiftPaths]);
104
+ return config;
105
+ },
106
+ ]);
107
+ };
68
108
  const createIndexSwift = (widgets, targetPath) => {
69
109
  const indexFilePath = path.join(targetPath, `index.swift`);
70
110
  const numberOfWidgets = widgets.length;
@@ -138,8 +178,8 @@ struct ${widget.name}: Widget {
138
178
  StaticConfiguration(kind: name, provider: WidgetsTimelineProvider(name: name)) { entry in
139
179
  WidgetsEntryView(entry: entry)
140
180
  }
141
- .configurationDisplayName("${widget.displayName}")
142
- .description("${widget.description}")
181
+ .configurationDisplayName(${JSON.stringify(widget.displayName)})
182
+ .description(${JSON.stringify(widget.description)})
143
183
  .supportedFamilies([.${widget.supportedFamilies.join(', .')}])${widget.contentMarginsDisabled ? '\n .contentMarginsDisabled()' : ''}
144
184
  }
145
185
  }`;
@@ -150,8 +190,8 @@ internal import ExpoWidgets
150
190
 
151
191
  // AppIntent
152
192
  struct ${widget.name}ConfigurationAppIntent: WidgetConfigurationIntent {
153
- static var title: LocalizedStringResource = "${widget.configuration?.title ?? widget.displayName} Configuration"
154
- ${widget.configuration?.description ? ` static var description: LocalizedStringResource = "${widget.configuration?.description}"\n` : ''}
193
+ static var title: LocalizedStringResource = ${JSON.stringify(`${widget.configuration?.title ?? widget.displayName} Configuration`)}
194
+ ${widget.configuration?.description ? ` static var description: LocalizedStringResource = ${JSON.stringify(widget.configuration.description)}\n` : ''}
155
195
  ${Object.entries(widget.configuration?.parameters ?? {})
156
196
  .map(([name, param]) => {
157
197
  let paramType;
@@ -171,7 +211,7 @@ ${Object.entries(widget.configuration?.parameters ?? {})
171
211
  default:
172
212
  paramType = 'String';
173
213
  }
174
- return ` @Parameter(title: "${param.title}", default: ${param.type === 'string' ? `"${param.default}"` : param.type === 'number' ? param.default : param.type === 'boolean' ? param.default : `${widget.name}${name[0]?.toUpperCase() + name.slice(1)}Enum.${param.default}`})\n var ${name}: ${paramType}`;
214
+ return ` @Parameter(title: ${JSON.stringify(param.title)}, default: ${param.type === 'string' ? JSON.stringify(param.default) : param.type === 'number' ? param.default : param.type === 'boolean' ? param.default : `${widget.name}${name[0]?.toUpperCase() + name.slice(1)}Enum.${param.default}`})\n var ${name}: ${paramType}`;
175
215
  })
176
216
  .join('\n')}
177
217
 
@@ -192,12 +232,12 @@ enum ${paramTypeName}: String, CaseIterable, AppEnum {
192
232
  })
193
233
  .join('\n ')}
194
234
 
195
- static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "${param.title}")
235
+ static var typeDisplayRepresentation = TypeDisplayRepresentation(name: ${JSON.stringify(param.title)})
196
236
 
197
237
  static var caseDisplayRepresentations: [${paramTypeName}: DisplayRepresentation] = [
198
238
  ${param.values
199
239
  .map((value) => {
200
- return `.${value.value}: DisplayRepresentation(title: "${value.name}")`;
240
+ return `.${value.value}: DisplayRepresentation(title: ${JSON.stringify(value.name)})`;
201
241
  })
202
242
  .join(',\n ')}
203
243
  ]
@@ -297,8 +337,8 @@ struct ${widget.name}: Widget {
297
337
  return AppIntentConfiguration(kind: name, intent: ${widget.name}ConfigurationAppIntent.self, provider: ${widget.name}TimelineProvider()) { entry in
298
338
  ${widget.name}EntryView(entry: entry)
299
339
  }
300
- .configurationDisplayName("${widget.displayName}")
301
- .description("${widget.description}")
340
+ .configurationDisplayName(${JSON.stringify(widget.displayName)})
341
+ .description(${JSON.stringify(widget.description)})
302
342
  .supportedFamilies([.${widget.supportedFamilies.join(', .')}])${widget.contentMarginsDisabled ? '\n .contentMarginsDisabled()' : ''}
303
343
  }
304
344
  }`;
@@ -4,6 +4,7 @@ import * as fs from 'fs';
4
4
  import * as path from 'path';
5
5
 
6
6
  import { WidgetConfig } from './types/WidgetConfig.type';
7
+ import { WidgetFamily } from './types/WidgetFamily.type';
7
8
 
8
9
  type WidgetSourceFilesProps = {
9
10
  targetName: string;
@@ -12,11 +13,52 @@ type WidgetSourceFilesProps = {
12
13
  onFilesGenerated: (files: string[]) => void;
13
14
  };
14
15
 
16
+ const VALID_WIDGET_FAMILIES: ReadonlySet<string> = new Set(Object.values(WidgetFamily));
17
+
18
+ function assertSwiftIdentifier(value: unknown, label: string): asserts value is string {
19
+ if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
20
+ throw new Error(`Invalid ${label} ${JSON.stringify(value)}: must be a Swift identifier.`);
21
+ }
22
+ }
23
+
24
+ function assertWidgetFamily(value: unknown): asserts value is WidgetFamily {
25
+ if (typeof value !== 'string' || !VALID_WIDGET_FAMILIES.has(value)) {
26
+ throw new Error(
27
+ `Invalid supportedFamilies entry ${JSON.stringify(value)}: must be one of ${[...VALID_WIDGET_FAMILIES].join(', ')}.`
28
+ );
29
+ }
30
+ }
31
+
32
+ function validateWidget(widget: WidgetConfig): void {
33
+ assertSwiftIdentifier(widget.name, 'widget name');
34
+ for (const family of widget.supportedFamilies) {
35
+ assertWidgetFamily(family);
36
+ }
37
+ if (widget.configuration) {
38
+ for (const [paramName, param] of Object.entries(widget.configuration.parameters)) {
39
+ assertSwiftIdentifier(paramName, 'parameter name');
40
+ if (param.type === 'number' && typeof param.default !== 'number') {
41
+ throw new Error(`Invalid default for ${JSON.stringify(paramName)}: must be a number.`);
42
+ } else if (param.type === 'boolean' && typeof param.default !== 'boolean') {
43
+ throw new Error(`Invalid default for ${JSON.stringify(paramName)}: must be a boolean.`);
44
+ } else if (param.type === 'enum') {
45
+ assertSwiftIdentifier(param.default, `default for ${JSON.stringify(paramName)}`);
46
+ for (const value of param.values) {
47
+ assertSwiftIdentifier(value.value, `enum case for ${JSON.stringify(paramName)}`);
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }
53
+
15
54
  const withWidgetSourceFiles: ConfigPlugin<WidgetSourceFilesProps> = (
16
55
  config,
17
56
  { widgets, targetName, onFilesGenerated, groupIdentifier }
18
- ) =>
19
- withDangerousMod(config, [
57
+ ) => {
58
+ for (const widget of widgets) {
59
+ validateWidget(widget);
60
+ }
61
+ return withDangerousMod(config, [
20
62
  'ios',
21
63
  async (config) => {
22
64
  const projectRoot = config.modRequest.platformProjectRoot;
@@ -50,6 +92,7 @@ const withWidgetSourceFiles: ConfigPlugin<WidgetSourceFilesProps> = (
50
92
  return config;
51
93
  },
52
94
  ]);
95
+ };
53
96
 
54
97
  const createIndexSwift = (widgets: WidgetConfig[], targetPath: string): string => {
55
98
  const indexFilePath = path.join(targetPath, `index.swift`);
@@ -143,8 +186,8 @@ struct ${widget.name}: Widget {
143
186
  StaticConfiguration(kind: name, provider: WidgetsTimelineProvider(name: name)) { entry in
144
187
  WidgetsEntryView(entry: entry)
145
188
  }
146
- .configurationDisplayName("${widget.displayName}")
147
- .description("${widget.description}")
189
+ .configurationDisplayName(${JSON.stringify(widget.displayName)})
190
+ .description(${JSON.stringify(widget.description)})
148
191
  .supportedFamilies([.${widget.supportedFamilies.join(', .')}])${widget.contentMarginsDisabled ? '\n .contentMarginsDisabled()' : ''}
149
192
  }
150
193
  }`;
@@ -155,8 +198,8 @@ internal import ExpoWidgets
155
198
 
156
199
  // AppIntent
157
200
  struct ${widget.name}ConfigurationAppIntent: WidgetConfigurationIntent {
158
- static var title: LocalizedStringResource = "${widget.configuration?.title ?? widget.displayName} Configuration"
159
- ${widget.configuration?.description ? ` static var description: LocalizedStringResource = "${widget.configuration?.description}"\n` : ''}
201
+ static var title: LocalizedStringResource = ${JSON.stringify(`${widget.configuration?.title ?? widget.displayName} Configuration`)}
202
+ ${widget.configuration?.description ? ` static var description: LocalizedStringResource = ${JSON.stringify(widget.configuration.description)}\n` : ''}
160
203
  ${Object.entries(widget.configuration?.parameters ?? {})
161
204
  .map(([name, param]) => {
162
205
  let paramType: string;
@@ -176,7 +219,7 @@ ${Object.entries(widget.configuration?.parameters ?? {})
176
219
  default:
177
220
  paramType = 'String';
178
221
  }
179
- return ` @Parameter(title: "${param.title}", default: ${param.type === 'string' ? `"${param.default}"` : param.type === 'number' ? param.default : param.type === 'boolean' ? param.default : `${widget.name}${name[0]?.toUpperCase() + name.slice(1)}Enum.${param.default}`})\n var ${name}: ${paramType}`;
222
+ return ` @Parameter(title: ${JSON.stringify(param.title)}, default: ${param.type === 'string' ? JSON.stringify(param.default) : param.type === 'number' ? param.default : param.type === 'boolean' ? param.default : `${widget.name}${name[0]?.toUpperCase() + name.slice(1)}Enum.${param.default}`})\n var ${name}: ${paramType}`;
180
223
  })
181
224
  .join('\n')}
182
225
 
@@ -196,12 +239,12 @@ enum ${paramTypeName}: String, CaseIterable, AppEnum {
196
239
  })
197
240
  .join('\n ')}
198
241
 
199
- static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "${param.title}")
242
+ static var typeDisplayRepresentation = TypeDisplayRepresentation(name: ${JSON.stringify(param.title)})
200
243
 
201
244
  static var caseDisplayRepresentations: [${paramTypeName}: DisplayRepresentation] = [
202
245
  ${param.values
203
246
  .map((value) => {
204
- return `.${value.value}: DisplayRepresentation(title: "${value.name}")`;
247
+ return `.${value.value}: DisplayRepresentation(title: ${JSON.stringify(value.name)})`;
205
248
  })
206
249
  .join(',\n ')}
207
250
  ]
@@ -301,8 +344,8 @@ struct ${widget.name}: Widget {
301
344
  return AppIntentConfiguration(kind: name, intent: ${widget.name}ConfigurationAppIntent.self, provider: ${widget.name}TimelineProvider()) { entry in
302
345
  ${widget.name}EntryView(entry: entry)
303
346
  }
304
- .configurationDisplayName("${widget.displayName}")
305
- .description("${widget.description}")
347
+ .configurationDisplayName(${JSON.stringify(widget.displayName)})
348
+ .description(${JSON.stringify(widget.description)})
306
349
  .supportedFamilies([.${widget.supportedFamilies.join(', .')}])${widget.contentMarginsDisabled ? '\n .contentMarginsDisabled()' : ''}
307
350
  }
308
351
  }`;
@@ -0,0 +1 @@
1
+ {"root":["./src/index.ts","./src/withappgroupentitlements.ts","./src/withappinfoplist.ts","./src/witheasconfig.ts","./src/withioswarning.ts","./src/withpodslinking.ts","./src/withpushnotifications.ts","./src/withwidgetsourcefiles.ts","./src/types/widgetconfig.type.ts","./src/types/widgetfamily.type.ts","./src/xcode/addbuildphases.ts","./src/xcode/addpbxgroup.ts","./src/xcode/addproductfile.ts","./src/xcode/addtargetdependency.ts","./src/xcode/addtopbxnativetargetsection.ts","./src/xcode/addtopbxprojectsection.ts","./src/xcode/addxcconfigurationlist.ts","./src/xcode/withtargetxcodeproject.ts"],"version":"5.9.2"}
package/spm.config.json CHANGED
@@ -12,6 +12,7 @@
12
12
  "React",
13
13
  "Hermes",
14
14
  "expo-modules-core/ExpoModulesCore",
15
+ "expo-modules-core/ExpoModulesWorklets",
15
16
  "@expo/ui/ExpoUI"
16
17
  ],
17
18
  "targets": [
@@ -25,6 +26,7 @@
25
26
  "React",
26
27
  "Hermes",
27
28
  "expo-modules-core/ExpoModulesCore",
29
+ "expo-modules-core/ExpoModulesWorklets",
28
30
  "@expo/ui/ExpoUI"
29
31
  ],
30
32
  "linkedFrameworks": [
@@ -1,23 +0,0 @@
1
- import Foundation
2
- import JavaScriptCore
3
-
4
- func createWidgetContext(layout: String) -> JSContext? {
5
- guard let context = JSContext() else {
6
- return nil
7
- }
8
-
9
- // Inject ExpoUI bundle
10
- guard let bundleURL = Bundle.main.url(forResource: "ExpoWidgets", withExtension: "bundle"),
11
- let bundle = Bundle(url: bundleURL),
12
- let url = bundle.url(forResource: "ExpoWidgets", withExtension: "bundle"),
13
- let bundleJS = try? String(contentsOf: url, encoding: .utf8) else {
14
- print("[ExpoWidgets] Missing ExpoWidgets.bundle")
15
- return nil
16
- }
17
- context.evaluateScript(bundleJS)
18
-
19
- // Inject layout
20
- let layoutValue = context.evaluateScript("(\(layout))")
21
- context.setObject(layoutValue, forKeyedSubscript: "__expoWidgetLayout" as NSString)
22
- return context
23
- }