@nstudio/nativescript-compiler 9.2.0-alpha.10 → 9.2.0-alpha.12

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 (181) hide show
  1. package/dist/api/ir.js +7 -1
  2. package/dist/cli/runtime.cjs +7 -1
  3. package/dist/css/css.js +30 -6
  4. package/dist/driver/cli.js +2 -0
  5. package/dist/driver/compile.js +23 -10
  6. package/dist/driver/paths.js +7 -0
  7. package/dist/driver/unimplemented.js +15 -0
  8. package/dist/kotlin/access.js +23 -5
  9. package/dist/kotlin/arguments.js +5 -0
  10. package/dist/kotlin/builtins.js +0 -4
  11. package/dist/kotlin/calls.js +6 -2
  12. package/dist/kotlin/class-methods.js +9 -3
  13. package/dist/kotlin/components.js +13 -8
  14. package/dist/kotlin/conversion.js +17 -5
  15. package/dist/kotlin/core-api.js +2 -13
  16. package/dist/kotlin/declarations.js +2 -0
  17. package/dist/kotlin/expression-statements.js +5 -4
  18. package/dist/kotlin/expressions.js +8 -3
  19. package/dist/kotlin/functions.js +13 -4
  20. package/dist/kotlin/global-calls.js +11 -0
  21. package/dist/kotlin/literals.js +58 -14
  22. package/dist/kotlin/names.js +2 -2
  23. package/dist/kotlin/native/api.js +9 -1
  24. package/dist/kotlin/native/calls.js +84 -3
  25. package/dist/kotlin/native/subclasses.js +4 -3
  26. package/dist/kotlin/native/types.js +8 -5
  27. package/dist/kotlin/operators.js +4 -1
  28. package/dist/kotlin/overrides.js +7 -5
  29. package/dist/kotlin/placement.js +3 -1
  30. package/dist/kotlin/prototype-calls.js +5 -0
  31. package/dist/kotlin/render.js +62 -0
  32. package/dist/kotlin/statements.js +9 -0
  33. package/dist/kotlin/static-calls.js +10 -7
  34. package/dist/kotlin/translator.js +31 -11
  35. package/dist/kotlin/type-facts.js +10 -2
  36. package/dist/kotlin/types.js +6 -6
  37. package/dist/plugins/native-android.js +37 -5
  38. package/dist/plugins/native-ios.js +2 -0
  39. package/dist/plugins/source.js +73 -23
  40. package/dist/program/app-modules.js +91 -16
  41. package/dist/program/app-paths.js +80 -12
  42. package/dist/program/class-mixins.js +463 -0
  43. package/dist/program/core-facts.js +7 -0
  44. package/dist/program/glob.js +274 -0
  45. package/dist/program/platform.js +32 -4
  46. package/dist/program/program.js +239 -38
  47. package/dist/program/source-lines.js +4 -1
  48. package/dist/program/vite-plugins.js +144 -0
  49. package/dist/semantics/apis/globals.js +2 -2
  50. package/dist/semantics/apis/object.js +1 -0
  51. package/dist/semantics/apis/statics.js +6 -0
  52. package/dist/semantics/ast.js +20 -2
  53. package/dist/semantics/classes.js +36 -1
  54. package/dist/semantics/facts.js +28 -1
  55. package/dist/semantics/globals.js +3 -0
  56. package/dist/semantics/lang.js +13 -1
  57. package/dist/semantics/nullish.js +29 -11
  58. package/dist/semantics/refuse-receivers.js +3 -3
  59. package/dist/semantics/refuse-scope.js +2 -7
  60. package/dist/semantics/runtime.js +1 -0
  61. package/dist/semantics/shapes.js +21 -1
  62. package/dist/semantics/states/value-states.js +1 -1
  63. package/dist/semantics/throws.js +1 -0
  64. package/dist/semantics/translator-methods.js +1 -1
  65. package/dist/semantics/types.js +21 -1
  66. package/dist/swift/access.js +25 -10
  67. package/dist/swift/arguments.js +10 -2
  68. package/dist/swift/assignment.js +12 -1
  69. package/dist/swift/builtins.js +0 -4
  70. package/dist/swift/calls.js +6 -2
  71. package/dist/swift/class-methods.js +3 -3
  72. package/dist/swift/components.js +28 -8
  73. package/dist/swift/construction.js +4 -0
  74. package/dist/swift/conversion.js +1 -1
  75. package/dist/swift/core-api.js +9 -12
  76. package/dist/swift/from-any.js +2 -2
  77. package/dist/swift/functions.js +13 -2
  78. package/dist/swift/generics.js +5 -1
  79. package/dist/swift/global-calls.js +2 -0
  80. package/dist/swift/literals.js +57 -10
  81. package/dist/swift/modules.js +1 -1
  82. package/dist/swift/names.js +1 -1
  83. package/dist/swift/native/sdk-tables.js +52 -4
  84. package/dist/swift/native/sdk.js +9 -1
  85. package/dist/swift/operators.js +4 -1
  86. package/dist/swift/parameters.js +5 -2
  87. package/dist/swift/placement.js +44 -4
  88. package/dist/swift/prototype-calls.js +17 -2
  89. package/dist/swift/render.js +64 -0
  90. package/dist/swift/results.js +1 -1
  91. package/dist/swift/statements.js +9 -0
  92. package/dist/swift/static-calls.js +13 -6
  93. package/dist/swift/types.js +9 -9
  94. package/dist/targets/android/build.js +18 -12
  95. package/dist/targets/ios/build.js +11 -10
  96. package/dist/targets/ios/dependencies.js +12 -0
  97. package/dist/targets/resources.js +15 -1
  98. package/dist/template/plan.js +105 -8
  99. package/dist/types/adapter-api.d.ts +13 -0
  100. package/dist/types/ir.d.ts +47 -0
  101. package/kit-android/generated/kotlin/org/nativescript/kit/__Objects.kt +102 -7485
  102. package/kit-android/generated/kotlin/org/nativescript/kit/application_application.kt +4 -4
  103. package/kit-android/generated/kotlin/org/nativescript/kit/image_source_index.kt +1 -1
  104. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_animation_common.kt +7 -3
  105. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_index.kt +3 -1
  106. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_base_index.kt +2 -4
  107. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_index.kt +5 -6
  108. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -3
  109. package/kit-android/generated/kotlin/org/nativescript/kit/ui_dialogs_index.kt +11 -6
  110. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_fragment_transitions.kt +1 -1
  111. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_common.kt +1 -1
  112. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_helper_for_android.kt +7 -5
  113. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_index.kt +6 -3
  114. package/kit-android/generated/kotlin/org/nativescript/kit/ui_gestures_touch_manager.kt +1 -1
  115. package/kit-android/generated/kotlin/org/nativescript/kit/ui_layouts_flexbox_layout_index.kt +1 -1
  116. package/kit-android/generated/kotlin/org/nativescript/kit/ui_search_bar_index.kt +4 -3
  117. package/kit-android/generated/kotlin/org/nativescript/kit/ui_segmented_bar_index.kt +2 -2
  118. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +1 -3
  119. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_index.kt +1 -1
  120. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_fade_transition.kt +1 -1
  121. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_flip_transition.kt +8 -8
  122. package/kit-android/generated/kotlin/org/nativescript/kit/utils_index.kt +1 -1
  123. package/kit-android/generated/source-lines.json +1 -1
  124. package/kit-android/gradlew.bat +94 -0
  125. package/kit-android/src/fromcore/kotlin/org/nativescript/kit/CoreBridge.kt +67 -1
  126. package/kit-android/src/main/kotlin/org/nativescript/kit/Signals.kt +15 -2
  127. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Prototypes.kt +26 -0
  128. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +4 -4
  129. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +26 -161
  130. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +9 -284
  131. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +11 -7
  132. package/kit-apple/Sources/NativeScriptKit/Core/Object_callback_thisArg_once.swift +1 -1
  133. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_index_section_view_ios_android.swift +7 -5
  134. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_oldIndex_newIndex.swift +4 -2
  135. package/kit-apple/Sources/NativeScriptKit/Core/{Object_iterator_prototype_for_keyFor_hasInstance_isConcatSpreadable_and_19_more_91b5f3.swift → Object_iterator_prototype_for_keyFor_hasInstance_isConcatSpreadable_and_19_more_fa18e1.swift} +28 -103
  136. package/kit-apple/Sources/NativeScriptKit/Core/__Namespace.Utils.swift +17 -15
  137. package/kit-apple/Sources/NativeScriptKit/Core/application-settings.index.ios.swift +8 -8
  138. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +4 -4
  139. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +7 -7
  140. package/kit-apple/Sources/NativeScriptKit/Core/data.observable.index.swift +3 -3
  141. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.index.ios.swift +2 -1
  142. package/kit-apple/Sources/NativeScriptKit/Core/image-source.index.ios.swift +1 -1
  143. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +40 -246
  144. package/kit-apple/Sources/NativeScriptKit/Core/manifest.json +1 -2
  145. package/kit-apple/Sources/NativeScriptKit/Core/ui.action-bar.index.ios.swift +3 -3
  146. package/kit-apple/Sources/NativeScriptKit/Core/ui.button.index.ios.swift +4 -4
  147. package/kit-apple/Sources/NativeScriptKit/Core/ui.content-view.index.swift +8 -8
  148. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +4 -4
  149. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.index.ios.swift +8 -8
  150. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-common.swift +1 -3
  151. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-helper.view-helper-common.swift +7 -7
  152. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.weak-event-listener.index.swift +3 -3
  153. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.index.ios.swift +4 -4
  154. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.index.ios.swift +2 -2
  155. package/kit-apple/Sources/NativeScriptKit/Core/ui.html-view.index.ios.swift +4 -4
  156. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.image-common.swift +2 -2
  157. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.index.ios.swift +4 -4
  158. package/kit-apple/Sources/NativeScriptKit/Core/ui.label.index.ios.swift +4 -4
  159. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.absolute-layout.index.ios.swift +4 -4
  160. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.dock-layout.index.ios.swift +4 -4
  161. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.flexbox-layout.index.ios.swift +3 -3
  162. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.grid-layout.index.ios.swift +4 -4
  163. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.stack-layout.index.ios.swift +4 -4
  164. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.wrap-layout.index.ios.swift +4 -4
  165. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +3 -3
  166. package/kit-apple/Sources/NativeScriptKit/Core/ui.page.index.ios.swift +4 -4
  167. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +10 -6
  168. package/kit-apple/Sources/NativeScriptKit/Core/ui.scroll-view.index.ios.swift +4 -4
  169. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.index.ios.swift +4 -4
  170. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.background.ios.swift +1 -1
  171. package/kit-apple/Sources/NativeScriptKit/Core/ui.tab-view.index.ios.swift +4 -4
  172. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.formatted-string.swift +2 -1
  173. package/kit-apple/Sources/NativeScriptKit/Core/utils.common.swift +9 -9
  174. package/kit-apple/Sources/NativeScriptKit/Core/utils.layout-helper.index.ios.swift +10 -10
  175. package/kit-apple/Sources/NativeScriptKit/CoreBridge.swift +67 -1
  176. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +4 -0
  177. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +25 -0
  178. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +6 -0
  179. package/kit-apple/Sources/NativeScriptKit/Signals.swift +20 -2
  180. package/package.json +2 -1
  181. package/kit-apple/Sources/NativeScriptKit/Core/Object_toString_charAt_charCodeAt_concat_indexOf_lastIndexOf_and_44_more_fc25df.swift +0 -481
package/dist/api/ir.js CHANGED
@@ -17,7 +17,13 @@ export function scopeTemplate(nodes, attribute) {
17
17
  case 'template':
18
18
  case 'local':
19
19
  case 'let':
20
+ case 'structural':
21
+ case 'bindTemplate':
20
22
  return { ...n, body: scopeTemplate(n.body, attribute) };
23
+ case 'component':
24
+ return n.slots ? { ...n, slots: Object.fromEntries(Object.entries(n.slots).map(([k, v]) => [k, scopeTemplate(v, attribute)])) } : n;
25
+ case 'slot':
26
+ return n.fallback ? { ...n, fallback: scopeTemplate(n.fallback, attribute) } : n;
21
27
  default:
22
28
  return n;
23
29
  }
@@ -25,5 +31,5 @@ export function scopeTemplate(nodes, attribute) {
25
31
  }
26
32
  /** The nodes with each `local` and `let` replaced by its body: what renders where the local is. */
27
33
  export function withoutLocals(nodes) {
28
- return nodes.flatMap((n) => (n.kind === 'local' || n.kind === 'let' ? withoutLocals(n.body) : [n]));
34
+ return nodes.flatMap((n) => (n.kind === 'local' || n.kind === 'let' ? withoutLocals(n.body) : n.kind === 'bindTemplate' ? [] : [n]));
29
35
  }
@@ -128,8 +128,14 @@ function copyArtifact(artifact, copyTo, projectDir) {
128
128
  return destination;
129
129
  }
130
130
  async function runNodeBin(scriptPath, args, cwd) {
131
+ const env = { ...process.env };
132
+ if (!env.NS_CLI_LIB && process.argv[1]) {
133
+ const candidate = (0, node_path_1.resolve)((0, node_path_1.dirname)(process.argv[1]), '..', 'lib', 'nativescript-cli-lib.js');
134
+ if ((0, node_fs_1.existsSync)(candidate))
135
+ env.NS_CLI_LIB = candidate;
136
+ }
131
137
  return new Promise((resolveCode, reject) => {
132
- const child = (0, node_child_process_1.spawn)(process.execPath, [scriptPath, ...args], { cwd, stdio: 'inherit' });
138
+ const child = (0, node_child_process_1.spawn)(process.execPath, [scriptPath, ...args], { cwd, stdio: 'inherit', env });
133
139
  child.on('error', reject);
134
140
  child.on('close', (code) => resolveCode(code ?? 1));
135
141
  });
package/dist/css/css.js CHANGED
@@ -10,17 +10,41 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
10
10
  import { BIN } from "../driver/paths.js";
11
11
  /** The NativeScript CLI's library, which the bundlers read nativescript.config.ts through. */
12
12
  function cliLibrary(app) {
13
+ const fromEnv = process.env.NS_CLI_LIB;
14
+ if (fromEnv && existsSync(fromEnv))
15
+ return fromEnv;
13
16
  const local = join(app, 'node_modules', 'nativescript', 'lib', 'nativescript-cli-lib.js');
14
17
  if (existsSync(local))
15
18
  return local;
19
+ const probeDir = (dir) => {
20
+ if (!dir)
21
+ return null;
22
+ const beside = join(dir, 'node_modules', 'nativescript', 'lib', 'nativescript-cli-lib.js');
23
+ if (existsSync(beside))
24
+ return beside;
25
+ for (const bin of process.platform === 'win32' ? ['ns.cmd', 'ns'] : ['ns']) {
26
+ const ns = join(dir, bin);
27
+ if (!existsSync(ns))
28
+ continue;
29
+ try {
30
+ const real = dirname(realpathSync(ns));
31
+ for (const candidate of [join(real, '..', 'lib', 'nativescript-cli-lib.js'), join(real, 'node_modules', 'nativescript', 'lib', 'nativescript-cli-lib.js')]) {
32
+ if (existsSync(candidate))
33
+ return candidate;
34
+ }
35
+ }
36
+ catch { }
37
+ }
38
+ return null;
39
+ };
16
40
  for (const dir of (process.env.PATH ?? '').split(delimiter)) {
17
- const ns = join(dir, 'ns');
18
- if (!existsSync(ns))
19
- continue;
20
- const lib = join(dirname(realpathSync(ns)), '..', 'lib', 'nativescript-cli-lib.js');
21
- if (existsSync(lib))
22
- return lib;
41
+ const found = probeDir(dir);
42
+ if (found)
43
+ return found;
23
44
  }
45
+ const besideNode = probeDir(dirname(process.execPath));
46
+ if (besideNode)
47
+ return besideNode;
24
48
  throw new Error("the NativeScript CLI (ns) is needed: its library reads nativescript.config.ts for the app's bundler");
25
49
  }
26
50
  /**
@@ -26,6 +26,7 @@ const FLAGS = {
26
26
  'keep-going': { type: 'boolean', help: "write the project anyway: the platform compiler's errors show what is incomplete" },
27
27
  'allow-unimplemented-properties': { type: 'boolean', help: 'warn, not stop, for properties core declares that the kit does not apply (release.allowUnimplementedProperties)' },
28
28
  'allow-core-mismatch': { type: 'boolean', help: 'build with an installed core the kit was not generated from (release.allowCoreMismatch)' },
29
+ 'allow-plugin-mismatch': { type: 'boolean', help: 'warn, not stop, when an installed plugin differs from its repository source (release.allowPluginMismatch)' },
29
30
  'allow-untested-frameworks': { type: 'boolean', help: 'build with framework versions the adapter is not tested with (release.allowUntestedFrameworks)' },
30
31
  'skip-toolchain-check': { type: 'boolean', help: 'do not check Xcode, the JDK or the Android SDK first' },
31
32
  'no-source-lines': { type: 'boolean', help: 'generated code names no TypeScript source lines' },
@@ -81,6 +82,7 @@ try {
81
82
  keepGoing: v['keep-going'],
82
83
  allowUnimplementedProperties: v['allow-unimplemented-properties'],
83
84
  allowCoreMismatch: v['allow-core-mismatch'],
85
+ allowPluginMismatch: v['allow-plugin-mismatch'],
84
86
  allowUntestedFrameworks: v['allow-untested-frameworks'],
85
87
  skipToolchainCheck: v['skip-toolchain-check'],
86
88
  sourceLines: !v['no-source-lines'],
@@ -11,6 +11,7 @@ import { BuildContext } from "../program/build-context.js";
11
11
  import { clearBuildCaches } from "../program/build-caches.js";
12
12
  import { pathAliases } from "../program/app-paths.js";
13
13
  import { appImports, reachedFrom, tsconfigIncluded } from "../program/app-modules.js";
14
+ import { loadViteAppPlugins } from "../program/vite-plugins.js";
14
15
  import { appDeclarations, createProgram, nodeModules } from "../program/program.js";
15
16
  import { corePatchRefusal } from "../program/core-patches.js";
16
17
  import { reachability } from "../program/reach.js";
@@ -99,10 +100,17 @@ export async function compile(o, build = new BuildContext()) {
99
100
  // `x.ts` beside `x.ios.ts` is the other platforms' module: the platform's own file is the one `./x` resolves to.
100
101
  const thisPlatform = platform === 'android' ? '.android.ts' : '.ios.ts';
101
102
  const platformSources = files.filter((f) => f.endsWith('.ts') && !f.endsWith('.d.ts') && f !== entry && !/polyfills\.ts$/.test(f) && !otherPlatform.test(f) && !(!/\.(ios|android)\.ts$/.test(f) && files.includes(f.replace(/\.ts$/, thisPlatform))));
102
- // The app's own specifiers: relative ones and its tsconfig's path aliases (`~/app/x`).
103
- const aliased = pathAliases(app);
103
+ // The app's own specifiers: relative ones, Vite app-plugin `resolveId` hooks, and its tsconfig's path aliases (`~/app/x`).
104
+ const vitePlugins = await loadViteAppPlugins(app);
105
+ const baseAliased = pathAliases(app);
106
+ const aliased = (spec, importer) => vitePlugins.resolveId(spec, importer) ?? baseAliased(spec);
104
107
  const appSpecifier = (spec) => spec.startsWith('.') || aliased(spec) !== undefined;
105
- const { importsOf, usedBy, workerScripts } = appImports(files, aliased, thisPlatform);
108
+ const readTransformed = (f) => vitePlugins.transform(readFileSync(f, 'utf8'), f);
109
+ const { importsOf, usedBy, workerScripts, discovered } = appImports(files, aliased, thisPlatform, app, readTransformed);
110
+ if (discovered.length) {
111
+ files.push(...discovered);
112
+ platformSources.push(...discovered.filter((f) => f.endsWith('.ts') && !f.endsWith('.d.ts') && f !== entry && !/polyfills\.ts$/.test(f) && !otherPlatform.test(f)));
113
+ }
106
114
  // The modules of the build: what the bundler reaches. Some frameworks' bundle is what the entry imports, lazy routes
107
115
  // included; another's, every file its tsconfig.json does not exclude (specs, mocks), and what those import.
108
116
  const included = adapter?.reach === 'entry' ? null : tsconfigIncluded(app, appDir);
@@ -234,7 +242,7 @@ export async function compile(o, build = new BuildContext()) {
234
242
  ];
235
243
  const replacements = { ...bindingReplacements, ...pluginReplacements(app, platform) };
236
244
  modules.push(...Object.values(replacements).filter((f) => !modules.includes(f)));
237
- let { checker, program, files: sourceFiles, pluginFiles, resolved, lenient: lenientApp, assignsFields } = createProgram(modules, virtual, platform, undefined, plugins, declarations, replacements, {}, aliased, undefined, build);
245
+ let { checker, program, files: sourceFiles, pluginFiles, resolved, lenient: lenientApp, assignsFields } = createProgram(modules, virtual, platform, undefined, plugins, declarations, replacements, {}, aliased, undefined, build, vitePlugins);
238
246
  // The binding contexts the program proves: closures read a proved class's members directly. The page factories build
239
247
  // each XML file's tree. The program is made again to type both.
240
248
  if (xml && xmlBindings) {
@@ -296,7 +304,7 @@ export async function compile(o, build = new BuildContext()) {
296
304
  }
297
305
  }
298
306
  if (changed)
299
- ({ checker, program, files: sourceFiles, pluginFiles, resolved, lenient: lenientApp, assignsFields } = createProgram(modules, virtual, platform, undefined, plugins, declarations, replacements, {}, aliased, undefined, build));
307
+ ({ checker, program, files: sourceFiles, pluginFiles, resolved, lenient: lenientApp, assignsFields } = createProgram(modules, virtual, platform, undefined, plugins, declarations, replacements, {}, aliased, undefined, build, vitePlugins));
300
308
  // Nothing parses XML or evaluates an expression at run time: core reads app objects by the keys the XML and app code name.
301
309
  if (xmlRunTimeFree) {
302
310
  const { planKeys, scriptKeys } = await import("../xml/keys.js");
@@ -313,8 +321,9 @@ export async function compile(o, build = new BuildContext()) {
313
321
  writeFileSync(process.env.NS_XML_PLAN, JSON.stringify(xmlPlan(await loadCoreXml(), appDir, xml.xml, program, platform, xml.pageStyles.map((f) => relative(appDir, f).split('\\').join('/'))), null, 1) + '\n');
314
322
  }
315
323
  const infos = new Map(components.map((c) => {
316
- const cls = program.getSourceFile(c.file)?.statements.find(ts.isClassDeclaration);
317
- return [c.name, { name: c.name, props: c.props, members: cls ? componentMembersOf(cls, checker) : COMPONENT_MEMBERS, outputs: c.outputs, outputFields: c.outputFields, optional: c.optional, passed: c.passed, fragment: behaviour.fragments && !c.page && isFragment(c.template), setters: c.setters, propAliases: c.propAliases, changes: c.changes, ...(c.doCheck ? { doCheck: true } : {}), ...(c.afterContentInit ? { afterContentInit: true } : {}), ...(c.afterContentChecked ? { afterContentChecked: true } : {}), ...(c.afterViewChecked ? { afterViewChecked: true } : {}), onPush: c.onPush }];
324
+ const sf = program.getSourceFile(c.file);
325
+ const cls = sf?.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === c.name) ?? sf?.statements.find(ts.isClassDeclaration);
326
+ return [c.name, { name: c.name, props: c.props, members: cls ? componentMembersOf(cls, checker) : COMPONENT_MEMBERS, outputs: c.outputs, outputFields: c.outputFields, optional: c.optional, passed: c.passed, fragment: behaviour.fragments && !c.page && isFragment(c.template), setters: c.setters, propAliases: c.propAliases, changes: c.changes, ...(c.doCheck ? { doCheck: true } : {}), ...(c.afterContentInit ? { afterContentInit: true } : {}), ...(c.afterContentChecked ? { afterContentChecked: true } : {}), ...(c.afterViewChecked ? { afterViewChecked: true } : {}), ...(c.slots?.length ? { slots: c.slots } : {}), onPush: c.onPush }];
318
327
  }));
319
328
  // A component whose template is one fragment component is a fragment too, however deep the chain.
320
329
  if (behaviour.fragments) {
@@ -330,9 +339,10 @@ export async function compile(o, build = new BuildContext()) {
330
339
  }
331
340
  }
332
341
  // A closed world: the plugin code the app reaches, checked against what npm installed before it is compiled.
333
- const appFiles = [...modules, ...components.map((c) => c.file)];
342
+ const appFiles = [...new Set([...modules, ...components.map((c) => c.file)])];
334
343
  const { reach, compiled: compiledPlugins } = closedWorld(program, resolved, appFiles, pluginFiles, platform, build);
335
- plugins.verify(compiledPlugins);
344
+ const allowPluginMismatch = !!o.allowPluginMismatch || releaseOptions(app, platform).allowPluginMismatch === true;
345
+ plugins.verify(compiledPlugins, allowPluginMismatch ? (msg) => console.warn(`warning: ${msg} (building anyway: release.allowPluginMismatch)`) : undefined);
336
346
  const properties = collectProperties(checker, sourceFiles);
337
347
  // The files the translated code says it came from: a component's source for its virtual class, a module's own file for a replacement of it.
338
348
  const sourceLines = o.sourceLines === false ? null : new SourceLines(new Map([...components.map((c) => [c.file, componentSource(c)]), ...[...overrides.keys()].map((f) => [f, f])]));
@@ -342,7 +352,9 @@ export async function compile(o, build = new BuildContext()) {
342
352
  if (sourceLines)
343
353
  sourceLines.name = (file) => sourceName(file);
344
354
  // Constructs no compiled release runs, all of them with their TypeScript lines, before anything is translated.
345
- const unsupported = preflight(checker, [...sourceFiles, ...compiledPlugins.map((f) => program.getSourceFile(f))], sourceLines ? (n) => sourceLines.locate(n) : undefined, (st) => !compiledPlugins.includes(st.getSourceFile().fileName) || reach.keeps(st), (f) => compiledPlugins.includes(f) && !writtenStrict(f, build.adapter));
355
+ const pluginSet = new Set(pluginFiles);
356
+ const appSourceFiles = sourceFiles.filter((f) => !pluginSet.has(f.fileName));
357
+ const unsupported = preflight(checker, [...appSourceFiles, ...compiledPlugins.map((f) => program.getSourceFile(f))], sourceLines ? (n) => sourceLines.locate(n) : undefined, (st) => !pluginSet.has(st.getSourceFile().fileName) || reach.keeps(st), (f) => pluginSet.has(f) && !writtenStrict(f, build.adapter));
346
358
  if (unsupported.length) {
347
359
  console.error(formatPreflight(unsupported));
348
360
  for (const f of unsupported)
@@ -468,6 +480,7 @@ export async function compile(o, build = new BuildContext()) {
468
480
  resolved,
469
481
  mounted,
470
482
  workers: [...workerScripts],
483
+ aliased,
471
484
  allowUnapplied,
472
485
  allErrors: !!o.allErrors,
473
486
  lenient: lenientApp,
@@ -9,6 +9,13 @@ export const KIT_APPLE_SOURCES = join(KIT_APPLE, 'Sources', 'NativeScriptKit');
9
9
  /** NativeScriptKit for Android: a Gradle project. */
10
10
  export const KIT_ANDROID = join(PACKAGE, 'kit-android');
11
11
  export const BIN = join(PACKAGE, 'bin');
12
+ /** Command and arguments to invoke the bundled Gradle wrapper on the current OS. */
13
+ export function gradleWrapper(args, kit = KIT_ANDROID) {
14
+ if (process.platform === 'win32') {
15
+ return { command: process.env.ComSpec || 'cmd.exe', args: ['/d', '/c', join(kit, 'gradlew.bat'), ...args] };
16
+ }
17
+ return { command: join(kit, 'gradlew'), args };
18
+ }
12
19
  /**
13
20
  * Where the compiler keeps what it fetches and derives once per machine (plugins' sources, their Android libraries,
14
21
  * tools it downloads), outside the installed package: $NS_COMPILED_CACHE, else `nativescript/compiled` in
@@ -110,6 +110,19 @@ export class PropertyGuard {
110
110
  for (const a of n.props)
111
111
  if (!props.get(n.name)?.includes(a.name))
112
112
  check(tag, a.name);
113
+ if (n.slots)
114
+ for (const slotNodes of Object.values(n.slots))
115
+ walk(slotNodes);
116
+ }
117
+ else if (n.kind === 'slot') {
118
+ if (n.fallback)
119
+ walk(n.fallback);
120
+ }
121
+ else if (n.kind === 'componentOutlet' || n.kind === 'templateOutlet') {
122
+ // Dynamic outlets have no static template children.
123
+ }
124
+ else if (n.kind === 'structural' || n.kind === 'bindTemplate') {
125
+ walk(n.body);
113
126
  }
114
127
  else if (n.kind === 'if')
115
128
  for (const b of n.branches)
@@ -119,6 +132,8 @@ export class PropertyGuard {
119
132
  }
120
133
  };
121
134
  walk(c.template);
135
+ for (const t of c.templates ?? [])
136
+ walk(t.body);
122
137
  }
123
138
  return dedupe(out);
124
139
  }
@@ -2,7 +2,9 @@
2
2
  import { heldLoss } from "../semantics/losses.js";
3
3
  import ts from 'typescript';
4
4
  import { propSignal } from "../semantics/signals.js";
5
- import { LIB_CONSTANTS, MATH } from "./library.js";
5
+ import { KIT_NAMES_ANDROID, LIB_CONSTANTS, MATH } from "./library.js";
6
+ import { prototypeClassSymbol } from "../semantics/classes.js";
7
+ import { isCoreDeclaration } from "../program/core-facts.js";
6
8
  import { mathFunctionValue } from "../semantics/apis/math.js";
7
9
  import { CONSOLE } from "../semantics/apis/console.js";
8
10
  import { libFunctionValueKind } from "../semantics/apis/statics.js";
@@ -83,9 +85,14 @@ export const accessMethods = {
83
85
  // `Function.prototype`: a function doing nothing.
84
86
  if (name === 'prototype' && ts.isIdentifier(target) && target.text === 'Function' && this.resolve(target)?.declarations?.every((d) => d.getSourceFile().isDeclarationFile))
85
87
  return 'JSFunction { null }';
86
- // Library mode: a class's prototype, the registry's object for it.
87
- if (name === 'prototype' && this.resolve(target)?.flags & ts.SymbolFlags.Class && !this.resolve(target)?.declarations?.every((d) => d.getSourceFile().isDeclarationFile))
88
- return `JSPrototypes.of(${this.expr(target)}::class.java)`;
88
+ // A class's prototype, the registry's object for it.
89
+ const protoSym = prototypeClassSymbol(target, name, this);
90
+ if (protoSym) {
91
+ const declOnly = protoSym.declarations?.every((d) => d.getSourceFile().isDeclarationFile);
92
+ const clsName = declOnly ? (isCoreDeclaration(protoSym.declarations?.[0]) ? (KIT_NAMES_ANDROID[protoSym.name] ?? protoSym.name) : null) : this.expr(target);
93
+ if (clsName)
94
+ return `JSPrototypes.of(${clsName}::class.java)`;
95
+ }
89
96
  if (ts.isIdentifier(target) && isLibGlobal(this, target)) {
90
97
  const constant = LIB_CONSTANTS[`${target.text}.${name}`];
91
98
  if (constant)
@@ -103,6 +110,12 @@ export const accessMethods = {
103
110
  }
104
111
  if (libFn === 'fromCharCode')
105
112
  return this.convert(`{ __args: JSArray<Double> -> ${RT.jsFromCharCode}(*__args.storage.toDoubleArray()) }`, '(JSArray<Double>) -> String', this.typeOf(e));
113
+ if (libFn === 'fromCodePoint')
114
+ return this.convert(`{ __args: JSArray<Double> -> ${RT.jsFromCodePoint}(*__args.storage.toDoubleArray()) }`, '(JSArray<Double>) -> String', this.typeOf(e));
115
+ if (libFn === 'mathRandom')
116
+ return this.convert('{ Math.random() }', '() -> Double', this.typeOf(e));
117
+ if (libFn === 'mathVariadic')
118
+ return this.convert(`{ __args: JSArray<Double> -> ${name === 'min' ? RT.jsMathMin : RT.jsMathMax}(*__args.storage.toDoubleArray()) }`, '(JSArray<Double>) -> Double', this.typeOf(e));
106
119
  if (libFn === 'typedArrayFrom')
107
120
  return this.convert(`{ __v: Any? -> JS${target.text}.from(__v) }`, `(Any?) -> JS${target.text}`, this.typeOf(e));
108
121
  if (libFn === 'isArray')
@@ -350,7 +363,7 @@ export const accessMethods = {
350
363
  if (!ts.isMethodSignature(d))
351
364
  return false;
352
365
  const owner = ts.isInterfaceDeclaration(d.parent) ? this.topName(d.parent, d.parent.name.text) : ts.isTypeLiteralNode(d.parent) && ts.isTypeAliasDeclaration(d.parent.parent) ? this.topName(d.parent.parent, d.parent.parent.name.text) : null;
353
- return !!owner && this.interfaces.has(owner) && !this.protocols.has(owner);
366
+ return !!owner && this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), owner) && !this.protocols.has(owner);
354
367
  }));
355
368
  },
356
369
  /** A key as its message names it. */
@@ -573,6 +586,11 @@ export const accessMethods = {
573
586
  const rt = this.typeOf(e);
574
587
  return isUntyped(spelledType(rt)) || isWriteTarget(e) ? code : this.fromAnyCode(code, rt, true);
575
588
  }
589
+ if (this.typeOf(e.expression) === 'Nothing') {
590
+ const code = `${RT.jsGet}(${this.coerce(e.expression, 'Any?')}, ${this.propertyKey(key)})`;
591
+ const rt = this.typeOf(e);
592
+ return isUntyped(spelledType(rt)) || isWriteTarget(e) ? code : this.fromAnyCode(code, rt, true);
593
+ }
576
594
  throw this.error(e, 'indexing this type', 'index-type');
577
595
  },
578
596
  /** `assertedUntyped`'s cast: to an object type other than the kit's own containers, promises, dates and errors. */
@@ -129,6 +129,11 @@ export const argumentsMethods = {
129
129
  break;
130
130
  }
131
131
  if (ts.isSpreadElement(a)) {
132
+ if (restAt >= 0 && k >= restAt && !appDeclared) {
133
+ out.push(`*${this.packed(list.slice(k), 'JSArray<Any?>', this.restSlot(e, 'Any?'))}.storage.toTypedArray()`);
134
+ covered = list.length;
135
+ break;
136
+ }
132
137
  const spread = k === list.length - 1 ? this.spreadArgs(a, k, params, restAt, appDeclared, slot) : null;
133
138
  if (!spread)
134
139
  throw this.error(a, 'a spread argument');
@@ -379,8 +379,6 @@ export const builtinMethods = {
379
379
  const fn = name === 'replace' ? RT.jsReplace : RT.jsReplaceAll;
380
380
  // A function value: called with the match, each group (undefined where it took no part), the match's index and the string.
381
381
  if (!(ts.isArrowFunction(second) || ts.isFunctionExpression(second)) && this.checker.getTypeAtLocation(second).getCallSignatures().length) {
382
- if (name === 'replaceAll')
383
- throw this.error(e, 'replaceAll with a function');
384
382
  // A rest parameter takes the arguments from its position on, which a call by script cannot give it.
385
383
  const decl = this.checker.getTypeAtLocation(second).getCallSignatures()[0]?.getDeclaration();
386
384
  const restAt = decl && !ts.isJSDocSignature(decl) ? decl.parameters.findIndex((p) => p.dotDotDotToken) : -1;
@@ -399,8 +397,6 @@ export const builtinMethods = {
399
397
  }
400
398
  if (!(ts.isArrowFunction(second) || ts.isFunctionExpression(second)))
401
399
  return `${fn}(${s}, ${r}, ${this.str(second)})`;
402
- if (name === 'replaceAll')
403
- throw this.error(e, 'replaceAll with a function');
404
400
  // The replacer gets the match, then each group, then the offset.
405
401
  const m = this.fresh('__match');
406
402
  // The match, each group (undefined where it took no part), the index, the input, then the groups object.
@@ -3,12 +3,13 @@ import ts from 'typescript';
3
3
  import { TYPED_ARRAYS, isLibGlobal } from "../semantics/globals.js";
4
4
  import { cast, functionTypeParts, ident, isFunctionType, kotlinString, optionalType, splitTopLevel, RT } from "./syntax.js";
5
5
  import { assertedReceiverCell, nullishField } from "../semantics/placement.js";
6
- import { intlConstructor, isObjectToStringCall, literalKey, mergedInterfaceMemberOf, isSelf } from "../semantics/lang.js";
6
+ import { hookedDynamicImport, intlConstructor, isObjectToStringCall, literalKey, mergedInterfaceMemberOf, isSelf } from "../semantics/lang.js";
7
7
  import { callableSignal } from "../semantics/signals.js";
8
8
  import { isLibDeclaration, isSymbolIterator, implementationOf } from "../semantics/ast.js";
9
9
  import { isStatic } from "../semantics/throws.js";
10
10
  import { constClassExpr, programBase } from "../semantics/classes.js";
11
11
  import { isKit, isNamed, isUntyped, spelledType } from "../semantics/types.js";
12
+ import { isKitInstanceMethod } from "../program/core-facts.js";
12
13
  import { globalOp } from "../semantics/apis/globals.js";
13
14
  export const callsMethods = {
14
15
  arity(e) {
@@ -95,6 +96,9 @@ export const callsMethods = {
95
96
  }
96
97
  if (callee.kind === ts.SyntaxKind.SuperKeyword)
97
98
  throw this.error(e, 'super() outside the start of a constructor');
99
+ const dynImport = hookedDynamicImport(e, this.framework.hooks);
100
+ if (dynImport)
101
+ return dynImport;
98
102
  // `getWindow<UIWindow>?.()`: the type arguments are only TypeScript's, and a function declaration is always there.
99
103
  const declaredFunction = (x) => ts.isIdentifier(x) && !!this.resolve(x)?.declarations?.some(ts.isFunctionDeclaration);
100
104
  if (ts.isExpressionWithTypeArguments(callee) && (!e.questionDotToken || declaredFunction(callee.expression)))
@@ -105,7 +109,7 @@ export const callsMethods = {
105
109
  const declaredMethod = ts.isPropertyAccessExpression(callee) && !!this.resolve(callee.name)?.declarations?.some((d) => ts.isMethodDeclaration(d) && !!d.body);
106
110
  // `iterator.next?.()`: a method the library declares on a typed value is always there too.
107
111
  const libMethod = !this.library && ts.isPropertyAccessExpression(callee) && !this.isAny(callee.expression) && !!this.resolve(callee.name)?.declarations?.length && this.resolve(callee.name).declarations.every((d) => isLibDeclaration(d) && (ts.isMethodSignature(d) || ts.isMethodDeclaration(d)));
108
- if (e.questionDotToken && !declaredMethod && !libMethod && !this.core?.isKitMethod(callee) && !declaredFunction(callee) && !(ts.isPropertyAccessExpression(callee) && mergedInterfaceMemberOf(callee, this.checker))) {
112
+ if (e.questionDotToken && !declaredMethod && !libMethod && !isKitInstanceMethod(this.core, callee) && !declaredFunction(callee) && !(ts.isPropertyAccessExpression(callee) && mergedInterfaceMemberOf(callee, this.checker))) {
109
113
  const fn = this.expr(callee);
110
114
  // A Java method read untyped (`window.getInsetsController?.()`): called as script calls it.
111
115
  if (/^js(Java)?Get(Optional)?\(/.test(fn))
@@ -7,7 +7,7 @@ import { kitMember } from "../kit/kit-index.js";
7
7
  import { runtimeKitIndex } from "./core-index.js";
8
8
  import { inheritsToString, toStringGivesNonString, uncheckedIteratorResult } from "../semantics/classes.js";
9
9
  import { isUntyped, spelledType } from "../semantics/types.js";
10
- import { isDisposerMember } from "../semantics/lang.js";
10
+ import { isDirectSymbolMethod } from "../semantics/lang.js";
11
11
  export const classMethodsMethods = {
12
12
  /**
13
13
  * `[fooProperty.setNative](value)`: the class's native setter for that registered property. The generated kit
@@ -67,8 +67,14 @@ export const classMethodsMethods = {
67
67
  const keyed = this.symbolMember(m.name);
68
68
  if (this.symbolMethodCode(k, m, keyed))
69
69
  return;
70
- if (keyed && isDisposerMember(keyed.member)) {
71
- lines.push(' ' + this.func(m, keyed.member, memberOpen));
70
+ if (keyed && isDirectSymbolMethod(keyed.member)) {
71
+ if (isStatic(m)) {
72
+ this.indent = ' ';
73
+ k.statics.push(' ' + this.func(m, keyed.member));
74
+ this.indent = ' ';
75
+ }
76
+ else
77
+ lines.push(' ' + this.func(m, keyed.member, memberOpen));
72
78
  return;
73
79
  }
74
80
  if (keyed)
@@ -3,7 +3,7 @@ import ts from 'typescript';
3
3
  import { atLossSite, HELD_LOSS } from "../semantics/losses.js";
4
4
  import { ident, isFunctionType, isNullable, kotlinString, nullishType, optionalType, ownReturns, RT } from "./syntax.js";
5
5
  import { UNKEYED, definesDuringConstruction, implementedOptionalMembers, restrictsField, definedField } from "../semantics/shapes.js";
6
- import { hasModifier, isLibDeclaration } from "../semantics/ast.js";
6
+ import { extendsHeritage, hasModifier, isLibDeclaration, nonSuperStatements } from "../semantics/ast.js";
7
7
  import { implementedInterfaces } from "../semantics/lang.js";
8
8
  import { isCoreDeclaration } from "../program/core-facts.js";
9
9
  import { isStatic } from "../semantics/throws.js";
@@ -210,18 +210,21 @@ export const componentMethods = {
210
210
  for (const m of implementedOptionalMembers(cls, this.checker))
211
211
  lines.push(` var ${ident(m.name.text)}: ${optionalType(this.typeOf(m))} = null`);
212
212
  // The constructor's body runs once every field has its value, as TypeScript's class fields come first.
213
- if (ctor?.body?.statements.length && ownReturns(ctor.body)) {
213
+ const ctorStmts = nonSuperStatements(ctor);
214
+ if (ctorStmts.length && ctor?.body && ownReturns(ctor.body)) {
214
215
  this.returnLabel = '__ctor';
215
- this.indent = ' ';
216
+ this.indent = ' ';
216
217
  try {
217
- lines.push(` init {\n run __ctor@${this.block(ctor.body, ' ')}\n }`);
218
+ lines.push(` init {\n run __ctor@{\n${this.statements(ctorStmts).join('\n')}\n }\n }`);
218
219
  }
219
220
  finally {
220
221
  this.returnLabel = null;
221
222
  }
222
223
  }
223
- else if (ctor?.body?.statements.length)
224
- lines.push(` init ${this.block(ctor.body, ' ')}`);
224
+ else if (ctorStmts.length) {
225
+ this.indent = ' ';
226
+ lines.push(` init {\n${this.statements(ctorStmts).join('\n')}\n }`);
227
+ }
225
228
  this.indent = '';
226
229
  statics.push(...(this.framework.hooks.componentStatics?.(this, cls) ?? []));
227
230
  return { params, lines, statics };
@@ -351,9 +354,11 @@ export const componentMethods = {
351
354
  const witnesses = [];
352
355
  const notOverrides = new Set();
353
356
  const appInterface = (n) => this.protocols.has(n) && [...implementedInterfaces(this.checker, cls).map((i) => this.checker.getTypeAtLocation(i).getSymbol()?.declarations?.find(ts.isInterfaceDeclaration)), ...(this.structural.get(cls) ?? [])].some((d) => !!d && this.topName(d, d.name.text) === n && !d.getSourceFile().isDeclarationFile);
357
+ const heritage = extendsHeritage(cls);
358
+ const baseSuper = heritage && this.classPlan(cls).base ? [`${this.type(this.checker.getTypeAtLocation(heritage), heritage)}()`] : [];
354
359
  const supertypes = this.implementedProtocols(cls, witnesses, notOverrides).filter(appInterface);
355
360
  if (!supertypes.length)
356
- return { supertypes, overrides: new Set(), lines: [] };
361
+ return { supertypes: baseSuper, overrides: new Set(), lines: [] };
357
362
  for (const i of supertypes)
358
363
  this.used.add(i);
359
364
  const overrides = this.overridden(cls, supertypes);
@@ -379,7 +384,7 @@ export const componentMethods = {
379
384
  fields.push({ name: m.name.text, type });
380
385
  }
381
386
  }
382
- return { supertypes, overrides, lines: [...witnesses, ...this.dynamicMembers(UNKEYED, { fields, className: cls.name?.text ?? null, accessors })] };
387
+ return { supertypes: [...baseSuper, ...supertypes], overrides, lines: [...witnesses, ...this.dynamicMembers(UNKEYED, { fields, className: cls.name?.text ?? null, accessors })] };
383
388
  },
384
389
  /**
385
390
  * Whether a class can implement an interface. A method whose untyped
@@ -52,7 +52,12 @@ export const conversionMethods = {
52
52
  const set = tracked.has(f.name) ? `jsKeySet(field, value, ${kotlinString(f.name)})` : 'value';
53
53
  // A view is made with no fields given: a number or boolean field's backing value unboxes.
54
54
  const unboxed = { Double: '0.0', Boolean: 'false', Int: '0', Long: '0L', Float: '0f' };
55
- lines.push(` ${overrides?.has(f.name) ? 'override ' : ''}var ${ident(memberOf(f))}: ${f.type} = ${unboxed[f.type] ? `${ident(memberOf(f))} ?: ${unboxed[f.type]}` : `${RT.jsUnchecked}(${ident(memberOf(f))})`}`, ` get() { val __r = jsRoot ?: return field; return ${field(f, '__r')} }`, ` set(value) { val __r = jsRoot; if (__r != null) { __r.jsSet(${kotlinString(f.name)}, ${RT.jsBox}(value)); return }; field = ${set}${writes(f)} }`);
55
+ // A view over an untyped object must not fabricate an empty JSArray for a missing or non-array property (`Array.isArray((v as T).arr)`).
56
+ const arrayField = !this.library ? /^JSArray<(.+)>(\??)$/.exec(f.type) : null;
57
+ const viewRead = arrayField
58
+ ? `${RT.jsField}(__r, ${f.key ?? kotlinString(f.name)}).let { __v -> if (__v is JSArray<*> || (__v != null && __v.javaClass.isArray)) ${RT.jsArrayFrom}(__v) { ${this.fromAny('it', arrayField[1])} } else ${arrayField[2] ? 'null' : `${RT.jsUnchecked}<${f.type}>(null)`} }`
59
+ : field(f, '__r');
60
+ lines.push(` ${overrides?.has(f.name) ? 'override ' : ''}var ${ident(memberOf(f))}: ${f.type} = ${unboxed[f.type] ? `${ident(memberOf(f))} ?: ${unboxed[f.type]}` : `${RT.jsUnchecked}(${ident(memberOf(f))})`}`, ` get() { val __r = jsRoot ?: return field; return ${viewRead} }`, ` set(value) { val __r = jsRoot; if (__r != null) { __r.jsSet(${kotlinString(f.name)}, ${RT.jsBox}(value)); return }; field = ${set}${writes(f)} }`);
56
61
  }
57
62
  }
58
63
  else
@@ -406,7 +411,7 @@ export const conversionMethods = {
406
411
  const record = unbox.composite === 'record' ? /^JSRecord<(.*)>(\??)$/.exec(type) : null;
407
412
  // App code: of objects it types as its own classes, which a package's copies (`{ ...entity }`) are not: each read as one.
408
413
  const entry = record?.[1].replace(/\?$/, '');
409
- if (record && !this.library && entry && (this.interfaces.has(entry) || this.isShapeType(entry))) {
414
+ if (record && !this.library && entry && this.isShapeType(entry)) {
410
415
  const read = (x) => `${RT.jsRecordOf}(${x}) { ${this.fromAny('it', record[1])} }`;
411
416
  if (!record[2])
412
417
  return read(code);
@@ -445,9 +450,16 @@ export const conversionMethods = {
445
450
  // A promise its type promises may be any thenable: adopted, as awaiting it or `Promise.resolve` would.
446
451
  const promised = unbox.composite === 'promise' ? /^JSPromise<(.*)>$/.exec(base) : null;
447
452
  if (promised) {
448
- // Kotlin cannot tell a promise's element type: objects read into classes are read as each value arrives.
449
- const read = this.readsIntoClass(promised[1]) ? ` { ${this.fromAny('it', promised[1])} }` : '';
450
- const of = (x) => `${RT.jsPromiseOf}<${promised[1]}>(${x})${read}`;
453
+ // Kotlin cannot tell a promise's element type: convert resolved values as each arrives (including Unit and shapes).
454
+ const inner = promised[1];
455
+ const innerBase = inner.replace(/\?$/, '');
456
+ const converted = inner === 'Unit'
457
+ ? 'Unit'
458
+ : this.readsIntoClass(inner) || (!this.library && !isUntyped(spelledType(inner)) && !this.isTypeParameterName(innerBase))
459
+ ? this.fromAny(this.marks.pureCode('it'), inner)
460
+ : 'it';
461
+ const read = converted !== 'it' ? ` { ${converted} }` : '';
462
+ const of = (x) => `${RT.jsPromiseOf}<${inner}>(${x})${read}`;
451
463
  return type.endsWith('?') ? `${RT.jsUnlessNullish}(${code}) { ${of('it')} }` : of(code);
452
464
  }
453
465
  // Library mode: JavaScript's null where an object goes (`cond ? entry.fragment : null`) is Kotlin's.
@@ -7,6 +7,7 @@ import { KIT_NAMES_ANDROID } from "./library.js";
7
7
  import { functionTypeParts, kotlinString, numberLiteral, splitTopLevel, RT } from "./syntax.js";
8
8
  import { KIT_ANDROID } from "../driver/paths.js";
9
9
  import { rethrowUnlessRefused } from "../semantics/refusals.js";
10
+ import { isMixinOwnMember } from "../semantics/classes.js";
10
11
  import { isUntyped, spelledType } from "../semantics/types.js";
11
12
  import { kotlinKitIndex, TOP_LEVEL, NATIVE_MEMBERS, SCRIPT_OBJECTS, KIT } from "./core-index.js";
12
13
  /** The native class a core view's `android` is. */
@@ -138,13 +139,6 @@ export class CoreKotlin extends KitTypes {
138
139
  }
139
140
  return null;
140
141
  }
141
- /** Whether `target.method` is a method the kit declares on target's class (an optional call of it is a plain call). */
142
- isKitMethod(callee) {
143
- if (!ts.isPropertyAccessExpression(callee))
144
- return false;
145
- const owner = this.owner(callee.expression);
146
- return !!owner && !owner.isStatic && kitMember(this.index, owner.name, callee.name.text)?.kind === 'func';
147
- }
148
142
  owner(e) {
149
143
  const found = this.declaredOwner(e);
150
144
  if (!found)
@@ -253,7 +247,7 @@ export class CoreKotlin extends KitTypes {
253
247
  * (`Utils.android` of utils/index is utils/native-helper's): that module's object.
254
248
  */
255
249
  ownerOf(target, name) {
256
- let owner = this.mixinOwn(name) ? null : (this.owner(target) ?? this.inheritedOwner(target, name));
250
+ let owner = isMixinOwnMember(name, this.t.checker, (s) => this.t.mixinOf(s)) ? null : (this.owner(target) ?? this.inheritedOwner(target, name));
257
251
  if (owner && !kitMember(this.index, owner.name, name.text))
258
252
  owner = this.renamedOwner(owner, name.text) ?? owner;
259
253
  if (!owner || !owner.isStatic || !owner.name.startsWith('Core_') || kitMember(this.index, owner.name, name.text))
@@ -282,11 +276,6 @@ export class CoreKotlin extends KitTypes {
282
276
  const root = cls && ts.isClassLike(cls) && !cls.getSourceFile().isDeclarationFile ? this.t.kitRootOf(cls) : null;
283
277
  return root ? { name: root, isStatic: false } : null;
284
278
  }
285
- /** A member a mixin class declares: the extension it becomes has it by name. */
286
- mixinOwn(name) {
287
- const decl = this.t.checker.getSymbolAtLocation(name)?.valueDeclaration;
288
- return !!decl && ts.isClassDeclaration(decl.parent) && !!this.t.mixinOf(this.t.checker.getSymbolAtLocation(decl.parent.name));
289
- }
290
279
  /**
291
280
  * `on`/`off`/`once` with a named function: a function value made once per
292
281
  * evaluation has no identity across them, so the kit matches a listener by
@@ -276,6 +276,8 @@ export const declarationsMethods = {
276
276
  .filter((x) => x !== el)
277
277
  .map((x) => {
278
278
  const key = x.propertyName ?? x.name;
279
+ if (ts.isComputedPropertyName(key))
280
+ return this.propertyKey(key.expression);
279
281
  if (!ts.isIdentifier(key) && !ts.isStringLiteral(key))
280
282
  throw this.error(x, 'a computed key beside an object rest pattern');
281
283
  return kotlinString(key.text);
@@ -37,10 +37,11 @@ export const exprStatementsMethods = {
37
37
  const replaced = this.patterns.prototypeMethod(e);
38
38
  if (replaced) {
39
39
  // A Page's native view made by a plugin (gesturehandler's PageLayout): the kit's factory hook, `this` the page.
40
- if (replaced.target !== 'Page' || replaced.method !== 'createNativeView')
41
- throw this.error(e, `replacing ${replaced.target}.prototype.${replaced.method}`);
42
- const ret = this.returnTypeOf(replaced.fn);
43
- return `Page.nativeViewFactory = fun Page.(): ${ret} ${this.functionBody(replaced.fn, ret, this.indent)}`;
40
+ if (replaced.target === 'Page' && replaced.method === 'createNativeView') {
41
+ const ret = this.returnTypeOf(replaced.fn);
42
+ return `Page.nativeViewFactory = fun Page.(): ${ret} ${this.functionBody(replaced.fn, ret, this.indent)}`;
43
+ }
44
+ return `JSPrototypes.of(${replaced.target}::class.java)[${kotlinString(replaced.method)}] = ${this.coerce(replaced.fn, 'Any?')}`;
44
45
  }
45
46
  // Assigning a class alias its class (`PageLayout = com.….PageLayout`): its uses already name the class.
46
47
  if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.EqualsToken && ts.isIdentifier(e.left)) {
@@ -256,14 +256,19 @@ export const expressionsMethods = {
256
256
  // An object of one shape asserted another's (`cur as ICalEvent` of a `Partial<ICalEvent> & {…}`): Kotlin's classes are apart, so
257
257
  // the object is read as the asserted interface's, by its keys.
258
258
  const [fromName, toName] = [from.replace(/\?$/, ''), to.replace(/\?$/, '')];
259
- const fieldClass = (n) => (this.interfaces.has(n) && !this.protocols.has(n)) || !!this.shapes.named(n);
260
- if (!this.library && fromName !== toName && fieldClass(fromName) && this.interfaces.has(toName) && !this.protocols.has(toName)) {
259
+ const fieldClass = (n) => (this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), n) && !this.protocols.has(n)) || !!this.shapes.named(n);
260
+ if (!this.library && fromName !== toName && fieldClass(fromName) && this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), toName) && !this.protocols.has(toName)) {
261
261
  return from.endsWith('?') ? `${this.expr(e.expression)}?.let { ${this.viewOf(toName, 'it')} }` : this.viewOf(toName, this.expr(e.expression));
262
262
  }
263
263
  if (from !== to && from.replace(/\?$/, '') !== to.replace(/\?$/, '') && this.isObjectRef(e) && this.isObjectRef(e.expression)) {
264
- // Library mode: a script assertion never fails, so a value of another class (a TabViewItem walked up to as a parent) reads as null where null fits.
264
+ // Library mode: a script assertion never fails, so a value of another class (a TabViewItem walked up to as a parent)
265
+ // or a null Java result (`dlg.findViewById(id) as TextView`) reads as null instead of throwing ClassCastException/NPE.
265
266
  if (this.library && this.isClassDowncast(e) && (isNullable(to) || this.functionLiteralArgument(e)))
266
267
  return safeCast(this.expr(e.expression), to.replace(/\?$/, ''));
268
+ if (this.library && this.native?.type(this.checker.getNonNullableType(this.checker.getTypeAtLocation(e))) && this.native?.type(this.checker.getNonNullableType(this.checker.getTypeAtLocation(e.expression)))) {
269
+ const safe = safeCast(this.expr(e.expression), to.replace(/\?$/, ''));
270
+ return isNullable(to) || this.nullOk.has(e) ? safe : this.unchecked(to, safe);
271
+ }
267
272
  return this.classCast(this.expr(e.expression), from, to);
268
273
  }
269
274
  if (from.endsWith('?') && !to.endsWith('?') && from.replace(/\?$/, '') === to)