vxrn 2.0.0-beta.99.1 → 2.6.0

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.
Files changed (210) hide show
  1. package/dist/backgroundComputation.mjs +145 -0
  2. package/dist/backgroundComputation.mjs.map +1 -0
  3. package/dist/backgroundComputation.native.js +163 -0
  4. package/dist/backgroundComputation.native.js.map +1 -0
  5. package/dist/backgroundComputationNative.mjs +16 -0
  6. package/dist/backgroundComputationNative.mjs.map +1 -0
  7. package/dist/backgroundComputationNative.native.js +18 -0
  8. package/dist/backgroundComputationNative.native.js.map +1 -0
  9. package/dist/config/getBaseViteConfigOnly.mjs +6 -10
  10. package/dist/config/getBaseViteConfigOnly.mjs.map +1 -1
  11. package/dist/config/getBaseViteConfigOnly.native.js +6 -10
  12. package/dist/config/getBaseViteConfigOnly.native.js.map +1 -1
  13. package/dist/config/getOptimizeDeps.mjs +2 -1
  14. package/dist/config/getOptimizeDeps.mjs.map +1 -1
  15. package/dist/config/getOptimizeDeps.native.js +2 -1
  16. package/dist/config/getOptimizeDeps.native.js.map +1 -1
  17. package/dist/config/getViteServerConfig.mjs +13 -0
  18. package/dist/config/getViteServerConfig.mjs.map +1 -1
  19. package/dist/config/getViteServerConfig.native.js +15 -1
  20. package/dist/config/getViteServerConfig.native.js.map +1 -1
  21. package/dist/constants/defaults.mjs +4 -0
  22. package/dist/constants/defaults.mjs.map +1 -1
  23. package/dist/constants/defaults.native.js +4 -0
  24. package/dist/constants/defaults.native.js.map +1 -1
  25. package/dist/exports/build.native.js +1 -1
  26. package/dist/exports/build.native.js.map +1 -1
  27. package/dist/exports/clean.native.js +1 -1
  28. package/dist/exports/clean.native.js.map +1 -1
  29. package/dist/exports/createServer.native.js +2 -2
  30. package/dist/exports/createServer.native.js.map +1 -1
  31. package/dist/exports/dev.mjs +3 -0
  32. package/dist/exports/dev.mjs.map +1 -1
  33. package/dist/exports/dev.native.js +6 -3
  34. package/dist/exports/dev.native.js.map +1 -1
  35. package/dist/exports/loadEnv.native.js +1 -1
  36. package/dist/exports/loadEnv.native.js.map +1 -1
  37. package/dist/exports/patch.native.js +1 -1
  38. package/dist/exports/patch.native.js.map +1 -1
  39. package/dist/exports/prebuild.mjs +0 -22
  40. package/dist/exports/prebuild.mjs.map +1 -1
  41. package/dist/exports/prebuild.native.js +1 -23
  42. package/dist/exports/prebuild.native.js.map +1 -1
  43. package/dist/exports/prebuildWithoutExpo.mjs +1116 -178
  44. package/dist/exports/prebuildWithoutExpo.mjs.map +1 -1
  45. package/dist/exports/prebuildWithoutExpo.native.js +1592 -243
  46. package/dist/exports/prebuildWithoutExpo.native.js.map +1 -1
  47. package/dist/exports/runAndroid.native.js +1 -1
  48. package/dist/exports/runAndroid.native.js.map +1 -1
  49. package/dist/exports/runIos.native.js +1 -1
  50. package/dist/exports/runIos.native.js.map +1 -1
  51. package/dist/exports/serve.native.js +1 -1
  52. package/dist/exports/serve.native.js.map +1 -1
  53. package/dist/exports/serveStaticAssets.native.js +1 -1
  54. package/dist/exports/serveStaticAssets.native.js.map +1 -1
  55. package/dist/index.js +4 -1
  56. package/dist/index.mjs +4 -1
  57. package/dist/index.native.js +4 -1
  58. package/dist/native-source-contract.mjs +3 -0
  59. package/dist/native-source-contract.native.js +3 -0
  60. package/dist/patches/builtInDepPatches.mjs +0 -13
  61. package/dist/patches/builtInDepPatches.mjs.map +1 -1
  62. package/dist/patches/builtInDepPatches.native.js +0 -13
  63. package/dist/patches/builtInDepPatches.native.js.map +1 -1
  64. package/dist/plugins/autoDepOptimizePlugin.mjs +3 -2
  65. package/dist/plugins/autoDepOptimizePlugin.mjs.map +1 -1
  66. package/dist/plugins/autoDepOptimizePlugin.native.js +6 -3
  67. package/dist/plugins/autoDepOptimizePlugin.native.js.map +1 -1
  68. package/dist/plugins/backgroundComputationPlugin.mjs +27 -0
  69. package/dist/plugins/backgroundComputationPlugin.mjs.map +1 -0
  70. package/dist/plugins/backgroundComputationPlugin.native.js +32 -0
  71. package/dist/plugins/backgroundComputationPlugin.native.js.map +1 -0
  72. package/dist/plugins/reactNativeCommonJsPlugin.native.js +3 -3
  73. package/dist/plugins/reactNativeCommonJsPlugin.native.js.map +1 -1
  74. package/dist/plugins/reactNativeDevAssetPlugin.mjs +2 -1
  75. package/dist/plugins/reactNativeDevAssetPlugin.mjs.map +1 -1
  76. package/dist/plugins/reactNativeDevAssetPlugin.native.js +3 -2
  77. package/dist/plugins/reactNativeDevAssetPlugin.native.js.map +1 -1
  78. package/dist/plugins/reactNativeDevServer.mjs +87 -24
  79. package/dist/plugins/reactNativeDevServer.mjs.map +1 -1
  80. package/dist/plugins/reactNativeDevServer.native.js +162 -45
  81. package/dist/plugins/reactNativeDevServer.native.js.map +1 -1
  82. package/dist/plugins/workletImportsPlugin.mjs +9 -30
  83. package/dist/plugins/workletImportsPlugin.mjs.map +1 -1
  84. package/dist/plugins/workletImportsPlugin.native.js +10 -35
  85. package/dist/plugins/workletImportsPlugin.native.js.map +1 -1
  86. package/dist/rn-commands/bundle/buildBundle.mjs +3 -3
  87. package/dist/rn-commands/bundle/buildBundle.mjs.map +1 -1
  88. package/dist/rn-commands/bundle/buildBundle.native.js +3 -3
  89. package/dist/rn-commands/bundle/buildBundle.native.js.map +1 -1
  90. package/dist/runtime/hmr-client.native.js +3 -7
  91. package/dist/runtime/hmr-client.native.js.map +1 -1
  92. package/dist/runtime/hmr-runtime.native.js +32 -40
  93. package/dist/runtime/hmr-runtime.native.js.map +1 -1
  94. package/dist/serve/node.native.js +2 -2
  95. package/dist/serve/node.native.js.map +1 -1
  96. package/dist/swift-package-id.mjs +3 -0
  97. package/dist/swift-package-id.native.js +3 -0
  98. package/dist/user-interface/index.native.js +6 -6
  99. package/dist/user-interface/index.native.js.map +1 -1
  100. package/dist/utils/compileNativeDevBytecode.mjs +93 -0
  101. package/dist/utils/compileNativeDevBytecode.mjs.map +1 -0
  102. package/dist/utils/compileNativeDevBytecode.native.js +98 -0
  103. package/dist/utils/compileNativeDevBytecode.native.js.map +1 -0
  104. package/dist/utils/createNativeDevEngine.mjs +227 -20
  105. package/dist/utils/createNativeDevEngine.mjs.map +1 -1
  106. package/dist/utils/createNativeDevEngine.native.js +249 -37
  107. package/dist/utils/createNativeDevEngine.native.js.map +1 -1
  108. package/dist/utils/execSync.native.js +1 -1
  109. package/dist/utils/execSync.native.js.map +1 -1
  110. package/dist/utils/getServerEntry.native.js +2 -2
  111. package/dist/utils/getServerEntry.native.js.map +1 -1
  112. package/dist/utils/nativeRun.mjs +32 -16
  113. package/dist/utils/nativeRun.mjs.map +1 -1
  114. package/dist/utils/nativeRun.native.js +43 -18
  115. package/dist/utils/nativeRun.native.js.map +1 -1
  116. package/dist/utils/nativeSourceContract.mjs +1823 -0
  117. package/dist/utils/nativeSourceContract.mjs.map +1 -0
  118. package/dist/utils/nativeSourceContract.native.js +2425 -0
  119. package/dist/utils/nativeSourceContract.native.js.map +1 -0
  120. package/dist/utils/patches.native.js +15 -24
  121. package/dist/utils/patches.native.js.map +1 -1
  122. package/dist/utils/printServerUrls.native.js +1 -1
  123. package/dist/utils/printServerUrls.native.js.map +1 -1
  124. package/dist/utils/scanDepsToOptimize.mjs +7 -1
  125. package/dist/utils/scanDepsToOptimize.mjs.map +1 -1
  126. package/dist/utils/scanDepsToOptimize.native.js +27 -2
  127. package/dist/utils/scanDepsToOptimize.native.js.map +1 -1
  128. package/dist/utils/swiftPackageId.mjs +31 -2
  129. package/dist/utils/swiftPackageId.mjs.map +1 -1
  130. package/dist/utils/swiftPackageId.native.js +50 -2
  131. package/dist/utils/swiftPackageId.native.js.map +1 -1
  132. package/dist/vxrn-vite-plugin.native.js +1 -1
  133. package/dist/vxrn-vite-plugin.native.js.map +1 -1
  134. package/expo-plugin.cjs +792 -2
  135. package/native-project-patches.cjs +201 -10
  136. package/package.json +34 -15
  137. package/src/backgroundComputation.ts +220 -0
  138. package/src/backgroundComputationNative.ts +23 -0
  139. package/src/config/getBaseViteConfigOnly.ts +8 -9
  140. package/src/config/getOptimizeDeps.ts +3 -1
  141. package/src/config/getViteServerConfig.ts +16 -0
  142. package/src/config/glbAssets.test.ts +228 -0
  143. package/src/constants/defaults.ts +6 -0
  144. package/src/exports/dev.ts +5 -1
  145. package/src/exports/expoPlugin.test.mjs +337 -15
  146. package/src/exports/prebuild.ts +0 -31
  147. package/src/exports/prebuildWithoutExpo.test.ts +1588 -48
  148. package/src/exports/prebuildWithoutExpo.ts +1573 -213
  149. package/src/index.ts +8 -0
  150. package/src/native-source-contract.ts +16 -0
  151. package/src/patches/builtInDepPatches.ts +0 -21
  152. package/src/plugins/autoDepOptimizePlugin.ts +7 -2
  153. package/src/plugins/backgroundComputationPlugin.test.ts +77 -0
  154. package/src/plugins/backgroundComputationPlugin.ts +29 -0
  155. package/src/plugins/reactNativeDevAssetPlugin.ts +5 -1
  156. package/src/plugins/reactNativeDevServer.test.ts +74 -0
  157. package/src/plugins/reactNativeDevServer.ts +145 -28
  158. package/src/plugins/rnCodegenPlugin.test.ts +30 -0
  159. package/src/plugins/workletImportsPlugin.ts +19 -37
  160. package/src/rn-commands/bundle/buildBundle.ts +5 -3
  161. package/src/swift-package-id.ts +1 -0
  162. package/src/utils/compileNativeDevBytecode.test.ts +168 -0
  163. package/src/utils/compileNativeDevBytecode.ts +117 -0
  164. package/src/utils/createNativeDevEngine.test.ts +643 -18
  165. package/src/utils/createNativeDevEngine.ts +278 -48
  166. package/src/utils/nativeRun.test.ts +125 -23
  167. package/src/utils/nativeRun.ts +51 -23
  168. package/src/utils/nativeSourceArtifacts.test.ts +39 -0
  169. package/src/utils/nativeSourceContract.test.ts +600 -0
  170. package/src/utils/nativeSourceContract.ts +1897 -0
  171. package/src/utils/scanDepsToOptimize.test.ts +80 -0
  172. package/src/utils/scanDepsToOptimize.ts +18 -7
  173. package/src/utils/swiftPackageId.ts +25 -1
  174. package/types/backgroundComputation.d.ts +28 -0
  175. package/types/backgroundComputation.d.ts.map +1 -0
  176. package/types/backgroundComputationNative.d.ts +2 -0
  177. package/types/backgroundComputationNative.d.ts.map +1 -0
  178. package/types/config/getBaseViteConfigOnly.d.ts.map +1 -1
  179. package/types/config/getOptimizeDeps.d.ts.map +1 -1
  180. package/types/config/getViteServerConfig.d.ts.map +1 -1
  181. package/types/constants/defaults.d.ts.map +1 -1
  182. package/types/exports/dev.d.ts.map +1 -1
  183. package/types/exports/prebuild.d.ts.map +1 -1
  184. package/types/exports/prebuildWithoutExpo.d.ts +6 -0
  185. package/types/exports/prebuildWithoutExpo.d.ts.map +1 -1
  186. package/types/index.d.ts +2 -0
  187. package/types/index.d.ts.map +1 -1
  188. package/types/native-source-contract.d.ts +2 -0
  189. package/types/native-source-contract.d.ts.map +1 -0
  190. package/types/patches/builtInDepPatches.d.ts.map +1 -1
  191. package/types/plugins/autoDepOptimizePlugin.d.ts.map +1 -1
  192. package/types/plugins/backgroundComputationPlugin.d.ts +3 -0
  193. package/types/plugins/backgroundComputationPlugin.d.ts.map +1 -0
  194. package/types/plugins/reactNativeDevAssetPlugin.d.ts.map +1 -1
  195. package/types/plugins/reactNativeDevServer.d.ts.map +1 -1
  196. package/types/plugins/workletImportsPlugin.d.ts.map +1 -1
  197. package/types/rn-commands/bundle/buildBundle.d.ts.map +1 -1
  198. package/types/swift-package-id.d.ts +2 -0
  199. package/types/swift-package-id.d.ts.map +1 -0
  200. package/types/utils/compileNativeDevBytecode.d.ts +3 -0
  201. package/types/utils/compileNativeDevBytecode.d.ts.map +1 -0
  202. package/types/utils/createNativeDevEngine.d.ts +7 -22
  203. package/types/utils/createNativeDevEngine.d.ts.map +1 -1
  204. package/types/utils/nativeRun.d.ts.map +1 -1
  205. package/types/utils/nativeSourceContract.d.ts +121 -0
  206. package/types/utils/nativeSourceContract.d.ts.map +1 -0
  207. package/types/utils/scanDepsToOptimize.d.ts +1 -0
  208. package/types/utils/scanDepsToOptimize.d.ts.map +1 -1
  209. package/types/utils/swiftPackageId.d.ts +1 -0
  210. package/types/utils/swiftPackageId.d.ts.map +1 -1
@@ -0,0 +1,1823 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, relative } from "node:path";
4
+ import { swiftPackageDirectories, swiftPackageId } from "./swiftPackageId.mjs";
5
+
6
+ const GENERATED_HEADER = "// generated by one typegen; edits will be replaced\n";
7
+ const SKIP_SOURCE_DIRS = /* @__PURE__ */ new Set([
8
+ "node_modules",
9
+ "ios",
10
+ "android",
11
+ "dist",
12
+ "types",
13
+ "build",
14
+ ".build"
15
+ ]);
16
+ function writeGeneratedFile(file, content) {
17
+ try {
18
+ if (readFileSync(file, "utf8") === content) return;
19
+ } catch (error) {
20
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") throw error;
21
+ }
22
+ const temporary = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);
23
+ try {
24
+ writeFileSync(temporary, content);
25
+ renameSync(temporary, file);
26
+ } finally {
27
+ rmSync(temporary, { force: true });
28
+ }
29
+ }
30
+ function fail(file, token, message) {
31
+ throw new Error(`${file}:${(token?.line ?? 0) + 1}:${(token?.column ?? 0) + 1}: ${message}`);
32
+ }
33
+ function tokens(file, source) {
34
+ const result = [];
35
+ let offset = 0;
36
+ let line = 0;
37
+ let column = 0;
38
+ const advance = () => {
39
+ if (source[offset] === "\n") {
40
+ line++;
41
+ column = 0;
42
+ } else column++;
43
+ offset++;
44
+ };
45
+ while (offset < source.length) {
46
+ const char = source[offset];
47
+ if (/\s/.test(char)) {
48
+ advance();
49
+ continue;
50
+ }
51
+ if (source.startsWith("//", offset)) {
52
+ while (offset < source.length && source[offset] !== "\n") advance();
53
+ continue;
54
+ }
55
+ if (source.startsWith("/*", offset)) {
56
+ let depth = 0;
57
+ do {
58
+ if (source.startsWith("/*", offset)) {
59
+ depth++;
60
+ advance();
61
+ advance();
62
+ } else if (source.startsWith("*/", offset)) {
63
+ depth--;
64
+ advance();
65
+ advance();
66
+ } else advance();
67
+ } while (depth > 0 && offset < source.length);
68
+ if (depth > 0) fail(file, {
69
+ text: "/*",
70
+ line,
71
+ column
72
+ }, "unclosed native source comment");
73
+ continue;
74
+ }
75
+ if (char === "\"" || char === "'") {
76
+ const quote = source.startsWith(char.repeat(3), offset) ? char.repeat(3) : char;
77
+ for (let n = 0; n < quote.length; n++) advance();
78
+ while (offset < source.length && !source.startsWith(quote, offset)) {
79
+ if (source[offset] === "\\") advance();
80
+ advance();
81
+ }
82
+ if (offset >= source.length) fail(file, {
83
+ text: quote,
84
+ line,
85
+ column
86
+ }, "unclosed native source string");
87
+ for (let n = 0; n < quote.length; n++) advance();
88
+ continue;
89
+ }
90
+ const start = offset;
91
+ const startLine = line;
92
+ const startColumn = column;
93
+ if (/[A-Za-z_]/.test(char)) {
94
+ while (offset < source.length && /[A-Za-z0-9_]/.test(source[offset])) advance();
95
+ } else if (source.startsWith("->", offset)) {
96
+ advance();
97
+ advance();
98
+ } else advance();
99
+ result.push({
100
+ text: source.slice(start, offset),
101
+ line: startLine,
102
+ column: startColumn
103
+ });
104
+ }
105
+ return result;
106
+ }
107
+ function close(file, list, start, left, right) {
108
+ let depth = 0;
109
+ for (let i = start; i < list.length; i++) {
110
+ if (list[i].text === left) depth++;
111
+ if (list[i].text === right && --depth === 0) return i;
112
+ }
113
+ fail(file, list[start], `unclosed ${left} in native export`);
114
+ }
115
+ function split(list, separator) {
116
+ const parts = [];
117
+ let start = 0;
118
+ let square = 0;
119
+ let angle = 0;
120
+ let round = 0;
121
+ for (let i = 0; i < list.length; i++) {
122
+ const value = list[i].text;
123
+ if (value === "[") square++;
124
+ if (value === "]") square--;
125
+ if (value === "<") angle++;
126
+ if (value === ">") angle--;
127
+ if (value === "(") round++;
128
+ if (value === ")") round--;
129
+ if (value === separator && square === 0 && angle === 0 && round === 0) {
130
+ parts.push(list.slice(start, i));
131
+ start = i + 1;
132
+ }
133
+ }
134
+ parts.push(list.slice(start));
135
+ return parts;
136
+ }
137
+ function arrayOf(element) {
138
+ return element.includes(" | ") ? `(${element})[]` : `${element}[]`;
139
+ }
140
+ function tsType(file, list, language, named) {
141
+ if (list.length === 0) fail(file, list[0], "native export needs an explicit type");
142
+ if (list.at(-1)?.text === "?") {
143
+ const inner = tsType(file, list.slice(0, -1), language, named);
144
+ return {
145
+ text: `${inner.text} | null`,
146
+ wire: inner.wire ? {
147
+ kind: "nullable",
148
+ inner: inner.wire
149
+ } : null
150
+ };
151
+ }
152
+ const value = list.map((token) => token.text).join("");
153
+ if (value === "String") return {
154
+ text: "string",
155
+ wire: null
156
+ };
157
+ if (value === "Bool" || value === "Boolean") return {
158
+ text: "boolean",
159
+ wire: null
160
+ };
161
+ if ([
162
+ "Double",
163
+ "Float",
164
+ "Int",
165
+ "Long"
166
+ ].includes(value)) return {
167
+ text: "number",
168
+ wire: null
169
+ };
170
+ if (value === "Void" || value === "Unit") return {
171
+ text: "void",
172
+ wire: null
173
+ };
174
+ const dateTypes = language === "swift" ? ["Date", "Foundation.Date"] : ["Date", "java.util.Date"];
175
+ if (dateTypes.includes(value)) return {
176
+ text: "Date",
177
+ wire: { kind: "date" }
178
+ };
179
+ const dataTypes = language === "swift" ? ["Data", "Foundation.Data"] : ["ByteArray"];
180
+ if (dataTypes.includes(value)) {
181
+ return {
182
+ text: "Uint8Array",
183
+ wire: { kind: "data" }
184
+ };
185
+ }
186
+ if (language === "swift" && list[0].text === "[" && list.at(-1)?.text === "]") {
187
+ const inner = list.slice(1, -1);
188
+ const entries = split(inner, ":");
189
+ if (entries.length === 1) {
190
+ const element = tsType(file, inner, language, named);
191
+ return {
192
+ text: arrayOf(element.text),
193
+ wire: element.wire ? {
194
+ kind: "array",
195
+ element: element.wire
196
+ } : null
197
+ };
198
+ }
199
+ if (entries.length === 2 && entries[0].map((token) => token.text).join("") === "String") {
200
+ const element = tsType(file, entries[1], language, named);
201
+ return {
202
+ text: `Record<string, ${element.text}>`,
203
+ wire: element.wire ? {
204
+ kind: "map",
205
+ value: element.wire
206
+ } : null
207
+ };
208
+ }
209
+ }
210
+ if (language === "kotlin" && list[1]?.text === "<" && list.at(-1)?.text === ">") {
211
+ const entries = split(list.slice(2, -1), ",");
212
+ if (list[0].text === "List" && entries.length === 1) {
213
+ const element = tsType(file, entries[0], language, named);
214
+ return {
215
+ text: arrayOf(element.text),
216
+ wire: element.wire ? {
217
+ kind: "array",
218
+ element: element.wire
219
+ } : null
220
+ };
221
+ }
222
+ if (list[0].text === "Map" && entries.length === 2 && entries[0].map((token) => token.text).join("") === "String") {
223
+ const element = tsType(file, entries[1], language, named);
224
+ return {
225
+ text: `Record<string, ${element.text}>`,
226
+ wire: element.wire ? {
227
+ kind: "map",
228
+ value: element.wire
229
+ } : null
230
+ };
231
+ }
232
+ }
233
+ if (list.length === 1 && /^[A-Z][A-Za-z0-9_]*$/.test(value)) {
234
+ const struct = named.structs.get(value);
235
+ if (struct) {
236
+ if (struct.generic) fail(file, list[0], `generic struct ${value} is unsupported`);
237
+ if (struct.problem) fail(file, list[0], struct.problem);
238
+ if (!struct.codable) fail(file, list[0], `struct ${value} must conform to Codable to cross the boundary`);
239
+ return {
240
+ text: value,
241
+ wire: {
242
+ kind: "struct",
243
+ name: value
244
+ }
245
+ };
246
+ }
247
+ const enumType = named.enums.get(value);
248
+ if (enumType) {
249
+ if (!enumType.usable) fail(file, list[0], enumType.problem);
250
+ return {
251
+ text: value,
252
+ wire: {
253
+ kind: "enum",
254
+ name: value
255
+ }
256
+ };
257
+ }
258
+ }
259
+ fail(file, list[0], `unsupported native export type ${value}`);
260
+ }
261
+ function parameters(file, list, language, named) {
262
+ if (list.length === 0) return [];
263
+ return split(list, ",").map((part, index) => {
264
+ if (part.some((token) => token.text === "=")) fail(file, part[0], "default native export arguments are unsupported");
265
+ const colon = part.findIndex((token) => token.text === ":");
266
+ if (colon < 0) fail(file, part[0], "native export parameter needs an explicit type");
267
+ const names = part.slice(0, colon).filter((token) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(token.text));
268
+ const name = (language === "swift" ? names.at(-1) : names[0])?.text ?? `arg${index}`;
269
+ if (name === "_") fail(file, part[0], "native export parameter needs an internal name");
270
+ const label = language === "swift" ? names[0]?.text ?? name : null;
271
+ const sourceType = part.slice(colon + 1);
272
+ const type = tsType(file, sourceType, language, named);
273
+ return {
274
+ name,
275
+ label,
276
+ type: type.text,
277
+ nativeType: sourceType.map((token) => token.text).join(""),
278
+ wire: type.wire ?? void 0
279
+ };
280
+ });
281
+ }
282
+ const DECLARATION_MODIFIERS = /* @__PURE__ */ new Set([
283
+ "private",
284
+ "fileprivate",
285
+ "public",
286
+ "internal",
287
+ "open",
288
+ "override",
289
+ "static",
290
+ "class",
291
+ "final",
292
+ "suspend",
293
+ "inline",
294
+ "operator",
295
+ "infix",
296
+ "tailrec",
297
+ "external",
298
+ "nonisolated",
299
+ "isolated",
300
+ "mutating",
301
+ "nonmutating",
302
+ "dynamic",
303
+ "required",
304
+ "convenience",
305
+ "optional"
306
+ ]);
307
+ function declarationStart(list, floor, keyword) {
308
+ let first = keyword;
309
+ while (first > floor) {
310
+ const text = list[first - 1].text;
311
+ if (DECLARATION_MODIFIERS.has(text)) {
312
+ first--;
313
+ continue;
314
+ }
315
+ if (list[first - 2]?.text === "@") {
316
+ first -= 2;
317
+ continue;
318
+ }
319
+ if (text === ")") {
320
+ let open = first - 1;
321
+ for (let depth = 0; open > floor; open--) {
322
+ if (list[open].text === ")") depth++;
323
+ if (list[open].text === "(" && --depth === 0) break;
324
+ }
325
+ if (list[open - 2]?.text === "@") {
326
+ first = open - 2;
327
+ continue;
328
+ }
329
+ }
330
+ break;
331
+ }
332
+ return first;
333
+ }
334
+ function subscriptionPayload(file, typeTokens, language, named) {
335
+ try {
336
+ if (typeTokens.at(-1)?.text === "?") return null;
337
+ let fn = typeTokens;
338
+ if (language === "swift" && fn[0]?.text === "@" && fn[1]?.text === "escaping") fn = fn.slice(2);
339
+ if (fn[0]?.text === "(" && close(file, fn, 0, "(", ")") === fn.length - 1 && fn.some((token) => token.text === "->")) {
340
+ fn = fn.slice(1, -1);
341
+ }
342
+ const arrow = fn.findIndex((token) => token.text === "->");
343
+ if (arrow <= 0 || fn[0]?.text !== "(" || close(file, fn, 0, "(", ")") !== arrow - 1) return null;
344
+ const result = fn.slice(arrow + 1);
345
+ const voidResult = result.length === 1 && (result[0].text === "Void" || result[0].text === "Unit") || result.length === 2 && result[0].text === "(" && result[1].text === ")";
346
+ if (!voidResult) return null;
347
+ const inner = fn.slice(1, arrow - 1);
348
+ if (inner.length === 0) return [];
349
+ return split(inner, ",").map((arg) => {
350
+ const colon = arg.findIndex((token) => token.text === ":");
351
+ const type = colon < 0 ? arg : arg.slice(colon + 1);
352
+ const resolved = tsType(file, type, language, named);
353
+ return {
354
+ type: resolved.text,
355
+ nativeType: type.map((token) => token.text).join(""),
356
+ wire: resolved.wire ?? void 0
357
+ };
358
+ });
359
+ } catch {
360
+ return null;
361
+ }
362
+ }
363
+ function methods(file, list, start, end, language, named) {
364
+ const result = [];
365
+ let i = start + 1;
366
+ let previous = i;
367
+ const keyword = language === "swift" ? "func" : "fun";
368
+ while (i < end) {
369
+ if (list[i].text === "{") {
370
+ i = close(file, list, i, "{", "}") + 1;
371
+ previous = i;
372
+ continue;
373
+ }
374
+ if (list[i].text !== keyword) {
375
+ i++;
376
+ continue;
377
+ }
378
+ const modifiers = list.slice(declarationStart(list, previous, i), i).map((token) => token.text);
379
+ const hidden = modifiers.includes("private") || modifiers.includes("fileprivate");
380
+ if (!hidden && (modifiers.includes("static") || modifiers.includes("class"))) {
381
+ fail(file, list[i], "static native exports are unsupported");
382
+ }
383
+ const name = list[i + 1]?.text;
384
+ if (!name || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) fail(file, list[i], "native export has no method name");
385
+ if (result.some((method) => method.name === name)) fail(file, list[i], `overloaded native export ${name} is unsupported`);
386
+ if (list[i + 2]?.text === "<") fail(file, list[i], "generic native exports are unsupported");
387
+ const open = i + 2;
388
+ if (list[open]?.text !== "(") fail(file, list[i], "native export has no parameter list");
389
+ const closing = close(file, list, open, "(", ")");
390
+ let headerEnd = closing + 1;
391
+ while (headerEnd < end && ![
392
+ "{",
393
+ "=",
394
+ ";"
395
+ ].includes(list[headerEnd].text)) headerEnd++;
396
+ const header = list.slice(closing + 1, headerEnd);
397
+ const separator = header.findIndex((token) => token.text === (language === "swift" ? "->" : ":"));
398
+ const sourceType = hidden || separator < 0 ? [] : header.slice(separator + 1);
399
+ const type = sourceType.length === 0 ? {
400
+ text: "void",
401
+ wire: null
402
+ } : tsType(file, sourceType, language, named);
403
+ let subscription;
404
+ if (!hidden && type.text === "void") {
405
+ const parts = split(list.slice(open + 1, closing), ",");
406
+ if (parts.length === 1 && parts[0].length > 0) {
407
+ const colon = parts[0].findIndex((token) => token.text === ":");
408
+ if (colon >= 0) {
409
+ const payload = subscriptionPayload(file, parts[0].slice(colon + 1), language, named);
410
+ if (payload) subscription = { payload };
411
+ }
412
+ }
413
+ }
414
+ if (!hidden) {
415
+ result.push({
416
+ name,
417
+ parameters: subscription ? [] : parameters(file, list.slice(open + 1, closing), language, named),
418
+ result: type.text,
419
+ nativeResult: sourceType.length === 0 ? language === "swift" ? "Void" : "Unit" : sourceType.map((token) => token.text).join(""),
420
+ resultWire: type.wire ?? void 0,
421
+ subscription,
422
+ throws: language === "swift" ? header.some((token) => token.text === "throws") : true,
423
+ async: language === "swift" ? header.some((token) => token.text === "async") : modifiers.includes("suspend")
424
+ });
425
+ }
426
+ if (list[headerEnd]?.text === "{") i = close(file, list, headerEnd, "{", "}") + 1;
427
+ else if (list[headerEnd]?.text === "=") {
428
+ const bodyLine = list[headerEnd].line;
429
+ i = headerEnd + 1;
430
+ while (i < end && list[i].line === bodyLine && list[i].text !== ";") i++;
431
+ } else i = headerEnd + 1;
432
+ previous = i;
433
+ }
434
+ return result;
435
+ }
436
+ function callbackProp(file, name, typeTokens, optional, language, named) {
437
+ const nullable = typeTokens.at(-1)?.text === "?";
438
+ let fn = nullable ? typeTokens.slice(0, -1) : typeTokens;
439
+ if (fn[0]?.text === "(" && close(file, fn, 0, "(", ")") === fn.length - 1 && fn.some((token) => token.text === "->")) {
440
+ fn = fn.slice(1, -1);
441
+ }
442
+ const arrow = fn.findIndex((token) => token.text === "->");
443
+ if (arrow < 0 || fn[0]?.text !== "(" || close(file, fn, 0, "(", ")") !== arrow - 1) return null;
444
+ const result = fn.slice(arrow + 1).map((token) => token.text).join("");
445
+ const unit = language === "swift" ? "Void" : "Unit";
446
+ if (result !== unit && !(language === "swift" && result === "()")) {
447
+ fail(file, typeTokens[0], `view callback ${name} must return ${unit}`);
448
+ }
449
+ const inner = fn.slice(1, arrow - 1);
450
+ const callback = inner.length === 0 ? [] : split(inner, ",").map((arg) => {
451
+ const colon = arg.findIndex((token) => token.text === ":");
452
+ const type = colon < 0 ? arg : arg.slice(colon + 1);
453
+ const resolved = tsType(file, type, language, named);
454
+ return {
455
+ type: resolved.text,
456
+ nativeType: type.map((token) => token.text).join(""),
457
+ wire: resolved.wire ?? void 0
458
+ };
459
+ });
460
+ const signature = `(${callback.map((arg, index) => `value${index}: ${arg.type}`).join(", ")}) => void`;
461
+ const nativeType = typeTokens.map((token) => token.text).join("");
462
+ return {
463
+ name,
464
+ type: nullable ? `(${signature}) | null` : signature,
465
+ nativeType,
466
+ optional,
467
+ callback
468
+ };
469
+ }
470
+ function viewProp(file, part, named) {
471
+ const colon = part.findIndex((token) => token.text === ":");
472
+ if (colon !== 1 || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(part[0].text)) {
473
+ fail(file, part[0], "composable parameter needs a name and an explicit type");
474
+ }
475
+ const name = part[0].text;
476
+ const equals = split(part.slice(colon + 1), "=");
477
+ const typeTokens = equals[0];
478
+ const fallback = equals[1]?.map((token) => token.text).join("");
479
+ const nativeType = typeTokens.map((token) => token.text).join("");
480
+ if (nativeType === "Modifier") {
481
+ if (fallback !== "Modifier") fail(file, part[0], "a composable modifier parameter needs the default Modifier");
482
+ return null;
483
+ }
484
+ const nullable = typeTokens.at(-1)?.text === "?";
485
+ if (fallback !== void 0 && !(nullable && fallback === "null")) {
486
+ fail(file, part[0], `composable parameter ${name} may only default to null`);
487
+ }
488
+ const optional = fallback !== void 0;
489
+ const callback = callbackProp(file, name, typeTokens, optional, "kotlin", named);
490
+ if (callback) return callback;
491
+ const resolved = tsType(file, typeTokens, "kotlin", named);
492
+ return {
493
+ name,
494
+ type: resolved.text,
495
+ nativeType,
496
+ optional,
497
+ callback: null,
498
+ wire: resolved.wire ?? void 0
499
+ };
500
+ }
501
+ const PLAIN_ATTRIBUTES = /* @__PURE__ */ new Set([
502
+ "MainActor",
503
+ "available",
504
+ "objc",
505
+ "nonobjc",
506
+ "preconcurrency"
507
+ ]);
508
+ function storedProperty(file, list, i, previous, end, owner) {
509
+ const at = list[i];
510
+ const own = list.slice(declarationStart(list, previous, i), i).map((token) => token.text);
511
+ const propName = list[i + 1]?.text ?? "";
512
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(propName)) fail(file, list[i], `${owner} has a property without a simple name`);
513
+ let stop = i + 2;
514
+ let depth = 0;
515
+ while (stop < end) {
516
+ const value = list[stop].text;
517
+ if (depth === 0 && (value === "=" || value === "{" || value === ";" || list[stop].line !== list[stop - 1].line)) break;
518
+ if (value === "(" || value === "[" || value === "<") depth++;
519
+ if (value === ")" || value === "]" || value === ">") depth--;
520
+ stop++;
521
+ }
522
+ const typeTokens = list[i + 2]?.text === ":" ? list.slice(i + 3, stop) : [];
523
+ const valued = list[stop]?.text === "=";
524
+ let next = stop;
525
+ if (valued) {
526
+ const valueLine = list[stop].line;
527
+ while (next < end && list[next].line === valueLine && list[next].text !== "{") next++;
528
+ }
529
+ const block = list[next]?.text === "{";
530
+ const computed = block && !valued && !["willSet", "didSet"].includes(list[next + 1]?.text);
531
+ const resume = block ? close(file, list, next, "{", "}") + 1 : next;
532
+ return {
533
+ at,
534
+ own,
535
+ propName,
536
+ typeTokens,
537
+ valued,
538
+ stop,
539
+ computed,
540
+ resume
541
+ };
542
+ }
543
+ function swiftView(file, list, keyword, floor, body, end, named) {
544
+ const modifiers = list.slice(declarationStart(list, floor, keyword), keyword).map((token) => token.text);
545
+ if (list[keyword].text !== "struct" || !modifiers.includes("public")) return null;
546
+ if (!list.slice(keyword + 2, body).some((token) => token.text === "View")) return null;
547
+ const name = list[keyword + 1].text;
548
+ if (!/^[A-Z][A-Za-z0-9_]*$/.test(name)) fail(file, list[keyword], "an imported view needs a capitalized name");
549
+ if (list[keyword + 2]?.text === "<") fail(file, list[keyword], `generic view ${name} is unsupported`);
550
+ const props = [];
551
+ let i = body + 1;
552
+ let previous = i;
553
+ while (i < end) {
554
+ const text = list[i].text;
555
+ if (text === "{") {
556
+ i = close(file, list, i, "{", "}") + 1;
557
+ previous = i;
558
+ continue;
559
+ }
560
+ if (text === "init" && list[i + 1]?.text === "(" && list[i - 1]?.text !== ".") {
561
+ fail(file, list[i], `view ${name} is imported through its memberwise initializer; remove init(...)`);
562
+ }
563
+ if (text !== "let" && text !== "var") {
564
+ i++;
565
+ continue;
566
+ }
567
+ const property = storedProperty(file, list, i, previous, end, `view ${name}`);
568
+ const { at, own, propName, typeTokens, valued, stop } = property;
569
+ i = property.resume;
570
+ previous = i;
571
+ const wrapper = own.findIndex((value, index) => own[index - 1] === "@" && !PLAIN_ATTRIBUTES.has(value));
572
+ if (property.computed || own.includes("static")) continue;
573
+ if (wrapper >= 0) {
574
+ if (valued || own[wrapper + 1] === "(") continue;
575
+ fail(file, at, `@${own[wrapper]} ${propName} in view ${name} needs a value; pass a plain value and a callback instead`);
576
+ }
577
+ if (own.includes("private") || own.includes("fileprivate")) {
578
+ if (valued) continue;
579
+ fail(file, at, `private ${propName} in view ${name} needs a value, or the view cannot be built from javascript`);
580
+ }
581
+ if (valued && text === "let") continue;
582
+ if (typeTokens.length === 0) fail(file, at, `view prop ${propName} needs an explicit type`);
583
+ const nullable = typeTokens.at(-1)?.text === "?";
584
+ if (valued && !(nullable && list[stop + 1]?.text === "nil" && list[stop + 2]?.line !== list[stop + 1].line)) {
585
+ fail(file, list[stop], `view prop ${propName} may only default to nil`);
586
+ }
587
+ const callback = callbackProp(file, propName, typeTokens, nullable, "swift", named);
588
+ if (callback) {
589
+ props.push(callback);
590
+ } else {
591
+ const resolved = tsType(file, typeTokens, "swift", named);
592
+ props.push({
593
+ name: propName,
594
+ type: resolved.text,
595
+ nativeType: typeTokens.map((token) => token.text).join(""),
596
+ optional: nullable,
597
+ callback: null,
598
+ wire: resolved.wire ?? void 0
599
+ });
600
+ }
601
+ }
602
+ return {
603
+ name,
604
+ props
605
+ };
606
+ }
607
+ function collectDataClass(file, list, keyword, name, token, generic, packageName) {
608
+ const modifiers = list.slice(declarationStart(list, 0, keyword - 1), keyword).map((entry) => entry.text);
609
+ let problem = null;
610
+ if (modifiers.includes("private")) {
611
+ problem = `data class ${name} must be public to cross the boundary`;
612
+ }
613
+ let scan = keyword + 2;
614
+ if (list[scan]?.text === "<") scan = close(file, list, scan, "<", ">") + 1;
615
+ while ([
616
+ "private",
617
+ "protected",
618
+ "public",
619
+ "internal",
620
+ "constructor"
621
+ ].includes(list[scan]?.text)) scan++;
622
+ const params = [];
623
+ if (list[scan]?.text === "(") {
624
+ const closing = close(file, list, scan, "(", ")");
625
+ for (const part of split(list.slice(scan + 1, closing), ",")) {
626
+ if (part.length > 0) params.push(part);
627
+ }
628
+ } else {
629
+ return null;
630
+ }
631
+ if (list.slice(keyword + 2, scan).some((entry) => entry.text === "private" || entry.text === "protected")) {
632
+ problem = problem ?? `data class ${name} must be public to cross the boundary`;
633
+ }
634
+ return {
635
+ name,
636
+ token,
637
+ generic,
638
+ codable: true,
639
+ problem,
640
+ body: [],
641
+ params,
642
+ packageName
643
+ };
644
+ }
645
+ function collectSwiftEnum(file, body, name, token, generic, header) {
646
+ const backing = header.some((entry) => entry.text === "String") ? "string" : header.some((entry) => entry.text === "Int") ? "number" : null;
647
+ if (generic) {
648
+ return {
649
+ name,
650
+ token,
651
+ generic,
652
+ usable: false,
653
+ problem: `generic enum ${name} is unsupported`,
654
+ backing: "string",
655
+ cases: []
656
+ };
657
+ }
658
+ if (!backing) {
659
+ return {
660
+ name,
661
+ token,
662
+ generic,
663
+ usable: false,
664
+ problem: `enum ${name} needs a String or Int backing to cross the boundary`,
665
+ backing: "string",
666
+ cases: []
667
+ };
668
+ }
669
+ const inherits = header.map((entry) => entry.text);
670
+ if (!inherits.includes("Codable") && !(inherits.includes("Decodable") && inherits.includes("Encodable"))) {
671
+ return {
672
+ name,
673
+ token,
674
+ generic,
675
+ usable: false,
676
+ problem: `enum ${name} must conform to Codable to cross the boundary`,
677
+ backing,
678
+ cases: []
679
+ };
680
+ }
681
+ const memberStarters = /* @__PURE__ */ new Set([
682
+ "func",
683
+ "var",
684
+ "let",
685
+ "init",
686
+ "deinit",
687
+ "subscript",
688
+ "static",
689
+ "public",
690
+ "private",
691
+ "fileprivate",
692
+ "internal",
693
+ "open",
694
+ "final",
695
+ "mutating",
696
+ "nonmutating",
697
+ "override",
698
+ "lazy",
699
+ "weak",
700
+ "unowned",
701
+ "required",
702
+ "convenience",
703
+ "dynamic",
704
+ "indirect",
705
+ "typealias",
706
+ "import"
707
+ ]);
708
+ const cases = [];
709
+ let problem = null;
710
+ let counter = 0;
711
+ let i = 0;
712
+ let depth = 0;
713
+ while (i < body.length) {
714
+ if (body[i].text === "{") {
715
+ depth++;
716
+ i++;
717
+ continue;
718
+ }
719
+ if (body[i].text === "}") {
720
+ depth--;
721
+ i++;
722
+ continue;
723
+ }
724
+ if (depth !== 0 || body[i].text !== "case") {
725
+ i++;
726
+ continue;
727
+ }
728
+ let stop = i + 1;
729
+ let inner = 0;
730
+ while (stop < body.length) {
731
+ const value = body[stop].text;
732
+ if (inner === 0 && (value === ";" || value === "case" || memberStarters.has(value))) break;
733
+ if (value === "(" || value === "[" || value === "<") inner++;
734
+ if (value === ")" || value === "]" || value === ">") inner--;
735
+ stop++;
736
+ if (inner < 0) break;
737
+ }
738
+ for (const item of split(body.slice(i + 1, stop), ",")) {
739
+ const itemName = item[0]?.text ?? "";
740
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(itemName)) continue;
741
+ if (item.some((entry) => entry.text === "(")) {
742
+ problem = problem ?? `enum ${name} has associated values, which cannot cross the boundary`;
743
+ continue;
744
+ }
745
+ if (item.some((entry) => entry.text === "=")) {
746
+ problem = problem ?? `enum ${name} has an explicit raw value, which cannot cross the boundary`;
747
+ continue;
748
+ }
749
+ cases.push({
750
+ name: itemName,
751
+ value: backing === "string" ? itemName : counter
752
+ });
753
+ counter++;
754
+ }
755
+ i = stop;
756
+ }
757
+ return {
758
+ name,
759
+ token,
760
+ generic,
761
+ usable: problem === null,
762
+ problem: problem ?? "",
763
+ backing,
764
+ cases
765
+ };
766
+ }
767
+ function collectKotlinEnum(file, body, name, token) {
768
+ const cases = [];
769
+ let i = 0;
770
+ const stopWords = /* @__PURE__ */ new Set([
771
+ ";",
772
+ "fun",
773
+ "val",
774
+ "var",
775
+ "init",
776
+ "companion",
777
+ "constructor",
778
+ "object",
779
+ "inner",
780
+ "abstract",
781
+ "open",
782
+ "override",
783
+ "lateinit",
784
+ "const",
785
+ "public",
786
+ "private",
787
+ "protected",
788
+ "internal"
789
+ ]);
790
+ while (i < body.length && !stopWords.has(body[i].text)) {
791
+ if (body[i].text === ",") {
792
+ i++;
793
+ continue;
794
+ }
795
+ if (body[i].text === "@") {
796
+ i += 2;
797
+ if (body[i]?.text === "(") i = close(file, body, i, "(", ")") + 1;
798
+ continue;
799
+ }
800
+ const entry = body[i].text;
801
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(entry)) break;
802
+ cases.push({
803
+ name: entry,
804
+ value: entry
805
+ });
806
+ i++;
807
+ while (i < body.length && (body[i].text === "(" || body[i].text === "{")) {
808
+ i = close(file, body, i, body[i].text, body[i].text === "(" ? ")" : "}") + 1;
809
+ }
810
+ }
811
+ return {
812
+ name,
813
+ token,
814
+ generic: false,
815
+ usable: cases.length > 0,
816
+ problem: cases.length > 0 ? "" : `enum class ${name} has no entries to cross the boundary`,
817
+ backing: "string",
818
+ cases
819
+ };
820
+ }
821
+ const STRUCT_MEMBER_WORDS = /* @__PURE__ */ new Set([
822
+ "init",
823
+ "deinit",
824
+ "func",
825
+ "subscript",
826
+ "struct",
827
+ "enum",
828
+ "class",
829
+ "extension",
830
+ "object",
831
+ "static"
832
+ ]);
833
+ function swiftStructFields(file, struct, named) {
834
+ const fields = [];
835
+ const body = struct.body;
836
+ const end = body.length;
837
+ let i = 0;
838
+ let previous = 0;
839
+ while (i < end) {
840
+ const text = body[i].text;
841
+ if (text === "{") {
842
+ i = close(file, body, i, "{", "}") + 1;
843
+ previous = i;
844
+ continue;
845
+ }
846
+ if (STRUCT_MEMBER_WORDS.has(text)) {
847
+ let scan = i + 1;
848
+ let angle = 0;
849
+ let round = 0;
850
+ while (scan < end) {
851
+ const value = body[scan].text;
852
+ if (value === "<") angle++;
853
+ else if (value === ">") angle--;
854
+ else if (value === "(") round++;
855
+ else if (value === ")") round--;
856
+ else if (value === "{" && angle === 0 && round === 0) break;
857
+ else if (value === ";" && angle === 0 && round === 0) break;
858
+ scan++;
859
+ }
860
+ i = body[scan]?.text === "{" ? close(file, body, scan, "{", "}") + 1 : scan + 1;
861
+ previous = i;
862
+ continue;
863
+ }
864
+ if (text !== "let" && text !== "var") {
865
+ i++;
866
+ continue;
867
+ }
868
+ const property = storedProperty(file, body, i, previous, end, `struct ${struct.name}`);
869
+ const { at, own, propName, typeTokens, valued } = property;
870
+ i = property.resume;
871
+ previous = i;
872
+ if (property.computed || own.includes("static")) continue;
873
+ const wrapper = own.findIndex((value, index) => own[index - 1] === "@" && !PLAIN_ATTRIBUTES.has(value));
874
+ if (wrapper >= 0) {
875
+ fail(file, at, `@${own[wrapper]} ${propName} in struct ${struct.name} is unsupported; cross a plain value instead`);
876
+ }
877
+ if (own.includes("private") || own.includes("fileprivate")) {
878
+ if (valued) continue;
879
+ fail(file, at, `private ${propName} in struct ${struct.name} needs a value, or calls cannot supply it`);
880
+ }
881
+ if (typeTokens.length === 0) fail(file, at, `struct ${struct.name} field ${propName} needs an explicit type`);
882
+ const resolved = tsType(file, typeTokens, "swift", named);
883
+ fields.push({
884
+ name: propName,
885
+ type: resolved.text,
886
+ nativeType: typeTokens.map((token) => token.text).join(""),
887
+ optional: valued,
888
+ wire: resolved.wire ?? void 0
889
+ });
890
+ }
891
+ return fields;
892
+ }
893
+ function kotlinStructFields(file, struct, named) {
894
+ const fields = [];
895
+ for (const part of struct.params) {
896
+ const keyword = part.findIndex((token) => token.text === "val" || token.text === "var");
897
+ if (keyword < 0) fail(file, part[0], `data class ${struct.name} field needs val or var`);
898
+ if (part.some((token) => token.text === "vararg")) {
899
+ fail(file, part[0], `data class ${struct.name} field ${part[keyword + 1]?.text ?? ""} is vararg, which cannot cross the boundary`);
900
+ }
901
+ const fieldName = part[keyword + 1]?.text ?? "";
902
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(fieldName)) {
903
+ fail(file, part[keyword], `data class ${struct.name} has a field without a simple name`);
904
+ }
905
+ let colon = -1;
906
+ let equals = -1;
907
+ let depth = 0;
908
+ for (let t = keyword + 2; t < part.length; t++) {
909
+ const value = part[t].text;
910
+ if (value === "(" || value === "[" || value === "<") depth++;
911
+ else if (value === ")" || value === "]" || value === ">") depth--;
912
+ else if (depth === 0 && value === ":" && colon < 0) colon = t;
913
+ else if (depth === 0 && value === "=" && equals < 0) equals = t;
914
+ }
915
+ if (colon < 0) fail(file, part[keyword], `data class ${struct.name} field ${fieldName} needs an explicit type`);
916
+ const typeTokens = part.slice(colon + 1, equals < 0 ? part.length : equals);
917
+ const fallback = equals < 0 ? void 0 : part.slice(equals + 1).map((token) => token.text).join("");
918
+ const resolved = tsType(file, typeTokens, "kotlin", named);
919
+ fields.push({
920
+ name: fieldName,
921
+ type: resolved.text,
922
+ nativeType: typeTokens.map((token) => token.text).join(""),
923
+ optional: equals >= 0,
924
+ wire: resolved.wire ?? void 0,
925
+ fallback
926
+ });
927
+ }
928
+ return fields;
929
+ }
930
+ function finalizeNamedTypes(file, language, named, structs, enums, modules, views) {
931
+ const reached = /* @__PURE__ */ new Set();
932
+ const queue = [];
933
+ const visitWire = (wire) => {
934
+ if (!wire) return;
935
+ if (wire.kind === "struct" || wire.kind === "enum") {
936
+ if (!reached.has(wire.name)) {
937
+ reached.add(wire.name);
938
+ if (wire.kind === "struct") queue.push(wire.name);
939
+ }
940
+ } else if (wire.kind === "array") visitWire(wire.element);
941
+ else if (wire.kind === "map") visitWire(wire.value);
942
+ else if (wire.kind === "nullable") visitWire(wire.inner);
943
+ };
944
+ for (const module of modules) {
945
+ for (const method of module.methods) {
946
+ for (const param of method.parameters) visitWire(param.wire);
947
+ visitWire(method.resultWire);
948
+ for (const arg of method.subscription?.payload ?? []) visitWire(arg.wire);
949
+ }
950
+ }
951
+ for (const view of views) {
952
+ for (const prop of view.props) {
953
+ visitWire(prop.wire);
954
+ for (const arg of prop.callback ?? []) visitWire(arg.wire);
955
+ }
956
+ }
957
+ const byName = new Map(structs.map((entry) => [entry.name, entry]));
958
+ const parsed = /* @__PURE__ */ new Map();
959
+ while (queue.length > 0) {
960
+ const name = queue.pop();
961
+ if (parsed.has(name)) continue;
962
+ const decl = byName.get(name);
963
+ if (!decl) continue;
964
+ const fields = language === "swift" ? swiftStructFields(file, decl, named) : kotlinStructFields(file, decl, named);
965
+ parsed.set(name, fields);
966
+ for (const field of fields) visitWire(field.wire);
967
+ }
968
+ return {
969
+ structs: structs.filter((entry) => reached.has(entry.name)).map((entry) => ({
970
+ name: entry.name,
971
+ fields: parsed.get(entry.name) ?? []
972
+ })),
973
+ enums: enums.filter((entry) => reached.has(entry.name)).map((entry) => ({
974
+ name: entry.name,
975
+ backing: entry.backing,
976
+ cases: entry.cases
977
+ }))
978
+ };
979
+ }
980
+ function collectNamedTypes(file, list, language, packageName) {
981
+ const structs = [];
982
+ const enums = [];
983
+ let depth = 0;
984
+ let i = 0;
985
+ while (i < list.length) {
986
+ const text = list[i].text;
987
+ if (text === "{") {
988
+ depth++;
989
+ i++;
990
+ continue;
991
+ }
992
+ if (text === "}") {
993
+ depth--;
994
+ i++;
995
+ continue;
996
+ }
997
+ if (depth !== 0) {
998
+ i++;
999
+ continue;
1000
+ }
1001
+ const isSwiftStruct = language === "swift" && text === "struct";
1002
+ const isSwiftEnum = language === "swift" && text === "enum";
1003
+ const isDataClass = language === "kotlin" && text === "class" && list[i - 1]?.text === "data";
1004
+ const isKotlinEnum = language === "kotlin" && text === "class" && list[i - 1]?.text === "enum";
1005
+ if (!isSwiftStruct && !isSwiftEnum && !isDataClass && !isKotlinEnum) {
1006
+ i++;
1007
+ continue;
1008
+ }
1009
+ const name = list[i + 1]?.text;
1010
+ if (!name || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
1011
+ i++;
1012
+ continue;
1013
+ }
1014
+ const token = list[i + 1];
1015
+ const generic = list[i + 2]?.text === "<";
1016
+ if (isDataClass) {
1017
+ const dataClass = collectDataClass(file, list, i, name, token, generic, packageName);
1018
+ let scan = i + 2;
1019
+ if (list[scan]?.text === "<") scan = close(file, list, scan, "<", ">") + 1;
1020
+ while ([
1021
+ "private",
1022
+ "protected",
1023
+ "public",
1024
+ "internal",
1025
+ "constructor"
1026
+ ].includes(list[scan]?.text)) scan++;
1027
+ i = list[scan]?.text === "(" ? close(file, list, scan, "(", ")") + 1 : i + 2;
1028
+ if (dataClass) structs.push(dataClass);
1029
+ continue;
1030
+ }
1031
+ let body = i + 2;
1032
+ let angle = 0;
1033
+ let round = 0;
1034
+ while (body < list.length) {
1035
+ const value = list[body].text;
1036
+ if (value === "<") angle++;
1037
+ else if (value === ">") angle--;
1038
+ else if (value === "(") round++;
1039
+ else if (value === ")") round--;
1040
+ else if (value === "{" && angle === 0 && round === 0) break;
1041
+ body++;
1042
+ }
1043
+ if (body >= list.length) {
1044
+ i++;
1045
+ continue;
1046
+ }
1047
+ const end = close(file, list, body, "{", "}");
1048
+ const header = list.slice(i + 2, body);
1049
+ if (isSwiftStruct) {
1050
+ const inherits = header.map((entry) => entry.text);
1051
+ const modifiers = list.slice(declarationStart(list, 0, i), i).map((entry) => entry.text);
1052
+ structs.push({
1053
+ name,
1054
+ token,
1055
+ generic,
1056
+ codable: inherits.includes("Codable") || inherits.includes("Decodable") && inherits.includes("Encodable"),
1057
+ problem: modifiers.includes("private") || modifiers.includes("fileprivate") ? `struct ${name} is private to its file and cannot cross the boundary` : null,
1058
+ body: list.slice(body + 1, end),
1059
+ params: [],
1060
+ packageName: void 0
1061
+ });
1062
+ } else {
1063
+ enums.push(language === "swift" ? collectSwiftEnum(file, list.slice(body + 1, end), name, token, generic, header) : collectKotlinEnum(file, list.slice(body + 1, end), name, token));
1064
+ }
1065
+ i = end + 1;
1066
+ }
1067
+ return {
1068
+ structs,
1069
+ enums,
1070
+ names: {
1071
+ structs: new Map(structs.map((entry) => [entry.name, {
1072
+ codable: entry.codable,
1073
+ generic: entry.generic,
1074
+ problem: entry.problem
1075
+ }])),
1076
+ enums: new Map(enums.map((entry) => [entry.name, {
1077
+ usable: entry.usable,
1078
+ problem: entry.problem
1079
+ }]))
1080
+ }
1081
+ };
1082
+ }
1083
+ function composableView(file, list, keyword, floor, named) {
1084
+ const modifiers = list.slice(declarationStart(list, floor, keyword), keyword).map((token) => token.text);
1085
+ if (!modifiers.some((value, index) => value === "@" && modifiers[index + 1] === "Composable")) return null;
1086
+ if (modifiers.includes("private") || modifiers.includes("internal")) return null;
1087
+ const name = list[keyword + 1]?.text;
1088
+ if (!name || !/^[A-Z][A-Za-z0-9_]*$/.test(name)) fail(file, list[keyword], "an imported composable needs a capitalized name");
1089
+ if (list[keyword + 2]?.text !== "(") fail(file, list[keyword], "generic or extension composables are unsupported");
1090
+ const closing = close(file, list, keyword + 2, "(", ")");
1091
+ if (list[closing + 1]?.text === ":") fail(file, list[closing + 1], `composable ${name} must return Unit`);
1092
+ const inner = list.slice(keyword + 3, closing);
1093
+ const props = inner.length === 0 ? [] : split(inner, ",").flatMap((part) => {
1094
+ if (part.length === 0) return [];
1095
+ const prop = viewProp(file, part, named);
1096
+ return prop ? [prop] : [];
1097
+ });
1098
+ return {
1099
+ name,
1100
+ props
1101
+ };
1102
+ }
1103
+ function nativeSourceContract(file, source) {
1104
+ const language = file.endsWith(".swift") ? "swift" : file.endsWith(".kt") ? "kotlin" : void 0;
1105
+ if (!language) throw new Error(`${file}: expected a .swift or .kt source file`);
1106
+ const list = tokens(file, source);
1107
+ const packageToken = language === "kotlin" ? list.findIndex((token) => token.text === "package") : -1;
1108
+ const packageName = packageToken < 0 ? void 0 : list.slice(packageToken + 1).filter((token) => token.line === list[packageToken].line).map((token) => token.text).join("");
1109
+ if (packageName && !/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(packageName)) {
1110
+ fail(file, list[packageToken], `unsupported kotlin package ${packageName}`);
1111
+ }
1112
+ const collected = collectNamedTypes(file, list, language, packageName);
1113
+ const named = collected.names;
1114
+ const modules = [];
1115
+ const views = [];
1116
+ let defaultView = false;
1117
+ let i = 0;
1118
+ let previous = 0;
1119
+ while (i < list.length) {
1120
+ const kind = list[i].text;
1121
+ const declaration2 = language === "swift" ? kind === "class" || kind === "struct" : kind === "object";
1122
+ if (language === "kotlin" && kind === "fun") {
1123
+ const view2 = composableView(file, list, i, previous, named);
1124
+ if (view2) {
1125
+ if (views.some((other) => other.name === view2.name)) fail(file, list[i], `overloaded composable ${view2.name} is unsupported`);
1126
+ views.push(view2);
1127
+ }
1128
+ i++;
1129
+ continue;
1130
+ }
1131
+ if (!declaration2) {
1132
+ if (kind === "{") {
1133
+ i = close(file, list, i, "{", "}") + 1;
1134
+ previous = i;
1135
+ } else i++;
1136
+ continue;
1137
+ }
1138
+ const name = list[i + 1]?.text;
1139
+ if (!name) fail(file, list[i], "native type has no name");
1140
+ let body = i + 2;
1141
+ while (body < list.length && list[body].text !== "{") body++;
1142
+ if (body === list.length) fail(file, list[i], "native type has no body");
1143
+ const end = close(file, list, body, "{", "}");
1144
+ const prefix = list.slice(previous, i).map((token) => token.text);
1145
+ if (language === "swift" && prefix.some((value, index) => value === "@" && prefix[index + 1] === "main")) {
1146
+ defaultView = true;
1147
+ }
1148
+ const inherits = list.slice(i + 2, body).map((token) => token.text);
1149
+ if (inherits.includes(language === "swift" ? "PeachModule" : "OneModule")) {
1150
+ modules.push({
1151
+ name,
1152
+ methods: methods(file, list, body, end, language, named)
1153
+ });
1154
+ }
1155
+ const view = language === "swift" ? swiftView(file, list, i, previous, body, end, named) : null;
1156
+ if (view) views.push(view);
1157
+ i = end + 1;
1158
+ previous = i;
1159
+ }
1160
+ const finalized = finalizeNamedTypes(file, language, named, collected.structs, collected.enums, modules, views);
1161
+ const structs = finalized.structs;
1162
+ const enums = finalized.enums;
1163
+ const canonical = JSON.stringify({
1164
+ language,
1165
+ packageName,
1166
+ modules,
1167
+ views,
1168
+ structs,
1169
+ enums,
1170
+ defaultView
1171
+ });
1172
+ const hash = createHash("sha256").update(canonical).digest("hex");
1173
+ const declarations = structs.map((struct) => `export interface ${struct.name} {${struct.fields.map((field) => ` ${field.name}${field.optional ? "?" : ""}: ${field.type};`).join("")} }`);
1174
+ declarations.push(...enums.map((type) => `export type ${type.name} = ${type.cases.map((entry) => typeof entry.value === "string" ? JSON.stringify(entry.value) : String(entry.value)).join(" | ")}`));
1175
+ declarations.push(...modules.map((module) => [
1176
+ `export declare const ${module.name}: {`,
1177
+ ...module.methods.map((method) => method.subscription ? ` ${method.name}(listener: (${method.subscription.payload.map((arg, index) => `value${index}: ${arg.type}`).join(", ")}) => void): () => void` : ` ${method.name}(${method.parameters.map((param) => `${param.name}: ${param.type}`).join(", ")}): Promise<${method.result}>`),
1178
+ "}"
1179
+ ].join("\n")));
1180
+ declarations.push(...views.map((view) => `export declare function ${view.name}(props: {${view.props.map((prop) => ` ${prop.name}${prop.optional ? "?" : ""}: ${prop.type}`).join(";")} }): ReactElement`));
1181
+ if (defaultView) {
1182
+ declarations.unshift("export default function SwiftPackage(props: Record<string, unknown>): ReactElement");
1183
+ }
1184
+ if (defaultView || views.length > 0) declarations.unshift("import type { ReactElement } from 'react'");
1185
+ const declaration = `${GENERATED_HEADER}${declarations.join("\n\n")}
1186
+ `;
1187
+ return {
1188
+ language,
1189
+ packageName,
1190
+ modules,
1191
+ views,
1192
+ structs,
1193
+ enums,
1194
+ defaultView,
1195
+ hash,
1196
+ declaration
1197
+ };
1198
+ }
1199
+ function kotlinSourceId(root, file) {
1200
+ const path = relative(root, file).replaceAll("\\", "/");
1201
+ if (path.startsWith("../") || !path.endsWith(".kt")) {
1202
+ throw new Error(`${file} is not a kotlin source under ${root}`);
1203
+ }
1204
+ return `K_${createHash("sha256").update(path).digest("hex").slice(0, 16)}`;
1205
+ }
1206
+ function swiftPodManifest(file, source) {
1207
+ const list = tokens(file, source);
1208
+ const modes = /* @__PURE__ */ new Set();
1209
+ let mainActorIsolation = false;
1210
+ for (let i = 0; i < list.length; i++) {
1211
+ if (list[i].text === "." && list[i + 1]?.text === "package" && list[i + 2]?.text === "(") {
1212
+ fail(file, list[i], "SwiftPM package dependencies are unsupported by One prebuild");
1213
+ }
1214
+ if (list[i].text === "." && list[i + 1]?.text === "swiftLanguageMode" && list[i + 2]?.text === "(") {
1215
+ const mode = /^v(\d+)$/.exec(list[i + 4]?.text ?? "");
1216
+ if (list[i + 3]?.text !== "." || !mode) fail(file, list[i], "unsupported swift language mode");
1217
+ modes.add(Number(mode[1]));
1218
+ }
1219
+ if (list[i].text === "swiftLanguageModes" && list[i + 1]?.text === ":") {
1220
+ const opening = i + 2;
1221
+ if (list[opening]?.text !== "[") fail(file, list[i], "unsupported swift language modes");
1222
+ const ending = close(file, list, opening, "[", "]");
1223
+ for (let j = opening; j < ending; j++) {
1224
+ if (list[j].text === "." && /^v\d+$/.test(list[j + 1]?.text ?? "")) {
1225
+ modes.add(Number(list[j + 1].text.slice(1)));
1226
+ }
1227
+ }
1228
+ }
1229
+ if (list[i].text === "." && list[i + 1]?.text === "defaultIsolation" && list[i + 2]?.text === "(") {
1230
+ if (list[i + 3]?.text !== "MainActor") fail(file, list[i], "unsupported swift default isolation");
1231
+ mainActorIsolation = true;
1232
+ }
1233
+ }
1234
+ if (modes.size > 1) throw new Error(`${file}: One pod needs one swift language mode; found ${[...modes].join(", ")}`);
1235
+ const languageMode = modes.values().next().value ?? 5;
1236
+ if (languageMode !== 5 && languageMode !== 6) {
1237
+ throw new Error(`${file}: unsupported swift language mode v${languageMode}`);
1238
+ }
1239
+ return {
1240
+ languageMode,
1241
+ mainActorIsolation
1242
+ };
1243
+ }
1244
+ function writeNativeSourceDeclaration(file) {
1245
+ const contract = nativeSourceContract(file, readFileSync(file, "utf8"));
1246
+ const extension = contract.language === "swift" ? ".swift" : ".kt";
1247
+ const declaration = join(dirname(file), `${basename(file, extension)}.d${extension}.ts`);
1248
+ if (contract.modules.length === 0 && contract.views.length === 0 && !contract.defaultView) {
1249
+ if (existsSync(declaration) && readFileSync(declaration, "utf8").startsWith(GENERATED_HEADER)) {
1250
+ rmSync(declaration, { force: true });
1251
+ }
1252
+ return contract;
1253
+ }
1254
+ writeGeneratedFile(declaration, contract.declaration);
1255
+ return contract;
1256
+ }
1257
+ function writeNativeSourceDeclarations(root) {
1258
+ const contracts = [];
1259
+ const visit = (dir) => {
1260
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1261
+ if (entry.name.startsWith(".") || SKIP_SOURCE_DIRS.has(entry.name)) continue;
1262
+ const file = join(dir, entry.name);
1263
+ if (entry.isDirectory()) visit(file);
1264
+ else if (entry.isFile() && /\.(swift|kt)$/.test(entry.name) && entry.name !== "Package.swift") {
1265
+ contracts.push(writeNativeSourceDeclaration(file));
1266
+ }
1267
+ }
1268
+ };
1269
+ visit(root);
1270
+ for (const packageDir of swiftPackageDirectories(root).values()) {
1271
+ writeSwiftPackageArtifacts(packageDir);
1272
+ }
1273
+ return contracts;
1274
+ }
1275
+ function writeSwiftPackageArtifacts(packageDir) {
1276
+ const contracts = [];
1277
+ const files = {};
1278
+ const modules = {};
1279
+ const views = {};
1280
+ const defaultViewFiles = [];
1281
+ const visit = (dir) => {
1282
+ const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1283
+ for (const entry of entries) {
1284
+ if (entry.name.startsWith(".") || SKIP_SOURCE_DIRS.has(entry.name)) continue;
1285
+ const file = join(dir, entry.name);
1286
+ if (entry.isDirectory()) visit(file);
1287
+ else if (entry.isFile() && entry.name.endsWith(".swift") && entry.name !== "Package.swift") {
1288
+ const contract = writeNativeSourceDeclaration(file);
1289
+ contracts.push(contract);
1290
+ const name = relative(packageDir, file).replaceAll("\\", "/");
1291
+ files[name] = [...contract.modules, ...contract.views].map((entry2) => entry2.name);
1292
+ for (const module of contract.modules) modules[module.name] = module.methods.map((method) => method.name);
1293
+ for (const view of contract.views) views[view.name] = view.props.map((prop) => prop.name);
1294
+ if (contract.defaultView) defaultViewFiles.push(name);
1295
+ }
1296
+ }
1297
+ };
1298
+ visit(packageDir);
1299
+ const packageId = swiftPackageId(packageDir);
1300
+ const rendered = renderSwiftSourceGlue(packageId, contracts);
1301
+ const descriptor = join(packageDir, ".one-native-source.json");
1302
+ const glue = join(packageDir, ".one-native-source.swift.txt");
1303
+ const exported = contracts.some((contract) => contract.modules.length > 0 || contract.views.length > 0);
1304
+ if (exported) {
1305
+ const json = `${JSON.stringify({
1306
+ generatedBy: "one typegen",
1307
+ packageId,
1308
+ hash: rendered.hash,
1309
+ files,
1310
+ modules,
1311
+ views,
1312
+ defaultViewFiles
1313
+ }, null, 2)}
1314
+ `;
1315
+ writeGeneratedFile(descriptor, json);
1316
+ writeGeneratedFile(glue, rendered.source);
1317
+ } else if (existsSync(descriptor) && readFileSync(descriptor, "utf8").includes("\"generatedBy\": \"one typegen\"")) {
1318
+ rmSync(descriptor, { force: true });
1319
+ rmSync(glue, { force: true });
1320
+ }
1321
+ return {
1322
+ packageId,
1323
+ hash: rendered.hash,
1324
+ files,
1325
+ modules,
1326
+ views,
1327
+ defaultViewFiles,
1328
+ contracts,
1329
+ glue: exported ? rendered.source : null
1330
+ };
1331
+ }
1332
+ function renderSwiftSourceGlue(packageId, contracts) {
1333
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(packageId)) {
1334
+ throw new Error(`invalid swift package id ${packageId}`);
1335
+ }
1336
+ for (const contract of contracts) {
1337
+ if (contract.language !== "swift") throw new Error("swift glue received a kotlin contract");
1338
+ }
1339
+ const modules = contracts.flatMap((contract) => contract.modules);
1340
+ const views = contracts.flatMap((contract) => contract.views);
1341
+ const names = /* @__PURE__ */ new Set();
1342
+ for (const { name } of [...modules, ...views]) {
1343
+ if (names.has(name)) throw new Error(`swift package ${packageId} declares ${name} twice`);
1344
+ names.add(name);
1345
+ }
1346
+ const hash = createHash("sha256").update(JSON.stringify({
1347
+ packageId,
1348
+ modules,
1349
+ views
1350
+ })).digest("hex");
1351
+ const hasMain = contracts.some((contract) => contract.defaultView);
1352
+ const bodyName = `OneNativeSourceBody_${packageId}`;
1353
+ const className = `OneNativeSource_${packageId}`;
1354
+ const viewsName = `OneNativeSourceViews_${packageId}`;
1355
+ const renderCase = (method, module) => {
1356
+ const subscription = method.subscription;
1357
+ if (subscription) {
1358
+ const channel = `OneNativeSource.${packageId}.${module.name}.${method.name}`;
1359
+ const closureArgs = subscription.payload.map((arg, index) => `a${index}: ${arg.nativeType}`).join(", ");
1360
+ const emitArgs = subscription.payload.map((_, index) => `a${index}`).join(", ");
1361
+ const prefix2 = `${method.throws ? "try " : ""}${method.async ? "await " : ""}`;
1362
+ return [
1363
+ ` case ${JSON.stringify(method.name)}:`,
1364
+ ` guard values.isEmpty else { throw NSError(domain: "OneNativeSource", code: 2, userInfo: [NSLocalizedDescriptionKey: "${packageId}.${module.name}.${method.name} subscribes; it takes no arguments"]) }`,
1365
+ ` let channel = ${JSON.stringify(channel)}`,
1366
+ ` ${prefix2}${module.name}Instance.${method.name}({ ${closureArgs ? `(${closureArgs}) in ` : ""}postEvent(channel, args([${emitArgs}])) })`,
1367
+ " return \"null\""
1368
+ ];
1369
+ }
1370
+ const lines = [` case ${JSON.stringify(method.name)}:`, ` guard values.count == ${method.parameters.length} else { throw NSError(domain: "OneNativeSource", code: 2, userInfo: [NSLocalizedDescriptionKey: "${packageId}.${module.name}.${method.name} expects ${method.parameters.length} arguments"]) }`];
1371
+ method.parameters.forEach((parameter, index) => {
1372
+ lines.push(` let arg${index} = try decode(values[${index}], as: ${parameter.nativeType}.self)`);
1373
+ });
1374
+ const argumentsText = method.parameters.map((parameter, index) => `${parameter.label === "_" ? "" : `${parameter.label}: `}arg${index}`).join(", ");
1375
+ const prefix = `${method.throws ? "try " : ""}${method.async ? "await " : ""}`;
1376
+ const call = `${module.name}Instance.${method.name}(${argumentsText})`;
1377
+ if (method.result === "void") {
1378
+ lines.push(` ${prefix}${call}`, " return \"null\"");
1379
+ } else {
1380
+ lines.push(` let result = ${prefix}${call}`);
1381
+ if (method.nativeResult === "Int") {
1382
+ lines.push(" guard abs(Double(result)) <= 9_007_199_254_740_991 else { throw NSError(domain: \"OneNativeSource\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"result exceeds the JavaScript safe integer range\"]) }");
1383
+ }
1384
+ lines.push(" return try encode(result)");
1385
+ }
1386
+ return lines;
1387
+ };
1388
+ const notLinked = " throw NSError(domain: \"OneNativeSource\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"native module \\(module) is not linked; rebuild the app\"])";
1389
+ const renderCall = () => modules.length === 0 ? [
1390
+ " static func call(_ module: String, _ method: String, _ argsJson: String) async throws -> String {",
1391
+ notLinked,
1392
+ " }"
1393
+ ] : [
1394
+ " static func call(_ module: String, _ method: String, _ argsJson: String) async throws -> String {",
1395
+ " guard let values = try JSONSerialization.jsonObject(with: Data(argsJson.utf8)) as? [Any] else {",
1396
+ " throw NSError(domain: \"OneNativeSource\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"arguments must be a JSON array\"])",
1397
+ " }",
1398
+ " switch module {",
1399
+ ...modules.flatMap((module) => [
1400
+ ` case ${JSON.stringify(`${packageId}.${module.name}`)}:`,
1401
+ " switch method {",
1402
+ ...module.methods.flatMap((method) => renderCase(method, module)),
1403
+ " default: throw NSError(domain: \"OneNativeSource\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"native method \\(module).\\(method) is not linked; rebuild the app\"])",
1404
+ " }"
1405
+ ]),
1406
+ " default:",
1407
+ ` ${notLinked}`,
1408
+ " }",
1409
+ " }"
1410
+ ];
1411
+ const renderViews = () => [
1412
+ " private static func missing(_ path: String) throws -> Any {",
1413
+ " throw NSError(domain: \"OneNativeSource\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"\\(path): required\"])",
1414
+ " }",
1415
+ " static func view(_ name: String, _ propsJson: String, _ emit: @escaping (String, String) -> Void) throws -> AnyView {",
1416
+ " guard let props = try JSONSerialization.jsonObject(with: Data(propsJson.utf8)) as? [String: Any] else {",
1417
+ " throw NSError(domain: \"OneNativeSource\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"props must be a JSON object\"])",
1418
+ " }",
1419
+ " switch name {",
1420
+ ...views.flatMap((view) => [
1421
+ ` case ${JSON.stringify(view.name)}:`,
1422
+ ` return AnyView(${view.name}(`,
1423
+ ...view.props.map((prop, index) => {
1424
+ const comma = index === view.props.length - 1 ? "" : ",";
1425
+ const key = JSON.stringify(prop.name);
1426
+ if (prop.callback) {
1427
+ const params = prop.callback.map((arg, n) => `a${n}: ${arg.nativeType}`).join(", ");
1428
+ const lambda = `{ (${params}) -> Void in emit(${key}, args([${prop.callback.map((_, n) => `a${n}`).join(", ")}])) }`;
1429
+ return ` ${prop.name}: ${prop.optional ? `(props[${key}] as? Bool) == true ? ${lambda} : nil` : lambda}${comma}`;
1430
+ }
1431
+ const input = prop.optional ? `props[${key}] ?? NSNull()` : `props[${key}] ?? missing(${JSON.stringify(`props.${prop.name}`)})`;
1432
+ return ` ${prop.name}: try decode(${input}, as: ${prop.nativeType}.self)${comma}`;
1433
+ }),
1434
+ " ))"
1435
+ ]),
1436
+ " default: throw NSError(domain: \"OneNativeSource\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"swift view \\(name) is not linked; rebuild the app\"])",
1437
+ " }",
1438
+ " }"
1439
+ ];
1440
+ const source = [
1441
+ "import Foundation",
1442
+ "import SwiftUI",
1443
+ "",
1444
+ `@MainActor public enum ${bodyName} {`,
1445
+ ` public static let hash = ${JSON.stringify(hash)}`,
1446
+ "#if os(WASI)",
1447
+ " private struct Request: Decodable { let module: String; let method: String; let argsJson: String; let contractHash: String }",
1448
+ " private struct Reply: Encodable { let ok: Bool; let value: String?; let error: String?; let pending: Int32? }",
1449
+ " private static var output: [UInt8] = []",
1450
+ " private static var finished: [Int32: Reply] = [:]",
1451
+ " private static var nextCall: Int32 = 0",
1452
+ " // peach runs tasks inline, so a call finishes before its task launch returns",
1453
+ " // unless it waits on the clock; then it answers pending and the host polls",
1454
+ " // it after running the timers.",
1455
+ " static func callWasm(_ payload: UnsafePointer<UInt8>?, _ length: Int32) -> UnsafeMutablePointer<UInt8>? {",
1456
+ " let id = nextCall",
1457
+ " nextCall &+= 1",
1458
+ " do {",
1459
+ " guard let payload, length >= 0 else { throw NSError(domain: \"OneNativeSource\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"missing call payload\"]) }",
1460
+ " let request = try JSONDecoder().decode(Request.self, from: Data(bytes: payload, count: Int(length)))",
1461
+ " guard request.contractHash == hash else { throw NSError(domain: \"OneNativeSource\", code: 4, userInfo: [NSLocalizedDescriptionKey: \"native module \\(request.module) changed; rebuild the app\"]) }",
1462
+ " Task {",
1463
+ " do {",
1464
+ " finished[id] = Reply(ok: true, value: try await call(request.module, request.method, request.argsJson), error: nil, pending: nil)",
1465
+ " } catch {",
1466
+ " // the native hosts name the method on everything a call throws",
1467
+ " finished[id] = Reply(ok: false, value: nil, error: \"\\(request.module).\\(request.method): \\(error.localizedDescription)\", pending: nil)",
1468
+ " }",
1469
+ " }",
1470
+ " } catch {",
1471
+ " finished[id] = Reply(ok: false, value: nil, error: error.localizedDescription, pending: nil)",
1472
+ " }",
1473
+ " return pollWasm(id)",
1474
+ " }",
1475
+ " static func pollWasm(_ id: Int32) -> UnsafeMutablePointer<UInt8>? {",
1476
+ " let reply = finished.removeValue(forKey: id) ?? Reply(ok: true, value: nil, error: nil, pending: id)",
1477
+ " let bytes = (try? JSONEncoder().encode(reply)) ?? Data(\"{\\\"ok\\\":false,\\\"error\\\":\\\"encoding failed\\\"}\".utf8)",
1478
+ " let count = UInt32(bytes.count)",
1479
+ " output = [UInt8(count & 0xff), UInt8((count >> 8) & 0xff), UInt8((count >> 16) & 0xff), UInt8(count >> 24)] + Array(bytes)",
1480
+ " return output.withUnsafeMutableBufferPointer { $0.baseAddress }",
1481
+ " }",
1482
+ " private struct Event: Encodable { let channel: String; let args: String }",
1483
+ " private static var pendingEvents: [Event] = []",
1484
+ " // under wasi there is no javascript runtime, so posted events queue",
1485
+ " // here and the peach host drains them with peach_poll_events, using",
1486
+ " // the same length-prefixed framing as pollWasm.",
1487
+ " static func pollEvents() -> UnsafeMutablePointer<UInt8>? {",
1488
+ " let events = pendingEvents",
1489
+ " pendingEvents = []",
1490
+ " let bytes = (try? JSONEncoder().encode(events)) ?? Data(\"[]\".utf8)",
1491
+ " let count = UInt32(bytes.count)",
1492
+ " output = [UInt8(count & 0xff), UInt8((count >> 8) & 0xff), UInt8((count >> 16) & 0xff), UInt8(count >> 24)] + Array(bytes)",
1493
+ " return output.withUnsafeMutableBufferPointer { $0.baseAddress }",
1494
+ " }",
1495
+ "#endif",
1496
+ ...modules.map((module) => ` private static let ${module.name}Instance = ${module.name}()`),
1497
+ " private nonisolated static let isoDate = Date.ISO8601FormatStyle()",
1498
+ " private nonisolated static let isoDateFractional = Date.ISO8601FormatStyle(includingFractionalSeconds: true)",
1499
+ " private nonisolated static func decodeDate(_ decoder: Decoder) throws -> Date {",
1500
+ " let container = try decoder.singleValueContainer()",
1501
+ " let text = try container.decode(String.self)",
1502
+ " if let date = (try? isoDateFractional.parse(text)) ?? (try? isoDate.parse(text)) { return date }",
1503
+ " throw DecodingError.dataCorruptedError(in: container, debugDescription: \"expected ISO date\")",
1504
+ " }",
1505
+ " private static func decode<T: Decodable>(_ value: Any, as type: T.Type) throws -> T {",
1506
+ " let data = try JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed])",
1507
+ " let decoder = JSONDecoder()",
1508
+ " decoder.dateDecodingStrategy = .custom { try decodeDate($0) }",
1509
+ " decoder.dataDecodingStrategy = .base64",
1510
+ " return try decoder.decode(T.self, from: data)",
1511
+ " }",
1512
+ " private static func encode(_ value: any Encodable) throws -> String {",
1513
+ " let encoder = JSONEncoder()",
1514
+ " encoder.dateEncodingStrategy = .iso8601",
1515
+ " encoder.dataEncodingStrategy = .base64",
1516
+ " return String(decoding: try encoder.encode(value), as: UTF8.self)",
1517
+ " }",
1518
+ " private static func encodeAny(_ value: any Encodable) -> String {",
1519
+ " (try? encode(value)) ?? \"null\"",
1520
+ " }",
1521
+ " // subscribe cases and view callbacks both encode callback arguments",
1522
+ " // as a json array, so this helper stays outside the view-only glue.",
1523
+ " private static func args(_ values: [any Encodable]) -> String {",
1524
+ " \"[\" + values.map { encodeAny($0) }.joined(separator: \",\") + \"]\"",
1525
+ " }",
1526
+ " // native events post over the one event bridge on device; under wasi",
1527
+ " // they queue for the peach host, which drains them with peach_poll_events.",
1528
+ " private static func postEvent(_ channel: String, _ args: String) {",
1529
+ " #if os(WASI)",
1530
+ " pendingEvents.append(Event(channel: channel, args: args))",
1531
+ " #else",
1532
+ " OneNativeSourceEmitter.send(channel, args)",
1533
+ " #endif",
1534
+ " }",
1535
+ ...renderCall(),
1536
+ ...views.length > 0 ? renderViews() : [],
1537
+ "}",
1538
+ "",
1539
+ "#if os(WASI)",
1540
+ "@_expose(wasm, \"peach_call\")",
1541
+ "@_cdecl(\"peach_call\")",
1542
+ `@MainActor public func peach_call(_ payload: UnsafePointer<UInt8>?, _ length: Int32) -> UnsafeMutablePointer<UInt8>? { ${bodyName}.callWasm(payload, length) }`,
1543
+ "@_expose(wasm, \"peach_call_poll\")",
1544
+ "@_cdecl(\"peach_call_poll\")",
1545
+ `@MainActor public func peach_call_poll(_ id: Int32) -> UnsafeMutablePointer<UInt8>? { ${bodyName}.pollWasm(id) }`,
1546
+ " // the host drains queued native events with this export, polling it",
1547
+ " // after running timers like it polls pending calls.",
1548
+ "@_expose(wasm, \"peach_poll_events\")",
1549
+ "@_cdecl(\"peach_poll_events\")",
1550
+ `@MainActor public func peach_poll_events() -> UnsafeMutablePointer<UInt8>? { ${bodyName}.pollEvents() }`,
1551
+ ...views.length > 0 ? [
1552
+ "@_expose(wasm, \"peach_register_views\")",
1553
+ "@_cdecl(\"peach_register_views\")",
1554
+ "@MainActor public func peach_register_views() {",
1555
+ " PeachTypedViews.register { name, contractHash, propsJson, emit in",
1556
+ ` guard contractHash == ${bodyName}.hash else { return AnyView(Text("swift view ${packageId}.\\(name) changed; rebuild the app").foregroundStyle(.red)) }`,
1557
+ ` do { return try ${bodyName}.view(name, propsJson, emit) } catch { return AnyView(Text("\\(name): \\(error.localizedDescription)").foregroundStyle(.red)) }`,
1558
+ " }",
1559
+ "}"
1560
+ ] : [],
1561
+ ...!hasMain ? [
1562
+ `@main struct OneNativeSourceMain_${packageId}: App {`,
1563
+ " var body: some Scene { WindowGroup { EmptyView() } }",
1564
+ "}"
1565
+ ] : [],
1566
+ "#endif",
1567
+ "",
1568
+ "#if canImport(ObjectiveC) && !os(WASI)",
1569
+ `@objc(${className}) @MainActor public final class ${className}: NSObject, OneNativeSourceDispatch {`,
1570
+ " public required override init() {}",
1571
+ ` public var contractHash: String { ${bodyName}.hash }`,
1572
+ ` public func call(_ module: String, _ method: String, _ argsJson: String) async throws -> String { try await ${bodyName}.call(module, method, argsJson) }`,
1573
+ "}",
1574
+ ...views.length > 0 ? [
1575
+ `@objc(${viewsName}) @MainActor public final class ${viewsName}: NSObject, OneNativeSourceViewDispatch {`,
1576
+ " public required override init() {}",
1577
+ ` public var contractHash: String { ${bodyName}.hash }`,
1578
+ ` public func view(_ name: String, _ propsJson: String, _ emit: @escaping (String, String) -> Void) throws -> AnyView { try ${bodyName}.view(name, propsJson, emit) }`,
1579
+ "}"
1580
+ ] : [],
1581
+ "#endif",
1582
+ ""
1583
+ ].join("\n");
1584
+ return {
1585
+ hash,
1586
+ source
1587
+ };
1588
+ }
1589
+ function renderKotlinSourceGlue(sourceId, contract) {
1590
+ if (contract.language !== "kotlin") throw new Error("kotlin glue received a swift contract");
1591
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(sourceId)) throw new Error(`invalid kotlin source id ${sourceId}`);
1592
+ const hash = createHash("sha256").update(JSON.stringify({
1593
+ sourceId,
1594
+ contract: contract.hash
1595
+ })).digest("hex");
1596
+ const structsByName = new Map(contract.structs.map((entry) => [entry.name, entry]));
1597
+ const enumsByName = new Map(contract.enums.map((entry) => [entry.name, entry]));
1598
+ const qualified = (name) => contract.packageName ? `${contract.packageName}.${name}` : name;
1599
+ const isDateType = (type) => type === "Date" || type === "java.util.Date";
1600
+ const mentions = (type, match) => {
1601
+ let rest = type;
1602
+ while (rest.endsWith("?")) rest = rest.slice(0, -1);
1603
+ if (rest.startsWith("List<") && rest.endsWith(">")) return mentions(rest.slice(5, -1), match);
1604
+ if (rest.startsWith("Map<String,") && rest.endsWith(">")) return mentions(rest.slice(11, -1), match);
1605
+ return match(rest);
1606
+ };
1607
+ const nativeTypes = [
1608
+ ...contract.modules.flatMap((module) => module.methods.flatMap((method) => [
1609
+ ...method.parameters.map((parameter) => parameter.nativeType),
1610
+ method.nativeResult,
1611
+ ...method.subscription?.payload.map((arg) => arg.nativeType) ?? []
1612
+ ])),
1613
+ ...contract.structs.flatMap((struct) => struct.fields.map((field) => field.nativeType)),
1614
+ ...contract.views.flatMap((view) => view.props.flatMap((prop) => [prop.nativeType, ...prop.callback?.map((arg) => arg.nativeType) ?? []]))
1615
+ ];
1616
+ const needsEvents = contract.modules.some((module) => module.methods.some((method) => method.subscription));
1617
+ const needsDate = nativeTypes.some((type) => mentions(type, isDateType));
1618
+ const needsData = nativeTypes.some((type) => mentions(type, (leaf) => leaf === "ByteArray"));
1619
+ const value = (type, input, path) => {
1620
+ if (type.endsWith("?")) {
1621
+ return `(${input}).let { raw -> if (raw == null || raw == JSONObject.NULL) null else ${value(type.slice(0, -1), "raw", path)} }`;
1622
+ }
1623
+ if (type === "String") return `readString(${input}, ${path})`;
1624
+ if (type === "Boolean") return `readBoolean(${input}, ${path})`;
1625
+ if (type === "Double") return `readDouble(${input}, ${path})`;
1626
+ if (type === "Float") return `readDouble(${input}, ${path}).toFloat()`;
1627
+ if (type === "Int") return `readInt(${input}, ${path})`;
1628
+ if (type === "Long") return `readLong(${input}, ${path})`;
1629
+ if (isDateType(type)) return `readDate(${input}, ${path})`;
1630
+ if (type === "ByteArray") return `readData(${input}, ${path})`;
1631
+ if (structsByName.has(type)) return `read${type}(${input}, ${path})`;
1632
+ if (enumsByName.has(type)) return `read${type}(${input}, ${path})`;
1633
+ if (type.startsWith("List<") && type.endsWith(">")) {
1634
+ return `readList(${input}, ${path}) { item, itemPath -> ${value(type.slice(5, -1), "item", "itemPath")} }`;
1635
+ }
1636
+ if (type.startsWith("Map<String,") && type.endsWith(">")) {
1637
+ return `readMap(${input}, ${path}) { item, itemPath -> ${value(type.slice(11, -1), "item", "itemPath")} }`;
1638
+ }
1639
+ throw new Error(`unsupported kotlin glue type ${type}`);
1640
+ };
1641
+ const encode = (type, accessor) => {
1642
+ if (type.endsWith("?")) {
1643
+ return `(${accessor}?.let { ${encode(type.slice(0, -1), "it")} } ?: JSONObject.NULL)`;
1644
+ }
1645
+ if (isDateType(type)) return `dateToString(${accessor})`;
1646
+ if (type === "ByteArray") return `android.util.Base64.encodeToString(${accessor}, android.util.Base64.NO_WRAP)`;
1647
+ if (structsByName.has(type)) return `encode${type}(${accessor})`;
1648
+ if (enumsByName.has(type)) return `${accessor}.name`;
1649
+ if (type.startsWith("List<") && type.endsWith(">")) {
1650
+ return `JSONArray().apply { for (item in ${accessor}) put(${encode(type.slice(5, -1), "item")}) }`;
1651
+ }
1652
+ if (type.startsWith("Map<String,") && type.endsWith(">")) {
1653
+ return `JSONObject().apply { for ((key, entry) in ${accessor}) put(key, ${encode(type.slice(11, -1), "entry")}) }`;
1654
+ }
1655
+ return `JSONObject.wrap(${accessor})`;
1656
+ };
1657
+ const structHelpers = contract.structs.flatMap((struct) => [
1658
+ `private fun read${struct.name}(value: Any, path: String): ${qualified(struct.name)} {`,
1659
+ " val obj = value as? JSONObject ?: error(\"$path: expected object\")",
1660
+ ` return ${qualified(struct.name)}(`,
1661
+ ...struct.fields.map((field) => {
1662
+ const fieldPath = `"$path.${field.name}"`;
1663
+ const required = `error("$path.${field.name}: required")`;
1664
+ const input = field.optional ? `(if (obj.has(${JSON.stringify(field.name)})) obj.get(${JSON.stringify(field.name)}) else ${field.fallback ?? required})` : `(obj.opt(${JSON.stringify(field.name)}) ?: ${required})`;
1665
+ return ` ${field.name} = ${value(field.nativeType, input, fieldPath)},`;
1666
+ }),
1667
+ " )",
1668
+ "}",
1669
+ `private fun encode${struct.name}(value: ${qualified(struct.name)}): JSONObject {`,
1670
+ " return JSONObject()",
1671
+ ...struct.fields.map((field) => ` .put(${JSON.stringify(field.name)}, ${encode(field.nativeType, `value.${field.name}`)})`),
1672
+ "}"
1673
+ ]);
1674
+ const enumHelpers = contract.enums.flatMap((entry) => [
1675
+ `private fun read${entry.name}(value: Any, path: String): ${qualified(entry.name)} {`,
1676
+ " val text = readString(value, path)",
1677
+ ` return try { ${qualified(entry.name)}.valueOf(text) } catch (e: IllegalArgumentException) { error("$path: expected one of ${entry.cases.map((item) => item.name).join(", ")}") }`,
1678
+ "}"
1679
+ ]);
1680
+ const source = [
1681
+ "import androidx.annotation.Keep",
1682
+ ...contract.views.length === 0 ? [] : ["import androidx.compose.runtime.Composable", "import dev.onejs.one.OneNativeSourceViewDispatch"],
1683
+ "import dev.onejs.one.OneNativeSourceDispatch",
1684
+ ...needsEvents ? ["import dev.onejs.one.source.OneNativeSourceEvents"] : [],
1685
+ "import org.json.JSONArray",
1686
+ "import org.json.JSONObject",
1687
+ "",
1688
+ "private fun readString(value: Any, path: String): String = value as? String ?: error(\"$path: expected string\")",
1689
+ "private fun readBoolean(value: Any, path: String): Boolean = value as? Boolean ?: error(\"$path: expected boolean\")",
1690
+ "private fun readDouble(value: Any, path: String): Double {",
1691
+ " val result = (value as? Number)?.toDouble() ?: error(\"$path: expected number\")",
1692
+ " if (!result.isFinite()) error(\"$path: expected finite number\")",
1693
+ " return result",
1694
+ "}",
1695
+ "private fun readInt(value: Any, path: String): Int {",
1696
+ " val result = readDouble(value, path)",
1697
+ " if (result % 1.0 != 0.0 || result < Int.MIN_VALUE || result > Int.MAX_VALUE) error(\"$path: expected Int\")",
1698
+ " return result.toInt()",
1699
+ "}",
1700
+ "private fun readLong(value: Any, path: String): Long {",
1701
+ " val result = readDouble(value, path)",
1702
+ " if (result % 1.0 != 0.0 || result < -9007199254740991.0 || result > 9007199254740991.0) error(\"$path: expected safe Long\")",
1703
+ " return result.toLong()",
1704
+ "}",
1705
+ "private fun <T> readList(value: Any, path: String, read: (Any, String) -> T): List<T> {",
1706
+ " val array = value as? JSONArray ?: error(\"$path: expected array\")",
1707
+ " return (0 until array.length()).map { index -> read(array.get(index), \"$path[$index]\") }",
1708
+ "}",
1709
+ "private fun <T> readMap(value: Any, path: String, read: (Any, String) -> T): Map<String, T> {",
1710
+ " val objectValue = value as? JSONObject ?: error(\"$path: expected object\")",
1711
+ " return objectValue.keys().asSequence().associateWith { key -> read(objectValue.get(key), \"$path.$key\") }",
1712
+ "}",
1713
+ ...needsDate ? [
1714
+ "private fun readDate(value: Any, path: String): java.util.Date {",
1715
+ " val text = readString(value, path)",
1716
+ ` for (pattern in arrayOf("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss'Z'")) {`,
1717
+ " try {",
1718
+ " return java.text.SimpleDateFormat(pattern, java.util.Locale.US).apply { timeZone = java.util.TimeZone.getTimeZone(\"UTC\"); isLenient = false }.parse(text) ?: error(\"$path: expected date\")",
1719
+ " } catch (parseError: java.text.ParseException) { }",
1720
+ " }",
1721
+ " error(\"$path: expected ISO date\")",
1722
+ "}",
1723
+ "private fun dateToString(value: java.util.Date): String =",
1724
+ ` java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.US).apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }.format(value)`
1725
+ ] : [],
1726
+ ...needsData ? [
1727
+ "private fun readData(value: Any, path: String): ByteArray {",
1728
+ " try {",
1729
+ " return android.util.Base64.decode(readString(value, path), android.util.Base64.NO_WRAP)",
1730
+ " } catch (decodeError: IllegalArgumentException) {",
1731
+ " error(\"$path: expected base64 data\")",
1732
+ " }",
1733
+ "}"
1734
+ ] : [],
1735
+ ...structHelpers,
1736
+ ...enumHelpers,
1737
+ "",
1738
+ `@Keep class OneNativeSource_${sourceId}: OneNativeSourceDispatch {`,
1739
+ ` override val contractHash = ${JSON.stringify(hash)}`,
1740
+ " override suspend fun call(module: String, method: String, argsJson: String): String {",
1741
+ " val args = JSONArray(argsJson)",
1742
+ " return when (module) {",
1743
+ ...contract.modules.flatMap((module) => [
1744
+ ` ${JSON.stringify(`${sourceId}.${module.name}`)} -> when (method) {`,
1745
+ ...module.methods.flatMap((method) => {
1746
+ const subscription = method.subscription;
1747
+ if (subscription) {
1748
+ const channel = `OneNativeSource.${sourceId}.${module.name}.${method.name}`;
1749
+ const closure = subscription.payload.length === 0 ? `{ OneNativeSourceEvents.send(${JSON.stringify(channel)}, JSONArray().toString()) }` : `{ ${subscription.payload.map((_, index) => `a${index}`).join(", ")} -> OneNativeSourceEvents.send(${JSON.stringify(channel)}, JSONArray()${subscription.payload.map((arg, index) => `.put(${encode(arg.nativeType, `a${index}`)})`).join("")}.toString()) }`;
1750
+ return [
1751
+ ` ${JSON.stringify(method.name)} -> {`,
1752
+ ` require(args.length() == 0) { "${sourceId}.${module.name}.${method.name} subscribes; it takes no arguments" }`,
1753
+ ` ${qualified(module.name)}.${method.name}(${closure})`,
1754
+ " \"null\"",
1755
+ " }"
1756
+ ];
1757
+ }
1758
+ const lines = [` ${JSON.stringify(method.name)} -> {`, ` require(args.length() == ${method.parameters.length}) { "${sourceId}.${module.name}.${method.name} expects ${method.parameters.length} arguments" }`];
1759
+ method.parameters.forEach((parameter, index) => {
1760
+ lines.push(` val arg${index} = ${value(parameter.nativeType, `args.get(${index})`, JSON.stringify(`args[${index}]`))}`);
1761
+ });
1762
+ const call = `${qualified(module.name)}.${method.name}(${method.parameters.map((_, index) => `arg${index}`).join(", ")})`;
1763
+ if (method.result === "void") {
1764
+ lines.push(` ${call}`, " \"null\"");
1765
+ } else {
1766
+ lines.push(` val result = ${call}`);
1767
+ if (method.nativeResult === "Long") {
1768
+ lines.push(" require(result >= -9007199254740991L && result <= 9007199254740991L) { \"result exceeds the JavaScript safe integer range\" }");
1769
+ }
1770
+ lines.push(` JSONArray().put(${encode(method.nativeResult, "result")}).toString().drop(1).dropLast(1)`);
1771
+ }
1772
+ return [...lines, " }"];
1773
+ }),
1774
+ " else -> error(\"native method $module.$method is not linked; rebuild the app\")",
1775
+ " }"
1776
+ ]),
1777
+ " else -> error(\"native module $module is not linked; rebuild the app\")",
1778
+ " }",
1779
+ " }",
1780
+ "}",
1781
+ "",
1782
+ ...contract.views.length === 0 ? [] : viewGlue(sourceId, contract, hash, value, encode)
1783
+ ].join("\n");
1784
+ return {
1785
+ hash,
1786
+ source
1787
+ };
1788
+ }
1789
+ function viewGlue(sourceId, contract, hash, value, encode) {
1790
+ const qualifier = contract.packageName ? `${contract.packageName}.` : "";
1791
+ return [
1792
+ `@Keep class OneNativeSourceViews_${sourceId}: OneNativeSourceViewDispatch {`,
1793
+ ` override val contractHash = ${JSON.stringify(hash)}`,
1794
+ " @Composable",
1795
+ " override fun Content(view: String, propsJson: String, emit: (String, String) -> Unit) {",
1796
+ " val props = JSONObject(propsJson)",
1797
+ " when (view) {",
1798
+ ...contract.views.flatMap((view) => [
1799
+ ` ${JSON.stringify(view.name)} -> ${qualifier}${view.name}(`,
1800
+ ...view.props.map((prop) => {
1801
+ const path = JSON.stringify(`props.${prop.name}`);
1802
+ if (prop.callback) {
1803
+ const args = prop.callback.map((_, index) => `a${index}`);
1804
+ const types = prop.callback.map((arg) => arg.nativeType);
1805
+ const body = `emit(${JSON.stringify(prop.name)}, JSONArray()${args.map((arg, index) => `.put(${encode(types[index], arg)})`).join("")}.toString())`;
1806
+ const lambda = `{ ${args.length > 0 ? `${args.join(", ")} -> ` : ""}${body} }`;
1807
+ return ` ${prop.name} = ${prop.nativeType.endsWith("?") ? `if (props.optBoolean(${JSON.stringify(prop.name)})) (${lambda}) else null` : lambda},`;
1808
+ }
1809
+ const input = prop.optional ? `(props.opt(${JSON.stringify(prop.name)}) ?: JSONObject.NULL)` : `(props.opt(${JSON.stringify(prop.name)}) ?: error(${JSON.stringify(`props.${prop.name}: required`)}))`;
1810
+ return ` ${prop.name} = ${value(prop.nativeType, input, path)},`;
1811
+ }),
1812
+ " )"
1813
+ ]),
1814
+ " else -> error(\"composable $view is not linked; rebuild the app\")",
1815
+ " }",
1816
+ " }",
1817
+ "}",
1818
+ ""
1819
+ ];
1820
+ }
1821
+
1822
+ export { kotlinSourceId, nativeSourceContract, renderKotlinSourceGlue, renderSwiftSourceGlue, swiftPodManifest, writeNativeSourceDeclaration, writeNativeSourceDeclarations, writeSwiftPackageArtifacts };
1823
+ //# sourceMappingURL=nativeSourceContract.mjs.map