@nstudio/nativescript-compiler 9.2.0-alpha.14 → 9.2.0-alpha.16

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 (90) hide show
  1. package/dist/driver/compile.js +4 -3
  2. package/dist/kotlin/arguments.js +2 -1
  3. package/dist/kotlin/builtins.js +14 -3
  4. package/dist/kotlin/class-accessors.js +1 -1
  5. package/dist/kotlin/class-constructor.js +3 -1
  6. package/dist/kotlin/class-declaration.js +3 -2
  7. package/dist/kotlin/class-methods.js +29 -12
  8. package/dist/kotlin/components.js +39 -14
  9. package/dist/kotlin/construction.js +4 -5
  10. package/dist/kotlin/conversion.js +16 -3
  11. package/dist/kotlin/core-api.js +14 -7
  12. package/dist/kotlin/declarations.js +1 -1
  13. package/dist/kotlin/expressions.js +10 -5
  14. package/dist/kotlin/modules.js +7 -3
  15. package/dist/kotlin/names.js +5 -2
  16. package/dist/kotlin/optional-chains.js +24 -5
  17. package/dist/kotlin/overrides.js +7 -2
  18. package/dist/kotlin/placement.js +5 -4
  19. package/dist/kotlin/translator.js +0 -39
  20. package/dist/kotlin/types.js +4 -5
  21. package/dist/kotlin/untyped-values.js +7 -1
  22. package/dist/program/program.js +3 -3
  23. package/dist/semantics/apis/array.js +11 -0
  24. package/dist/semantics/classes.js +24 -0
  25. package/dist/semantics/config.js +2 -0
  26. package/dist/semantics/forms/by-name.js +45 -19
  27. package/dist/semantics/globals.js +8 -2
  28. package/dist/semantics/lang.js +21 -1
  29. package/dist/semantics/ledger.js +0 -24
  30. package/dist/semantics/platform-globals.js +0 -16
  31. package/dist/semantics/refusals.js +1 -1
  32. package/dist/semantics/runtime.js +2 -0
  33. package/dist/semantics/throws.js +7 -0
  34. package/dist/semantics/worker-state.js +41 -1
  35. package/dist/swift/assignment.js +3 -0
  36. package/dist/swift/builtins.js +8 -10
  37. package/dist/swift/class-accessors.js +1 -1
  38. package/dist/swift/class-declaration.js +3 -2
  39. package/dist/swift/class-methods.js +19 -2
  40. package/dist/swift/construction.js +5 -1
  41. package/dist/swift/conversion.js +1 -1
  42. package/dist/swift/expressions.js +2 -4
  43. package/dist/swift/from-any.js +5 -0
  44. package/dist/swift/global-calls.js +8 -1
  45. package/dist/swift/object-classes.js +2 -1
  46. package/dist/swift/placement.js +6 -0
  47. package/dist/swift/protocols.js +30 -20
  48. package/dist/swift/types.js +4 -3
  49. package/dist/targets/ios/build.js +22 -7
  50. package/docs/cli/compile-ios.md +1 -1
  51. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_properties_index.kt +6 -6
  52. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -1
  53. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Collections.kt +15 -6
  54. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Promise.kt +1 -1
  55. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +13 -2
  56. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +0 -12
  57. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +0 -39
  58. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +0 -44
  59. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +19 -2
  60. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +17 -0
  61. package/kit-apple/Sources/NativeScriptKit/Core/color.index.ios.swift +60 -0
  62. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +90 -25
  63. package/kit-apple/Sources/NativeScriptKit/Core/text.text-common.swift +9 -1
  64. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +13 -2
  65. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view-base.index.swift +26 -2
  66. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.gestures-common.swift +2 -0
  67. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.liquid-glass-container.index.ios.swift +12 -2
  68. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.root-layout.root-layout-common.swift +46 -6
  69. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +37 -3
  70. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.split-view-common.swift +12 -1
  71. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-selector.swift +50 -6
  72. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.text-base-common.swift +13 -1
  73. package/kit-apple/Sources/NativeScriptKit/Runtime/Collections.swift +5 -1
  74. package/kit-apple/Sources/NativeScriptKit/Runtime/Dynamic.swift +13 -2
  75. package/kit-apple/Sources/NativeScriptKit/Runtime/Errors.swift +10 -2
  76. package/kit-apple/Sources/NativeScriptKit/Runtime/Functions.swift +57 -12
  77. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +12 -3
  78. package/kit-apple/Sources/NativeScriptKit/Runtime/Promise.swift +56 -29
  79. package/kit-apple/Sources/NativeScriptKit/Runtime/Realm.swift +92 -0
  80. package/kit-apple/Sources/NativeScriptKit/Runtime/Record.swift +25 -5
  81. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +13 -4
  82. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExpEngine.swift +14 -5
  83. package/kit-apple/Sources/NativeScriptKit/Runtime/Symbol.swift +28 -6
  84. package/kit-apple/Sources/NativeScriptKit/Runtime/Threads.swift +2 -2
  85. package/kit-apple/Sources/NativeScriptKit/Runtime/Timers.swift +93 -47
  86. package/kit-apple/Sources/NativeScriptKit/Runtime/TypedArrays.swift +37 -9
  87. package/kit-apple/Sources/NativeScriptKit/Runtime/Values.swift +6 -4
  88. package/kit-apple/Sources/NativeScriptKit/Runtime/Views.swift +11 -2
  89. package/kit-apple/Sources/NativeScriptKit/Runtime/Workers.swift +680 -0
  90. package/package.json +1 -1
@@ -470,7 +470,8 @@ export const placementMethods = {
470
470
  const call = `${this.library ? this.refName(e) : ident(e.text)}(${names.map((n, k) => this.convert(n, g.params[k], f.params[k])).join(', ')})`;
471
471
  return `{ ${g.params.map((p, k) => `${names[k]}: ${p}`).join(', ')} -> ${call} }`;
472
472
  }
473
- if (f && g && f.params.length <= g.params.length && (f.params.length < g.params.length || f.params.some((p, k) => p !== g.params[k] && this.convert('x', g.params[k], p) !== 'x')) && f.params.length <= g.params.length && (g.ret === 'Unit' || g.ret === f.ret || (isUntyped(spelledType(g.ret)) && (this.library || f.ret !== 'Unit')) || (!this.library && isUntyped(spelledType(f.ret))))) {
473
+ const voidPromiseRet = !this.library && !!f && !!g && f.ret === 'JSPromise<Unit>' && /^JSPromise<.+>$/.test(g.ret) && g.ret !== f.ret;
474
+ if (f && g && f.params.length <= g.params.length && (f.params.length < g.params.length || voidPromiseRet || f.params.some((p, k) => p !== g.params[k] && this.convert('x', g.params[k], p) !== 'x')) && (g.ret === 'Unit' || g.ret === f.ret || voidPromiseRet || (isUntyped(spelledType(g.ret)) && (this.library || f.ret !== 'Unit')) || (!this.library && isUntyped(spelledType(f.ret))))) {
474
475
  const names = g.params.map((_, k) => this.marks.pureCode(`__a${k}`));
475
476
  const fn = this.functionValue(e);
476
477
  // A function field Kotlin declares nullable (one left unset): unwrapped where it is called.
@@ -479,8 +480,8 @@ export const placementMethods = {
479
480
  .slice(0, f.params.length)
480
481
  .map((n, k) => this.convert(n, g.params[k], f.params[k]))
481
482
  .join(', ')})`;
482
- // An untyped result is read as the slot's.
483
- const call = isUntyped(spelledType(f.ret)) && g.ret !== 'Unit' && !isUntyped(spelledType(g.ret)) && !this.library ? this.fromAny(called, g.ret) : called;
483
+ // An untyped result (or Promise<void> into Promise<T | void>) is read as the slot's.
484
+ const call = voidPromiseRet || (isUntyped(spelledType(f.ret)) && g.ret !== 'Unit' && !isUntyped(spelledType(g.ret)) && !this.library) ? this.fromAny(called, g.ret) : called;
484
485
  const adapter = `{ ${g.params.map((p, k) => `${names[k]}: ${p}`).join(', ')} -> ${call} }`;
485
486
  // An optional member (`closeCallback?: …`) given to an optional parameter (`cb?: …`): undefined stays undefined,
486
487
  // as the checker without strictNullChecks types neither as optional.
@@ -567,7 +568,7 @@ export const placementMethods = {
567
568
  return elements(code);
568
569
  }
569
570
  }
570
- if (!this.library && sb === 'JSPromise<Any?>' && /^JSPromise<(.+)>$/.test(tb))
571
+ if (!this.library && (sb === 'JSPromise<Any?>' || sb === 'JSPromise<Unit>') && /^JSPromise<(.+)>$/.test(tb) && tb !== sb)
571
572
  return this.fromAny(this.functionValue(e), target);
572
573
  if (head(sb) && head(sb) === head(tb) && sb !== tb)
573
574
  return cast(this.functionValue(e), target);
@@ -1,4 +1,3 @@
1
- import { dirname as pathDirname, resolve as pathResolve } from 'node:path';
2
1
  import { heldLoss } from "../semantics/losses.js";
3
2
  import ts from 'typescript';
4
3
  import { KOTLIN_LEDGER } from "../semantics/ledger.js";
@@ -87,9 +86,6 @@ export class Translator {
87
86
  nativeDeclared = (d) => !!this.native?.isNativeDeclaration(d);
88
87
  /** The innermost statement or expression being translated: where code made from a type alone is placed. */
89
88
  translating;
90
- /** Android: the worker scripts compiled with the app, by file, and the name the entry registers each under. */
91
- workerScripts;
92
- resolveAlias;
93
89
  /** The generated kit: a module's name for `AppModules.runImport`, set where modules `await import(…)` reaches run when imported. */
94
90
  moduleKey;
95
91
  /** The program's whole-program answers, shared with any translator of the same checker and files. */
@@ -148,8 +144,6 @@ export class Translator {
148
144
  this.framework = new Framework(c.hooks);
149
145
  this.checker = checker;
150
146
  this.lenient = c.lenient ?? false;
151
- this.workerScripts = c.workerScripts ?? null;
152
- this.resolveAlias = c.resolveAlias ?? null;
153
147
  this.moduleThread = c.moduleThread ?? null;
154
148
  this.moduleKey = c.moduleKey;
155
149
  this.components = components;
@@ -731,39 +725,6 @@ export class Translator {
731
725
  });
732
726
  return `object : ${this.className(base)}() {\n${members.join('\n')}\n}`;
733
727
  }
734
- /** `new Worker('~/x')`, `new Worker('./x')`, or `new Worker(new URL('./x', import.meta.url))`: the worker script it names, when the app compiled it. */
735
- workerScript(e) {
736
- let spec = null;
737
- if (ts.isStringLiteralLike(e)) {
738
- spec = e.text;
739
- }
740
- else if (ts.isNewExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'URL') {
741
- const [s, base] = e.arguments ?? [];
742
- if (s && ts.isStringLiteralLike(s) && base && base.getText() === 'import.meta.url')
743
- spec = s.text;
744
- }
745
- if (!spec || !this.workerScripts?.size)
746
- return null;
747
- const file = e.getSourceFile().fileName;
748
- const target = spec.startsWith('.') ? pathResolve(pathDirname(file), spec) : this.resolveAlias?.(spec, file);
749
- if (target) {
750
- const stem = target.replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
751
- for (const f of [stem + '.ts', stem + '.android.ts', stem + '.tsx', stem + '/index.ts', stem + '/index.android.ts']) {
752
- const script = this.workerScripts.get(f);
753
- if (script)
754
- return script;
755
- }
756
- }
757
- if (spec.startsWith('~/') || spec.startsWith('@/')) {
758
- const rel = spec.slice(2).replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
759
- for (const [key, script] of this.workerScripts) {
760
- const norm = key.replace(/\\/g, '/');
761
- if ([`/${rel}.ts`, `/${rel}.android.ts`, `/${rel}.tsx`, `/${rel}/index.ts`, `/${rel}/index.android.ts`].some((s) => norm.endsWith(s)))
762
- return script;
763
- }
764
- }
765
- return null;
766
- }
767
728
  /**
768
729
  * A function literal stored where untyped code calls it (`global.onmessage = (m: Msg) => …`): jsCall passes
769
730
  * JavaScript values, so typed parameters are converted from them inside.
@@ -1,7 +1,7 @@
1
1
  // TypeScript types as Kotlin types: representations, held and optional forms, shapes.
2
2
  import ts from 'typescript';
3
3
  import { KIT_NAMES_ANDROID } from "./library.js";
4
- import { BUFFER_TYPES, WEB_DICTIONARIES, isWebClass } from "../semantics/globals.js";
4
+ import { BUFFER_TYPES, WEB_DICTIONARIES, webClassName } from "../semantics/globals.js";
5
5
  import { SPELLING, spell, destructuringSource, functionTypeParts, kotlinString, nullishType, optionalElementsType, optionalType, presentConst, RT } from "./syntax.js";
6
6
  import { ambientBase, evolvingArrayRead, evolvingArrayType, isAmbientClass, isRegExpProtocol, memberOwner, namesOwnTypeParameter, tokenClassBase, isArguments } from "../semantics/lang.js";
7
7
  import { nullishSignalType } from "../semantics/signals.js";
@@ -183,10 +183,9 @@ export const typesMethods = {
183
183
  return a ? this.type(a, where) : 'Any?';
184
184
  };
185
185
  if (name && sym?.declarations?.length && sym.declarations.every((d) => d.getSourceFile().isDeclarationFile)) {
186
- if (isWebClass(this.ledger, name))
187
- return `JS${name}`;
188
- if (name === 'DedicatedWorkerGlobalScope' && this.ledger.workerGlobals)
189
- return 'JSWorker';
186
+ const web = webClassName(this.ledger, name);
187
+ if (web)
188
+ return web;
190
189
  if (WEB_DICTIONARIES.includes(name) && (sym.declarations[0].getSourceFile().fileName === '/__shims__/globals.d.ts' || isLibDeclaration(sym.declarations[0])))
191
190
  return 'Any?';
192
191
  }
@@ -312,7 +312,13 @@ export const untypedValuesMethods = {
312
312
  const kept = this.pluginFiles.has(decl.getSourceFile().fileName) ? [] : (decl.typeParameters ?? []).filter((p) => !this.erasesTypeParameter(p));
313
313
  const generic = kept.length ? `<${kept.map((p) => (!this.library && this.classConstraint(p) ? this.type(this.checker.getTypeFromTypeNode(p.constraint), p).replace(/\?$/, '') : 'Any?')).join(', ')}>` : '';
314
314
  // One reading `arguments` takes them all (`__arguments`).
315
- const args = this.readsArguments(decl) ? ['JSArray<Any?>(__a.toMutableList())'] : decl.parameters.map((q, k) => (q.dotDotDotToken ? `JSArray(__a.drop(${k}).map { ${generic ? `${RT.jsUnchecked}(it)` : this.fromAnyCode('it', this.typeOf(q.name).replace(/^JSArray<(.*)>$/, '$1'), true)} }.toMutableList())` : generic ? `${RT.jsUnchecked}(__a.getOrNull(${k}))` : this.fromAnyCode(this.marks.pureCode(`__a.getOrNull(${k})`), this.paramType(q), true)));
315
+ const argOf = (q, k) => {
316
+ if (q.dotDotDotToken)
317
+ return `JSArray(__a.drop(${k}).map { ${generic ? `${RT.jsUnchecked}(it)` : this.fromAnyCode('it', this.typeOf(q.name).replace(/^JSArray<(.*)>$/, '$1'), true)} }.toMutableList())`;
318
+ const raw = generic ? `${RT.jsUnchecked}(__a.getOrNull(${k}))` : this.fromAnyCode(this.marks.pureCode(`__a.getOrNull(${k})`), this.paramType(q), true);
319
+ return this.constantDefault(q) ? `if (__a.getOrNull(${k}) == null) ${this.stored(q.initializer, q, this.paramType(q))} else ${raw}` : raw;
320
+ };
321
+ const args = this.readsArguments(decl) ? ['JSArray<Any?>(__a.toMutableList())'] : decl.parameters.map(argOf);
316
322
  const arity = decl.parameters.findIndex((q) => !!q.questionToken || !!q.initializer || !!q.dotDotDotToken);
317
323
  if (this.implicitThis(decl))
318
324
  return `JSMethod(${arity < 0 ? decl.parameters.length : arity}) ${lambda(['__self', '__a'], `${name}${generic}(${['__self', ...args].join(', ')})${this.returnTypeOf(decl) === 'Unit' ? '; null' : ''}`)}`;
@@ -434,7 +434,7 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
434
434
  }
435
435
  }
436
436
  // A package the app replaces for the native build is the app's module.
437
- const replacement = !m.startsWith('.') && !m.startsWith('/') ? replacements[packageOf(m)] : undefined;
437
+ const replacement = !m.startsWith('.') && !isAbsolute(m) ? replacements[packageOf(m)] : undefined;
438
438
  if (replacement)
439
439
  return { resolvedModule: { resolvedFileName: replacement, extension: ts.Extension.Ts } };
440
440
  // A plugin is compiled from its source: an import that reaches its code resolves to the file it was built from,
@@ -446,7 +446,7 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
446
446
  const augments = ts.isModuleDeclaration(lit.parent) && lit.parent.name === lit && !!plugins?.all().some((p) => containing.startsWith(p.root + '/'));
447
447
  // Every import of `rxjs` (including `import type` and `.d.ts` files like `@angular/cdk`) must resolve to the same compiled `rxjs` source so Observable/OperatorFunction types match across the whole program.
448
448
  const sharedRxjs = m === 'rxjs' || m.startsWith('rxjs/');
449
- if (plugins && (isSource(containing) || pluginFiles.has(containing) || augments || containing.startsWith('/__shims__/') || (containing.endsWith('.d.ts') && sharedRxjs)) && !m.startsWith('.') && !m.startsWith('/') && !notPlugin(packageOf(m)) && (!typeOnly || sharedRxjs)) {
449
+ if (plugins && (isSource(containing) || pluginFiles.has(containing) || augments || containing.startsWith('/__shims__/') || (containing.endsWith('.d.ts') && sharedRxjs)) && !m.startsWith('.') && !isAbsolute(m) && !notPlugin(packageOf(m)) && (!typeOnly || sharedRxjs)) {
450
450
  const js = runtimeFile(m, modules, platform, localPackages);
451
451
  if (js) {
452
452
  plugins.get(js.packageDir);
@@ -470,7 +470,7 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
470
470
  }
471
471
  }
472
472
  // Type-only imports of local `file:` packages (outside node_modules): resolve to the package's typings.
473
- if (!m.startsWith('.') && !m.startsWith('/')) {
473
+ if (!m.startsWith('.') && !isAbsolute(m)) {
474
474
  const localDir = localPackages.get(packageOf(m));
475
475
  if (localDir) {
476
476
  const deep = m.slice(packageOf(m).length).replace(/^\//, '');
@@ -1,4 +1,5 @@
1
1
  // `Array`'s functions, and those of the buffer types.
2
+ import ts from 'typescript';
2
3
  import { apiEntry, apiTable } from "./api.js";
3
4
  export const ARRAY_STATICS = apiTable('static', {
4
5
  // Function.prototype's, which `Array(...list)` reads as.
@@ -67,3 +68,13 @@ export const GENERIC_ARRAY_METHODS = new Set([...Object.keys(ARRAY_METHODS), 'co
67
68
  export function arrayMember(name) {
68
69
  return apiEntry(ARRAY_METHODS, name);
69
70
  }
71
+ /** How `array.flat(depth?)` lowers for a receiver whose element type is `element`. */
72
+ export function typedFlatPlan(e, element, untyped) {
73
+ const arg = e.arguments[0];
74
+ if (!arg)
75
+ return { kind: 'default' };
76
+ if (untyped)
77
+ return { kind: 'depth', arg, untyped: true };
78
+ const levels = Math.min(Number(ts.isNumericLiteral(arg) ? arg.text : NaN), /^(JSArray<)*/.exec(element)[0].length / 8);
79
+ return levels >= 1 ? { kind: 'chain', suffix: '.flat()'.repeat(levels) } : { kind: 'depth', arg, untyped: false };
80
+ }
@@ -75,6 +75,30 @@ export function rootMethod(m, checker) {
75
75
  root = up;
76
76
  return root;
77
77
  }
78
+ /** The Error runtime base name (e.g. `'JSError'`) that `cls`'s hierarchy extends through program base classes, or null. */
79
+ export function rootErrorBase(cls, checker) {
80
+ let root = cls;
81
+ for (let b = programBase(root, checker); b; b = programBase(b, checker))
82
+ root = b;
83
+ const h = root.heritageClauses?.find((x) => x.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
84
+ return h ? (ERRORS[h.expression.getText()] ?? null) : null;
85
+ }
86
+ /** The non-static member or constructor parameter property of `name` declared on `cls` or a program base class. */
87
+ export function ownClassMember(cls, name, checker) {
88
+ for (let c = cls; c; c = programBase(c, checker)) {
89
+ const m = c.members.find((x) => !isStatic(x) && x.name?.getText() === name);
90
+ if (m)
91
+ return m;
92
+ const param = c.members.find(ts.isConstructorDeclaration)?.parameters.find((p) => ts.isIdentifier(p.name) && p.name.text === name && ts.canHaveModifiers(p) && !!ts.getModifiers(p)?.length);
93
+ if (param)
94
+ return param;
95
+ }
96
+ return undefined;
97
+ }
98
+ /** If `m` is a property or parameter property redeclaring a program base class's field/accessor, that base member; else null. */
99
+ export function redeclaredMember(m, checker) {
100
+ return ts.isPropertyDeclaration(m) || ts.isParameter(m) ? redeclaredField(m, checker) : null;
101
+ }
78
102
  /** The field, accessor or parameter property a program base class declares under a field's name, which the field redeclares. */
79
103
  export function redeclaredField(m, checker) {
80
104
  const cls = ts.isParameter(m) ? (ts.isParameterPropertyDeclaration(m, m.parent) ? m.parent.parent : undefined) : m.parent;
@@ -19,6 +19,8 @@ export function configFields(config, ledger) {
19
19
  allowUnapplied: config.allowUnapplied ?? false,
20
20
  lines: config.lines ?? null,
21
21
  errors: config.errors ?? null,
22
+ workerScripts: config.workerScripts ?? null,
23
+ resolveAlias: config.resolveAlias ?? null,
22
24
  };
23
25
  }
24
26
  /** What a translator reads of its build, from a config that may leave it out: a build of its own, with no framework. */
@@ -4,6 +4,7 @@ import { O, U, declarationFile, hasStatic, unionOfObjects, untyped } from "./flo
4
4
  import { LIB_FILE, isTemplateMethod } from "../trust.js";
5
5
  import { implementedInterfaces, literalKey, mergedInterfaceMemberOf } from "../lang.js";
6
6
  import { programBase } from "../classes.js";
7
+ import { hasMappedIntersection } from "../types.js";
7
8
  export const byNameCallsMethods = {
8
9
  /**
9
10
  * Members the framework may call where the program can't see (`FrameworkModel.calledByFramework`), but the template
@@ -119,11 +120,21 @@ export const byNameCallsMethods = {
119
120
  }
120
121
  }
121
122
  };
123
+ const erasedUntyped = (t) => {
124
+ if (untyped(t))
125
+ return true;
126
+ const n = c.getNonNullableType(t);
127
+ return untyped(n) || (n.isIntersection() && hasMappedIntersection(n));
128
+ };
122
129
  const open = (slots) => slots.filter((s) => {
123
130
  const r = this.find(s);
124
131
  // A part's type is the value's own (an array literal's elements), not the type its holder declares.
125
- return !!r.type && (untyped(r.type) || (!!r.decl && unionOfObjects(r.type))) && !(r.decl && LIB_FILE.test(r.decl.getSourceFile().fileName));
132
+ return !!r.type && (erasedUntyped(r.type) || (!!r.decl && unionOfObjects(r.type))) && !(r.decl && LIB_FILE.test(r.decl.getSourceFile().fileName));
126
133
  });
134
+ // A class implementing a mapped-type intersection erased to Any? (`implements Ds3ControllerAsync`) is called dynamically by name.
135
+ for (const cls of this.classes)
136
+ if (implementedInterfaces(c, cls).some((i) => erasedUntyped(c.getTypeAtLocation(i))))
137
+ found.add(cls);
127
138
  // Placed by generated code, or only into `bindingContext`s and the generated code's own slots.
128
139
  const byKeys = (x, slots) => !!keyedFile && (keyedFile(x.getSourceFile()) || (!this.heldUntyped.has(x) && slots.every((s) => keyedSlot(s.decl))));
129
140
  for (const [x, slots] of this.placed) {
@@ -134,7 +145,7 @@ export const byNameCallsMethods = {
134
145
  for (const x of this.placedUntyped)
135
146
  classOf(x, byKeys(x, open(this.placed.get(x) ?? [])));
136
147
  const visit = (n) => {
137
- if ((ts.isAsExpression(n) || ts.isTypeAssertionExpression(n)) && untyped(c.getTypeAtLocation(n)))
148
+ if ((ts.isAsExpression(n) || ts.isTypeAssertionExpression(n)) && erasedUntyped(c.getTypeAtLocation(n)))
138
149
  classOf(n.expression);
139
150
  if (ts.isElementAccessExpression(n)) {
140
151
  const key = ts.skipOuterExpressions(n.argumentExpression);
@@ -299,6 +310,8 @@ export const byNameCallsMethods = {
299
310
  const c = this.checker, viewed = new Map();
300
311
  const extendsInterface = (t, wanted, depth = 0) => depth < 32 && (t.getSymbol() === wanted || (t.isClassOrInterface() && c.getBaseTypes(t).some((b) => extendsInterface(b, wanted, depth + 1))));
301
312
  const names = (cls, wanted) => {
313
+ if (!(wanted.declarations ?? []).some(ts.isInterfaceDeclaration))
314
+ return false;
302
315
  // A library base's own interface (`extends Error` where `Error` is wanted) is the class's too.
303
316
  if (extendsInterface(c.getTypeAtLocation(cls.name ?? cls), wanted))
304
317
  return true;
@@ -309,27 +322,40 @@ export const byNameCallsMethods = {
309
322
  }
310
323
  return false;
311
324
  };
312
- for (const x of this.placed.keys()) {
325
+ for (const [x, slots] of this.placed) {
326
+ const rawTypes = [];
313
327
  const at = c.getContextualType(x);
314
- const wt = at && c.getNonNullableType(at);
315
- const wanted = wt?.getSymbol();
316
- if (!wanted || !(wanted.flags & (ts.SymbolFlags.TypeLiteral | ts.SymbolFlags.Interface)) || wanted.flags & ts.SymbolFlags.Class || wt.getCallSignatures().length || wt.getConstructSignatures().length || !wt.getProperties().length)
317
- continue;
328
+ if (at)
329
+ rawTypes.push(at);
330
+ for (const s of slots) {
331
+ const rt = this.find(s).type;
332
+ if (rt)
333
+ rawTypes.push(rt);
334
+ }
318
335
  const t = c.getNonNullableType(c.getTypeAtLocation(x));
319
- for (const part of t.isUnion() ? t.types : [t]) {
320
- const cls = part.getSymbol()?.declarations?.find((d) => ts.isClassLike(d) && !declarationFile(d));
321
- if (cls && part.getConstructSignatures().length) {
322
- for (let b = cls; b; b = programBase(b, c))
323
- this.viewedStatic.add(b);
336
+ for (const raw of rawTypes) {
337
+ const wt = c.getNonNullableType(raw);
338
+ const wanted = wt.getSymbol();
339
+ const intersection = wt.isIntersection() && !wt.types.some((u) => (u.getSymbol()?.flags ?? 0) & ts.SymbolFlags.Class);
340
+ if (!intersection && (!wanted || !(wanted.flags & (ts.SymbolFlags.TypeLiteral | ts.SymbolFlags.Interface)) || wanted.flags & ts.SymbolFlags.Class))
324
341
  continue;
325
- }
326
- if (!cls || names(cls, wanted))
342
+ if (wt.getCallSignatures().length || wt.getConstructSignatures().length || !wt.getProperties().length)
327
343
  continue;
328
- const keys = wt.getProperties().map((p) => p.name);
329
- for (let b = cls; b; b = programBase(b, c)) {
330
- const into = viewed.get(b) ?? viewed.set(b, new Set()).get(b);
331
- for (const k of keys)
332
- into.add(k);
344
+ for (const part of t.isUnion() ? t.types : [t]) {
345
+ const cls = part.getSymbol()?.declarations?.find((d) => ts.isClassLike(d) && !declarationFile(d));
346
+ if (cls && part.getConstructSignatures().length) {
347
+ for (let b = cls; b; b = programBase(b, c))
348
+ this.viewedStatic.add(b);
349
+ continue;
350
+ }
351
+ if (!cls || (wanted && names(cls, wanted)))
352
+ continue;
353
+ const keys = wt.getProperties().map((p) => p.name);
354
+ for (let b = cls; b; b = programBase(b, c)) {
355
+ const into = viewed.get(b) ?? viewed.set(b, new Set()).get(b);
356
+ for (const k of keys)
357
+ into.add(k);
358
+ }
333
359
  }
334
360
  }
335
361
  }
@@ -18,8 +18,14 @@ const WORKER_CLASSES = ['Worker', 'MessageEvent', 'ErrorEvent', 'URL'];
18
18
  /** Web API classes that have native/kit representations (as opposed to DOM-only element/node interfaces held untyped). */
19
19
  export const ALL_WEB_CLASSES = new Set([...WEB_CLASSES, ...WORKER_CLASSES, 'URLSearchParams', 'AbortController', 'AbortSignal', 'Blob', 'File', 'FormData', 'Headers', 'Request', 'Response', 'Event', 'EventTarget', 'CustomEvent', 'CloseEvent', 'WebSocket', 'ReadableStream', 'WritableStream', 'TransformStream']);
20
20
  /** `name` is a web class the kit implements. */
21
- export function isWebClass(ledger, name) {
22
- return WEB_CLASSES.includes(name) || (ledger.workerGlobals && WORKER_CLASSES.includes(name));
21
+ export function isWebClass(_ledger, name) {
22
+ return WEB_CLASSES.includes(name) || WORKER_CLASSES.includes(name);
23
+ }
24
+ /** The kit class name for a web or worker global class (`Worker` → `JSWorker`, `DedicatedWorkerGlobalScope` → `JSWorker`). */
25
+ export function webClassName(ledger, name) {
26
+ if (name === 'DedicatedWorkerGlobalScope')
27
+ return 'JSWorker';
28
+ return isWebClass(ledger, name) ? `JS${name}` : null;
23
29
  }
24
30
  /** The web's option and algorithm dictionaries, plus global-object web interfaces read by key. */
25
31
  export const WEB_DICTIONARIES = ['TextDecoderOptions', 'Algorithm', 'HmacKeyGenParams', 'RsaKeyGenParams', 'RsaHashedKeyGenParams', 'RsaOaepParams', 'Performance', 'Storage'];
@@ -1,12 +1,17 @@
1
1
  import ts from 'typescript';
2
- import { isSymbolAsyncIterator, isSymbolIterator } from "./ast.js";
2
+ import { isLibDeclaration, isSymbolAsyncIterator, isSymbolIterator } from "./ast.js";
3
3
  import { SHIM_GLOBAL_OBJECT_VARS } from "./globals.js";
4
+ import { implementedInterfaces } from "./lang/members.js";
4
5
  export { evolvingArrayRead, evolvingArrayType, evolvingElementContext, spreadOperand, openSpreadType, intersectionAliasMembers, iterationThrows, iteratedType, iteratesCheckedResult } from "./lang/arrays.js";
5
6
  export { unsafeReceiver, uncheckedMatch, leadingNeverRead, redeclaredBeside, thisArgCall, withoutThisArg, thisArgBound, takesReceiver, ignoresThisArg } from "./lang/this-args.js";
6
7
  export { isAmbientClass, ambientBase, ambientAddedMemberOf, implementedInterfaces, runtimeTypeName, mergedInterfaceMemberOf, augmentedPropertyRead, optionalBodilessMethod, undeclaredMemberOf, classesHeldUntyped, hasStatic, admitsUndefined, assertedOperand, undefinedLiteral, onlyUndefined, resultsAreUndefinedElements, implementedInterfaceDeclarations, accessedDeclaration, memberOwner, namesOwnTypeParameter } from "./lang/members.js";
7
8
  export { slotType, nullSetFields, initializedNull, assignedValues, definitelyAssignedFields, containsThis, alwaysThrows, alwaysEnds, statementLevel } from "./lang/fields.js";
8
9
  export { readWrite, compoundOperator, asOperation, assignmentOf, globalProxyUse, builtinPrototypeAlias, aliasedPrototypeMember, tokenClassBase, isArguments, escapesArguments, canReadArguments, inferredFunctionName, functionProperty, isConstant, isSelf, objectMethod, literalMethod, prototypeAlias, methodValues } from "./lang/prototypes.js";
9
10
  // JavaScript semantics both translators share, decided from the syntax tree and the checker.
11
+ /** Whether `t`'s symbol has an explicit `interface` declaration (not a mapped/`Pick` type alias erased to `Any?`). */
12
+ export function isEmittedInterface(t) {
13
+ return (t.getSymbol()?.declarations ?? []).some(ts.isInterfaceDeclaration);
14
+ }
10
15
  /** A type written with `| null` or `| undefined`, which code checked without strictNullChecks types without them. */
11
16
  export function nullableTypeNode(t) {
12
17
  return !!t && ts.isUnionTypeNode(t) && t.types.some((x) => x.kind === ts.SyntaxKind.UndefinedKeyword || (ts.isLiteralTypeNode(x) && x.literal.kind === ts.SyntaxKind.NullKeyword));
@@ -242,3 +247,18 @@ export function substitutedExpr(subst, e, branchingOnly = false) {
242
247
  return null;
243
248
  return { bare, code };
244
249
  }
250
+ /** Member names of declared TypeScript interfaces left out of a class's native conformances, so dynamic views (`fromJS` / `init(jsObject:)`) can read them by name. */
251
+ export function droppedProtocolMemberNames(checker, cls, protocols, implemented, ifaceName, skipped) {
252
+ const out = new Set();
253
+ for (const i of implementedInterfaces(checker, cls)) {
254
+ const t = checker.getTypeAtLocation(i);
255
+ if (!isEmittedInterface(t) || isLibDeclaration(t.getSymbol()?.declarations?.[0]))
256
+ continue;
257
+ const name = ifaceName(i);
258
+ if (!protocols.has(name) || implemented.includes(name) || skipped(i, t, name))
259
+ continue;
260
+ for (const p of t.getProperties())
261
+ out.add(p.name);
262
+ }
263
+ return out;
264
+ }
@@ -10,23 +10,15 @@ export const LEDGER_KINDS = {
10
10
  looseReads: 'gap',
11
11
  checkedParameters: 'platform',
12
12
  implicitThisUnconstructed: 'gap',
13
- workerGlobals: 'gap',
14
13
  nativeSdk: 'platform',
15
14
  freesOnLastReference: 'platform',
16
15
  failedUnwrapThrows: 'gap',
17
16
  subclassFieldsBeforeBase: 'platform',
18
17
  typedArrays: 'gap',
19
- typedFlat: 'gap',
20
- functionObjects: 'gap',
21
18
  functionIdentity: 'gap',
22
19
  unboundGenerics: 'gap',
23
20
  indexConversions: 'gap',
24
- accessorNameClash: 'gap',
25
- genericAsyncResult: 'gap',
26
- orAssignTyped: 'gap',
27
- errorSubclassConstructor: 'gap',
28
21
  errorSubclassKeyOrder: 'gap',
29
- unmetInterfaceMembers: 'gap',
30
22
  pluginsWrittenStrict: 'gap',
31
23
  functionElementsUntyped: 'platform',
32
24
  errorClassObjects: 'platform',
@@ -56,23 +48,15 @@ export const SWIFT_LEDGER = {
56
48
  looseReads: true,
57
49
  checkedParameters: false,
58
50
  implicitThisUnconstructed: true,
59
- workerGlobals: false,
60
51
  nativeSdk: 'apple',
61
52
  freesOnLastReference: true,
62
53
  failedUnwrapThrows: false,
63
54
  subclassFieldsBeforeBase: true,
64
55
  typedArrays: true,
65
- typedFlat: true,
66
- functionObjects: true,
67
56
  functionIdentity: true,
68
57
  unboundGenerics: true,
69
58
  indexConversions: true,
70
- accessorNameClash: true,
71
- genericAsyncResult: true,
72
- orAssignTyped: true,
73
- errorSubclassConstructor: true,
74
59
  errorSubclassKeyOrder: false,
75
- unmetInterfaceMembers: true,
76
60
  pluginsWrittenStrict: true,
77
61
  functionElementsUntyped: true,
78
62
  errorClassObjects: false,
@@ -102,23 +86,15 @@ export const KOTLIN_LEDGER = {
102
86
  looseReads: false,
103
87
  checkedParameters: true,
104
88
  implicitThisUnconstructed: false,
105
- workerGlobals: true,
106
89
  nativeSdk: 'android',
107
90
  freesOnLastReference: false,
108
91
  failedUnwrapThrows: true,
109
92
  subclassFieldsBeforeBase: false,
110
93
  typedArrays: false,
111
- typedFlat: false,
112
- functionObjects: false,
113
94
  functionIdentity: false,
114
95
  unboundGenerics: false,
115
96
  indexConversions: false,
116
- accessorNameClash: false,
117
- genericAsyncResult: false,
118
- orAssignTyped: false,
119
- errorSubclassConstructor: false,
120
97
  errorSubclassKeyOrder: true,
121
- unmetInterfaceMembers: false,
122
98
  pluginsWrittenStrict: false,
123
99
  functionElementsUntyped: false,
124
100
  errorClassObjects: true,
@@ -1,20 +1,4 @@
1
- import ts from 'typescript';
2
1
  /** The typings of the platform a build does not bind (`Ledger.nativeSdk`): what they declare only the other platform's code holds. */
3
2
  export function otherPlatformTypings(ledger) {
4
3
  return ledger.nativeSdk === 'apple' ? /[\\/]@nativescript[\\/]types-android[\\/]/ : /[\\/]@nativescript[\\/]types-ios[\\/]/;
5
4
  }
6
- /**
7
- * The worker API's globals both platforms type (program.ts `WORKER_GLOBALS`), which only Android's kit runs: an iOS build
8
- * refuses each, where the platform's own names (Darwin's `close`) would otherwise take their place.
9
- */
10
- const IOS_REFUSED = { Worker: 'worker', postMessage: 'worker', close: 'worker', URL: 'library-member' };
11
- /** The refusal an iOS build gives `e` where it is, or is read from, one of those globals; null otherwise. */
12
- export function iosRefusedGlobal(e, checker) {
13
- let x = e;
14
- while (ts.isNewExpression(x) || ts.isCallExpression(x) || ts.isPropertyAccessExpression(x) || ts.isElementAccessExpression(x) || ts.isParenthesizedExpression(x) || ts.isAsExpression(x) || ts.isNonNullExpression(x) || ts.isTypeAssertionExpression(x))
15
- x = x.expression;
16
- if (!ts.isIdentifier(x) || !Object.hasOwn(IOS_REFUSED, x.text))
17
- return null;
18
- const decls = checker.getSymbolAtLocation(x)?.declarations ?? [];
19
- return decls.length && decls.every((d) => d.getSourceFile().fileName === '/__shims__/globals.d.ts') ? { id: IOS_REFUSED[x.text], name: x.text } : null;
20
- }
@@ -70,7 +70,7 @@ export function allRefusals(adapter) {
70
70
  return { ...REFUSALS, ...adapter?.refusals };
71
71
  }
72
72
  export const REPORT_HEADER = 'Constructs a compiled release does not run, with a rewrite for each:';
73
- export const ISSUES_URL = 'https://github.com/NativeScript/NativeScript/issues';
73
+ export const ISSUES_URL = 'https://github.com/nstudio/nativescript-compiler/issues';
74
74
  const GAP_NOTE = `This is a compiler gap, not your code: please report it at ${ISSUES_URL}`;
75
75
  /**
76
76
  * A construct the build refuses: a declared limit of compiled releases or a gap of the compiler, of kind `id`, at `at`
@@ -285,6 +285,7 @@ const SWIFT_ONLY = [
285
285
  'jsCancelAnimationFrame',
286
286
  'jsCheckStack',
287
287
  'jsChecked',
288
+ 'jsClose',
288
289
  'jsCompare',
289
290
  'jsConstructor',
290
291
  'jsConverted',
@@ -351,6 +352,7 @@ const SWIFT_ONLY = [
351
352
  'jsOffScriptThread',
352
353
  'jsPostDecrement',
353
354
  'jsPostIncrement',
355
+ 'jsPostMessage',
354
356
  'jsPostUpdate',
355
357
  'jsPreDecrement',
356
358
  'jsPreIncrement',
@@ -51,6 +51,10 @@ const THROWING_BUILTINS = new Set([
51
51
  'btoa',
52
52
  'Crypto.getRandomValues',
53
53
  'TextDecoder.decode',
54
+ 'Worker.postMessage',
55
+ 'DedicatedWorkerGlobalScope.postMessage',
56
+ 'postMessage',
57
+ 'close',
54
58
  ]);
55
59
  /**
56
60
  * Which functions throw, worked out across the call graph: a function is
@@ -566,6 +570,9 @@ export class Throws {
566
570
  // A buffer or a view of an invalid length is a RangeError.
567
571
  if (ts.isNewExpression(call) && ts.isIdentifier(call.expression) && BUFFER_TYPES.has(call.expression.text) && c.getSymbolAtLocation(call.expression)?.declarations?.every((d) => d.getSourceFile().isDeclarationFile))
568
572
  return true;
573
+ // `new Worker(...)` and `new URL(...)` throw when the script is absent/already running or the URL is invalid.
574
+ if (ts.isNewExpression(call) && ts.isIdentifier(call.expression) && (call.expression.text === 'Worker' || call.expression.text === 'URL') && c.getSymbolAtLocation(call.expression)?.declarations?.every((d) => d.getSourceFile().isDeclarationFile))
575
+ return true;
569
576
  // A weak reference to an untyped value refuses a primitive.
570
577
  if (ts.isNewExpression(call) && ts.isIdentifier(call.expression) && call.expression.text === 'WeakRef' && args[0] && this.untyped(args[0]))
571
578
  return true;
@@ -1,6 +1,46 @@
1
1
  import ts from 'typescript';
2
- import { relative } from 'node:path';
2
+ import { dirname, relative, resolve } from 'node:path';
3
3
  import { evaluatedImports } from "../program/module-order.js";
4
+ /**
5
+ * `new Worker('~/x')`, `new Worker('./x')`, or `new Worker(new URL('./x', import.meta.url))`:
6
+ * resolves the worker script path against the build's `workerScripts` map for `platform`.
7
+ */
8
+ export function resolveWorkerScript(name, args, workerScripts, resolveAlias, platform) {
9
+ if (name !== 'Worker' || !workerScripts?.size || !args.length)
10
+ return null;
11
+ const e = args[0];
12
+ let spec = null;
13
+ if (ts.isStringLiteralLike(e)) {
14
+ spec = e.text;
15
+ }
16
+ else if (ts.isNewExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'URL') {
17
+ const [s, base] = e.arguments ?? [];
18
+ if (s && ts.isStringLiteralLike(s) && base && base.getText() === 'import.meta.url')
19
+ spec = s.text;
20
+ }
21
+ if (!spec || !workerScripts?.size)
22
+ return null;
23
+ const file = e.getSourceFile().fileName;
24
+ const ext = platform === 'android' ? '.android.ts' : '.ios.ts';
25
+ const target = spec.startsWith('.') ? resolve(dirname(file), spec) : resolveAlias?.(spec, file);
26
+ if (target) {
27
+ const stem = target.replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
28
+ for (const f of [stem + '.ts', stem + ext, stem + '.tsx', stem + '/index.ts', stem + `/index${ext}`]) {
29
+ const script = workerScripts.get(f);
30
+ if (script)
31
+ return script;
32
+ }
33
+ }
34
+ if (spec.startsWith('~/') || spec.startsWith('@/')) {
35
+ const rel = spec.slice(2).replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
36
+ for (const [key, script] of workerScripts) {
37
+ const norm = key.replace(/\\/g, '/');
38
+ if ([`/${rel}.ts`, `/${rel}${ext}`, `/${rel}.tsx`, `/${rel}/index.ts`, `/${rel}/index${ext}`].some((s) => norm.endsWith(s)))
39
+ return script;
40
+ }
41
+ }
42
+ return null;
43
+ }
4
44
  /** Methods that change the array, map, set or typed array they are called on. */
5
45
  const MUTATORS = new Set(['push', 'pop', 'shift', 'unshift', 'splice', 'set', 'fill', 'sort', 'reverse', 'copyWithin', 'delete', 'clear', 'add']);
6
46
  /** `Object.assign(X, …)` and the like: functions that change their first argument. */
@@ -243,6 +243,9 @@ export const assignmentMethods = {
243
243
  if (left.expression.kind !== ts.SyntaxKind.SuperKeyword && this.isInstanceMethod(left.name))
244
244
  return `${RT.jsExpandoSet}(${this.expr(left.expression)}, ${swiftString(left.name.text)}, ${this.stored(right, left, 'Any?', checks)})`;
245
245
  }
246
+ if (ts.isPropertyAccessExpression(left) && !this.library && this.typeOf(left.expression).replace(/[?!]$/, '') === 'JSWorker' && (left.name.text === 'onmessage' || left.name.text === 'onerror')) {
247
+ return `${RT.jsSet}(${this.expr(left.expression)}, ${swiftString(left.name.text)}, ${this.stored(right, left, 'Any?', checks)})`;
248
+ }
246
249
  if (ts.isPropertyAccessExpression(left) && this.isAny(left.expression))
247
250
  return `${RT.jsSet}(${this.expr(left.expression)}, ${swiftString(left.name.text)}, ${this.stored(right, left, 'Any?', checks)})`;
248
251
  // An array written at a key that may be no index (`frames[time]`, time untyped): as script writes it.