nitrogen 0.2.24 → 0.29.5

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 (241) hide show
  1. package/README.md +18 -108
  2. package/lib/Logger.js +56 -0
  3. package/lib/autolinking/Autolinking.js +1 -0
  4. package/lib/autolinking/android/createCMakeExtension.js +109 -0
  5. package/lib/autolinking/android/createGradleExtension.js +36 -0
  6. package/lib/autolinking/android/createHybridObjectInitializer.js +159 -0
  7. package/lib/autolinking/createAndroidAutolinking.js +13 -0
  8. package/lib/autolinking/createIOSAutolinking.js +19 -0
  9. package/lib/autolinking/ios/createHybridObjectInitializer.js +97 -0
  10. package/lib/autolinking/ios/createPodspecRubyExtension.js +69 -0
  11. package/lib/autolinking/ios/createSwiftCxxBridge.js +117 -0
  12. package/lib/autolinking/ios/createSwiftUmbrellaHeader.js +74 -0
  13. package/lib/config/NitroConfig.js +112 -0
  14. package/lib/config/NitroUserConfig.js +88 -0
  15. package/lib/config/getConfig.js +84 -0
  16. package/lib/createGitAttributes.js +11 -0
  17. package/lib/createPlatformSpec.js +127 -0
  18. package/lib/getFiles.js +28 -0
  19. package/lib/getPlatformSpecs.js +153 -0
  20. package/lib/index.js +113 -10
  21. package/lib/init.js +123 -0
  22. package/lib/nitrogen.js +165 -0
  23. package/lib/prettifyDirectory.js +27 -0
  24. package/lib/syntax/BridgedType.js +1 -0
  25. package/lib/syntax/CodeNode.js +1 -0
  26. package/lib/syntax/HybridObjectSpec.js +1 -0
  27. package/lib/syntax/Method.js +108 -0
  28. package/lib/syntax/Parameter.js +65 -0
  29. package/lib/syntax/Property.js +147 -0
  30. package/lib/syntax/SourceFile.js +7 -0
  31. package/lib/syntax/c++/CppEnum.js +110 -0
  32. package/lib/syntax/c++/CppHybridObject.js +146 -0
  33. package/lib/syntax/c++/CppHybridObjectRegistration.js +18 -0
  34. package/lib/syntax/c++/CppStruct.js +108 -0
  35. package/lib/syntax/c++/CppUnion.js +88 -0
  36. package/lib/syntax/c++/getForwardDeclaration.js +14 -0
  37. package/lib/syntax/c++/includeNitroHeader.js +34 -0
  38. package/lib/syntax/createType.js +303 -0
  39. package/lib/syntax/getAllTypes.js +11 -0
  40. package/lib/syntax/getCustomTypeConfig.js +53 -0
  41. package/lib/syntax/getHybridObjectName.d.ts +36 -0
  42. package/lib/syntax/getHybridObjectName.js +10 -0
  43. package/lib/syntax/getInterfaceProperties.js +9 -0
  44. package/lib/syntax/getReferencedTypes.js +47 -0
  45. package/lib/syntax/helpers.js +53 -0
  46. package/lib/syntax/isCoreType.js +47 -0
  47. package/lib/syntax/kotlin/FbjniHybridObject.js +261 -0
  48. package/lib/syntax/kotlin/JNINativeRegistrations.js +7 -0
  49. package/lib/syntax/kotlin/KotlinBoxedPrimitive.js +17 -0
  50. package/lib/syntax/kotlin/KotlinCxxBridgedType.js +893 -0
  51. package/lib/syntax/kotlin/KotlinEnum.js +113 -0
  52. package/lib/syntax/kotlin/KotlinFunction.js +256 -0
  53. package/lib/syntax/kotlin/KotlinHybridObject.js +177 -0
  54. package/lib/syntax/kotlin/KotlinHybridObjectRegistration.js +26 -0
  55. package/lib/syntax/kotlin/KotlinStruct.js +172 -0
  56. package/lib/syntax/kotlin/KotlinVariant.js +191 -0
  57. package/lib/syntax/swift/SwiftCxxBridgedType.js +819 -0
  58. package/lib/syntax/swift/SwiftCxxTypeHelper.js +613 -0
  59. package/lib/syntax/swift/SwiftEnum.js +52 -0
  60. package/lib/syntax/swift/SwiftFunction.js +83 -0
  61. package/lib/syntax/swift/SwiftHybridObject.js +103 -0
  62. package/lib/syntax/swift/SwiftHybridObjectBridge.js +451 -0
  63. package/lib/syntax/swift/SwiftHybridObjectRegistration.js +42 -0
  64. package/lib/syntax/swift/SwiftStruct.js +75 -0
  65. package/lib/syntax/swift/SwiftVariant.js +58 -0
  66. package/lib/syntax/types/ArrayBufferType.js +37 -0
  67. package/lib/syntax/types/ArrayType.d.ts +12 -0
  68. package/lib/syntax/types/ArrayType.js +52 -0
  69. package/lib/syntax/types/BigIntType.js +27 -0
  70. package/lib/syntax/types/BooleanType.js +27 -0
  71. package/lib/syntax/types/CustomType.d.ts +14 -0
  72. package/lib/syntax/types/CustomType.js +36 -0
  73. package/lib/syntax/types/DateType.js +35 -0
  74. package/lib/syntax/types/EnumType.js +101 -0
  75. package/lib/syntax/types/ErrorType.js +37 -0
  76. package/lib/syntax/types/FunctionType.js +147 -0
  77. package/lib/syntax/types/HybridObjectBaseType.js +38 -0
  78. package/lib/syntax/types/HybridObjectType.js +131 -0
  79. package/lib/syntax/types/MapType.js +37 -0
  80. package/lib/syntax/types/NamedWrappingType.js +27 -0
  81. package/lib/syntax/types/NullType.js +23 -0
  82. package/lib/syntax/types/NumberType.js +27 -0
  83. package/lib/syntax/types/OptionalType.js +59 -0
  84. package/lib/syntax/types/PromiseType.js +62 -0
  85. package/lib/syntax/types/RecordType.js +47 -0
  86. package/lib/syntax/types/ResultWrappingType.js +44 -0
  87. package/lib/syntax/types/StringType.js +35 -0
  88. package/lib/syntax/types/StructType.js +61 -0
  89. package/lib/syntax/types/TupleType.js +39 -0
  90. package/lib/syntax/types/Type.js +1 -0
  91. package/lib/syntax/types/VariantType.js +75 -0
  92. package/lib/syntax/types/VoidType.js +27 -0
  93. package/lib/syntax/types/getTypeAs.js +12 -0
  94. package/lib/utils.js +126 -0
  95. package/lib/views/CppHybridViewComponent.js +256 -0
  96. package/lib/views/createHostComponentJs.js +27 -0
  97. package/lib/views/kotlin/KotlinHybridViewManager.js +229 -0
  98. package/lib/views/swift/SwiftHybridViewManager.js +131 -0
  99. package/lib/writeFile.js +19 -0
  100. package/package.json +58 -29
  101. package/src/Logger.ts +63 -0
  102. package/src/autolinking/Autolinking.ts +9 -0
  103. package/src/autolinking/android/createCMakeExtension.ts +126 -0
  104. package/src/autolinking/android/createGradleExtension.ts +43 -0
  105. package/src/autolinking/android/createHybridObjectInitializer.ts +174 -0
  106. package/src/autolinking/createAndroidAutolinking.ts +28 -0
  107. package/src/autolinking/createIOSAutolinking.ts +24 -0
  108. package/src/autolinking/ios/createHybridObjectInitializer.ts +112 -0
  109. package/src/autolinking/ios/createPodspecRubyExtension.ts +76 -0
  110. package/src/autolinking/ios/createSwiftCxxBridge.ts +137 -0
  111. package/src/autolinking/ios/createSwiftUmbrellaHeader.ts +90 -0
  112. package/src/config/NitroConfig.ts +139 -0
  113. package/src/config/NitroUserConfig.ts +105 -0
  114. package/src/config/getConfig.ts +91 -0
  115. package/src/createGitAttributes.ts +15 -0
  116. package/src/createPlatformSpec.ts +176 -0
  117. package/src/getFiles.ts +31 -0
  118. package/src/getPlatformSpecs.ts +202 -0
  119. package/src/index.ts +146 -0
  120. package/src/init.ts +186 -0
  121. package/src/nitrogen.ts +246 -0
  122. package/src/prettifyDirectory.ts +32 -0
  123. package/src/syntax/BridgedType.ts +59 -0
  124. package/src/syntax/CodeNode.ts +24 -0
  125. package/src/syntax/HybridObjectSpec.ts +14 -0
  126. package/src/syntax/Method.ts +154 -0
  127. package/src/syntax/Parameter.ts +81 -0
  128. package/src/syntax/Property.ts +203 -0
  129. package/src/syntax/SourceFile.ts +80 -0
  130. package/src/syntax/c++/CppEnum.ts +128 -0
  131. package/src/syntax/c++/CppHybridObject.ts +165 -0
  132. package/src/syntax/c++/CppHybridObjectRegistration.ts +39 -0
  133. package/src/syntax/c++/CppStruct.ts +129 -0
  134. package/src/syntax/c++/CppUnion.ts +105 -0
  135. package/src/syntax/c++/getForwardDeclaration.ts +19 -0
  136. package/src/syntax/c++/includeNitroHeader.ts +40 -0
  137. package/src/syntax/createType.ts +365 -0
  138. package/src/syntax/getAllTypes.ts +18 -0
  139. package/src/syntax/getCustomTypeConfig.ts +71 -0
  140. package/src/syntax/getHybridObjectName.ts +48 -0
  141. package/src/syntax/getInterfaceProperties.ts +21 -0
  142. package/src/syntax/getReferencedTypes.ts +57 -0
  143. package/src/syntax/helpers.ts +79 -0
  144. package/src/syntax/isCoreType.ts +60 -0
  145. package/src/syntax/kotlin/FbjniHybridObject.ts +313 -0
  146. package/src/syntax/kotlin/JNINativeRegistrations.ts +19 -0
  147. package/src/syntax/kotlin/KotlinBoxedPrimitive.ts +19 -0
  148. package/src/syntax/kotlin/KotlinCxxBridgedType.ts +942 -0
  149. package/src/syntax/kotlin/KotlinEnum.ts +130 -0
  150. package/src/syntax/kotlin/KotlinFunction.ts +277 -0
  151. package/src/syntax/kotlin/KotlinHybridObject.ts +205 -0
  152. package/src/syntax/kotlin/KotlinHybridObjectRegistration.ts +51 -0
  153. package/src/syntax/kotlin/KotlinStruct.ts +198 -0
  154. package/src/syntax/kotlin/KotlinVariant.ts +212 -0
  155. package/src/syntax/swift/SwiftCxxBridgedType.ts +874 -0
  156. package/src/syntax/swift/SwiftCxxTypeHelper.ts +674 -0
  157. package/src/syntax/swift/SwiftEnum.ts +65 -0
  158. package/src/syntax/swift/SwiftFunction.ts +91 -0
  159. package/src/syntax/swift/SwiftHybridObject.ts +121 -0
  160. package/src/syntax/swift/SwiftHybridObjectBridge.ts +522 -0
  161. package/src/syntax/swift/SwiftHybridObjectRegistration.ts +75 -0
  162. package/src/syntax/swift/SwiftStruct.ts +85 -0
  163. package/src/syntax/swift/SwiftVariant.ts +67 -0
  164. package/src/syntax/types/ArrayBufferType.ts +49 -0
  165. package/src/syntax/types/ArrayType.ts +62 -0
  166. package/src/syntax/types/BigIntType.ts +35 -0
  167. package/src/syntax/types/BooleanType.ts +35 -0
  168. package/src/syntax/types/CustomType.ts +47 -0
  169. package/src/syntax/types/DateType.ts +43 -0
  170. package/src/syntax/types/EnumType.ts +130 -0
  171. package/src/syntax/types/ErrorType.ts +44 -0
  172. package/src/syntax/types/FunctionType.ts +167 -0
  173. package/src/syntax/types/HybridObjectBaseType.ts +54 -0
  174. package/src/syntax/types/HybridObjectType.ts +198 -0
  175. package/src/syntax/types/MapType.ts +49 -0
  176. package/src/syntax/types/NamedWrappingType.ts +33 -0
  177. package/src/syntax/types/NullType.ts +30 -0
  178. package/src/syntax/types/NumberType.ts +34 -0
  179. package/src/syntax/types/OptionalType.ts +66 -0
  180. package/src/syntax/types/PromiseType.ts +72 -0
  181. package/src/syntax/types/RecordType.ts +56 -0
  182. package/src/syntax/types/ResultWrappingType.ts +53 -0
  183. package/src/syntax/types/StringType.ts +44 -0
  184. package/src/syntax/types/StructType.ts +83 -0
  185. package/src/syntax/types/TupleType.ts +53 -0
  186. package/src/syntax/types/Type.ts +82 -0
  187. package/src/syntax/types/VariantType.ts +92 -0
  188. package/src/syntax/types/VoidType.ts +34 -0
  189. package/src/syntax/types/getTypeAs.ts +15 -0
  190. package/src/utils.ts +162 -0
  191. package/src/views/CppHybridViewComponent.ts +304 -0
  192. package/src/views/createHostComponentJs.ts +34 -0
  193. package/src/views/kotlin/KotlinHybridViewManager.ts +258 -0
  194. package/src/views/swift/SwiftHybridViewManager.ts +153 -0
  195. package/src/writeFile.ts +27 -0
  196. package/.jshintignore +0 -6
  197. package/.jshintrc +0 -3
  198. package/.npmignore +0 -3
  199. package/.travis.yml +0 -13
  200. package/LICENSE +0 -13
  201. package/browser/nitrogen-min.js +0 -3
  202. package/browser/nitrogen.js +0 -6369
  203. package/lib/apiKey.js +0 -67
  204. package/lib/blob.js +0 -57
  205. package/lib/commandManager.js +0 -350
  206. package/lib/device.js +0 -19
  207. package/lib/memoryStore.js +0 -24
  208. package/lib/message.js +0 -298
  209. package/lib/permission.js +0 -121
  210. package/lib/principal.js +0 -330
  211. package/lib/service.js +0 -347
  212. package/lib/session.js +0 -494
  213. package/lib/user.js +0 -20
  214. package/publish +0 -2
  215. package/scripts/build-documentation +0 -4
  216. package/scripts/build-module +0 -27
  217. package/scripts/module.js +0 -12
  218. package/scripts/postamble.js +0 -1
  219. package/scripts/preamble.js +0 -2
  220. package/scripts/run-test-server +0 -9
  221. package/test/config.js +0 -12
  222. package/test/fixtures/images/image.jpg +0 -0
  223. package/test/fixtures/images/motion0.jpg +0 -0
  224. package/test/fixtures/images/motion1.jpg +0 -0
  225. package/test/fixtures/images/motion2.jpg +0 -0
  226. package/test/fixtures/index.js +0 -76
  227. package/test/main.js +0 -5
  228. package/test/memoryStore.js +0 -22
  229. package/test/mocha.opts +0 -3
  230. package/test/units/apiKey.js +0 -46
  231. package/test/units/blob.js +0 -35
  232. package/test/units/commandManager.js +0 -67
  233. package/test/units/device.js +0 -26
  234. package/test/units/heartbeat.js +0 -28
  235. package/test/units/message.js +0 -79
  236. package/test/units/permissions.js +0 -43
  237. package/test/units/principal.js +0 -116
  238. package/test/units/service.js +0 -92
  239. package/test/units/session.js +0 -97
  240. package/test/units/user.js +0 -48
  241. package/yuidoc.json +0 -8
@@ -0,0 +1,83 @@
1
+ import { NitroConfig } from '../../config/NitroConfig.js';
2
+ import { indent } from '../../utils.js';
3
+ import { createFileMetadataString } from '../helpers.js';
4
+ import { SwiftCxxBridgedType } from './SwiftCxxBridgedType.js';
5
+ export function createSwiftFunctionBridge(functionType) {
6
+ const swiftClassName = functionType.specializationName;
7
+ const bridgeNamespace = NitroConfig.current.getSwiftBridgeNamespace('swift');
8
+ const argsTypes = functionType.parameters.map((p) => {
9
+ const bridged = new SwiftCxxBridgedType(p);
10
+ return `${p.escapedName}: ${bridged.getTypeCode('swift')}`;
11
+ });
12
+ const returnType = new SwiftCxxBridgedType(functionType.returnType);
13
+ const argsForward = functionType.parameters.map((p) => {
14
+ const bridged = new SwiftCxxBridgedType(p);
15
+ return bridged.parseFromCppToSwift(p.escapedName, 'swift');
16
+ });
17
+ let body;
18
+ if (functionType.returnType.kind === 'void') {
19
+ body = `
20
+ self.closure(${argsForward.join(', ')})
21
+ `.trim();
22
+ }
23
+ else {
24
+ body = `
25
+ let __result: ${functionType.returnType.getCode('swift')} = self.closure(${argsForward.join(', ')})
26
+ return ${returnType.parseFromSwiftToCpp('__result', 'swift')}
27
+ `.trim();
28
+ }
29
+ const extraImports = functionType
30
+ .getRequiredImports('swift')
31
+ .map((i) => `import ${i.name}`);
32
+ const code = `
33
+ ${createFileMetadataString(`${swiftClassName}.swift`)}
34
+
35
+ import NitroModules
36
+ ${extraImports.join('\n')}
37
+
38
+ /**
39
+ * Wraps a Swift \`${functionType.getCode('swift')}\` as a class.
40
+ * This class can be used from C++, e.g. to wrap the Swift closure as a \`std::function\`.
41
+ */
42
+ public final class ${swiftClassName} {
43
+ public typealias bridge = ${bridgeNamespace}
44
+
45
+ private let closure: ${functionType.getCode('swift')}
46
+
47
+ public init(_ closure: @escaping ${functionType.getCode('swift')}) {
48
+ self.closure = closure
49
+ }
50
+
51
+ @inline(__always)
52
+ public func call(${argsTypes.join(', ')}) -> ${returnType.getTypeCode('swift')} {
53
+ ${indent(body, ' ')}
54
+ }
55
+
56
+ /**
57
+ * Casts this instance to a retained unsafe raw pointer.
58
+ * This acquires one additional strong reference on the object!
59
+ */
60
+ @inline(__always)
61
+ public func toUnsafe() -> UnsafeMutableRawPointer {
62
+ return Unmanaged.passRetained(self).toOpaque()
63
+ }
64
+
65
+ /**
66
+ * Casts an unsafe pointer to a \`${swiftClassName}\`.
67
+ * The pointer has to be a retained opaque \`Unmanaged<${swiftClassName}>\`.
68
+ * This removes one strong reference from the object!
69
+ */
70
+ @inline(__always)
71
+ public static func fromUnsafe(_ pointer: UnsafeMutableRawPointer) -> ${swiftClassName} {
72
+ return Unmanaged<${swiftClassName}>.fromOpaque(pointer).takeRetainedValue()
73
+ }
74
+ }
75
+ `.trim();
76
+ return {
77
+ content: code,
78
+ language: 'swift',
79
+ name: `${swiftClassName}.swift`,
80
+ platform: 'ios',
81
+ subdirectory: [],
82
+ };
83
+ }
@@ -0,0 +1,103 @@
1
+ import { indent } from '../../utils.js';
2
+ import { createSwiftHybridViewManager } from '../../views/swift/SwiftHybridViewManager.js';
3
+ import { getHybridObjectName } from '../getHybridObjectName.js';
4
+ import { createFileMetadataString, isNotDuplicate } from '../helpers.js';
5
+ import { HybridObjectType } from '../types/HybridObjectType.js';
6
+ import { createSwiftHybridObjectCxxBridge } from './SwiftHybridObjectBridge.js';
7
+ export function createSwiftHybridObject(spec) {
8
+ const name = getHybridObjectName(spec.name);
9
+ const protocolName = name.HybridTSpec;
10
+ const properties = spec.properties.map((p) => p.getCode('swift')).join('\n');
11
+ const methods = spec.methods.map((p) => p.getCode('swift')).join('\n');
12
+ const extraImports = [
13
+ ...spec.properties.flatMap((p) => p.getRequiredImports('swift')),
14
+ ...spec.methods.flatMap((m) => m.getRequiredImports('swift')),
15
+ ...spec.baseTypes.flatMap((b) => new HybridObjectType(b).getRequiredImports('swift')),
16
+ ];
17
+ const protocolBaseClasses = ['HybridObject'];
18
+ const classBaseClasses = [];
19
+ if (spec.baseTypes.length > 0) {
20
+ if (spec.baseTypes.length > 1) {
21
+ throw new Error(`${name.T}: Inheriting from multiple HybridObject bases is not yet supported in Swift!`);
22
+ }
23
+ const base = spec.baseTypes[0];
24
+ const baseName = getHybridObjectName(base.name);
25
+ protocolBaseClasses.push(`${baseName.HybridTSpec}_protocol`);
26
+ classBaseClasses.push(`${baseName.HybridTSpec}_base`);
27
+ }
28
+ if (spec.isHybridView) {
29
+ protocolBaseClasses.push('HybridView');
30
+ }
31
+ const hasBaseClass = classBaseClasses.length > 0;
32
+ const baseMembers = [];
33
+ baseMembers.push(`private weak var cxxWrapper: ${name.HybridTSpecCxx}? = nil`);
34
+ if (hasBaseClass) {
35
+ baseMembers.push(`public override init() { super.init() }`);
36
+ }
37
+ else {
38
+ baseMembers.push(`public init() { }`);
39
+ }
40
+ baseMembers.push(`
41
+ public ${hasBaseClass ? 'override func' : 'func'} getCxxWrapper() -> ${name.HybridTSpecCxx} {
42
+ #if DEBUG
43
+ guard self is ${name.HybridTSpec} else {
44
+ fatalError("\`self\` is not a \`${name.HybridTSpec}\`! Did you accidentally inherit from \`${name.HybridTSpec}_base\` instead of \`${name.HybridTSpec}\`?")
45
+ }
46
+ #endif
47
+ if let cxxWrapper = self.cxxWrapper {
48
+ return cxxWrapper
49
+ } else {
50
+ let cxxWrapper = ${name.HybridTSpecCxx}(self as! ${name.HybridTSpec})
51
+ self.cxxWrapper = cxxWrapper
52
+ return cxxWrapper
53
+ }
54
+ }`.trim());
55
+ const imports = ['import NitroModules'];
56
+ imports.push(...extraImports.map((i) => `import ${i.name}`).filter(isNotDuplicate));
57
+ const protocolCode = `
58
+ ${createFileMetadataString(`${protocolName}.swift`)}
59
+
60
+ import Foundation
61
+ ${imports.join('\n')}
62
+
63
+ /// See \`\`${protocolName}\`\`
64
+ public protocol ${protocolName}_protocol: ${protocolBaseClasses.join(', ')} {
65
+ // Properties
66
+ ${indent(properties, ' ')}
67
+
68
+ // Methods
69
+ ${indent(methods, ' ')}
70
+ }
71
+
72
+ /// See \`\`${protocolName}\`\`
73
+ open class ${protocolName}_base${classBaseClasses.length > 0 ? `: ${classBaseClasses.join(',')}` : ''} {
74
+ ${indent(baseMembers.join('\n'), ' ')}
75
+ }
76
+
77
+ /**
78
+ * A Swift base-protocol representing the ${spec.name} HybridObject.
79
+ * Implement this protocol to create Swift-based instances of ${spec.name}.
80
+ * \`\`\`swift
81
+ * class ${name.HybridT} : ${protocolName} {
82
+ * // ...
83
+ * }
84
+ * \`\`\`
85
+ */
86
+ public typealias ${protocolName} = ${protocolName}_protocol & ${protocolName}_base
87
+ `;
88
+ const swiftBridge = createSwiftHybridObjectCxxBridge(spec);
89
+ const files = [];
90
+ files.push({
91
+ content: protocolCode,
92
+ language: 'swift',
93
+ name: `${protocolName}.swift`,
94
+ subdirectory: [],
95
+ platform: 'ios',
96
+ });
97
+ files.push(...swiftBridge);
98
+ if (spec.isHybridView) {
99
+ const viewFiles = createSwiftHybridViewManager(spec);
100
+ files.push(...viewFiles);
101
+ }
102
+ return files;
103
+ }
@@ -0,0 +1,451 @@
1
+ import { SwiftCxxBridgedType } from './SwiftCxxBridgedType.js';
2
+ import { indent } from '../../utils.js';
3
+ import { createFileMetadataString, escapeCppName, isNotDuplicate, } from '../helpers.js';
4
+ import { getHybridObjectName } from '../getHybridObjectName.js';
5
+ import { getForwardDeclaration } from '../c++/getForwardDeclaration.js';
6
+ import { NitroConfig } from '../../config/NitroConfig.js';
7
+ import { includeHeader } from '../c++/includeNitroHeader.js';
8
+ import { getUmbrellaHeaderName } from '../../autolinking/ios/createSwiftUmbrellaHeader.js';
9
+ import { HybridObjectType } from '../types/HybridObjectType.js';
10
+ import { addKnownType } from '../createType.js';
11
+ import { ResultWrappingType } from '../types/ResultWrappingType.js';
12
+ /**
13
+ * Creates a Swift class that bridges Swift over to C++.
14
+ * We need this because not all Swift types are accessible in C++, and vice versa.
15
+ *
16
+ * For example, Enums need to be converted to Int32 (because of a Swift compiler bug),
17
+ * Promise<..> has to be converted to a Promise<..>, exceptions have to be handled
18
+ * via custom Result types, etc..
19
+ */
20
+ export function createSwiftHybridObjectCxxBridge(spec) {
21
+ const name = getHybridObjectName(spec.name);
22
+ const moduleName = spec.config.getIosModuleName();
23
+ const bridgeNamespace = spec.config.getSwiftBridgeNamespace('swift');
24
+ const propertiesBridge = spec.properties.map((p) => getPropertyForwardImplementation(p));
25
+ const methodsBridge = spec.methods.map((m) => getMethodForwardImplementation(m));
26
+ const baseClasses = spec.baseTypes.map((base) => {
27
+ const baseName = getHybridObjectName(base.name);
28
+ return baseName.HybridTSpecCxx;
29
+ });
30
+ const hasBase = baseClasses.length > 0;
31
+ if (spec.isHybridView && !hasBase) {
32
+ methodsBridge.push(`
33
+ public final func getView() -> UnsafeMutableRawPointer {
34
+ return Unmanaged.passRetained(__implementation.view).toOpaque()
35
+ }
36
+ `.trim(), `
37
+ public final func beforeUpdate() {
38
+ __implementation.beforeUpdate()
39
+ }
40
+ `.trim(), `
41
+ public final func afterUpdate() {
42
+ __implementation.afterUpdate()
43
+ }
44
+ `.trim());
45
+ }
46
+ const hybridObject = new HybridObjectType(spec);
47
+ const bridgedType = new SwiftCxxBridgedType(hybridObject);
48
+ const bridge = bridgedType.getRequiredBridge();
49
+ if (bridge == null)
50
+ throw new Error(`HybridObject Type should have a bridge!`);
51
+ const weakifyBridge = bridge.dependencies.find((d) => d.funcName.startsWith('weakify'));
52
+ if (weakifyBridge == null)
53
+ throw new Error(`HybridObject ${spec.name} does not have a weakify_..() bridge!`);
54
+ const cppWeakPtrName = escapeCppName(hybridObject.getCode('c++', { mode: 'weak' }));
55
+ const baseGetCxxPartOverrides = spec.baseTypes.map((base) => {
56
+ const baseHybridObject = new HybridObjectType(base);
57
+ const bridgedBase = new SwiftCxxBridgedType(baseHybridObject);
58
+ const baseBridge = bridgedBase.getRequiredBridge();
59
+ if (baseBridge == null)
60
+ throw new Error(`HybridObject ${base.name}'s bridge cannot be null!`);
61
+ const upcastBridge = bridge.dependencies.find((b) => b.funcName.includes(escapeCppName(spec.name)) &&
62
+ b.funcName.includes(escapeCppName(base.name)));
63
+ if (upcastBridge == null)
64
+ throw new Error(`HybridObject ${spec.name}'s upcast-bridge cannot be found! ${JSON.stringify(baseBridge)}`);
65
+ return `
66
+ public override func getCxxPart() -> bridge.${baseBridge.specializationName} {
67
+ let ownCxxPart: bridge.${bridge.specializationName} = getCxxPart()
68
+ return bridge.${upcastBridge.funcName}(ownCxxPart)
69
+ }`.trim();
70
+ });
71
+ const imports = ['import NitroModules'];
72
+ const extraSwiftImports = [
73
+ ...spec.properties.flatMap((p) => p.getRequiredImports('swift')),
74
+ ...spec.methods.flatMap((m) => m.getRequiredImports('swift')),
75
+ ];
76
+ imports.push(...extraSwiftImports.map((i) => `import ${i.name}`).filter(isNotDuplicate));
77
+ const swiftCxxWrapperCode = `
78
+ ${createFileMetadataString(`${name.HybridTSpecCxx}.swift`)}
79
+
80
+ import Foundation
81
+ ${imports.join('\n')}
82
+
83
+ /**
84
+ * A class implementation that bridges ${name.HybridTSpec} over to C++.
85
+ * In C++, we cannot use Swift protocols - so we need to wrap it in a class to make it strongly defined.
86
+ *
87
+ * Also, some Swift types need to be bridged with special handling:
88
+ * - Enums need to be wrapped in Structs, otherwise they cannot be accessed bi-directionally (Swift bug: https://github.com/swiftlang/swift/issues/75330)
89
+ * - Other HybridObjects need to be wrapped/unwrapped from the Swift TCxx wrapper
90
+ * - Throwing methods need to be wrapped with a Result<T, Error> type, as exceptions cannot be propagated to C++
91
+ */
92
+ ${hasBase ? `open class ${name.HybridTSpecCxx} : ${baseClasses.join(', ')}` : `open class ${name.HybridTSpecCxx}`} {
93
+ /**
94
+ * The Swift <> C++ bridge's namespace (\`${NitroConfig.current.getSwiftBridgeNamespace('c++')}\`)
95
+ * from \`${moduleName}-Swift-Cxx-Bridge.hpp\`.
96
+ * This contains specialized C++ templates, and C++ helper functions that can be accessed from Swift.
97
+ */
98
+ public typealias bridge = ${bridgeNamespace}
99
+
100
+ /**
101
+ * Holds an instance of the \`${name.HybridTSpec}\` Swift protocol.
102
+ */
103
+ private var __implementation: any ${name.HybridTSpec}
104
+
105
+ /**
106
+ * Holds a weak pointer to the C++ class that wraps the Swift class.
107
+ */
108
+ private var __cxxPart: bridge.${cppWeakPtrName}
109
+
110
+ /**
111
+ * Create a new \`${name.HybridTSpecCxx}\` that wraps the given \`${name.HybridTSpec}\`.
112
+ * All properties and methods bridge to C++ types.
113
+ */
114
+ public init(_ implementation: any ${name.HybridTSpec}) {
115
+ self.__implementation = implementation
116
+ self.__cxxPart = .init()
117
+ ${hasBase ? 'super.init(implementation)' : '/* no base class */'}
118
+ }
119
+
120
+ /**
121
+ * Get the actual \`${name.HybridTSpec}\` instance this class wraps.
122
+ */
123
+ @inline(__always)
124
+ public func get${name.HybridTSpec}() -> any ${name.HybridTSpec} {
125
+ return __implementation
126
+ }
127
+
128
+ /**
129
+ * Casts this instance to a retained unsafe raw pointer.
130
+ * This acquires one additional strong reference on the object!
131
+ */
132
+ public ${hasBase ? 'override func' : 'func'} toUnsafe() -> UnsafeMutableRawPointer {
133
+ return Unmanaged.passRetained(self).toOpaque()
134
+ }
135
+
136
+ /**
137
+ * Casts an unsafe pointer to a \`${name.HybridTSpecCxx}\`.
138
+ * The pointer has to be a retained opaque \`Unmanaged<${name.HybridTSpecCxx}>\`.
139
+ * This removes one strong reference from the object!
140
+ */
141
+ public ${hasBase ? 'override class func' : 'class func'} fromUnsafe(_ pointer: UnsafeMutableRawPointer) -> ${name.HybridTSpecCxx} {
142
+ return Unmanaged<${name.HybridTSpecCxx}>.fromOpaque(pointer).takeRetainedValue()
143
+ }
144
+
145
+ /**
146
+ * Gets (or creates) the C++ part of this Hybrid Object.
147
+ * The C++ part is a \`${bridge.cxxType}\`.
148
+ */
149
+ public func getCxxPart() -> bridge.${bridge.specializationName} {
150
+ let cachedCxxPart = self.__cxxPart.lock()
151
+ if cachedCxxPart.__convertToBool() {
152
+ return cachedCxxPart
153
+ } else {
154
+ let newCxxPart = bridge.${bridge.funcName}(self.toUnsafe())
155
+ __cxxPart = bridge.${weakifyBridge.funcName}(newCxxPart)
156
+ return newCxxPart
157
+ }
158
+ }
159
+
160
+ ${indent(baseGetCxxPartOverrides.join('\n'), ' ')}
161
+
162
+ /**
163
+ * Get the memory size of the Swift class (plus size of any other allocations)
164
+ * so the JS VM can properly track it and garbage-collect the JS object if needed.
165
+ */
166
+ @inline(__always)
167
+ public ${hasBase ? 'override var' : 'var'} memorySize: Int {
168
+ return MemoryHelper.getSizeOf(self.__implementation) + self.__implementation.memorySize
169
+ }
170
+
171
+ /**
172
+ * Call dispose() on the Swift class.
173
+ * This _may_ be called manually from JS.
174
+ */
175
+ @inline(__always)
176
+ public ${hasBase ? 'override func' : 'func'} dispose() {
177
+ self.__implementation.dispose()
178
+ }
179
+
180
+ // Properties
181
+ ${indent(propertiesBridge.join('\n\n'), ' ')}
182
+
183
+ // Methods
184
+ ${indent(methodsBridge.join('\n\n'), ' ')}
185
+ }
186
+ `;
187
+ const cppProperties = spec.properties
188
+ .map((p) => {
189
+ const bridged = new SwiftCxxBridgedType(p.type);
190
+ let getter;
191
+ let setter;
192
+ const getterName = p.getGetterName('swift');
193
+ const setterName = p.getSetterName('swift');
194
+ if (bridged.needsSpecialHandling) {
195
+ // we need custom C++ -> Swift conversion code
196
+ getter = `
197
+ auto __result = _swiftPart.${getterName}();
198
+ return ${bridged.parseFromSwiftToCpp('__result', 'c++')};
199
+ `;
200
+ setter = `_swiftPart.${setterName}(${bridged.parseFromCppToSwift(p.name, 'c++')});`;
201
+ }
202
+ else {
203
+ // just forward value directly
204
+ getter = `return _swiftPart.${getterName}();`;
205
+ setter = `_swiftPart.${setterName}(std::forward<decltype(${p.name})>(${p.name}));`;
206
+ }
207
+ return p.getCode('c++', { inline: true, override: true, noexcept: true }, {
208
+ getter: getter.trim(),
209
+ setter: setter.trim(),
210
+ });
211
+ })
212
+ .join('\n');
213
+ const cppMethods = spec.methods
214
+ .map((m) => {
215
+ const params = m.parameters
216
+ .map((p) => {
217
+ const bridged = new SwiftCxxBridgedType(p.type);
218
+ if (bridged.needsSpecialHandling) {
219
+ // we need custom C++ -> Swift conversion code
220
+ return bridged.parseFromCppToSwift(p.name, 'c++');
221
+ }
222
+ else {
223
+ // just forward value directly
224
+ return `std::forward<decltype(${p.name})>(${p.name})`;
225
+ }
226
+ })
227
+ .join(', ');
228
+ const bridgedReturnType = new SwiftCxxBridgedType(m.returnType, true);
229
+ const hasResult = m.returnType.kind !== 'void';
230
+ let body;
231
+ if (hasResult) {
232
+ // func returns something
233
+ body = `
234
+ auto __result = _swiftPart.${m.name}(${params});
235
+ if (__result.hasError()) [[unlikely]] {
236
+ std::rethrow_exception(__result.error());
237
+ }
238
+ auto __value = std::move(__result.value());
239
+ return ${bridgedReturnType.parseFromSwiftToCpp('__value', 'c++')};
240
+ `.trim();
241
+ }
242
+ else {
243
+ // void func
244
+ body = `
245
+ auto __result = _swiftPart.${m.name}(${params});
246
+ if (__result.hasError()) [[unlikely]] {
247
+ std::rethrow_exception(__result.error());
248
+ }
249
+ `.trim();
250
+ }
251
+ return m.getCode('c++', { inline: true, override: true }, body);
252
+ })
253
+ .join('\n');
254
+ const allBridgedTypes = [
255
+ ...spec.properties.flatMap((p) => new SwiftCxxBridgedType(p.type)),
256
+ ...spec.methods.flatMap((m) => {
257
+ const bridgedReturn = new SwiftCxxBridgedType(m.returnType);
258
+ const bridgedParams = m.parameters.map((p) => new SwiftCxxBridgedType(p.type));
259
+ return [bridgedReturn, ...bridgedParams];
260
+ }),
261
+ ];
262
+ const cxxNamespace = spec.config.getCxxNamespace('c++');
263
+ const iosModuleName = spec.config.getIosModuleName();
264
+ const extraImports = allBridgedTypes.flatMap((b) => b.getRequiredImports('c++'));
265
+ const cppBaseClasses = [`public virtual ${name.HybridTSpec}`];
266
+ const cppBaseCtorCalls = [`HybridObject(${name.HybridTSpec}::TAG)`];
267
+ for (const base of spec.baseTypes) {
268
+ const baseName = getHybridObjectName(base.name);
269
+ cppBaseClasses.push(`public virtual ${baseName.HybridTSpecSwift}`);
270
+ cppBaseCtorCalls.push(`${baseName.HybridTSpecSwift}(swiftPart)`);
271
+ extraImports.push({
272
+ language: 'c++',
273
+ name: `${baseName.HybridTSpecSwift}.hpp`,
274
+ space: 'user',
275
+ forwardDeclaration: getForwardDeclaration('class', baseName.HybridTSpecSwift, cxxNamespace),
276
+ });
277
+ }
278
+ const extraForwardDeclarations = extraImports
279
+ .map((i) => i.forwardDeclaration)
280
+ .filter((v) => v != null)
281
+ .filter(isNotDuplicate);
282
+ const extraIncludes = extraImports
283
+ .map((i) => includeHeader(i))
284
+ .filter(isNotDuplicate);
285
+ // TODO: Remove forward declaration once Swift fixes the wrong order in generated -Swift.h headers!
286
+ const cppHybridObjectCode = `
287
+ ${createFileMetadataString(`${name.HybridTSpecSwift}.hpp`)}
288
+
289
+ #pragma once
290
+
291
+ #include "${name.HybridTSpec}.hpp"
292
+
293
+ ${getForwardDeclaration('class', name.HybridTSpecCxx, iosModuleName)}
294
+
295
+ ${extraForwardDeclarations.join('\n')}
296
+
297
+ ${extraIncludes.join('\n')}
298
+
299
+ #include "${getUmbrellaHeaderName()}"
300
+
301
+ namespace ${cxxNamespace} {
302
+
303
+ /**
304
+ * The C++ part of ${name.HybridTSpecCxx}.swift.
305
+ *
306
+ * ${name.HybridTSpecSwift} (C++) accesses ${name.HybridTSpecCxx} (Swift), and might
307
+ * contain some additional bridging code for C++ <> Swift interop.
308
+ *
309
+ * Since this obviously introduces an overhead, I hope at some point in
310
+ * the future, ${name.HybridTSpecCxx} can directly inherit from the C++ class ${name.HybridTSpec}
311
+ * to simplify the whole structure and memory management.
312
+ */
313
+ class ${name.HybridTSpecSwift}: ${cppBaseClasses.join(', ')} {
314
+ public:
315
+ // Constructor from a Swift instance
316
+ explicit ${name.HybridTSpecSwift}(const ${iosModuleName}::${name.HybridTSpecCxx}& swiftPart):
317
+ ${indent(cppBaseCtorCalls.join(',\n'), ' ')},
318
+ _swiftPart(swiftPart) { }
319
+
320
+ public:
321
+ // Get the Swift part
322
+ inline ${iosModuleName}::${name.HybridTSpecCxx}& getSwiftPart() noexcept {
323
+ return _swiftPart;
324
+ }
325
+
326
+ public:
327
+ inline size_t getExternalMemorySize() noexcept override {
328
+ return _swiftPart.getMemorySize();
329
+ }
330
+ void dispose() noexcept override {
331
+ _swiftPart.dispose();
332
+ }
333
+
334
+ public:
335
+ // Properties
336
+ ${indent(cppProperties, ' ')}
337
+
338
+ public:
339
+ // Methods
340
+ ${indent(cppMethods, ' ')}
341
+
342
+ private:
343
+ ${iosModuleName}::${name.HybridTSpecCxx} _swiftPart;
344
+ };
345
+
346
+ } // namespace ${cxxNamespace}
347
+ `;
348
+ const cppHybridObjectCodeCpp = `
349
+ ${createFileMetadataString(`${name.HybridTSpecSwift}.cpp`)}
350
+
351
+ #include "${name.HybridTSpecSwift}.hpp"
352
+
353
+ namespace ${cxxNamespace} {
354
+ } // namespace ${cxxNamespace}
355
+ `;
356
+ const files = [];
357
+ files.push(...allBridgedTypes.flatMap((b) => b.getExtraFiles()));
358
+ files.push({
359
+ content: swiftCxxWrapperCode,
360
+ language: 'swift',
361
+ name: `${name.HybridTSpecCxx}.swift`,
362
+ subdirectory: [],
363
+ platform: 'ios',
364
+ });
365
+ files.push({
366
+ content: cppHybridObjectCode,
367
+ language: 'c++',
368
+ name: `${name.HybridTSpecSwift}.hpp`,
369
+ subdirectory: [],
370
+ platform: 'ios',
371
+ });
372
+ files.push({
373
+ content: cppHybridObjectCodeCpp,
374
+ language: 'c++',
375
+ name: `${name.HybridTSpecSwift}.cpp`,
376
+ subdirectory: [],
377
+ platform: 'ios',
378
+ });
379
+ return files;
380
+ }
381
+ function getPropertyForwardImplementation(property) {
382
+ const bridgedType = new SwiftCxxBridgedType(property.type);
383
+ const convertToCpp = bridgedType.parseFromSwiftToCpp(`self.__implementation.${property.name}`, 'swift');
384
+ const convertFromCpp = bridgedType.parseFromCppToSwift('newValue', 'swift');
385
+ const getter = `
386
+ @inline(__always)
387
+ get {
388
+ return ${indent(convertToCpp, ' ')}
389
+ }
390
+ `.trim();
391
+ const setter = `
392
+ @inline(__always)
393
+ set {
394
+ self.__implementation.${property.name} = ${indent(convertFromCpp, ' ')}
395
+ }
396
+ `.trim();
397
+ const body = [getter];
398
+ if (!property.isReadonly) {
399
+ body.push(setter);
400
+ }
401
+ const code = `
402
+ public final var ${property.name}: ${bridgedType.getTypeCode('swift')} {
403
+ ${indent(body.join('\n'), ' ')}
404
+ }
405
+ `;
406
+ return code.trim();
407
+ }
408
+ function getMethodForwardImplementation(method) {
409
+ // wrapped return in a std::expected
410
+ const resultType = new ResultWrappingType(method.returnType);
411
+ addKnownType(`expected_${resultType.getCode('c++')}`, resultType, 'swift');
412
+ const bridgedResultType = new SwiftCxxBridgedType(resultType, true);
413
+ const resultBridge = bridgedResultType.getRequiredBridge();
414
+ if (resultBridge == null)
415
+ throw new Error(`Result type (${bridgedResultType.getTypeCode('c++')}) does not have a bridge!`);
416
+ const bridgedErrorType = new SwiftCxxBridgedType(resultType.error, true);
417
+ const returnType = new SwiftCxxBridgedType(method.returnType, true);
418
+ const params = method.parameters.map((p) => {
419
+ const bridgedType = new SwiftCxxBridgedType(p.type);
420
+ return `${p.name}: ${bridgedType.getTypeCode('swift')}`;
421
+ });
422
+ const passParams = method.parameters.map((p) => {
423
+ const bridgedType = new SwiftCxxBridgedType(p.type);
424
+ return `${p.name}: ${bridgedType.parseFromCppToSwift(p.name, 'swift')}`;
425
+ });
426
+ let body;
427
+ if (returnType.hasType) {
428
+ body = `
429
+ let __result = try self.__implementation.${method.name}(${passParams.join(', ')})
430
+ let __resultCpp = ${returnType.parseFromSwiftToCpp('__result', 'swift')}
431
+ return bridge.${resultBridge.funcName}(__resultCpp)
432
+ `.trim();
433
+ }
434
+ else {
435
+ body = `
436
+ try self.__implementation.${method.name}(${passParams.join(', ')})
437
+ return bridge.${resultBridge.funcName}()
438
+ `.trim();
439
+ }
440
+ return `
441
+ @inline(__always)
442
+ public final func ${method.name}(${params.join(', ')}) -> ${bridgedResultType.getTypeCode('swift')} {
443
+ do {
444
+ ${indent(body, ' ')}
445
+ } catch (let __error) {
446
+ let __exceptionPtr = ${indent(bridgedErrorType.parseFromSwiftToCpp('__error', 'swift'), ' ')}
447
+ return bridge.${resultBridge.funcName}(__exceptionPtr)
448
+ }
449
+ }
450
+ `.trim();
451
+ }
@@ -0,0 +1,42 @@
1
+ import { NitroConfig } from '../../config/NitroConfig.js';
2
+ import { indent } from '../../utils.js';
3
+ import { getHybridObjectName } from '../getHybridObjectName.js';
4
+ import { HybridObjectType } from '../types/HybridObjectType.js';
5
+ import { SwiftCxxBridgedType } from './SwiftCxxBridgedType.js';
6
+ export function getHybridObjectConstructorCall(hybridObjectName) {
7
+ const swiftNamespace = NitroConfig.current.getIosModuleName();
8
+ const autolinkingClassName = `${swiftNamespace}Autolinking`;
9
+ return `${swiftNamespace}::${autolinkingClassName}::create${hybridObjectName}();`;
10
+ }
11
+ export function createSwiftHybridObjectRegistration({ hybridObjectName, swiftClassName, }) {
12
+ const { HybridTSpecCxx, HybridTSpecSwift, HybridTSpec } = getHybridObjectName(hybridObjectName);
13
+ const type = new HybridObjectType(hybridObjectName, 'swift', [], NitroConfig.current);
14
+ const bridge = new SwiftCxxBridgedType(type);
15
+ return {
16
+ swiftFunction: `
17
+ /**
18
+ * Creates an instance of a Swift class that implements \`${HybridTSpec}\`,
19
+ * and wraps it in a Swift class that can directly interop with C++ (\`${HybridTSpecCxx}\`)
20
+ *
21
+ * This is generated by Nitrogen and will initialize the class specified
22
+ * in the \`"autolinking"\` property of \`nitro.json\` (in this case, \`${swiftClassName}\`).
23
+ */
24
+ public static func create${hybridObjectName}() -> ${bridge.getTypeCode('swift')} {
25
+ let hybridObject = ${swiftClassName}()
26
+ return ${indent(bridge.parseFromSwiftToCpp('hybridObject', 'swift'), ' ')}
27
+ }
28
+ `.trim(),
29
+ requiredImports: [
30
+ { name: `${HybridTSpecSwift}.hpp`, language: 'c++', space: 'user' },
31
+ ],
32
+ cppCode: `
33
+ HybridObjectRegistry::registerHybridObjectConstructor(
34
+ "${hybridObjectName}",
35
+ []() -> std::shared_ptr<HybridObject> {
36
+ ${type.getCode('c++')} hybridObject = ${getHybridObjectConstructorCall(hybridObjectName)}
37
+ return hybridObject;
38
+ }
39
+ );
40
+ `.trim(),
41
+ };
42
+ }