@ts-for-gir/lib 3.3.0 → 4.0.0-beta.2

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 (313) hide show
  1. package/README.md +0 -1
  2. package/lib/conflict-resolver.d.ts +2 -39
  3. package/lib/conflict-resolver.js +4 -228
  4. package/lib/conflict-resolver.js.map +1 -1
  5. package/lib/constants.d.ts +3 -7
  6. package/lib/constants.js +6 -16
  7. package/lib/constants.js.map +1 -1
  8. package/lib/dependency-manager.d.ts +3 -5
  9. package/lib/dependency-manager.js +10 -17
  10. package/lib/dependency-manager.js.map +1 -1
  11. package/lib/formatters/default.d.ts +4 -0
  12. package/lib/formatters/default.js +7 -0
  13. package/lib/formatters/default.js.map +1 -0
  14. package/lib/formatters/formatter.d.ts +3 -0
  15. package/lib/formatters/formatter.js +3 -0
  16. package/lib/formatters/formatter.js.map +1 -0
  17. package/lib/formatters/json.d.ts +4 -0
  18. package/lib/formatters/json.js +7 -0
  19. package/lib/formatters/json.js.map +1 -0
  20. package/lib/generators/dts/gio.d.ts +2 -0
  21. package/lib/generators/dts/gio.js +9 -0
  22. package/lib/generators/dts/gio.js.map +1 -0
  23. package/lib/generators/dts/glib.d.ts +2 -0
  24. package/lib/generators/dts/glib.js +514 -0
  25. package/lib/generators/dts/glib.js.map +1 -0
  26. package/lib/generators/dts/gobject.d.ts +2 -0
  27. package/lib/generators/dts/gobject.js +117 -0
  28. package/lib/generators/dts/gobject.js.map +1 -0
  29. package/lib/generators/dts-inline.d.ts +8 -0
  30. package/lib/generators/dts-inline.js +59 -0
  31. package/lib/generators/dts-inline.js.map +1 -0
  32. package/lib/generators/dts-modules.d.ts +8 -0
  33. package/lib/generators/dts-modules.js +100 -0
  34. package/lib/generators/dts-modules.js.map +1 -0
  35. package/lib/generators/dts.d.ts +45 -0
  36. package/lib/generators/dts.js +682 -0
  37. package/lib/generators/dts.js.map +1 -0
  38. package/lib/generators/generator.d.ts +45 -0
  39. package/lib/generators/generator.js +9 -0
  40. package/lib/generators/generator.js.map +1 -0
  41. package/lib/generators/index.d.ts +5 -0
  42. package/lib/generators/index.js +6 -0
  43. package/lib/generators/index.js.map +1 -0
  44. package/lib/generators/json.d.ts +256 -0
  45. package/lib/generators/json.js +869 -0
  46. package/lib/generators/json.js.map +1 -0
  47. package/lib/generics/clutter.d.ts +26 -0
  48. package/lib/generics/clutter.js +49 -0
  49. package/lib/generics/clutter.js.map +1 -0
  50. package/lib/generics/generify.d.ts +2 -0
  51. package/lib/generics/generify.js +39 -0
  52. package/lib/generics/generify.js.map +1 -0
  53. package/lib/generics/gio.d.ts +7 -0
  54. package/lib/generics/gio.js +51 -0
  55. package/lib/generics/gio.js.map +1 -0
  56. package/lib/generics/glib.d.ts +7 -0
  57. package/lib/generics/glib.js +18 -0
  58. package/lib/generics/glib.js.map +1 -0
  59. package/lib/generics/meta.d.ts +21 -0
  60. package/lib/generics/meta.js +26 -0
  61. package/lib/generics/meta.js.map +1 -0
  62. package/lib/generics/st.d.ts +16 -0
  63. package/lib/generics/st.js +92 -0
  64. package/lib/generics/st.js.map +1 -0
  65. package/lib/generics/visitor.d.ts +20 -0
  66. package/lib/generics/visitor.js +259 -0
  67. package/lib/generics/visitor.js.map +1 -0
  68. package/lib/gir/alias.d.ts +24 -0
  69. package/lib/gir/alias.js +43 -0
  70. package/lib/gir/alias.js.map +1 -0
  71. package/lib/gir/base.d.ts +62 -0
  72. package/lib/gir/base.js +95 -0
  73. package/lib/gir/base.js.map +1 -0
  74. package/lib/gir/class.d.ts +189 -0
  75. package/lib/gir/class.js +1132 -0
  76. package/lib/gir/class.js.map +1 -0
  77. package/lib/gir/const.d.ts +25 -0
  78. package/lib/gir/const.js +43 -0
  79. package/lib/gir/const.js.map +1 -0
  80. package/lib/gir/enum.d.ts +45 -0
  81. package/lib/gir/enum.js +164 -0
  82. package/lib/gir/enum.js.map +1 -0
  83. package/lib/gir/function.d.ts +199 -0
  84. package/lib/gir/function.js +683 -0
  85. package/lib/gir/function.js.map +1 -0
  86. package/lib/gir/generics.d.ts +5 -0
  87. package/lib/gir/generics.js +57 -0
  88. package/lib/gir/generics.js.map +1 -0
  89. package/lib/gir/namespace.d.ts +21 -0
  90. package/lib/gir/namespace.js +57 -0
  91. package/lib/gir/namespace.js.map +1 -0
  92. package/lib/gir/nodes.d.ts +11 -0
  93. package/lib/gir/nodes.js +12 -0
  94. package/lib/gir/nodes.js.map +1 -0
  95. package/lib/gir/property.d.ts +60 -0
  96. package/lib/gir/property.js +128 -0
  97. package/lib/gir/property.js.map +1 -0
  98. package/lib/gir/registry.d.ts +51 -0
  99. package/lib/gir/registry.js +144 -0
  100. package/lib/gir/registry.js.map +1 -0
  101. package/lib/gir/signal.d.ts +33 -0
  102. package/lib/gir/signal.js +165 -0
  103. package/lib/gir/signal.js.map +1 -0
  104. package/lib/gir/util.d.ts +49 -0
  105. package/lib/gir/util.js +556 -0
  106. package/lib/gir/util.js.map +1 -0
  107. package/lib/gir-factory.d.ts +2 -2
  108. package/lib/gir-factory.js +8 -44
  109. package/lib/gir-factory.js.map +1 -1
  110. package/lib/gir-module.d.ts +61 -221
  111. package/lib/gir-module.js +387 -2106
  112. package/lib/gir-module.js.map +1 -1
  113. package/lib/gir.d.ts +251 -0
  114. package/lib/gir.js +638 -0
  115. package/lib/gir.js.map +1 -0
  116. package/lib/index.d.ts +5 -4
  117. package/lib/index.js +7 -4
  118. package/lib/index.js.map +1 -1
  119. package/lib/injection/callbacks/index.d.ts +0 -1
  120. package/lib/injection/callbacks/index.js +0 -1
  121. package/lib/injection/callbacks/index.js.map +1 -1
  122. package/lib/injection/classes/index.d.ts +0 -1
  123. package/lib/injection/classes/index.js +0 -1
  124. package/lib/injection/classes/index.js.map +1 -1
  125. package/lib/injection/injector.d.ts +2 -3
  126. package/lib/injection/injector.js +6 -8
  127. package/lib/injection/injector.js.map +1 -1
  128. package/lib/injections/gee08.d.ts +7 -0
  129. package/lib/injections/gee08.js +68 -0
  130. package/lib/injections/gee08.js.map +1 -0
  131. package/lib/injections/gee1.d.ts +7 -0
  132. package/lib/injections/gee1.js +28 -0
  133. package/lib/injections/gee1.js.map +1 -0
  134. package/lib/injections/gio.d.ts +7 -0
  135. package/lib/injections/gio.js +431 -0
  136. package/lib/injections/gio.js.map +1 -0
  137. package/lib/injections/glib.d.ts +7 -0
  138. package/lib/injections/glib.js +204 -0
  139. package/lib/injections/glib.js.map +1 -0
  140. package/lib/injections/gobject.d.ts +7 -0
  141. package/lib/injections/gobject.js +479 -0
  142. package/lib/injections/gobject.js.map +1 -0
  143. package/lib/injections/inject.d.ts +4 -0
  144. package/lib/injections/inject.js +28 -0
  145. package/lib/injections/inject.js.map +1 -0
  146. package/lib/injections/tracker1.d.ts +7 -0
  147. package/lib/injections/tracker1.js +30 -0
  148. package/lib/injections/tracker1.js.map +1 -0
  149. package/lib/library-version.js.map +1 -1
  150. package/lib/logger.d.ts +1 -3
  151. package/lib/logger.js +3 -8
  152. package/lib/logger.js.map +1 -1
  153. package/lib/messages.d.ts +1 -4
  154. package/lib/messages.js +1 -3
  155. package/lib/messages.js.map +1 -1
  156. package/lib/registry.d.ts +9 -0
  157. package/lib/registry.js +13 -0
  158. package/lib/registry.js.map +1 -0
  159. package/lib/symtable.js +1 -1
  160. package/lib/symtable.js.map +1 -1
  161. package/lib/transformation.d.ts +4 -5
  162. package/lib/transformation.js +31 -127
  163. package/lib/transformation.js.map +1 -1
  164. package/lib/types/generate-config.d.ts +4 -11
  165. package/lib/types/gir-alias-element.d.ts +3 -12
  166. package/lib/types/gir-bitfield-element.d.ts +3 -14
  167. package/lib/types/gir-callable-param-element.d.ts +3 -31
  168. package/lib/types/gir-callable-params.d.ts +7 -0
  169. package/lib/types/gir-callable-params.js +2 -0
  170. package/lib/types/gir-callable-params.js.map +1 -0
  171. package/lib/types/gir-callable-return.d.ts +3 -20
  172. package/lib/types/gir-callback-element.d.ts +3 -12
  173. package/lib/types/gir-class-element.d.ts +3 -34
  174. package/lib/types/gir-constant-element.d.ts +3 -14
  175. package/lib/types/gir-constructor-element.d.ts +3 -5
  176. package/lib/types/gir-enum-element.d.ts +3 -16
  177. package/lib/types/gir-field-element.d.ts +3 -16
  178. package/lib/types/gir-function-element.d.ts +3 -5
  179. package/lib/types/gir-instance-parameter.d.ts +2 -17
  180. package/lib/types/gir-interface-element.d.ts +4 -19
  181. package/lib/types/gir-member-element.d.ts +4 -16
  182. package/lib/types/gir-method-element.d.ts +4 -10
  183. package/lib/types/gir-namespace.d.ts +14 -17
  184. package/lib/types/gir-property-element.d.ts +3 -22
  185. package/lib/types/gir-record-element.d.ts +3 -23
  186. package/lib/types/gir-repository.d.ts +3 -14
  187. package/lib/types/gir-signal.d.ts +3 -18
  188. package/lib/types/gir-union-element.d.ts +3 -16
  189. package/lib/types/gir-virtual-method.d.ts +3 -7
  190. package/lib/types/index.d.ts +3 -54
  191. package/lib/types/index.js +3 -54
  192. package/lib/types/index.js.map +1 -1
  193. package/lib/types/parsed-gir.d.ts +3 -2
  194. package/lib/types/transformations.d.ts +1 -8
  195. package/lib/types/user-config.d.ts +0 -11
  196. package/lib/types.d.ts +23 -0
  197. package/lib/types.js +2 -0
  198. package/lib/types.js.map +1 -0
  199. package/lib/util.d.ts +20 -0
  200. package/lib/util.js +67 -0
  201. package/lib/util.js.map +1 -0
  202. package/lib/utils.d.ts +2 -30
  203. package/lib/utils.js +0 -56
  204. package/lib/utils.js.map +1 -1
  205. package/lib/validators/class.d.ts +7 -0
  206. package/lib/validators/class.js +217 -0
  207. package/lib/validators/class.js.map +1 -0
  208. package/lib/validators/interface.d.ts +5 -0
  209. package/lib/validators/interface.js +16 -0
  210. package/lib/validators/interface.js.map +1 -0
  211. package/lib/visitor.d.ts +35 -0
  212. package/lib/visitor.js +29 -0
  213. package/lib/visitor.js.map +1 -0
  214. package/package.json +14 -10
  215. package/lib/gir-parser.d.ts +0 -2
  216. package/lib/gir-parser.js +0 -69
  217. package/lib/gir-parser.js.map +0 -1
  218. package/lib/injection/callbacks/node-gtk/index.d.ts +0 -2
  219. package/lib/injection/callbacks/node-gtk/index.js +0 -2
  220. package/lib/injection/callbacks/node-gtk/index.js.map +0 -1
  221. package/lib/injection/classes/node-gtk/gdk-4.0.d.ts +0 -2
  222. package/lib/injection/classes/node-gtk/gdk-4.0.js +0 -32
  223. package/lib/injection/classes/node-gtk/gdk-4.0.js.map +0 -1
  224. package/lib/injection/classes/node-gtk/gio-2.0.d.ts +0 -2
  225. package/lib/injection/classes/node-gtk/gio-2.0.js +0 -14
  226. package/lib/injection/classes/node-gtk/gio-2.0.js.map +0 -1
  227. package/lib/injection/classes/node-gtk/glib-2.0.d.ts +0 -2
  228. package/lib/injection/classes/node-gtk/glib-2.0.js +0 -19
  229. package/lib/injection/classes/node-gtk/glib-2.0.js.map +0 -1
  230. package/lib/injection/classes/node-gtk/gobject-2.0.d.ts +0 -2
  231. package/lib/injection/classes/node-gtk/gobject-2.0.js +0 -66
  232. package/lib/injection/classes/node-gtk/gobject-2.0.js.map +0 -1
  233. package/lib/injection/classes/node-gtk/graphene-1.0.d.ts +0 -2
  234. package/lib/injection/classes/node-gtk/graphene-1.0.js +0 -133
  235. package/lib/injection/classes/node-gtk/graphene-1.0.js.map +0 -1
  236. package/lib/injection/classes/node-gtk/gtk-3.0.d.ts +0 -2
  237. package/lib/injection/classes/node-gtk/gtk-3.0.js +0 -31
  238. package/lib/injection/classes/node-gtk/gtk-3.0.js.map +0 -1
  239. package/lib/injection/classes/node-gtk/gtk-4.0.d.ts +0 -2
  240. package/lib/injection/classes/node-gtk/gtk-4.0.js +0 -52
  241. package/lib/injection/classes/node-gtk/gtk-4.0.js.map +0 -1
  242. package/lib/injection/classes/node-gtk/index.d.ts +0 -2
  243. package/lib/injection/classes/node-gtk/index.js +0 -19
  244. package/lib/injection/classes/node-gtk/index.js.map +0 -1
  245. package/lib/injection/classes/node-gtk/pango-1.0.d.ts +0 -2
  246. package/lib/injection/classes/node-gtk/pango-1.0.js +0 -31
  247. package/lib/injection/classes/node-gtk/pango-1.0.js.map +0 -1
  248. package/lib/types/build-type.d.ts +0 -1
  249. package/lib/types/build-type.js +0 -2
  250. package/lib/types/build-type.js.map +0 -1
  251. package/lib/types/environment.d.ts +0 -1
  252. package/lib/types/environment.js +0 -2
  253. package/lib/types/environment.js.map +0 -1
  254. package/lib/types/gir-any-type.d.ts +0 -5
  255. package/lib/types/gir-any-type.js +0 -2
  256. package/lib/types/gir-any-type.js.map +0 -1
  257. package/lib/types/gir-array-type.d.ts +0 -20
  258. package/lib/types/gir-array-type.js +0 -3
  259. package/lib/types/gir-array-type.js.map +0 -1
  260. package/lib/types/gir-boolean.d.ts +0 -1
  261. package/lib/types/gir-boolean.js +0 -2
  262. package/lib/types/gir-boolean.js.map +0 -1
  263. package/lib/types/gir-boxed-element.d.ts +0 -15
  264. package/lib/types/gir-boxed-element.js +0 -2
  265. package/lib/types/gir-boxed-element.js.map +0 -1
  266. package/lib/types/gir-c-include.d.ts +0 -7
  267. package/lib/types/gir-c-include.js +0 -2
  268. package/lib/types/gir-c-include.js.map +0 -1
  269. package/lib/types/gir-callable-attrs.d.ts +0 -15
  270. package/lib/types/gir-callable-attrs.js +0 -3
  271. package/lib/types/gir-callable-attrs.js.map +0 -1
  272. package/lib/types/gir-callable-param.d.ts +0 -7
  273. package/lib/types/gir-callable-param.js +0 -2
  274. package/lib/types/gir-callable-param.js.map +0 -1
  275. package/lib/types/gir-direction.d.ts +0 -7
  276. package/lib/types/gir-direction.js +0 -9
  277. package/lib/types/gir-direction.js.map +0 -1
  278. package/lib/types/gir-doc-element.d.ts +0 -68
  279. package/lib/types/gir-doc-element.js +0 -2
  280. package/lib/types/gir-doc-element.js.map +0 -1
  281. package/lib/types/gir-implements.d.ts +0 -8
  282. package/lib/types/gir-implements.js +0 -2
  283. package/lib/types/gir-implements.js.map +0 -1
  284. package/lib/types/gir-include.d.ts +0 -9
  285. package/lib/types/gir-include.js +0 -2
  286. package/lib/types/gir-include.js.map +0 -1
  287. package/lib/types/gir-info-attrs.d.ts +0 -13
  288. package/lib/types/gir-info-attrs.js +0 -2
  289. package/lib/types/gir-info-attrs.js.map +0 -1
  290. package/lib/types/gir-info-elements.d.ts +0 -5
  291. package/lib/types/gir-info-elements.js +0 -2
  292. package/lib/types/gir-info-elements.js.map +0 -1
  293. package/lib/types/gir-package.d.ts +0 -7
  294. package/lib/types/gir-package.js +0 -2
  295. package/lib/types/gir-package.js.map +0 -1
  296. package/lib/types/gir-prerequisite.d.ts +0 -5
  297. package/lib/types/gir-prerequisite.js +0 -2
  298. package/lib/types/gir-prerequisite.js.map +0 -1
  299. package/lib/types/gir-transfer-ownership-type.d.ts +0 -5
  300. package/lib/types/gir-transfer-ownership-type.js +0 -7
  301. package/lib/types/gir-transfer-ownership-type.js.map +0 -1
  302. package/lib/types/gir-transfer-ownership.d.ts +0 -9
  303. package/lib/types/gir-transfer-ownership.js +0 -2
  304. package/lib/types/gir-transfer-ownership.js.map +0 -1
  305. package/lib/types/gir-type.d.ts +0 -14
  306. package/lib/types/gir-type.js +0 -2
  307. package/lib/types/gir-type.js.map +0 -1
  308. package/lib/types/gir-var-args.d.ts +0 -5
  309. package/lib/types/gir-var-args.js +0 -2
  310. package/lib/types/gir-var-args.js.map +0 -1
  311. package/lib/types/module-type.d.ts +0 -1
  312. package/lib/types/module-type.js +0 -2
  313. package/lib/types/module-type.js.map +0 -1
package/lib/gir-module.js CHANGED
@@ -1,22 +1,20 @@
1
1
  // TODO move this class into a web-worker? https://www.npmjs.com/package/web-worker
2
- import { Transformation, FULL_TYPE_MAP, PRIMITIVE_TYPE_MAP, ARRAY_TYPE_MAP, IGNORE_GIR_TYPE_TS_DOC_TYPES, } from './transformation.js';
3
- import { STATIC_NAME_ALREADY_EXISTS, MAX_CLASS_PARENT_DEPTH } from './constants.js';
2
+ /* eslint-disable @typescript-eslint/no-unused-vars */
3
+ import { IGNORE_GIR_TYPE_TS_DOC_TYPES, Transformation } from './transformation.js';
4
4
  import { Logger } from './logger.js';
5
- import { Injector } from './injection/injector.js';
6
- import { GirFactory } from './gir-factory.js';
7
- import { ConflictResolver } from './conflict-resolver.js';
8
5
  import { DependencyManager } from './dependency-manager.js';
9
- import { NO_TSDATA, WARN_NOT_FOUND_TYPE, WARN_CONSTANT_ALREADY_EXPORTED, WARN_DUPLICATE_SYMBOL, WARN_DUPLICATE_PARAMETER, WARN_DUPLICATE_ENUM_IDENTIFIER, } from './messages.js';
10
- import { isEqual, find, clone, girBool, removeNamespace, addNamespace, girElementIsIntrospectable, underscores, } from './utils.js';
6
+ import { find } from './utils.js';
11
7
  import { SymTable } from './symtable.js';
12
8
  import { LibraryVersion } from './library-version.js';
13
- import { GirDirection } from './types/index.js';
9
+ import { ClosureType, TypeIdentifier, PromiseType, VoidType, BooleanType, TupleType, BinaryType, NullableType, ObjectType, } from './gir.js';
10
+ import { IntrospectedAlias } from './gir/alias.js';
11
+ import { IntrospectedBase } from './gir/base.js';
12
+ import { IntrospectedBaseClass, IntrospectedClass, IntrospectedRecord, IntrospectedInterface } from './gir/class.js';
13
+ import { IntrospectedConstant } from './gir/const.js';
14
+ import { IntrospectedEnum, IntrospectedError } from './gir/enum.js';
15
+ import { IntrospectedFunction, IntrospectedCallback, } from './gir/function.js';
16
+ import { isPrimitiveType } from './gir/util.js';
14
17
  export class GirModule {
15
- config;
16
- /**
17
- * Array of all gir modules
18
- */
19
- static allGirModules = [];
20
18
  /**
21
19
  * E.g. 'Gtk'
22
20
  */
@@ -24,7 +22,7 @@ export class GirModule {
24
22
  /**
25
23
  * E.g. '4.0'
26
24
  */
27
- version = '0.0';
25
+ version;
28
26
  /**
29
27
  * E.g. 'Gtk-4.0'
30
28
  */
@@ -35,6 +33,7 @@ export class GirModule {
35
33
  */
36
34
  importNamespace;
37
35
  importName;
36
+ prefixes = [];
38
37
  /**
39
38
  * The version of the library as an object.
40
39
  * E.g. `{ major: 4, minor: 0, patch: 0 }` or as string `4.0.0`'
@@ -51,44 +50,39 @@ export class GirModule {
51
50
  get allDependencies() {
52
51
  return [...new Set([...this.dependencies, ...this.transitiveDependencies])];
53
52
  }
54
- repo;
55
- ns = { $: { name: '', version: '0.0' } };
56
53
  /**
57
54
  * Used to find namespaces that are used in other modules
58
55
  */
59
56
  symTable;
60
57
  transformation;
61
- girFactory = new GirFactory();
62
58
  dependencyManager;
63
- conflictResolver;
64
59
  log;
65
- inject;
66
60
  extends;
67
61
  /**
68
62
  * To prevent constants from being exported twice, the names already exported are saved here for comparison.
69
63
  * Please note: Such a case is only known for Zeitgeist-2.0 with the constant "ATTACHMENT"
70
64
  */
71
65
  constNames = {};
72
- constructor(xml, config) {
66
+ name;
67
+ c_prefixes;
68
+ _members;
69
+ _enum_constants;
70
+ _resolve_names = new Map();
71
+ __dts__references;
72
+ package_version;
73
+ parent;
74
+ config;
75
+ constructor(repo, name, version, prefixes, config) {
76
+ this.name = name;
77
+ this.version = version;
78
+ this.c_prefixes = [...prefixes];
79
+ this.package_version = ['0', '0'];
73
80
  this.config = config;
74
- this.repo = xml.repository;
75
- if (!this.repo.namespace || !this.repo.namespace.length) {
76
- throw new Error(`Namespace not found!`);
77
- }
78
81
  this.dependencyManager = DependencyManager.getInstance(this.config);
79
- this.dependencies = this.dependencyManager.fromGirIncludes(this.repo.include || []);
80
- this.ns = this.repo.namespace[0];
81
- this.namespace = this.ns.$.name;
82
- this.version = this.ns.$.version;
83
- this.packageName = `${this.namespace}-${this.version}`;
84
- this.libraryVersion = new LibraryVersion(this.ns.constant, this.version);
85
- this.transformation = new Transformation(config);
86
- this.log = new Logger(config.environment, config.verbose, this.packageName || 'GirModule');
87
- this.conflictResolver = new ConflictResolver(config.environment, config.verbose);
88
- this.inject = new Injector(this.config.environment);
89
- this.importNamespace = this.transformation.transformModuleNamespaceName(this.packageName);
90
- this.importName = this.transformation.transformImportName(this.packageName);
91
- this.symTable = new SymTable(this.config, this.packageName, this.namespace);
82
+ this.dependencies = this.dependencyManager.fromGirIncludes(repo.include || []);
83
+ }
84
+ get ns() {
85
+ return this;
92
86
  }
93
87
  checkTransitiveDependencies(transitiveDependencies) {
94
88
  // Always pull in GObject-2.0, as we may need it for e.g. GObject-2.0.type
@@ -121,7 +115,8 @@ export class GirModule {
121
115
  tags: [],
122
116
  };
123
117
  if (girDoc.doc?.[0]?._) {
124
- let text = String(girDoc.doc?.[0]?._ || '');
118
+ // TODO: Somehow _ is not a string
119
+ let text = `${girDoc.doc?.[0]?._ || ''}`;
125
120
  text = this.transformation.transformGirDocText(text);
126
121
  tsDoc.text = text;
127
122
  }
@@ -140,22 +135,16 @@ export class GirModule {
140
135
  return tags;
141
136
  }
142
137
  getTsDocReturnTags(girElement) {
143
- const girReturnValue = girElement?.['return-value']?.[0];
144
- if (!girReturnValue || !girReturnValue.doc?.[0]?._) {
138
+ const girReturnValue = girElement?.returnTypeDoc;
139
+ if (!girReturnValue) {
145
140
  return [];
146
141
  }
147
- try {
148
- const returnTag = {
149
- tagName: 'returns',
150
- paramName: '',
151
- text: this.transformation.transformGirDocTagText(String(girReturnValue.doc[0]._)),
152
- };
153
- return [returnTag];
154
- }
155
- catch (error) {
156
- console.debug('Error: on getTsDocReturnTags, girReturnValue.doc: ', girReturnValue.doc);
157
- throw error;
158
- }
142
+ const returnTag = {
143
+ tagName: 'returns',
144
+ paramName: '',
145
+ text: this.transformation.transformGirDocTagText(girReturnValue),
146
+ };
147
+ return [returnTag];
159
148
  }
160
149
  getTsDocInParamTags(inParams) {
161
150
  const tags = [];
@@ -163,2118 +152,358 @@ export class GirModule {
163
152
  return tags;
164
153
  }
165
154
  for (const inParam of inParams) {
166
- if (!inParam._tsData) {
167
- throw new Error(NO_TSDATA('getTsDocInParamTags'));
168
- }
169
- if (!inParam._tsData?.doc) {
170
- inParam._tsData.doc = this.getTsDoc(inParam);
171
- }
172
- if (inParam._tsData?.name) {
155
+ if (inParam.name) {
173
156
  tags.push({
174
- paramName: inParam._tsData.name,
157
+ paramName: inParam.name,
175
158
  tagName: 'param',
176
- text: inParam._tsData.doc.text
177
- ? this.transformation.transformGirDocTagText(inParam._tsData.doc.text)
178
- : '',
159
+ text: typeof inParam.doc === 'string' ? this.transformation.transformGirDocTagText(inParam.doc) : '',
179
160
  });
180
161
  }
181
162
  }
182
163
  return tags;
183
164
  }
184
- annotateFunctionArguments(girFunc) {
185
- const funcName = girFunc._fullSymName;
186
- if (funcName && girFunc.parameters) {
187
- for (const girParams of girFunc.parameters) {
188
- if (girParams.parameter) {
189
- for (const girParam of girParams.parameter) {
190
- girParam._module = this;
191
- if (girParam.$ && girParam.$.name) {
192
- girParam._fullSymName = `${funcName}.${girParam.$.name}`;
193
- }
194
- }
195
- }
196
- }
197
- }
165
+ registerResolveName(resolveName, namespace, name) {
166
+ this._resolve_names.set(resolveName, new TypeIdentifier(name, namespace));
198
167
  }
199
- annotateFunctionReturn(girFunc) {
200
- const retVals = girFunc['return-value'];
201
- if (retVals && girFunc._fullSymName)
202
- for (const retVal of retVals) {
203
- retVal._module = this;
204
- retVal.girTypeName = 'callable-return';
205
- if (retVal.$ && retVal.$.name) {
206
- retVal._fullSymName = `${girFunc._fullSymName}.${retVal.$.name}`;
207
- }
208
- }
209
- }
210
- /**
211
- * Functions which are not part of a class
212
- * @param girFuncs
213
- */
214
- annotateFunctions(girFuncs) {
215
- if (Array.isArray(girFuncs))
216
- for (const girFunc of girFuncs) {
217
- if (girFunc?.$?.name) {
218
- // girFunc._girType = girType
219
- girFunc._fullSymName = `${this.namespace}.${girFunc.$.name}`;
220
- this.annotateFunctionArguments(girFunc);
221
- this.annotateFunctionReturn(girFunc);
222
- }
223
- }
224
- }
225
- /**
226
- * Functions and methods of a class
227
- */
228
- annotateMethods(girClass, girFuncs) {
229
- if (Array.isArray(girFuncs))
230
- for (const girFunc of girFuncs) {
231
- if (girFunc?.$?.name) {
232
- // girFunc._girType = girType
233
- // girFunc._tsType = tsType
234
- girFunc._class = girClass;
235
- const nsName = girClass ? girClass._fullSymName : this.namespace;
236
- if (nsName)
237
- girFunc._fullSymName = `${nsName}.${girFunc.$.name}`;
238
- this.annotateFunctionArguments(girFunc);
239
- this.annotateFunctionReturn(girFunc);
240
- }
241
- }
242
- }
243
- /**
244
- * Variables which are not part of a class
245
- */
246
- annotateVariables(girVars) {
247
- for (const girVar of girVars) {
248
- girVar._module = this;
249
- if (girVar.$ && girVar.$.name) {
250
- girVar._fullSymName = `${this.namespace}.${girVar.$.name}`;
251
- }
168
+ get members() {
169
+ if (!this._members) {
170
+ this._members = new Map();
252
171
  }
172
+ return this._members;
253
173
  }
254
- /**
255
- * Fields are variables which are part of a class
256
- * @see https://www.typescriptlang.org/docs/handbook/2/classes.html#fields
257
- */
258
- annotateFields(girClass, girVars) {
259
- for (const girVar of girVars) {
260
- const nsName = girClass ? girClass._fullSymName : this.namespace;
261
- girVar._module = this;
262
- if (girClass) {
263
- girVar._class = girClass;
264
- }
265
- if (girVar.$ && girVar.$.name && nsName) {
266
- girVar._fullSymName = `${nsName}.${girVar.$.name}`;
267
- }
268
- }
269
- }
270
- annotateClass(girClass) {
271
- girClass._module = this;
272
- girClass._fullSymName = `${this.namespace}.${girClass.$.name}`;
273
- const constructors = Array.isArray(girClass.constructor) ? girClass.constructor : [];
274
- const signals = (girClass.signal ||
275
- girClass['glib:signal'] ||
276
- []);
277
- const functions = girClass.function || [];
278
- const methods = girClass.method || [];
279
- const vMethods = girClass['virtual-method'] || new Array();
280
- const properties = girClass.property;
281
- const fields = girClass.field;
282
- this.annotateMethods(girClass, constructors);
283
- this.annotateMethods(girClass, functions);
284
- this.annotateMethods(girClass, methods);
285
- this.annotateMethods(girClass, vMethods);
286
- this.annotateMethods(girClass, signals);
287
- if (properties)
288
- this.annotateFields(girClass, properties);
289
- if (fields)
290
- this.annotateFields(girClass, fields);
291
- }
292
- /**
293
- * Annotates the custom `_module`, `_fullSymName` and `_girType` properties.
294
- * Also registers the element on the `symTable`.
295
- * @param girElements
296
- * @param girType
297
- */
298
- annotateAndRegisterGirElement(girElements) {
299
- for (const girElement of girElements) {
300
- if (girElement?.$ && girElement.$.name) {
301
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
302
- if (!girElementIsIntrospectable(girElement))
303
- continue;
304
- girElement._module = this;
305
- girElement._fullSymName = `${this.namespace}.${girElement.$.name}`;
306
- if (this.symTable.get(this.allDependencies, girElement._fullSymName)) {
307
- this.log.warn(WARN_DUPLICATE_SYMBOL(girElement._fullSymName));
308
- }
309
- this.symTable.set(this.allDependencies, girElement._fullSymName, girElement);
310
- }
174
+ get enum_constants() {
175
+ if (!this._enum_constants) {
176
+ this._enum_constants = new Map();
311
177
  }
178
+ return this._enum_constants;
312
179
  }
313
- /**
314
- * TODO: find better name for this method
315
- * @param girVar
316
- * @param fullTypeName
317
- * @returns e.g.
318
- * ```ts
319
- * {
320
- * namespace: "Gtk",
321
- * resValue: "Gtk.Widget"
322
- * }
323
- *
324
- */
325
- fullTypeLookup(girVar, fullTypeName) {
326
- let resValue = '';
327
- let namespace = '';
328
- if (!fullTypeName) {
329
- return {
330
- value: resValue,
331
- fullTypeName,
332
- namespace,
333
- };
334
- }
335
- // Fully qualify our type name
336
- if (!fullTypeName.includes('.')) {
337
- let tryFullTypeName = '';
338
- if (!resValue && girVar._module && girVar._module !== this) {
339
- tryFullTypeName = `${girVar._module.namespace}.${fullTypeName}`;
340
- resValue = this.fullTypeLookupWithNamespace(tryFullTypeName).value;
341
- if (resValue) {
342
- fullTypeName = tryFullTypeName;
343
- namespace = girVar._module.namespace;
344
- }
345
- }
346
- if (!resValue) {
347
- tryFullTypeName = `${this.namespace}.${fullTypeName}`;
348
- resValue = this.fullTypeLookupWithNamespace(tryFullTypeName).value;
349
- if (resValue) {
350
- fullTypeName = tryFullTypeName;
351
- namespace = this.namespace;
352
- }
353
- }
354
- const girClass = girVar._class;
355
- if (!resValue && girClass?._module?.namespace && girClass._module !== this) {
356
- tryFullTypeName = `${girClass._module.namespace}.${fullTypeName}`;
357
- resValue = this.fullTypeLookupWithNamespace(tryFullTypeName).value;
358
- if (resValue) {
359
- fullTypeName = tryFullTypeName;
360
- namespace = girClass?._module?.namespace;
361
- }
362
- }
363
- }
364
- if (!resValue && fullTypeName) {
365
- resValue = this.fullTypeLookupWithNamespace(fullTypeName).value;
366
- }
367
- return {
368
- value: resValue,
369
- namespace,
370
- };
371
- }
372
- /**
373
- * this method needs to be refactored, an array can also be an array of an array for example
374
- * @param girVar
375
- * @returns
376
- */
377
- getArrayData(girVar) {
378
- let arrayType = null;
379
- let arrCType;
380
- let isArray = false;
381
- let overrideTypeName;
382
- let typeArray;
383
- let collection;
384
- if (girVar.array) {
385
- collection = girVar.array;
386
- }
387
- else if (/^GLib.S?List$/.test(girVar.type?.[0].$?.name || '')) {
388
- // This converts GLib.List<T> / GLib.SList<T> to T[]
389
- collection = girVar.type;
390
- }
391
- if (collection && collection.length > 0) {
392
- isArray = true;
393
- typeArray = collection[0].type;
394
- if (collection[0].$) {
395
- const ea = collection[0].$;
396
- arrCType = ea['c:type'];
397
- }
398
- }
399
- if (typeArray && typeArray?.length > 0) {
400
- arrayType = typeArray[0];
401
- }
402
- if (this.config.environment == 'gjs' && isArray && arrayType?.$?.name && ARRAY_TYPE_MAP[arrayType.$.name]) {
403
- isArray = false;
404
- overrideTypeName = ARRAY_TYPE_MAP[arrayType.$.name];
405
- }
406
- return {
407
- arrCType,
408
- arrayType,
409
- isArray,
410
- overrideTypeName,
411
- };
412
- }
413
- /**
414
- * Get the typescript type of a GirElement like a `GirPropertyElement` or `GirCallableReturn`
415
- * @param girVar
416
- */
417
- getTsType(girVar, tsClass, girTypeName, defaults = {}) {
418
- let type = girVar.type?.[0];
419
- let fullTypeName = null;
420
- let typeName = defaults.type || '';
421
- let isFunction = defaults.isFunction || false;
422
- let isCallback = defaults.isCallback || false;
423
- const nullable = this.typeIsNullable(girVar, girTypeName) || defaults.nullable || false;
424
- const optional = this.typeIsOptional(girVar, girTypeName) || defaults.optional || false;
425
- const girCallbacks = [];
426
- const array = this.getArrayData(girVar);
427
- if (array.overrideTypeName) {
428
- typeName = array.overrideTypeName;
429
- }
430
- if (array.arrayType) {
431
- type = array.arrayType;
432
- }
433
- const cType = type?.$ ? type.$['c:type'] : array.arrCType;
434
- fullTypeName = type?.$?.name || null;
435
- const callbacks = girVar.callback;
436
- if (!typeName && callbacks?.length) {
437
- for (const girCallback of callbacks) {
438
- if (!girElementIsIntrospectable(girCallback))
439
- continue;
440
- if (!girCallback._tsData) {
441
- const tsCallback = this.getFunctionTsData(girCallback, 'callback', tsClass, {
442
- isStatic: false,
443
- isArrowType: true,
444
- isGlobal: false,
445
- isVirtual: false,
446
- returnType: null,
447
- generics: [],
448
- });
449
- if (!tsCallback)
450
- continue;
451
- girCallback._tsData = {
452
- ...tsCallback,
453
- girTypeName: 'callback',
454
- tsTypeName: this.girFactory.girTypeNameToTsTypeName('callback', false),
455
- tsCallbackInterface: this.getCallbackInterfaceTsData(girCallback),
456
- doc: this.getTsDoc(girCallback),
457
- overloads: [],
458
- };
459
- }
460
- if (girCallback._tsData) {
461
- girCallbacks.push(girCallback);
462
- isFunction = true;
463
- isCallback = true;
464
- }
465
- }
466
- }
467
- if (!isFunction) {
468
- const res = this.fullTypeLookup(girVar, fullTypeName);
469
- if (res.value) {
470
- typeName = res.value;
471
- fullTypeName = typeName;
180
+ accept(visitor) {
181
+ for (const key of [...this.members.keys()]) {
182
+ const member = this.members.get(key);
183
+ if (!member)
184
+ continue;
185
+ if (Array.isArray(member)) {
186
+ this.members.set(key, member.map((m) => {
187
+ return m.accept(visitor);
188
+ }));
472
189
  }
473
- }
474
- if (!typeName && type?.$?.name && PRIMITIVE_TYPE_MAP[type.$.name]) {
475
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
476
- typeName = PRIMITIVE_TYPE_MAP[type.$.name];
477
- }
478
- if (cType) {
479
- const parsedCType = PRIMITIVE_TYPE_MAP[cType];
480
- if (!typeName && parsedCType) {
481
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
482
- typeName = parsedCType;
190
+ else {
191
+ this.members.set(key, member.accept(visitor));
483
192
  }
484
193
  }
485
- if (!typeName) {
486
- typeName = 'any';
487
- const logName = cType || fullTypeName || girVar.$.name || '';
488
- this.log.warn(WARN_NOT_FOUND_TYPE(logName));
489
- }
490
- // TODO: transform array to type with generics?
491
- const tsType = this.girFactory.newTsType({
492
- ...defaults,
493
- type: typeName,
494
- optional,
495
- nullable,
496
- callbacks: girCallbacks,
497
- isArray: array.isArray,
498
- isFunction,
499
- isCallback,
500
- });
501
- return tsType;
194
+ return this;
502
195
  }
503
- /**
504
- *
505
- * @param girFunc
506
- * @returns
507
- */
508
- getReturnType(girFunc, tsClass, generics = []) {
509
- const girTypeName = 'callable-return';
510
- let outArrayLengthIndex = -1;
511
- if (girFunc['return-value'] && girFunc['return-value'].length > 1) {
512
- throw new Error('Several return values found!');
513
- }
514
- // There are no multiple return values, so we always use index 0
515
- const girVar = girFunc['return-value']?.[0] || null;
516
- // We still use an array to allow multiple return values for later
517
- const returnTypes = [];
518
- if (girVar) {
519
- returnTypes.push(this.getTsType(girVar, tsClass, girTypeName, { generics }));
520
- outArrayLengthIndex = girVar.array && girVar.array[0].$?.length ? Number(girVar.array[0].$.length) : -1;
521
- }
522
- else {
523
- returnTypes.push(this.girFactory.newTsType({ type: 'void', generics }));
524
- }
525
- const retTypeIsVoid = returnTypes.length === 1 && returnTypes[0].type === 'void';
526
- return { returnTypes, outArrayLengthIndex, retTypeIsVoid };
527
- }
528
- arrayLengthIndexLookup(girVar) {
529
- if (!girVar.array)
530
- return -1;
531
- const arr = girVar.array[0];
532
- if (!arr.$)
533
- return -1;
534
- if (arr.$.length) {
535
- return parseInt(arr.$.length);
536
- }
537
- return -1;
538
- }
539
- closureDataIndexLookup(girVar) {
540
- if (!girVar.$.closure)
541
- return -1;
542
- return parseInt(girVar.$.closure);
543
- }
544
- destroyDataIndexLookup(girVar) {
545
- if (!girVar.$.destroy)
546
- return -1;
547
- return parseInt(girVar.$.destroy);
548
- }
549
- processParams(params, skip, getIndex) {
550
- for (const param of params) {
551
- const index = getIndex(param);
552
- if (index < 0)
553
- continue;
554
- if (index >= params.length)
555
- continue;
556
- skip.push(params[index]);
557
- }
196
+ getImportsForCPrefix(c_prefix) {
197
+ return this.parent.namespacesForPrefix(c_prefix);
558
198
  }
559
- /**
560
- * Checks if the parameter is nullable (which results in ` | null`).
561
- *
562
- * @param girVar girVar to test
563
- */
564
- typeIsNullable(girVar, girTypeName) {
565
- const a = girVar.$;
566
- if (!a)
567
- return false;
568
- const type = girVar.type?.[0];
569
- const cType = type?.$?.['c:type'];
570
- // Ignore depreciated `allow-none` if one of the new implementation `optional` or `nullable` is set
571
- if (a.optional || a.nullable) {
572
- return girBool(a.nullable);
573
- }
574
- if (girTypeName === 'constant') {
575
- return false; // constants are never nullable
576
- }
577
- // UTF-8 string pointers can be null, e.g. `gchar*`, see https://github.com/gjsify/ts-for-gir/issues/108
578
- if (type?.$?.name === 'utf8' && !cType?.startsWith('const ') && cType?.endsWith('*')) {
579
- return true;
580
- }
581
- // If the default value is NULL, handle this as nullable
582
- if (a['default-value'] === 'NULL') {
583
- return true;
584
- }
585
- return girBool(a.nullable) || girBool(a['allow-none']) || girBool(a['null-ok']);
199
+ // TODO: Move this into the generator
200
+ hasImport(name) {
201
+ return this.dependencies.some((dep) => dep.importName === name);
586
202
  }
587
- /**
588
- * Checks if the parameter is optional (which results in `foo?: bar`).
589
- * @param girVar girVar to test
590
- */
591
- typeIsOptional(girVar, girTypeName) {
592
- const a = girVar.$;
593
- if (!a)
594
- return false;
595
- // Ignore depreciated `allow-none` if one of the new implementation `optional` or `nullable` is set
596
- if (a.optional || a.nullable) {
597
- return girBool(a.optional);
203
+ _getImport(name) {
204
+ if (name === this.name) {
205
+ return this;
598
206
  }
599
- if (girTypeName === 'constant') {
600
- return false; // constants are never optional
601
- }
602
- return girBool(a.optional) || girBool(a['allow-none']) || girBool(a['null-ok']);
603
- }
604
- /**
605
- * Checks if the property is readonly.
606
- * @param girCallback
607
- */
608
- typeIsReadonly(girProp) {
609
- const cType = girProp.type?.[0].$?.['c:type'];
610
- return (!girBool(girProp.$.writable) ||
611
- girBool(girProp.$['construct-only']) ||
612
- (cType ? cType.startsWith('const ') : false) // c type is const and therefore readonly, isn't?
613
- );
614
- }
615
- setParameterTsData(girParam, girParams, paramNames, skip, parent) {
616
- const girTypeName = 'callable-param';
617
- // I think it's safest to force inout params to have the
618
- // same type for in and out
619
- const tsType = this.getTsType(girParam, parent.parent, girTypeName);
620
- // const optDirection = girParam.$.direction
621
- if (girParam._tsData) {
622
- // this.log.warn('[setParameterTsData] _tsData already set!')
623
- return girParam._tsData;
624
- }
625
- if (tsType.isCallback) {
626
- throw new Error('Callback type is not implemented here');
627
- }
628
- let paramName = this.transformation.transformParameterName(girParam, false);
629
- if (paramNames.includes(paramName)) {
630
- this.log.warn(WARN_DUPLICATE_PARAMETER(paramName, girParam._fullSymName));
631
- paramName += '_';
632
- }
633
- paramNames.push(paramName);
634
- // In Typescript no optional parameters are allowed if the following ones are not optional
635
- if (tsType.optional) {
636
- const index = girParams.indexOf(girParam);
637
- const following = girParams
638
- .slice(index)
639
- .filter(() => skip.indexOf(girParam) === -1)
640
- .filter((p) => p.$.direction !== GirDirection.Out);
641
- if (following.some((p) => !this.typeIsOptional(p, girTypeName))) {
642
- tsType.optional = false;
207
+ const dep = this.dependencies.find((dep) => dep.namespace === name) ??
208
+ this.transitiveDependencies.find((dep) => dep.namespace === name);
209
+ // Handle finding imports via their other prefixes
210
+ if (!dep) {
211
+ this.log.info(`Failed to find namespace ${name} in dependencies, resolving via c:prefixes`);
212
+ // TODO: It might make more sense to move this conversion _before_
213
+ // the _getImport call.
214
+ const resolvedNamespaces = this.dependencyManager.namespacesForPrefix(name);
215
+ if (resolvedNamespaces.length > 0) {
216
+ this.log.info(`Found namespaces for prefix ${name}: ${resolvedNamespaces.map((r) => `${r.name} (${r.version})`).join(', ')}`);
643
217
  }
644
- }
645
- const tsParam = {
646
- name: paramName,
647
- type: [tsType],
648
- isRest: false,
649
- girTypeName,
650
- doc: this.getTsDoc(girParam),
651
- parent,
652
- };
653
- girParam._tsData = tsParam;
654
- // // TODO: remove this, wee need a special solution for Gio.AsyncReadyCallback instead
655
- girParam = this.inject.toParameterType(girParam);
656
- return girParam._tsData;
657
- }
658
- getInstanceParameterTsData(instanceParameter) {
659
- const typeName = instanceParameter.type?.[0]?.$?.name || undefined;
660
- const rec = typeName ? this.ns.record?.find((r) => r.$.name == typeName) : undefined;
661
- const structFor = rec?.$['glib:is-gtype-struct-for'];
662
- if (structFor && instanceParameter.$.name) {
663
- // TODO: Should use of a constructor, and even of an instance, be discouraged?
664
- return {
665
- name: instanceParameter.$.name,
666
- structFor,
667
- };
668
- }
669
- return undefined;
670
- }
671
- setParametersTsData(outArrayLengthIndex, girParams = [], parent) {
672
- const outParams = [];
673
- const inParams = [];
674
- const paramNames = [];
675
- const instanceParameters = [];
676
- if (girParams && girParams.length > 0) {
677
- for (const girParam of girParams) {
678
- const params = girParam?.parameter || [];
679
- // Instance parameter needs to be exposed for class methods (see comment above getClassMethods())
680
- const instanceParameter = girParams[0]['instance-parameter']?.[0];
681
- if (instanceParameter) {
682
- instanceParameter._tsData = this.getInstanceParameterTsData(instanceParameter);
683
- if (instanceParameter._tsData) {
684
- instanceParameters.push(instanceParameter);
685
- }
218
+ for (const resolvedNamespace of resolvedNamespaces) {
219
+ if (resolvedNamespace.name === this.name && resolvedNamespace.version === this.version) {
220
+ return this;
686
221
  }
687
- if (params.length) {
688
- const skip = outArrayLengthIndex === -1 ? [] : [params[outArrayLengthIndex]];
689
- this.processParams(params, skip, (girVar) => this.arrayLengthIndexLookup(girVar));
690
- this.processParams(params, skip, (girVar) => this.closureDataIndexLookup(girVar));
691
- this.processParams(params, skip, (girVar) => this.destroyDataIndexLookup(girVar));
692
- for (const param of params) {
693
- if (skip.includes(param)) {
694
- continue;
695
- }
696
- param._tsData = this.setParameterTsData(param, params, paramNames, skip, parent);
697
- const optDirection = param.$.direction;
698
- if (optDirection === GirDirection.Out ||
699
- optDirection === GirDirection.Inout ||
700
- optDirection === GirDirection.InOut) {
701
- outParams.push(param);
702
- if (optDirection === GirDirection.Out)
703
- continue;
704
- }
705
- inParams.push(param);
706
- }
222
+ const dep = this.dependencies.find((dep) => dep.namespace === resolvedNamespace.name && dep.version === resolvedNamespace.version) ??
223
+ this.transitiveDependencies.find((dep) => dep.namespace === resolvedNamespace.name && dep.version === resolvedNamespace.version);
224
+ if (dep) {
225
+ return this.parent.namespace(resolvedNamespace.name, dep.version);
707
226
  }
708
227
  }
709
228
  }
710
- return { outParams, paramNames, inParams, instanceParameters };
711
- }
712
- getVariableTsData(girVar, girTypeName, tsTypeName, tsClass, optional = false, nullable = false, allowQuotes = false, generics = []) {
713
- if (!girVar.$.name)
714
- return undefined;
715
- if (!girVar ||
716
- !girVar.$ ||
717
- !girBool(girVar.$.introspectable, true) ||
718
- girBool(girVar.$.private)) {
719
- return undefined;
720
- }
721
- if (girVar._tsData) {
722
- // this.log.warn('[getVariableTsData] _tsData already set!')
723
- return girVar._tsData;
724
- }
725
- let name = girVar.$.name;
726
- if (tsTypeName === 'constructor-property') {
727
- name = this.transformation.transformConstructorPropertyName(girVar.$.name, allowQuotes);
229
+ let version = dep?.version;
230
+ if (!version) {
231
+ version = this.parent.assertDefaultVersionOf(name);
728
232
  }
729
- else {
730
- switch (girTypeName) {
731
- case 'property':
732
- name = this.transformation.transformPropertyName(girVar.$.name, allowQuotes);
733
- break;
734
- case 'constant':
735
- name = this.transformation.transformConstantName(girVar.$.name, allowQuotes);
736
- break;
737
- case 'field':
738
- name = this.transformation.transformFieldName(girVar.$.name, allowQuotes);
739
- break;
740
- }
741
- }
742
- // Use the out type because it can be a union which isn't appropriate
743
- // for a property
744
- const tsType = this.getTsType(girVar, tsClass, girTypeName, { optional, nullable, generics });
745
- const tsData = {
746
- name,
747
- type: [tsType],
748
- isInjected: false,
749
- girTypeName,
750
- tsTypeName,
751
- doc: this.getTsDoc(girVar),
752
- };
753
- tsData.doc.tags.push(...this.getTsDocGirElementTags(tsData.tsTypeName, tsData.girTypeName));
754
- return tsData;
233
+ return this.parent.namespace(name, version);
755
234
  }
756
- /**
757
- *
758
- * @param girProp
759
- * @param girTypeName
760
- * @param tsTypeName
761
- * @param construct construct means include the property even if it's construct-only,
762
- * @param optional optional means if it's construct-only it will also be marked optional (?)
763
- * @param nullable
764
- * @returns
765
- */
766
- getPropertyTsData(girProp, girTypeName, tsTypeName, tsClass, construct = false, optional, nullable) {
767
- if (!girBool(girProp.$.writable) && construct)
768
- return undefined;
769
- if (girBool(girProp.$.private))
770
- return undefined;
771
- if (girProp._tsData) {
772
- // this.log.warn('[getPropertyTsData] _tsData already set!')
773
- return girProp._tsData;
235
+ getInstalledImport(name) {
236
+ if (name === this.name) {
237
+ return this;
774
238
  }
775
- if (optional === undefined)
776
- optional = this.typeIsOptional(girProp, girTypeName);
777
- if (nullable === undefined)
778
- nullable = this.typeIsNullable(girProp, girTypeName);
779
- const readonly = !construct && this.typeIsReadonly(girProp);
780
- let tsData;
781
- switch (girTypeName) {
782
- case 'property':
783
- tsData = this.getVariableTsData(girProp, girTypeName, tsTypeName, tsClass, construct && optional, construct && nullable, true);
784
- break;
785
- case 'field':
786
- if (tsTypeName !== 'property') {
787
- throw new Error(`Wrong tsType: "${tsTypeName}" for girType: "${girTypeName}`);
788
- }
789
- tsData = this.getVariableTsData(girProp, girTypeName, tsTypeName, tsClass, construct && optional, construct && nullable, true);
790
- break;
791
- default:
792
- throw new Error(`Unknown property type: ${girTypeName}`);
239
+ const dep = this.dependencies.find((dep) => dep.namespace === name) ??
240
+ this.transitiveDependencies.find((dep) => dep.namespace === name);
241
+ let version = dep?.version;
242
+ if (!version) {
243
+ version = this.parent.defaultVersionOf(name) ?? undefined;
793
244
  }
794
- if (!tsData?.name) {
795
- return undefined;
245
+ if (!version) {
246
+ return null;
796
247
  }
797
- tsData = {
798
- ...tsData,
799
- readonly,
800
- };
801
- return tsData;
248
+ const namespace = this.parent.namespace(name, version);
249
+ return namespace;
802
250
  }
803
- /**
804
- *
805
- * @param girFunc
806
- * @param prefix E.g. vfunc
807
- * @param overrideReturnType
808
- * @param isArrowType
809
- * @param indentCount
810
- */
811
- getFunctionTsData(girFunc, girTypeName, tsClass, overwrite) {
812
- if (!girFunc || !girFunc.$ || !girBool(girFunc.$.introspectable, true) || girFunc.$['shadowed-by']) {
813
- return undefined;
251
+ assertInstalledImport(name) {
252
+ const namespace = this._getImport(name);
253
+ if (!namespace) {
254
+ throw new Error(`Failed to import ${name} in ${this.name}, not installed or accessible.`);
814
255
  }
815
- let hasUnresolvedConflict;
816
- // TODO: Fix that we overwrite tsData every time seems wrong to me, but if I just return the already defined `_tsData` leads to problems with the overload methods
817
- if (girFunc._tsData) {
818
- hasUnresolvedConflict = girFunc._tsData?.hasUnresolvedConflict; // WORKAROUND do not overwrite conflicts
819
- }
820
- let name = girFunc.$.name;
821
- const { returnTypes, outArrayLengthIndex, retTypeIsVoid } = this.getReturnType(girFunc, tsClass);
822
- const shadows = girFunc.$.shadows;
823
- if (shadows) {
824
- name = shadows;
256
+ return namespace;
257
+ }
258
+ getMembers(name) {
259
+ const members = this.members.get(name);
260
+ if (Array.isArray(members)) {
261
+ return [...members];
825
262
  }
826
- // Overwrites
827
- overwrite.isStatic = overwrite.isStatic || girTypeName === 'static-function' || girTypeName === 'constructor';
828
- overwrite.isGlobal = overwrite.isGlobal || girTypeName === 'function';
829
- overwrite.isVirtual = overwrite.isVirtual || girTypeName === 'virtual';
830
- overwrite.isInjected = overwrite.isInjected || false;
831
- // Function name transformation by environment
832
- name = this.transformation.transformFunctionName(name, overwrite.isVirtual);
833
- const tsData = {
834
- isArrowType: overwrite.isArrowType,
835
- isStatic: overwrite.isStatic,
836
- isGlobal: overwrite.isGlobal,
837
- isVirtual: overwrite.isVirtual,
838
- isInjected: overwrite.isInjected,
839
- returnTypes,
840
- retTypeIsVoid,
841
- name,
842
- overrideReturnType: overwrite.returnType || undefined,
843
- inParams: [],
844
- outParams: [],
845
- instanceParameters: [],
846
- generics: overwrite.generics,
847
- hasUnresolvedConflict,
848
- girTypeName: girTypeName,
849
- tsTypeName: this.girFactory.girTypeNameToTsTypeName(girTypeName, overwrite.isStatic),
850
- doc: this.getTsDoc(girFunc),
851
- overloads: [],
852
- parent: tsClass,
853
- };
854
- const { inParams, outParams, instanceParameters } = this.setParametersTsData(outArrayLengthIndex, girFunc.parameters, tsData);
855
- tsData.inParams.push(...inParams);
856
- tsData.outParams.push(...outParams);
857
- tsData.instanceParameters.push(...instanceParameters);
858
- tsData.doc.tags.push(...this.getTsDocGirElementTags(tsData.tsTypeName, tsData.girTypeName));
859
- tsData.doc.tags.push(...this.getTsDocInParamTags(tsData?.inParams));
860
- tsData.doc.tags.push(...this.getTsDocReturnTags(girFunc));
861
- return tsData;
263
+ return members ? [members] : [];
862
264
  }
863
- overloadPromisifiedFunctions(girFunctions) {
864
- if (!this.config.promisify)
865
- return;
866
- const promisifyAsyncReturn = ['Gio.AsyncReadyCallback', 'AsyncReadyCallback'];
867
- const promisifyFuncMap = {};
868
- // Find the functions that can be promisified
869
- for (const girFunction of girFunctions) {
870
- const tsFunction = girFunction._tsData;
871
- if (!tsFunction)
872
- continue;
873
- // Check if function name satisfies async,finish scheme
874
- const isAsync = tsFunction.name.endsWith('_async') || tsFunction.name.endsWith('_begin');
875
- const isFinish = tsFunction.name.endsWith('_finish');
876
- if (!isAsync && !isFinish)
877
- continue;
878
- // Handle async functions
879
- if (isAsync) {
880
- if (tsFunction.inParams.length === 0)
881
- continue;
882
- const lastParam = tsFunction.inParams[tsFunction.inParams.length - 1];
883
- if (lastParam.type && lastParam.type.length > 0) {
884
- const type = lastParam.type[0].$.name;
885
- if (type && promisifyAsyncReturn.includes(type)) {
886
- if (!(tsFunction.name in promisifyFuncMap))
887
- promisifyFuncMap[tsFunction.name] = {};
888
- promisifyFuncMap[tsFunction.name].asyncFn = tsFunction;
889
- }
890
- }
891
- }
892
- // Handle finish functions
893
- if (isFinish) {
894
- if (tsFunction.returnTypes.length === 0)
895
- continue;
896
- let name = `${tsFunction.name.replace(/(_finish)$/, '')}_async`;
897
- if (!(name in promisifyFuncMap))
898
- name = `${tsFunction.name.replace(/(_finish)$/, '')}_begin`;
899
- if (!(name in promisifyFuncMap))
900
- promisifyFuncMap[name] = {};
901
- promisifyFuncMap[name].finishFn = tsFunction;
265
+ getMemberWithoutOverrides(name) {
266
+ if (this.members.has(name)) {
267
+ const member = this.members.get(name);
268
+ if (!Array.isArray(member)) {
269
+ return member;
902
270
  }
271
+ return null;
903
272
  }
904
- // Generate TsFunctions for promisify-able functions and add to the array
905
- for (const [, func] of Object.entries(promisifyFuncMap)) {
906
- if (!func.asyncFn || !func.finishFn)
907
- continue;
908
- const inParams = this.girFactory.newGirCallableParamElements(func.asyncFn.inParams.slice(0, -1), func.asyncFn);
909
- const outParams = this.girFactory.newGirCallableParamElements(func.finishFn.outParams, func.asyncFn);
910
- const returnTypes = this.girFactory.newTsTypes(outParams.length > 0 ? [] : func.finishFn.returnTypes);
911
- let docReturnText = func.finishFn.doc.tags.find((tag) => tag.tagName === 'returns')?.text || '';
912
- if (docReturnText) {
913
- docReturnText = `A Promise of: ${docReturnText}`;
914
- }
915
- else {
916
- docReturnText = `A Promise of the result of {@link ${func.asyncFn.name}}`;
273
+ const resolvedName = this._resolve_names.get(name);
274
+ if (resolvedName) {
275
+ const member = this.members.get(resolvedName.name);
276
+ if (!Array.isArray(member)) {
277
+ return member;
917
278
  }
918
- const docText = `Promisified version of {@link ${func.asyncFn.name}}\n\n${func.asyncFn.doc.text}`;
919
- const docTags = func.asyncFn.doc.tags.filter((tag) => tag.paramName !== 'callback' && tag.paramName !== 'returns');
920
- docTags.push({
921
- tagName: 'returns',
922
- text: docReturnText,
923
- paramName: '',
924
- });
925
- const doc = this.girFactory.newTsDoc({
926
- text: docText,
927
- tags: docTags,
928
- });
929
- const promisifyFn = this.girFactory.newTsFunction({
930
- ...func.asyncFn,
931
- inParams,
932
- outParams,
933
- returnTypes,
934
- isPromise: true,
935
- doc,
936
- }, func.asyncFn.parent);
937
- func.asyncFn.overloads.push(promisifyFn);
938
279
  }
280
+ return null;
939
281
  }
940
- getCallbackInterfaceTsData(girCallback) {
941
- if (!girElementIsIntrospectable(girCallback))
942
- return undefined;
943
- const namespace = this.namespace;
944
- const tsDataInterface = {
945
- name: `${namespace}.${girCallback.$.name}`,
946
- generics: [],
947
- };
948
- return tsDataInterface;
949
- }
950
- setCallbackTsData(girCallback, tsClass) {
951
- const tsFunction = this.getFunctionTsData(girCallback, 'callback', tsClass, {
952
- isStatic: false,
953
- isArrowType: true,
954
- isGlobal: false,
955
- isVirtual: false,
956
- returnType: null,
957
- generics: [],
958
- });
959
- if (tsFunction) {
960
- const tsCallback = {
961
- ...tsFunction,
962
- girTypeName: 'callback',
963
- tsTypeName: this.girFactory.girTypeNameToTsTypeName('callback', false),
964
- tsCallbackInterface: this.getCallbackInterfaceTsData(girCallback),
965
- overloads: [],
966
- };
967
- girCallback._tsData = tsCallback;
968
- this.inject.toCallback(girCallback);
282
+ assertClass(name) {
283
+ const clazz = this.getClass(name);
284
+ if (!clazz) {
285
+ throw new Error(`Class ${name} does not exist in namespace ${this.name}.`);
969
286
  }
970
- return girCallback._tsData;
287
+ return clazz;
971
288
  }
972
- getSignalCallbackInterfaceTsData(girCallback, girClass) {
973
- if (!girElementIsIntrospectable(girCallback))
974
- return undefined;
975
- if (!girClass._tsData || !girClass._module) {
976
- throw new Error(NO_TSDATA('getSignalCallbackTsData'));
977
- }
978
- const className = girClass._tsData.name;
979
- const signalName = girCallback.$.name;
980
- const signalInterfaceName = this.transformation.transformSignalInterfaceName(signalName);
981
- const namespace = girClass._module.namespace;
982
- const tsDataInterface = {
983
- name: `${namespace}.${className}.${signalInterfaceName}SignalCallback`,
984
- generics: [],
985
- overwriteDoc: {
986
- text: `Signal callback interface for \`${signalName}\``,
987
- tags: [],
988
- },
989
- };
990
- return tsDataInterface;
991
- }
992
- getConstructorFunctionTsData(parentClass, girConstructor) {
993
- if (!girElementIsIntrospectable(girConstructor))
994
- return;
995
- const constructorTypeName = addNamespace(parentClass.name, parentClass.namespace);
996
- return this.getFunctionTsData(girConstructor, 'constructor', parentClass, {
997
- isStatic: true,
998
- isArrowType: false,
999
- isGlobal: false,
1000
- isVirtual: false,
1001
- returnType: constructorTypeName,
1002
- generics: [],
1003
- });
1004
- }
1005
- getSignalCallbackTsData(girSignalFunc, girClass) {
1006
- if (!girClass._tsData) {
1007
- throw new Error(NO_TSDATA('getSignalCallbackTsData'));
1008
- }
1009
- if (girSignalFunc._tsData) {
1010
- return girSignalFunc._tsData;
1011
- }
1012
- // Leads to errors here
1013
- // if (!girElementIsIntrospectable(girSignalFunc)) return undefined
1014
- const name = this.transformation.transform('signalName', girSignalFunc.$.name);
1015
- const { returnTypes, outArrayLengthIndex, retTypeIsVoid } = this.getReturnType(girSignalFunc, girClass._tsData);
1016
- if (this.config.environment === 'node') {
1017
- returnTypes[0].type === 'void';
289
+ getClass(name) {
290
+ const member = this.getMemberWithoutOverrides(name);
291
+ if (member instanceof IntrospectedBaseClass) {
292
+ return member;
1018
293
  }
1019
- const tsCallback = {
1020
- name,
1021
- returnTypes,
1022
- isArrowType: true,
1023
- isStatic: false,
1024
- isGlobal: false,
1025
- isVirtual: false,
1026
- isInjected: false,
1027
- retTypeIsVoid,
1028
- inParams: [],
1029
- instanceParameters: [],
1030
- outParams: [],
1031
- generics: [],
1032
- girTypeName: 'callback',
1033
- tsTypeName: this.girFactory.girTypeNameToTsTypeName('callback', false),
1034
- doc: this.getTsDoc(girSignalFunc),
1035
- overloads: [],
1036
- parent: girClass._tsData,
1037
- };
1038
- const { inParams, outParams, instanceParameters } = this.setParametersTsData(outArrayLengthIndex, girSignalFunc.parameters, tsCallback);
1039
- if (this.config.environment === 'gjs') {
1040
- inParams.unshift(this.girFactory.newGirCallableParamElement({
1041
- name: '$obj',
1042
- type: [
1043
- {
1044
- type: girClass._tsData.name,
1045
- },
1046
- ],
1047
- }, tsCallback));
1048
- }
1049
- tsCallback.inParams.push(...inParams);
1050
- tsCallback.outParams.push(...outParams);
1051
- tsCallback.instanceParameters.push(...instanceParameters);
1052
- tsCallback.doc.tags.push(...this.getTsDocGirElementTags(tsCallback.tsTypeName, tsCallback.girTypeName));
1053
- tsCallback.doc.tags.push(...this.getTsDocInParamTags(tsCallback?.inParams));
1054
- tsCallback.doc.tags.push(...this.getTsDocReturnTags(girSignalFunc));
1055
- return tsCallback;
294
+ return null;
1056
295
  }
1057
- /**
1058
- * Generates signal methods like `connect`, `connect_after` and `emit` on Gjs or `connect`, `on`, `once`, `off` and `emit` an node-gtk
1059
- * for a default gir signal element
1060
- * @param girSignal
1061
- * @returns
1062
- */
1063
- getClassSignalMethodsTsData(girSignal, parentClass) {
1064
- if (!girSignal._tsData) {
1065
- throw new Error(NO_TSDATA('getClassSignalMethodsTsData'));
296
+ getEnum(name) {
297
+ const member = this.getMemberWithoutOverrides(name);
298
+ if (member instanceof IntrospectedEnum) {
299
+ return member;
1066
300
  }
1067
- const inParams = girSignal._tsData.inParams.slice(1).map((inParam) => {
1068
- const injectParam = {
1069
- ...inParam._tsData,
1070
- type: inParam._tsData?.type || [],
1071
- name: inParam._tsData?.name || 'unknown',
1072
- };
1073
- return injectParam;
1074
- });
1075
- return this.girFactory.newTsSignalMethods(girSignal._tsData?.name, girSignal._tsData?.tsCallbackInterface?.name, inParams, parentClass, this.config.environment, false);
301
+ return null;
1076
302
  }
1077
- /**
1078
- * Generates signal methods for the GObject properties of a gir class element
1079
- * @param girClass
1080
- */
1081
- getClassPropertySignalsMethods(girClass) {
1082
- if (!girClass._tsData) {
1083
- throw new Error(NO_TSDATA('getClassPropertySignalsMethods'));
303
+ getAlias(name) {
304
+ const member = this.getMemberWithoutOverrides(name);
305
+ if (member instanceof IntrospectedAlias) {
306
+ return member;
1084
307
  }
1085
- const tsMethods = [];
1086
- const propertyNames = this.getClassNonStaticPropertyNames(girClass);
1087
- const namespacePrefix = this.namespace === 'GObject' ? '' : 'GObject.';
1088
- // TODO: Signals: Generate SignalMethods instead of direct types
1089
- for (const propertyName of propertyNames) {
1090
- let callbackType = 'any';
1091
- if (this.config.environment === 'gjs') {
1092
- const objParam = `$obj: ${girClass._tsData.name}`;
1093
- // TODO: create arrowType object instead of a pure string type, see Pango-1.0.Pango.FontMapClass.load_font for an example
1094
- callbackType = `((${objParam}, pspec: ${namespacePrefix}ParamSpec) => void)`;
1095
- }
1096
- else if (this.config.environment === 'node') {
1097
- callbackType = `(...args: any[]) => void`;
1098
- }
1099
- tsMethods.push(...this.girFactory.newTsSignalMethods(`notify::${propertyName}`, callbackType, [], girClass._tsData, this.config.environment));
1100
- }
1101
- return tsMethods;
308
+ return null;
1102
309
  }
1103
- getGeneralSignalsMethods(parentClass) {
1104
- return this.girFactory.newTsSignalMethods(undefined, undefined, [], parentClass, this.config.environment, true);
1105
- }
1106
- setSignalTsData(girSignal, girClass) {
1107
- if (!girClass._tsData) {
1108
- throw NO_TSDATA('setSignalTsData');
1109
- }
1110
- if (!girSignal._tsData) {
1111
- girSignal._tsData = {
1112
- ...this.getSignalCallbackTsData(girSignal, girClass),
1113
- tsCallbackInterface: this.getSignalCallbackInterfaceTsData(girSignal, girClass),
1114
- tsMethods: [],
1115
- girTypeName: 'signal',
1116
- tsTypeName: this.girFactory.girTypeNameToTsTypeName('signal', false),
1117
- doc: this.getTsDoc(girSignal),
1118
- overloads: [],
1119
- };
1120
- girSignal._tsData.doc.tags.push(...this.getTsDocGirElementTags(girSignal._tsData.tsTypeName, girSignal._tsData.girTypeName));
1121
- // TODO: this are the callback parameters
1122
- girSignal._tsData.doc.tags.push(...this.getTsDocInParamTags(girSignal._tsData?.inParams));
1123
- girSignal._tsData.doc.tags.push(...this.getTsDocReturnTags(girSignal));
1124
- if (!girSignal._tsData) {
1125
- throw NO_TSDATA('setSignalTsData');
1126
- }
1127
- girSignal._tsData.tsMethods = this.getClassSignalMethodsTsData(girSignal, girClass._tsData);
1128
- }
1129
- return girSignal._tsData;
310
+ hasSymbol(name) {
311
+ return this.members.has(name);
1130
312
  }
1131
- fixEnumerationDuplicateIdentifier(girEnum) {
1132
- if (!girElementIsIntrospectable(girEnum))
1133
- return girEnum;
1134
- if (!girEnum._tsData) {
1135
- throw new Error(NO_TSDATA('fixEnumerationDuplicateIdentifier'));
313
+ resolveSymbolFromTypeName(name) {
314
+ const resolvedName = this._resolve_names.get(name);
315
+ if (!resolvedName) {
316
+ return null;
1136
317
  }
1137
- if (!girEnum.member?.length) {
1138
- return girEnum;
318
+ const member = this.members.get(resolvedName.name);
319
+ if (member instanceof IntrospectedBase) {
320
+ return member.name;
1139
321
  }
1140
- const memberNames = [];
1141
- for (const girEnumMember of girEnum.member) {
1142
- if (!girEnumMember._tsData) {
1143
- throw new Error(NO_TSDATA('fixEnumerationDuplicateIdentifier'));
1144
- }
1145
- if (memberNames.find((name) => name === girEnumMember._tsData?.name)) {
1146
- const renamed = '_' + girEnumMember._tsData.name;
1147
- this.log.warn(WARN_DUPLICATE_ENUM_IDENTIFIER(girEnumMember._tsData.name, renamed));
1148
- girEnumMember._tsData.name = renamed;
1149
- }
1150
- memberNames.push(girEnumMember._tsData.name);
1151
- }
1152
- return girEnum;
322
+ return null;
1153
323
  }
1154
- getEnumerationMemberTsData(girEnumMember, girTypeName) {
1155
- const memberName = girEnumMember.$.name || girEnumMember.$['glib:nick'] || girEnumMember.$['c:identifier'];
1156
- if (!girElementIsIntrospectable(girEnumMember, memberName))
1157
- return undefined;
1158
- if (girEnumMember._tsData) {
1159
- // this.log.warn('[getEnumerationMemberTsData] _tsData already set!')
1160
- return girEnumMember._tsData;
324
+ findClassCallback(name) {
325
+ const clazzes = Array.from(this.members.values()).filter((m) => m instanceof IntrospectedBaseClass);
326
+ const res = clazzes
327
+ .map((m) => [m, m.callbacks.find((c) => c.name === name || c.resolve_names.includes(name))])
328
+ .find((r) => r[1] != null);
329
+ if (res) {
330
+ return [res[0].name, res[1].name];
1161
331
  }
1162
- const name = this.transformation.transformEnumMember(memberName);
1163
- const tsData = {
1164
- name,
1165
- girTypeName,
1166
- tsTypeName: this.girFactory.girTypeNameToTsTypeName(girTypeName, false),
1167
- doc: this.getTsDoc(girEnumMember),
1168
- };
1169
- tsData.doc.tags.push(...this.getTsDocGirElementTags(tsData.tsTypeName, tsData.girTypeName));
1170
- return tsData;
1171
- }
1172
- getEnumerationTsData(girEnum, girTypeName) {
1173
- if (!girElementIsIntrospectable(girEnum))
1174
- return undefined;
1175
- if (girEnum._tsData) {
1176
- // this.log.warn('[getEnumerationMemberTsData] _tsData already set!')
1177
- return girEnum._tsData;
1178
- }
1179
- // E.g. the NetworkManager-1.0 has enum names starting with 80211
1180
- const name = this.transformation.transformEnumName(girEnum);
1181
- const tsData = {
1182
- name,
1183
- girTypeName,
1184
- tsTypeName: this.girFactory.girTypeNameToTsTypeName(girTypeName, false),
1185
- doc: this.getTsDoc(girEnum),
332
+ else {
333
+ return [null, name];
334
+ }
335
+ }
336
+ /**
337
+ * This is an internal method to add TypeScript <reference>
338
+ * comments when overrides use parts of the TypeScript standard
339
+ * libraries that are newer than default.
340
+ */
341
+ ___dts___addReference(reference) {
342
+ this.__dts__references ??= [];
343
+ this.__dts__references.push(reference);
344
+ }
345
+ static load(repo, config, registry) {
346
+ const ns = repo.repository[0]?.namespace?.[0];
347
+ if (!ns)
348
+ throw new Error(`Missing namespace in ${repo.repository[0].package[0].$.name}`);
349
+ const modName = ns.$['name'];
350
+ const version = ns.$['version'];
351
+ // TODO: Hardcoding HarfBuzz here leads to issues when loading...
352
+ // Hardcode harfbuzz version for now...
353
+ // if (modName === 'HarfBuzz' && version === '0.0') {
354
+ // version = '2.0'
355
+ // }
356
+ const options = {
357
+ loadDocs: !config.noComments,
358
+ propertyCase: 'both',
359
+ verbose: config.verbose,
1186
360
  };
1187
- tsData.doc.tags.push(...this.getTsDocGirElementTags(tsData.tsTypeName, tsData.girTypeName));
1188
- return tsData;
1189
- }
1190
- getAliasTsData(girAlias, tsClass) {
1191
- if (!girElementIsIntrospectable(girAlias))
1192
- return undefined;
1193
- const girTypeName = 'alias';
1194
- if (girAlias._tsData) {
1195
- // this.log.warn('[getEnumerationMemberTsData] _tsData already set!')
1196
- return girAlias._tsData;
1197
- }
1198
- const { type: typeName } = this.getTsType(girAlias, tsClass, girTypeName);
1199
- const name = girAlias.$.name;
1200
- const tsData = {
1201
- name,
1202
- type: typeName,
1203
- girTypeName,
1204
- tsTypeName: this.girFactory.girTypeNameToTsTypeName(girTypeName, false),
361
+ if (!modName) {
362
+ throw new Error('Invalid GIR file: no namespace name specified.');
363
+ }
364
+ if (!version) {
365
+ throw new Error('Invalid GIR file: no version name specified.');
366
+ }
367
+ const c_prefix = ns.$?.['c:identifier-prefixes']?.split(',') ?? [];
368
+ if (options.verbose) {
369
+ console.debug(`Parsing ${modName}...`);
370
+ }
371
+ const building = new GirModule(repo.repository[0], modName, version, c_prefix, config);
372
+ building.parent = registry;
373
+ // Set the namespace object here to prevent re-parsing the namespace if
374
+ // another namespace imports it.
375
+ registry.register(building);
376
+ const prefixes = repo.repository[0]?.$?.['c:identifier-prefixes']?.split(',');
377
+ const unknownPrefixes = prefixes?.filter((pre) => pre !== modName);
378
+ if (unknownPrefixes && unknownPrefixes.length > 0) {
379
+ console.log(`Found additional prefixes for ${modName}: ${unknownPrefixes.join(', ')}`);
380
+ building.prefixes.push(...unknownPrefixes);
381
+ }
382
+ const importConflicts = (el) => {
383
+ return !building.hasImport(el.name);
1205
384
  };
1206
- return tsData;
1207
- }
1208
- getConstantTsData(girConst, tsClass) {
1209
- if (!girElementIsIntrospectable(girConst))
1210
- return undefined;
1211
- if (girConst._tsData) {
1212
- // this.log.warn('[getConstantTsData] _tsData already set!')
1213
- return girConst._tsData;
1214
- }
1215
- let tsData = this.getVariableTsData(girConst, 'constant', 'constant', tsClass, false, false, false);
1216
- if (tsData?.name) {
1217
- if (!this.constNames[tsData.name]) {
1218
- this.constNames[tsData.name] = girConst;
1219
- }
1220
- else {
1221
- this.log.warn(WARN_CONSTANT_ALREADY_EXPORTED(tsData.name));
1222
- tsData = undefined;
1223
- }
1224
- }
1225
- return tsData;
1226
- }
1227
- // FIXME: https://github.com/gjsify/ts-for-gir/issues/145
1228
- // FIXME: https://github.com/gjsify/ts-for-gir/issues/131
1229
- getClassConstructPropsTsData(girClass, constructPropNames) {
1230
- const constructProps = [];
1231
- const girProperties = girClass.property;
1232
- if (!girProperties?.length) {
1233
- return constructProps;
1234
- }
1235
- for (const girProp of girProperties) {
1236
- if (!girElementIsIntrospectable(girProp) || !girProp.$.name)
1237
- continue;
1238
- // Do not modify the original girProp, create a new one by clone `girProp` to `girConstrProp`
1239
- const girConstrProp = clone(girProp);
1240
- if (!girClass._tsData)
1241
- continue;
1242
- if (!girConstrProp._tsData) {
1243
- girConstrProp._tsData = this.getPropertyTsData(girConstrProp, 'property', 'constructor-property', girClass._tsData, true, true, true, 0);
1244
- }
1245
- if (!girConstrProp._tsData) {
1246
- continue;
1247
- }
1248
- const localName = this.checkOrSetLocalName(girConstrProp, constructPropNames, 'property');
1249
- if (!localName?.added) {
1250
- continue;
1251
- }
1252
- if (girConstrProp._fullSymName) {
1253
- this.symTable.set(this.allDependencies, girConstrProp._fullSymName, girConstrProp);
1254
- }
1255
- constructProps.push(girConstrProp);
1256
- // Clone property with the name in underscores, see https://github.com/gjsify/ts-for-gir/issues/138
1257
- // const underscoresProperty = this.clonePropertyForUnderscores(girConstrProp)
1258
- // if (underscoresProperty && underscoresProperty._fullSymName) {
1259
- // girProperties.push(underscoresProperty)
1260
- // this.symTable.set(this.allDependencies, underscoresProperty._fullSymName, underscoresProperty)
1261
- // }
1262
- }
1263
- return constructProps;
1264
- }
1265
- /**
1266
- * Some class/static methods are defined in a separate record which is not
1267
- * exported, but the methods are available as members of the JS constructor.
1268
- * In gjs one can use an instance of the object, a JS constructor or a GType
1269
- * as the method's instance-parameter.
1270
- * @see https://discourse.gnome.org/t/using-class-methods-like-gtk-widget-class-get-css-name-from-gjs/4001
1271
- * @param girClass
1272
- */
1273
- getClassRecordMethods(girClass) {
1274
- const girMethods = [];
1275
- if (!girClass.$.name)
1276
- return girMethods;
1277
- const fName = girClass.$.name + 'Class';
1278
- let rec = this.ns.record?.find((r) => r.$.name == fName);
1279
- if (!rec || !this.isGtypeStructFor(girClass, rec)) {
1280
- rec = this.ns.record?.find((r) => this.isGtypeStructFor(girClass, r));
1281
- fName == rec?.$.name;
1282
- }
1283
- if (!rec)
1284
- return girMethods;
1285
- // Record methods
1286
- const methods = rec.method || [];
1287
- for (const girMethod of methods) {
1288
- if (!girElementIsIntrospectable(girMethod) || !girClass._tsData)
1289
- continue;
1290
- if (!girMethod._tsData)
1291
- girMethod._tsData = this.getFunctionTsData(girMethod, 'static-function', girClass._tsData, {
1292
- isStatic: true,
1293
- isArrowType: false,
1294
- isGlobal: false,
1295
- isVirtual: false,
1296
- returnType: null,
1297
- generics: [],
1298
- });
1299
- if (!girMethod._tsData)
1300
- continue;
1301
- if (girMethod._tsData) {
1302
- if (girMethod._fullSymName)
1303
- this.symTable.set(this.allDependencies, girMethod._fullSymName, girMethod);
1304
- girMethods.push(girMethod);
1305
- }
1306
- }
1307
- this.overloadPromisifiedFunctions(methods);
1308
- return girMethods;
1309
- }
1310
- /**
1311
- * Instance methods
1312
- * @param girClass
1313
- * @param localNames
1314
- */
1315
- getClassMethodsTsData(girClass, localNames) {
1316
- const girMethods = [];
1317
- if (girClass.method) {
1318
- for (const girMethod of girClass.method) {
1319
- if (!girElementIsIntrospectable(girMethod) || !girClass._tsData)
1320
- continue;
1321
- if (!girMethod._tsData)
1322
- girMethod._tsData = this.getFunctionTsData(girMethod, 'method', girClass._tsData, {
1323
- isStatic: false,
1324
- isArrowType: false,
1325
- isGlobal: false,
1326
- isVirtual: false,
1327
- returnType: null,
1328
- generics: [],
1329
- });
1330
- if (!girMethod._tsData)
1331
- continue;
1332
- const localName = this.checkOrSetLocalName(girMethod, localNames, 'method');
1333
- if (localName?.added && localName.method) {
1334
- if (girMethod._fullSymName)
1335
- this.symTable.set(this.allDependencies, girMethod._fullSymName, girMethod);
1336
- girMethods.push(localName.method);
1337
- }
1338
- }
1339
- this.overloadPromisifiedFunctions(girClass.method);
1340
- }
1341
- return girMethods;
1342
- }
1343
- getClassFieldsTsData(girClass, localNames) {
1344
- const girFields = [];
1345
- if (!girClass._tsData) {
1346
- this.log.warn(NO_TSDATA('setClassFieldsTsData'));
1347
- return girFields;
1348
- }
1349
- if (girClass.field) {
1350
- for (const girField of girClass.field) {
1351
- if (!girElementIsIntrospectable(girField))
1352
- continue;
1353
- if (!girField._tsData)
1354
- girField._tsData = this.getVariableTsData(girField, 'field', 'property', girClass._tsData, false, false, false);
1355
- if (!girField._tsData) {
1356
- continue;
1357
- }
1358
- const localName = this.checkOrSetLocalName(girField, localNames, 'field');
1359
- if (localName?.added && localName.field) {
1360
- if (girField._fullSymName)
1361
- this.symTable.set(this.allDependencies, girField._fullSymName, girField);
1362
- girFields.push(localName.field);
1363
- }
1364
- }
1365
- }
1366
- return girFields;
1367
- }
1368
- getGObjectProperties(girClass) {
1369
- const girProperties = [];
1370
- if (girClass._fullSymName && !STATIC_NAME_ALREADY_EXISTS.includes(girClass._fullSymName)) {
1371
- // Records, classes and interfaces all have a static name
1372
- const type = this.girFactory.newTsType({ type: 'string' });
1373
- const staticNameProp = this.girFactory.newGirProperty({
1374
- isStatic: true,
1375
- name: 'name',
1376
- type: [type],
1377
- girTypeName: 'property',
1378
- });
1379
- girProperties.push(staticNameProp);
1380
- }
1381
- if (girClass._tsData?.isDerivedFromGObject && girClass._module) {
1382
- if (this.config.environment === 'gjs') {
1383
- const type = this.girFactory.newTsType({
1384
- // TODO: Type not as string
1385
- type: 'GObject.GType',
1386
- generics: this.girFactory.newGenerics([
1387
- {
1388
- value: girClass._tsData.name,
1389
- },
1390
- ]),
1391
- });
1392
- const staticGTypeProp = this.girFactory.newGirProperty({
1393
- isStatic: true,
1394
- name: '$gtype',
1395
- type: [type],
1396
- girTypeName: 'property',
1397
- });
1398
- girProperties.push(staticGTypeProp);
1399
- }
1400
- else if (this.config.environment === 'node') {
1401
- const staticGTypeProp = this.girFactory.newGirProperty({
1402
- isStatic: false,
1403
- name: '__gtype__',
1404
- type: [{ type: 'number' }],
1405
- girTypeName: 'property',
1406
- });
1407
- girProperties.push(staticGTypeProp);
1408
- }
1409
- }
1410
- return girProperties;
1411
- }
1412
- /**
1413
- * Create a clone object of a property with the name in upper camel case
1414
- * See github.com/gjsify/ts-for-gir/issues/138
1415
- * @param girProperty
1416
- * @returns
1417
- */
1418
- clonePropertyForUnderscores(girProperty) {
1419
- // Only for GJS
1420
- if (this.config.environment === 'node') {
1421
- return undefined;
1422
- }
1423
- const propertyName = girProperty._tsData?.name;
1424
- if (!propertyName) {
1425
- return undefined;
1426
- }
1427
- const underscoresPropertyName = underscores(propertyName);
1428
- // Nothing has changed
1429
- if (underscoresPropertyName === propertyName) {
1430
- return undefined;
1431
- }
1432
- const upperCamelCaseGirProperty = clone(girProperty);
1433
- upperCamelCaseGirProperty._tsData = clone(upperCamelCaseGirProperty._tsData);
1434
- if (!upperCamelCaseGirProperty._tsData) {
1435
- return undefined;
1436
- }
1437
- upperCamelCaseGirProperty._tsData.name = underscoresPropertyName;
1438
- upperCamelCaseGirProperty._fullSymName = upperCamelCaseGirProperty._fullSymName?.replace(propertyName, underscoresPropertyName);
1439
- return upperCamelCaseGirProperty;
1440
- }
1441
- getClassPropertiesTsData(girClass, localNames) {
1442
- const girProperties = [];
1443
- const properties = girClass.property;
1444
- if (properties) {
1445
- for (const girProperty of properties) {
1446
- if (!girElementIsIntrospectable(girProperty) || !girClass._tsData)
1447
- continue;
1448
- girProperty._tsData = this.getPropertyTsData(girProperty, 'property', 'property', girClass._tsData);
1449
- if (!girProperty._tsData)
1450
- continue;
1451
- {
1452
- const localName = this.checkOrSetLocalName(girProperty, localNames, 'property');
1453
- if (localName?.added && localName.property) {
1454
- if (girProperty._fullSymName) {
1455
- this.symTable.set(this.allDependencies, girProperty._fullSymName, girProperty);
1456
- }
1457
- girProperties.push(localName.property);
1458
- }
1459
- }
1460
- // Add a new property with the name in lower camel case, see https://github.com/gjsify/ts-for-gir/issues/138
1461
- // {
1462
- // const underscoresProperty = this.clonePropertyForUnderscores(girProperty)
1463
- // if (underscoresProperty) {
1464
- // const localName = this.checkOrSetLocalName(underscoresProperty, localNames, 'property')
1465
- // if (localName?.added && localName.property) {
1466
- // if (underscoresProperty._fullSymName) {
1467
- // this.symTable.set(
1468
- // this.allDependencies,
1469
- // underscoresProperty._fullSymName,
1470
- // underscoresProperty,
1471
- // )
1472
- // }
1473
- // girProperties.push(localName.property)
1474
- // }
1475
- // }
1476
- // }
1477
- }
1478
- }
1479
- return girProperties;
1480
- }
1481
- getClassNonStaticPropertyNames(girClass) {
1482
- const propertyNames = [];
1483
- if (!girClass._tsData) {
1484
- return propertyNames;
1485
- }
1486
- const girProperties = girClass._tsData.properties;
1487
- if (girProperties.length > 0) {
1488
- for (const girProperty of girProperties) {
1489
- if (!girElementIsIntrospectable(girProperty))
1490
- continue;
1491
- if (girProperty.$.name &&
1492
- !propertyNames.includes(girProperty.$.name) &&
1493
- !girProperty._tsData?.isStatic) {
1494
- propertyNames.push(girProperty.$.name);
1495
- }
1496
- }
1497
- }
1498
- // Extended property names
1499
- for (const fullSymName of Object.keys(girClass._tsData.inherit)) {
1500
- const girProperties = girClass._tsData.inherit[fullSymName]?.class.properties;
1501
- if (girProperties.length > 0) {
1502
- for (const girProperty of girProperties) {
1503
- if (!girElementIsIntrospectable(girProperty))
1504
- continue;
1505
- if (girProperty.$.name &&
1506
- !propertyNames.includes(girProperty.$.name) &&
1507
- !girProperty._tsData?.isStatic) {
1508
- propertyNames.push(girProperty.$.name);
1509
- }
1510
- }
1511
- }
1512
- }
1513
- // Implemented property names
1514
- for (const fullSymName of Object.keys(girClass._tsData.implements)) {
1515
- const girProperties = girClass._tsData.implements[fullSymName]?.interface.properties;
1516
- if (girProperties.length > 0) {
1517
- for (const girProperty of girProperties) {
1518
- if (!girElementIsIntrospectable(girProperty))
1519
- continue;
1520
- if (girProperty._tsData &&
1521
- girProperty.$.name &&
1522
- !propertyNames.includes(girProperty.$.name) &&
1523
- !girProperty._tsData?.isStatic) {
1524
- propertyNames.push(girProperty.$.name);
1525
- }
1526
- }
1527
- }
1528
- }
1529
- return propertyNames;
1530
- }
1531
- getClassConstructorsTsData(girClass) {
1532
- if (!girClass._tsData) {
1533
- throw new Error(NO_TSDATA('getClassConstructorsTsData'));
1534
- }
1535
- const girConstructors = [];
1536
- // JS constructor(s)
1537
- if (girClass._tsData?.isDerivedFromGObject) {
1538
- const constructorInParam = {
1539
- name: 'config',
1540
- type: [
1541
- {
1542
- optional: true,
1543
- type: girClass._tsData.constructPropInterfaceName,
1544
- },
1545
- ],
1546
- };
1547
- const realConstructor = this.girFactory.newGirFunction({
1548
- name: 'constructor',
1549
- isStatic: true,
1550
- inParams: [constructorInParam],
1551
- girTypeName: 'constructor',
1552
- }, girClass._tsData);
1553
- const initConstructor = this.girFactory.newGirFunction({
1554
- name: '_init',
1555
- inParams: [constructorInParam],
1556
- girTypeName: 'method',
1557
- }, girClass._tsData);
1558
- girConstructors.push(realConstructor, initConstructor);
1559
- }
1560
- if (Array.isArray(girClass.constructor)) {
1561
- for (const girConstructor of girClass.constructor) {
1562
- if (!girElementIsIntrospectable(girConstructor))
1563
- continue;
1564
- girConstructor._tsData = this.getConstructorFunctionTsData(girClass._tsData, girConstructor);
1565
- if (!girConstructor._tsData?.name)
1566
- continue;
1567
- // Also add `new` pseudo constructors
1568
- const ADD_NEW_PSEUDO_CONSTRUCTOR = true;
1569
- // Inject an additional real constructor if static new(...) exists
1570
- if (girConstructor._tsData.name === 'new') {
1571
- const realConstructor = clone(girConstructor);
1572
- realConstructor._tsData = clone(realConstructor._tsData);
1573
- if (realConstructor._tsData) {
1574
- realConstructor._tsData.overloads = [];
1575
- realConstructor.$.name = 'constructor';
1576
- realConstructor._tsData.name = 'constructor';
1577
- girConstructors.push(realConstructor);
1578
- }
1579
- if (ADD_NEW_PSEUDO_CONSTRUCTOR) {
1580
- girConstructors.push(girConstructor);
1581
- }
385
+ if (ns.enumeration) {
386
+ // Get the requested enums
387
+ ns.enumeration
388
+ ?.map((enumeration) => {
389
+ if (enumeration.$['glib:error-domain']) {
390
+ return IntrospectedError.fromXML(enumeration, building, options);
1582
391
  }
1583
392
  else {
1584
- girConstructors.push(girConstructor);
1585
- }
1586
- }
1587
- }
1588
- return girConstructors;
1589
- }
1590
- getClassVirtualMethodsTsData(girClass) {
1591
- const methods = girClass['virtual-method'] || [];
1592
- const girMethods = [];
1593
- for (const girVMethod of methods) {
1594
- if (!girElementIsIntrospectable(girVMethod) || !girClass._tsData)
1595
- continue;
1596
- girVMethod._tsData = this.getFunctionTsData(girVMethod, 'virtual', girClass._tsData, {
1597
- isStatic: false,
1598
- isArrowType: false,
1599
- isGlobal: false,
1600
- isVirtual: true,
1601
- returnType: null,
1602
- generics: [],
393
+ return IntrospectedEnum.fromXML(enumeration, building, options);
394
+ }
395
+ })
396
+ .forEach((c) => building.members.set(c.name, c));
397
+ }
398
+ // Constants
399
+ if (ns.constant) {
400
+ ns.constant
401
+ ?.filter(isIntrospectable)
402
+ .map((constant) => IntrospectedConstant.fromXML(constant, building, options))
403
+ .filter(importConflicts)
404
+ .forEach((c) => building.members.set(c.name, c));
405
+ }
406
+ // Get the requested functions
407
+ if (ns.function) {
408
+ ns.function
409
+ ?.filter(isIntrospectable)
410
+ .map((func) => IntrospectedFunction.fromXML(func, building, options))
411
+ .filter(importConflicts)
412
+ .forEach((c) => building.members.set(c.name, c));
413
+ }
414
+ if (ns.callback) {
415
+ ns.callback
416
+ ?.filter(isIntrospectable)
417
+ .map((callback) => IntrospectedCallback.fromXML(callback, building, options))
418
+ .filter(importConflicts)
419
+ .forEach((c) => building.members.set(c.name, c));
420
+ }
421
+ if (ns['glib:boxed']) {
422
+ ns['glib:boxed']
423
+ ?.filter(isIntrospectable)
424
+ .map((boxed) => new IntrospectedAlias({
425
+ name: boxed.$['glib:name'],
426
+ namespace: building,
427
+ type: new NullableType(ObjectType),
428
+ }))
429
+ .forEach((c) => building.members.set(c.name, c));
430
+ }
431
+ // Bitfield is a type of enum
432
+ if (ns.bitfield) {
433
+ ns.bitfield
434
+ ?.filter(isIntrospectable)
435
+ .map((field) => IntrospectedEnum.fromXML(field, building, options, true))
436
+ .forEach((c) => building.members.set(c.name, c));
437
+ }
438
+ // The `enum_constants` map maps the C identifiers (GTK_BUTTON_TYPE_Y)
439
+ // to the name of the enum (Button) to resolve references (Gtk.Button.Y)
440
+ Array.from(building.members.values())
441
+ .filter((m) => m instanceof IntrospectedEnum)
442
+ .forEach((m) => {
443
+ m.members.forEach((member) => {
444
+ building.enum_constants.set(member.c_identifier, [m.name, member.name]);
1603
445
  });
1604
- if (!girVMethod._tsData)
1605
- continue;
1606
- if (girVMethod?._tsData?.name) {
1607
- girMethods.push(girVMethod);
1608
- }
1609
- }
1610
- return girMethods;
1611
- }
1612
- /**
1613
- *
1614
- * @param girClass This is the class / interface the `parentClass` implements signals from
1615
- * @returns
1616
- */
1617
- getClassSignalsTsData(girClass) {
1618
- const girSignals = [];
1619
- const signals = girClass.signal ||
1620
- girClass['glib:signal'] ||
1621
- [];
1622
- if (signals) {
1623
- for (const girSignal of signals) {
1624
- girSignal._tsData = this.setSignalTsData(girSignal, girClass);
1625
- if (!girSignal._tsData)
1626
- continue;
1627
- if (girSignal._fullSymName)
1628
- this.symTable.set(this.allDependencies, girSignal._fullSymName, girSignal);
1629
- girSignals.push(girSignal);
1630
- }
1631
- }
1632
- return girSignals;
1633
- }
1634
- getClassParentObject(parentName, namespace, type) {
1635
- let qualifiedParentName;
1636
- let parentModName;
1637
- // WORKAROUND: Fix wrong parent names
1638
- if ((this.packageName === 'GstAudio-0.10' || this.packageName === 'ClutterGst-1.0') &&
1639
- (parentName === 'GstBase.BaseTransform' ||
1640
- parentName === 'GstBase.BaseSink' ||
1641
- parentName === 'GstBase.PushSrc')) {
1642
- const rename = parentName.replace('GstBase.', 'Gst.');
1643
- this.log.warn(`[getClassParentObject] Rename parent class "${parentName}" -> "${rename}"`);
1644
- parentName = rename;
1645
- }
1646
- if (parentName === 'GraniteServicesSettingsSerializable') {
1647
- parentName = 'ServicesSettingsSerializable';
1648
- this.log.warn(`[getClassParentObject] Rename parent class "GraniteServicesSettingsSerializable" -> "ServicesSettingsSerializable"`);
1649
- }
1650
- if (parentName.indexOf('.') < 0) {
1651
- qualifiedParentName = namespace + '.' + parentName;
1652
- parentModName = namespace;
1653
- }
1654
- else {
1655
- qualifiedParentName = parentName;
1656
- const split = parentName.split('.');
1657
- parentName = split[split.length - 1];
1658
- parentModName = split.slice(0, split.length - 1).join('.');
1659
- }
1660
- const localParentName = parentModName == namespace ? parentName : qualifiedParentName;
1661
- const dependencyExists = !!this.symTable.get(this.allDependencies, qualifiedParentName);
1662
- const cls = this.getClassParent({
1663
- qualifiedParentName,
1664
- parentName,
1665
- });
1666
- return {
1667
- qualifiedParentName,
1668
- localParentName,
1669
- type,
1670
- parentName,
1671
- cls,
1672
- dependencyExists,
1673
- // TODO: are there other types that can be inherited or implemented?
1674
- girTypeName: type === 'parent' ? 'class' : 'interface',
1675
- };
1676
- }
1677
- getClassParents(girClass) {
1678
- const parents = [];
1679
- if (!girClass._module?.namespace) {
1680
- throw new Error('Namespace not found!');
1681
- }
1682
- if (!girClass._tsData) {
1683
- throw new Error(NO_TSDATA('getClassParents'));
1684
- }
1685
- const prerequisites = girClass?.prerequisite;
1686
- const implmts = girClass?.implements;
1687
- if (implmts) {
1688
- for (const implement of implmts) {
1689
- const parentName = implement.$?.name;
1690
- if (!parentName)
1691
- continue;
1692
- const parent = this.getClassParentObject(parentName, girClass._module.namespace, 'implements');
1693
- if (parent.dependencyExists) {
1694
- parents.push(parent);
1695
- }
1696
- }
1697
- }
1698
- if (prerequisites) {
1699
- for (const prerequisite of prerequisites) {
1700
- const parentName = prerequisite.$?.name;
1701
- if (!parentName)
1702
- continue;
1703
- const parent = this.getClassParentObject(parentName, girClass._module.namespace, 'prerequisite');
1704
- if (parent.dependencyExists) {
1705
- parents.push(parent);
1706
- }
1707
- }
1708
- }
1709
- if (girClass.$.parent) {
1710
- const parentName = girClass.$.parent;
1711
- if (parentName) {
1712
- const parent = this.getClassParentObject(parentName, girClass._module.namespace, 'parent');
1713
- if (parent.dependencyExists) {
1714
- parents.push(parent);
1715
- }
1716
- }
1717
- }
1718
- // Please reply: Do all interfaces always inherit from GObject.Object?
1719
- // If this is a interface and GObject.Object is not in the parents array, add GObject.Object to the parents
1720
- if (girClass._tsData.girTypeName === 'interface' && girClass._fullSymName !== 'GObject.Object') {
1721
- if (!parents.find((parent) => parent.qualifiedParentName === 'GObject.Object')) {
1722
- // TODO make sure this class exists in symTable
1723
- const gObjectObjectCls = this.symTable.getByHand('GObject-2.0.GObject.Object') || undefined;
1724
- const parent = {
1725
- qualifiedParentName: 'GObject.Object',
1726
- localParentName: girClass._module.namespace === 'GObject' ? 'Object' : 'GObject.Object',
1727
- type: 'parent',
1728
- parentName: 'Object',
1729
- cls: gObjectObjectCls,
1730
- dependencyExists: !!gObjectObjectCls,
1731
- girTypeName: 'class',
1732
- };
1733
- if (parent.dependencyExists) {
1734
- parents.push(parent);
1735
- }
1736
- }
1737
- }
1738
- return parents;
1739
- }
1740
- setClassBaseTsData(girClass, girTypeName) {
1741
- if (!girClass?.$?.name)
1742
- return undefined;
1743
- const girModule = girClass._module ? girClass._module : this;
1744
- let className = this.transformation.transformClassName(girClass.$.name);
1745
- /**
1746
- * E.g. 'Gtk'
1747
- */
1748
- const namespace = girModule.namespace;
1749
- /**
1750
- * E.g. '3.0'
1751
- */
1752
- const version = girModule.version;
1753
- let qualifiedName;
1754
- if (!className.includes('.')) {
1755
- qualifiedName = namespace + '.' + className;
1756
- }
1757
- else {
1758
- qualifiedName = className;
1759
- const split = className.split('.');
1760
- className = split[split.length - 1];
1761
- }
1762
- girClass._tsData = {
1763
- name: className,
1764
- qualifiedName,
1765
- parents: [],
1766
- namespace,
1767
- version,
1768
- isAbstract: this.isAbstractClass(girClass),
1769
- localNames: {},
1770
- constructPropNames: {},
1771
- inheritConstructPropInterfaceNames: [],
1772
- constructPropInterfaceName: `${namespace}.${className}.ConstructorProperties`,
1773
- fields: [],
1774
- properties: [],
1775
- conflictProperties: [],
1776
- constructProps: [],
1777
- propertySignalMethods: [],
1778
- methods: [],
1779
- conflictMethods: [],
1780
- virtualMethods: [],
1781
- constructors: [],
1782
- staticFunctions: [],
1783
- signals: [],
1784
- generics: [],
1785
- inherit: {},
1786
- implements: {},
1787
- girTypeName,
1788
- tsTypeName: this.girFactory.girTypeNameToTsTypeName(girTypeName, false),
1789
- doc: this.getTsDoc(girClass),
1790
- };
1791
- girClass._tsData.doc.tags.push(...this.getTsDocGirElementTags(girClass._tsData.tsTypeName, girClass._tsData.girTypeName));
1792
- girClass._tsData.parents = this.getClassParents(girClass);
1793
- if (girClass._tsData.parents.length) {
1794
- for (const parent of girClass._tsData.parents) {
1795
- girClass._tsData.inheritConstructPropInterfaceNames.push(`${parent.qualifiedParentName}.ConstructorProperties`);
1796
- }
1797
- }
1798
- girClass._tsData.isDerivedFromGObject = this.isDerivedFromGObject(girClass);
1799
- return girClass._tsData;
1800
- }
1801
- setClassTsData(girClass, girTypeName) {
1802
- if (!girClass?.$?.name)
1803
- return undefined;
1804
- if (girClass._tsData) {
1805
- return girClass._tsData;
1806
- }
1807
- girClass._tsData = this.setClassBaseTsData(girClass, girTypeName);
1808
- if (!girClass._tsData) {
1809
- return undefined;
1810
- }
1811
- // BASE
1812
- if (girClass._tsData.isDerivedFromGObject) {
1813
- girClass._tsData.constructProps.push(...this.getClassConstructPropsTsData(girClass, girClass._tsData.constructPropNames));
1814
- }
1815
- girClass._tsData.constructors.push(...this.getClassConstructorsTsData(girClass));
1816
- girClass._tsData.staticFunctions.push(...this.getClassStaticFunctionsTsData(girClass, girClass._tsData));
1817
- girClass._tsData.fields.push(...this.getClassFieldsTsData(girClass, girClass._tsData.localNames));
1818
- girClass._tsData.properties.push(...this.getClassPropertiesTsData(girClass, girClass._tsData.localNames));
1819
- girClass._tsData.methods.push(...this.getClassMethodsTsData(girClass, girClass._tsData.localNames));
1820
- girClass._tsData.virtualMethods.push(...this.getClassVirtualMethodsTsData(girClass));
1821
- girClass._tsData.signals.push(...this.getClassSignalsTsData(girClass));
1822
- girClass._tsData.properties.push(...this.getGObjectProperties(girClass));
1823
- // Copy fields, properties, methods, virtual methods and signals from inheritance tree
1824
- this.traverseInheritanceTree(girClass, girClass._tsData.girTypeName, (extendsCls, depth) => {
1825
- if (!girClass._tsData || !extendsCls._tsData || !extendsCls._fullSymName || !extendsCls._module) {
1826
- return;
1827
- }
1828
- if (girClass._fullSymName === extendsCls._fullSymName) {
1829
- return;
1830
- }
1831
- const key = extendsCls._module.packageName + '.' + extendsCls._fullSymName;
1832
- if (girClass._tsData.inherit[key])
1833
- return;
1834
- girClass._tsData.inherit[key] = {
1835
- depth,
1836
- class: extendsCls._tsData,
1837
- };
1838
446
  });
1839
- // Copy properties, methods and signals from implemented interface
1840
- this.forEachInterface(girClass, girClass._tsData.girTypeName, (iface, depth) => {
1841
- if (!girClass._tsData || !iface._tsData || !iface._fullSymName || !iface._module) {
1842
- return;
1843
- }
1844
- if (girClass._fullSymName === iface._fullSymName) {
1845
- return;
1846
- }
1847
- const key = iface._module.packageName + '.' + iface._fullSymName;
1848
- if (girClass._tsData.implements[key])
1849
- return;
1850
- girClass._tsData.implements[key] = {
1851
- depth,
1852
- interface: iface._tsData,
1853
- };
1854
- });
1855
- this.inject.toClass(girClass);
1856
- girClass._tsData.propertySignalMethods.push(...this.getClassPropertySignalsMethods(girClass), ...this.getGeneralSignalsMethods(girClass._tsData));
1857
- if (this.config.fixConflicts) {
1858
- this.conflictResolver.repairClass(girClass);
1859
- }
1860
- return girClass._tsData;
1861
- }
1862
- isDerivedFromGObject(girClass) {
1863
- if (typeof girClass._tsData?.isDerivedFromGObject === 'boolean')
1864
- return girClass._tsData.isDerivedFromGObject;
1865
- let ret = false;
1866
- const onClassOrInterface = (cls) => {
1867
- if (cls._tsData?.isDerivedFromGObject === true || cls._fullSymName === 'GObject.Object') {
1868
- ret = true;
1869
- }
1870
- };
1871
- if (!girClass._tsData)
1872
- throw new Error(NO_TSDATA('isDerivedFromGObject'));
1873
- this.traverseInheritanceTree(girClass, girClass._tsData.tsTypeName, onClassOrInterface);
1874
- this.forEachInterface(girClass, girClass._tsData.tsTypeName, onClassOrInterface);
1875
- return ret;
1876
- }
1877
- getClassParent(parent) {
1878
- let parentPtr = undefined;
1879
- if (this.symTable.get(this.allDependencies, parent.qualifiedParentName)) {
1880
- parentPtr =
1881
- this.symTable.get(this.allDependencies, parent.qualifiedParentName) || undefined;
1882
- }
1883
- if (!parentPtr && parent.parentName == 'Object') {
1884
- parentPtr = this.symTable.getByHand('GObject-2.0.GObject.Object') || undefined;
1885
- }
1886
- return parentPtr;
1887
- }
1888
- traverseInheritanceTree(girClass, gitTypeName, callback, depth = 0, recursive = true) {
1889
- if (!girClass.$.name)
1890
- return;
1891
- if (!girClass._tsData)
1892
- girClass._tsData = this.setClassTsData(girClass, gitTypeName);
1893
- if (!girClass._tsData)
1894
- return;
1895
- callback(girClass, depth);
1896
- const parents = girClass._tsData.parents;
1897
- if (recursive && parents.length) {
1898
- ++depth;
1899
- if (depth >= MAX_CLASS_PARENT_DEPTH) {
1900
- this.log.error('[traverseInheritanceTree] Maximum recursion depth reached');
1901
- return;
1902
- }
1903
- for (const parent of parents) {
1904
- if (!parent.parentName || parent.type !== 'parent') {
1905
- continue;
1906
- }
1907
- if (parent.cls) {
1908
- if (parent.cls === girClass) {
1909
- this.log.warn('[traverseInheritanceTree] A class cannot inherit itself');
1910
- continue;
1911
- }
1912
- this.traverseInheritanceTree(parent.cls, parent.girTypeName, callback, depth, recursive);
1913
- }
1914
- }
1915
- }
1916
- }
1917
- forEachInterface(girIface, girTypeName, callback, recursive = true, depth = 0) {
1918
- if (!girIface.$.name)
1919
- return;
1920
- if (!girIface._tsData)
1921
- girIface._tsData = this.setClassTsData(girIface, girTypeName);
1922
- if (!girIface._tsData) {
1923
- throw new Error(NO_TSDATA('forEachInterface'));
1924
- }
1925
- const parents = girIface._tsData.parents;
1926
- if (parents.length) {
1927
- ++depth;
1928
- for (const parent of parents) {
1929
- if (!parent.parentName || parent.type === 'parent') {
1930
- continue;
1931
- }
1932
- if (parent.cls) {
1933
- callback(parent.cls, depth);
1934
- // iface's prerequisite is also an interface, or it's
1935
- // a class and we also want to recurse classes
1936
- if (recursive)
1937
- this.forEachInterface(parent.cls, parent.girTypeName, callback, recursive, depth);
1938
- }
1939
- }
1940
- }
1941
- }
1942
- /**
1943
- *
1944
- * @param girElement
1945
- * @param localNames Can be (constructor) properties, fields or methods
1946
- * @param type
1947
- */
1948
- checkOrSetLocalName(girElement, localNames, type) {
1949
- let isOverloadable = false;
1950
- if (!girElement._tsData) {
1951
- return null;
1952
- }
1953
- const name = girElement._tsData?.name;
1954
- if (!name) {
1955
- return null;
1956
- }
1957
- // Methods are overloadable by typescript
1958
- // TODO Add support for properties
1959
- if (type === 'method') {
1960
- isOverloadable = true;
1961
- }
1962
- // Only names of the same type are overloadable
1963
- if (localNames[name]?.type && localNames[name].type !== type) {
1964
- // In GIO there are some methods and properties with the same name
1965
- // E.g. on `WebKit2.WebView.isLoading` and `WebKit2.WebView.isLoading()`
1966
- // See Gjs doc https://gjs-docs.gnome.org/webkit240~4.0_api/webkit2.webview#property-is_loading
1967
- // TODO prefer functions over properties (Overwrite the properties with the functions if they have the same name)
1968
- return null;
1969
- }
1970
- // If name is found in localNames this variable was already defined
1971
- if (localNames?.[name]?.[type]?._tsData) {
1972
- // Ignore duplicates with the same type
1973
- // TODO should we use `this.functionSignaturesMatch` here?
1974
- if (type === 'method') {
1975
- const tsMethod1 = girElement._tsData;
1976
- const tsMethod2 = localNames[name][type]._tsData;
1977
- if (!tsMethod1 || !tsMethod2) {
1978
- return null;
1979
- }
1980
- // if (ConflictResolver.functionConflict(tsMethod1, tsMethod2)) {
1981
- // return null
1982
- // }
1983
- }
1984
- else {
1985
- // TODO better handling of property and field
1986
- if (isEqual(localNames[name][type]?._tsData, girElement._tsData)) {
1987
- return null;
1988
- }
1989
- }
1990
- // Ignore if current method is not overloadable
1991
- if (!isOverloadable) {
1992
- return null;
1993
- }
1994
- }
1995
- localNames[name] = localNames[name] || {};
1996
- const localName = {
1997
- ...localNames[name],
1998
- [type]: girElement,
1999
- type,
2000
- };
2001
- localNames[name] = localName;
2002
- return { ...localName, added: true };
2003
- }
2004
- isGtypeStructFor(e, rec) {
2005
- const isFor = rec.$['glib:is-gtype-struct-for'];
2006
- return isFor && isFor == e.$.name;
2007
- }
2008
- /**
2009
- * E.g GObject.ObjectClass is a abstract class and required by UPowerGlib-1.0, UDisks-2.0 and others
2010
- * @param girClass
2011
- * @returns `true` if this is this a abstract class.
2012
- */
2013
- isAbstractClass(girClass) {
2014
- return girClass.$?.['glib:is-gtype-struct-for'] ? true : false;
2015
- }
2016
- /**
2017
- *
2018
- * @param girClass
2019
- * @returns
2020
- */
2021
- getOtherStaticFunctions(girClass) {
2022
- const girFunctions = [];
2023
- if (!girClass._tsData)
2024
- return girFunctions;
2025
- if (girClass.function?.length) {
2026
- for (const girFunction of girClass.function) {
2027
- girFunction._tsData = this.getFunctionTsData(girFunction, 'static-function', girClass._tsData, {
2028
- isStatic: true,
2029
- isArrowType: false,
2030
- isGlobal: false,
2031
- isVirtual: false,
2032
- returnType: null,
2033
- generics: [],
2034
- });
2035
- if (!girFunction._tsData?.name)
2036
- continue;
2037
- if (girFunction._tsData.name.startsWith('new'))
2038
- continue;
2039
- girFunctions.push(girFunction);
2040
- }
2041
- }
2042
- return girFunctions;
2043
- }
2044
- getStaticNewFunctions(girClass, parentClass) {
2045
- const girFunctions = [];
2046
- if (girClass.function?.length) {
2047
- for (const girFunction of girClass.function) {
2048
- girFunction._tsData = this.getConstructorFunctionTsData(parentClass, girFunction);
2049
- if (!girFunction._tsData?.name.startsWith('new'))
2050
- continue;
2051
- girFunctions.push(girFunction);
2052
- }
2053
- }
2054
- return girFunctions;
2055
- }
2056
- /**
2057
- * Static methods, <constructor> and <function>
2058
- * @param girClass
2059
- * @param constructorTypeName Used to overwrite the constructor return type
2060
- * @param useReference This value should be `false` for inherited and implemented classes / interfaces.
2061
- * Otherwise other modules would overwrite the return value of the constructor methods
2062
- */
2063
- getClassStaticFunctionsTsData(girClass, parentClass) {
2064
- const girStaticFuncs = [];
2065
- girStaticFuncs.push(...this.getStaticNewFunctions(girClass, parentClass));
2066
- girStaticFuncs.push(...this.getOtherStaticFunctions(girClass));
2067
- girStaticFuncs.push(...this.getClassRecordMethods(girClass));
2068
- return girStaticFuncs;
2069
- }
2070
- setModuleTsData() {
2071
- if (this.ns.enumeration) {
2072
- for (const girEnum of this.ns.enumeration) {
2073
- if (girEnum.member) {
2074
- for (const girEnumMember of girEnum.member) {
2075
- girEnumMember._tsData = this.getEnumerationMemberTsData(girEnumMember, 'enum-member');
2076
- if (!girEnumMember._tsData)
2077
- continue;
447
+ // Get the requested classes
448
+ if (ns.class) {
449
+ ns.class
450
+ ?.filter(isIntrospectable)
451
+ .map((klass) => IntrospectedClass.fromXML(klass, building, options))
452
+ .filter(importConflicts)
453
+ .forEach((c) => building.members.set(c.name, c));
454
+ }
455
+ if (ns.record) {
456
+ ns.record
457
+ ?.filter(isIntrospectable)
458
+ .map((record) => IntrospectedRecord.fromXML(record, building, options))
459
+ .filter(importConflicts)
460
+ .forEach((c) => building.members.set(c.name, c));
461
+ }
462
+ if (ns.union) {
463
+ ns.union
464
+ ?.filter(isIntrospectable)
465
+ .map((union) => IntrospectedRecord.fromXML(union, building, options))
466
+ .filter(importConflicts)
467
+ .forEach((c) => building.members.set(c.name, c));
468
+ }
469
+ if (ns.interface) {
470
+ ns.interface
471
+ ?.map((inter) => IntrospectedInterface.fromXML(inter, building, options))
472
+ .filter(importConflicts)
473
+ .forEach((c) => building.members.set(c.name, c));
474
+ }
475
+ if (ns.alias) {
476
+ ns.alias
477
+ ?.filter(isIntrospectable)
478
+ // Avoid attempting to alias non-introspectable symbols.
479
+ .map((b) => {
480
+ b.type = b.type
481
+ ?.filter((t) => !!(t && t.$.name))
482
+ .map((t) => {
483
+ if (t.$.name &&
484
+ !building.hasSymbol(t.$.name) &&
485
+ !isPrimitiveType(t.$.name) &&
486
+ !t.$.name.includes('.')) {
487
+ return { $: { name: 'unknown', 'c:type': 'unknown' } };
2078
488
  }
2079
- }
2080
- girEnum._tsData = this.getEnumerationTsData(girEnum, 'enum');
2081
- this.fixEnumerationDuplicateIdentifier(girEnum);
2082
- if (!girEnum._tsData)
2083
- continue;
2084
- }
2085
- }
2086
- if (this.ns.bitfield)
2087
- for (const girBitfield of this.ns.bitfield) {
2088
- if (girBitfield.member)
2089
- for (const girEnumMember of girBitfield.member) {
2090
- girEnumMember._tsData = this.getEnumerationMemberTsData(girEnumMember, 'bitfield-member');
2091
- }
2092
- girBitfield._tsData = this.getEnumerationTsData(girBitfield, 'bitfield');
2093
- if (!girBitfield._tsData)
2094
- continue;
2095
- this.fixEnumerationDuplicateIdentifier(girBitfield);
2096
- }
2097
- if (this.ns.constant)
2098
- for (const girConst of this.ns.constant) {
2099
- girConst._tsData = this.getConstantTsData(girConst, null);
2100
- if (!girConst._tsData)
2101
- continue;
2102
- }
2103
- if (this.ns.function) {
2104
- for (const girFunc of this.ns.function) {
2105
- girFunc._tsData = this.getFunctionTsData(girFunc, 'function', null, {
2106
- isStatic: false,
2107
- isArrowType: false,
2108
- isGlobal: true,
2109
- isVirtual: false,
2110
- returnType: null,
2111
- generics: [],
489
+ return t;
2112
490
  });
2113
- if (!girFunc._tsData)
2114
- continue;
2115
- }
2116
- this.overloadPromisifiedFunctions(this.ns.function);
2117
- }
2118
- if (this.ns.callback)
2119
- for (const girCallback of this.ns.callback) {
2120
- girCallback._tsData = this.setCallbackTsData(girCallback, null);
2121
- }
2122
- if (this.ns.interface)
2123
- for (const girIface of this.ns.interface) {
2124
- girIface._tsData = this.setClassTsData(girIface, 'interface');
2125
- }
2126
- if (this.ns.class)
2127
- for (const girClass of this.ns.class) {
2128
- girClass._tsData = this.setClassTsData(girClass, 'class');
2129
- if (!girClass._tsData)
2130
- continue;
2131
- }
2132
- if (this.ns.record)
2133
- for (const girRecord of this.ns.record) {
2134
- girRecord._tsData = this.setClassTsData(girRecord, 'record');
2135
- if (!girRecord._tsData)
2136
- continue;
2137
- }
2138
- if (this.ns.union)
2139
- for (const girUnion of this.ns.union) {
2140
- girUnion._tsData = this.setClassTsData(girUnion, 'union');
2141
- if (!girUnion._tsData)
2142
- continue;
2143
- }
2144
- if (this.ns.alias) {
2145
- for (const girAlias of this.ns.alias) {
2146
- // GType is not a number in GJS
2147
- if (this.packageName !== 'GObject-2.0' || girAlias.$.name !== 'Type')
2148
- girAlias._tsData = this.getAliasTsData(girAlias, null);
2149
- if (!girAlias._tsData)
2150
- continue;
2151
- }
2152
- }
2153
- }
2154
- /**
2155
- * TODO: find better name for this method
2156
- * @param fullTypeName
2157
- * @returns
2158
- */
2159
- fullTypeLookupWithNamespace(fullTypeName) {
2160
- let resValue = '';
2161
- let namespace = '';
2162
- // Check overwrites first
2163
- if (!resValue && fullTypeName && FULL_TYPE_MAP(this.config.environment, fullTypeName)) {
2164
- resValue = FULL_TYPE_MAP(this.config.environment, fullTypeName) || '';
2165
- }
2166
- // Only use the fullTypeName as the type if it is found in the symTable
2167
- if (!resValue && this.symTable.get(this.allDependencies, fullTypeName)) {
2168
- if (fullTypeName.startsWith(this.namespace + '.')) {
2169
- resValue = removeNamespace(fullTypeName, this.namespace);
2170
- resValue = this.transformation.transformTypeName(resValue);
2171
- // TODO: check if resValue is a class, enum or interface before transformClassName
2172
- resValue = this.transformation.transformClassName(resValue);
2173
- namespace = this.namespace;
2174
- resValue = namespace + '.' + resValue;
2175
- }
2176
- else {
2177
- const resValues = fullTypeName.split('.');
2178
- resValues.map((name) => this.transformation.transformTypeName(name));
2179
- // TODO: check if resValues[resValues.length - 1] is a class, enum, interface before transformClassName
2180
- resValues[resValues.length - 1] = this.transformation.transformClassName(resValues[resValues.length - 1]);
2181
- resValue = resValues.join('.');
2182
- namespace = resValues[0];
2183
- }
2184
- }
2185
- return {
2186
- value: resValue,
2187
- namespace,
2188
- };
2189
- }
2190
- loadInheritance(inheritanceTable) {
2191
- // Class hierarchy
2192
- for (const girClass of this.ns.class ? this.ns.class : []) {
2193
- let parent = null;
2194
- if (girClass.$ && girClass.$.parent)
2195
- parent = girClass.$.parent;
2196
- if (!parent)
2197
- continue;
2198
- if (!girClass._fullSymName)
2199
- continue;
2200
- if (!parent.includes('.')) {
2201
- parent = addNamespace(parent, this.namespace);
2202
- }
2203
- const className = girClass._fullSymName;
2204
- const arr = inheritanceTable[className] || [];
2205
- arr.push(parent);
2206
- inheritanceTable[className] = arr;
2207
- }
2208
- // Class interface implementations
2209
- for (const girClass of this.ns.class ? this.ns.class : []) {
2210
- if (!girClass._fullSymName)
2211
- continue;
2212
- const names = [];
2213
- if (girClass.implements) {
2214
- for (const girImplements of girClass.implements) {
2215
- if (girImplements.$.name) {
2216
- let name = girImplements.$.name;
2217
- if (!name.includes('.')) {
2218
- name = girClass._fullSymName.substring(0, girClass._fullSymName.indexOf('.') + 1) + name;
2219
- }
2220
- names.push(name);
2221
- }
2222
- }
2223
- }
2224
- if (names.length > 0) {
2225
- const className = girClass._fullSymName;
2226
- const arr = inheritanceTable[className] || [];
2227
- inheritanceTable[className] = arr.concat(names);
2228
- }
2229
- }
2230
- }
2231
- loadTypes() {
2232
- if (this.ns.bitfield)
2233
- this.annotateAndRegisterGirElement(this.ns.bitfield);
2234
- if (this.ns.callback)
2235
- this.annotateAndRegisterGirElement(this.ns.callback);
2236
- if (this.ns.class)
2237
- this.annotateAndRegisterGirElement(this.ns.class);
2238
- if (this.ns.constant)
2239
- this.annotateAndRegisterGirElement(this.ns.constant);
2240
- if (this.ns.enumeration)
2241
- this.annotateAndRegisterGirElement(this.ns.enumeration);
2242
- if (this.ns.function)
2243
- this.annotateAndRegisterGirElement(this.ns.function);
2244
- if (this.ns.interface)
2245
- this.annotateAndRegisterGirElement(this.ns.interface);
2246
- if (this.ns.record)
2247
- this.annotateAndRegisterGirElement(this.ns.record);
2248
- if (this.ns.union)
2249
- this.annotateAndRegisterGirElement(this.ns.union);
2250
- if (this.ns.alias)
2251
- this.annotateAndRegisterGirElement(this.ns.alias);
2252
- if (this.ns.callback)
2253
- for (const girCallback of this.ns.callback)
2254
- this.annotateFunctionArguments(girCallback);
2255
- for (const girClass of this.ns.class || []) {
2256
- this.annotateClass(girClass, 'class');
2257
- }
2258
- for (const girClass of this.ns.record || []) {
2259
- this.annotateClass(girClass, 'record');
2260
- }
2261
- for (const girClass of this.ns.interface || []) {
2262
- this.annotateClass(girClass, 'interface');
2263
- }
2264
- if (this.ns.function)
2265
- this.annotateFunctions(this.ns.function);
2266
- if (this.ns.callback)
2267
- this.annotateFunctions(this.ns.callback);
2268
- if (this.ns.constant)
2269
- this.annotateVariables(this.ns.constant);
2270
- }
2271
- /**
2272
- * Before processing the typescript data, each module should be initialized first.
2273
- * This is done in the `GenerationHandler`.
2274
- */
2275
- init(inheritanceTable) {
2276
- this.loadTypes();
2277
- this.loadInheritance(inheritanceTable);
491
+ return b;
492
+ })
493
+ .map((alias) => IntrospectedAlias.fromXML(alias, building, options))
494
+ .filter((alias) => alias != null)
495
+ .forEach((c) => building.members.set(c.name, c));
496
+ }
497
+ building.namespace = building.ns.name;
498
+ building.version = building.ns.version;
499
+ building.packageName = `${building.namespace}-${building.version}`;
500
+ building.libraryVersion = new LibraryVersion(ns.constant, building.version);
501
+ building.transformation = new Transformation(config);
502
+ building.log = new Logger(config.verbose, building.packageName || 'GirModule');
503
+ building.importNamespace = building.transformation.transformModuleNamespaceName(building.packageName);
504
+ building.importName = building.transformation.transformImportName(building.packageName);
505
+ building.symTable = new SymTable(building.config, building.packageName, building.namespace);
506
+ return building;
2278
507
  }
2279
508
  /**
2280
509
  * Start processing the typescript data
@@ -2287,7 +516,59 @@ export class GirModule {
2287
516
  this.libraryVersion = glibModule.libraryVersion;
2288
517
  }
2289
518
  }
2290
- this.setModuleTsData();
2291
519
  }
2292
520
  }
521
+ export const isIntrospectable = (e) => !e || !e.$ || !e.$.introspectable || e.$.introspectable === '1';
522
+ export const isDeprecated = (e) => e && e.$ && e.$.deprecated === '1';
523
+ export const deprecatedVersion = (e) => e?.$?.['deprecated-version'];
524
+ export const introducedVersion = (e) => e?.$?.version;
525
+ export function promisifyNamespaceFunctions(namespace) {
526
+ return namespace.members.forEach((node) => {
527
+ if (!(node instanceof IntrospectedFunction))
528
+ return;
529
+ if (node.parameters.length < 1)
530
+ return;
531
+ const last_param = node.parameters[node.parameters.length - 1];
532
+ if (!last_param)
533
+ return;
534
+ const last_param_unwrapped = last_param.type.unwrap();
535
+ if (!(last_param_unwrapped instanceof ClosureType))
536
+ return;
537
+ const internal = last_param_unwrapped.type;
538
+ if (internal instanceof TypeIdentifier && internal.is('Gio', 'AsyncReadyCallback')) {
539
+ const async_res = [
540
+ ...Array.from(namespace.members.values()).filter((m) => m instanceof IntrospectedFunction),
541
+ ].find((m) => m.name === `${node.name.replace(/_async$/, '')}_finish` || m.name === `${node.name}_finish`);
542
+ if (async_res) {
543
+ const async_parameters = node.parameters.slice(0, -1).map((p) => p.copy());
544
+ const sync_parameters = node.parameters.map((p) => p.copy({ isOptional: false }));
545
+ const output_parameters = async_res.output_parameters;
546
+ let async_return = new PromiseType(async_res.return());
547
+ if (output_parameters.length > 0) {
548
+ const raw_return = async_res.return();
549
+ if (raw_return.equals(VoidType) || raw_return.equals(BooleanType)) {
550
+ const [output_type, ...output_types] = output_parameters.map((op) => op.type);
551
+ async_return = new PromiseType(new TupleType(output_type, ...output_types));
552
+ }
553
+ else {
554
+ const [...output_types] = output_parameters.map((op) => op.type);
555
+ async_return = new PromiseType(new TupleType(raw_return, ...output_types));
556
+ }
557
+ }
558
+ namespace.members.set(node.name, [
559
+ node.copy({
560
+ parameters: async_parameters,
561
+ return_type: async_return,
562
+ }),
563
+ node.copy({
564
+ parameters: sync_parameters,
565
+ }),
566
+ node.copy({
567
+ return_type: new BinaryType(async_return, node.return()),
568
+ }),
569
+ ]);
570
+ }
571
+ }
572
+ });
573
+ }
2293
574
  //# sourceMappingURL=gir-module.js.map