@nativescript/compiler-angular 0.0.0-stage → 9.2.0-alpha.9

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.
@@ -0,0 +1,685 @@
1
+ package org.nativescript.kit
2
+
3
+ import java.util.IdentityHashMap
4
+
5
+ // @angular/core as compiled Angular apps call it: dependency injection, the references it injects, bootstrap.
6
+
7
+ typealias EffectRef = Effect
8
+
9
+ /** `inject(DestroyRef)`: callbacks run when the injecting component's scope ends. */
10
+ class DestroyRef internal constructor(owner: Owner?) {
11
+ private val owner = java.lang.ref.WeakReference(owner)
12
+
13
+ /** Registers the callback; the function returned unregisters it. */
14
+ fun onDestroy(callback: () -> Unit): () -> Unit {
15
+ var active = true
16
+ owner.get()?.onCleanup { if (active) jsReport { callback() } }
17
+ return { active = false }
18
+ }
19
+
20
+ companion object {
21
+ fun current(): DestroyRef = DestroyRef(Owner.current)
22
+ }
23
+ }
24
+
25
+ /** `ElementRef`: a view of a template, as a view query (`@ViewChild('ref', { read: ElementRef })`) gives it. */
26
+ class ElementRef(nativeElement: Any? = null) {
27
+ var nativeElement: Any? = nativeElement
28
+ private set
29
+
30
+ /** A component's own ElementRef, made with the component: its template's root view, once made. */
31
+ fun attach(host: Any?) { nativeElement = host }
32
+
33
+ companion object {
34
+ private val hosts = mutableListOf<Any?>()
35
+
36
+ /** Makes a directive of an element: its `inject(ElementRef)` is the element. */
37
+ fun <T> hosting(host: Any?, make: () -> T): T {
38
+ hosts.add(host)
39
+ try { return make() } finally { hosts.removeAt(hosts.size - 1) }
40
+ }
41
+
42
+ /** `inject(ElementRef)`: the element whose directive is being made; elsewhere, a ref to no view. */
43
+ fun current(): ElementRef = ElementRef(hosts.lastOrNull())
44
+ }
45
+ }
46
+
47
+ /** `SimpleChange`: one input's change, as `ngOnChanges` receives it. */
48
+ class SimpleChange(var previousValue: Any?, var currentValue: Any?, var firstChange: Boolean) {
49
+ fun isFirstChange(): Boolean = firstChange
50
+ }
51
+
52
+ fun forwardRef(fn: () -> Any?): Any? = fn
53
+
54
+ fun resolveForwardRef(value: Any?): Any? {
55
+ val flat = jsBox(value) ?: return null
56
+ if (flat is Function0<*>) return try { flat.invoke() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)); null }
57
+ if (flat is JSFunction && flat.length == 0) return try { flat.invoke() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)); null }
58
+ return value
59
+ }
60
+
61
+ class Optional
62
+ class Self
63
+ class SkipSelf
64
+ class Host
65
+ class Inject(val token: Any?)
66
+
67
+ /**
68
+ * The root injector: `providedIn: 'root'` services, each made on first use in the root scope (its
69
+ * `inject(DestroyRef)` and effects belong there) and destroyed with the app, after which the next
70
+ * use makes a new one, as a new bootstrap does.
71
+ */
72
+ object AppInjector {
73
+ internal var owner = Owner(null)
74
+ internal val services = HashMap<Class<*>, Any>()
75
+ private val making = HashSet<Class<*>>()
76
+
77
+ @Suppress("UNCHECKED_CAST")
78
+ fun <T : Any> service(type: Class<T>, make: () -> T): T {
79
+ Injector.current?.let { active ->
80
+ if (active !== Injector.shared) {
81
+ val found = active.get(type, Injector.NOT_FOUND, null, root = false)
82
+ if (found !== Injector.NOT_FOUND && type.isInstance(found)) return found as T
83
+ }
84
+ }
85
+ Injector.lookupClassOverride(type)?.let { if (type.isInstance(it)) return it as T }
86
+ services[type]?.let { return it as T }
87
+ if (!making.add(type)) throw JSException(JSError("NG0200: Circular dependency in DI detected for ${type.simpleName}"))
88
+ try {
89
+ val made = Injector.atRoot { untrack { owner.run(make) } }
90
+ services[type] = made
91
+ return made
92
+ } finally {
93
+ making.remove(type)
94
+ }
95
+ }
96
+
97
+ fun destroy() {
98
+ val old = owner
99
+ owner = Owner(null)
100
+ services.clear()
101
+ making.clear()
102
+ Injector.reset()
103
+ old.dispose()
104
+ }
105
+ }
106
+
107
+ typealias NodeInjector = Injector
108
+
109
+ class Injector(providers: Any? = null, private val parent: Injector? = null) {
110
+ /** A component's injector ([enter]): what its providers make belongs to the component, and goes when it does. */
111
+ private var owner: Owner? = null
112
+ private var entered: Injector? = null
113
+ private val instanceValues = IdentityHashMap<Any, Any?>()
114
+ private val instanceFactories = IdentityHashMap<Any, () -> Any?>()
115
+ private val instanceMultiFactories = IdentityHashMap<Any, MutableList<() -> Any?>>()
116
+ /** An environment injector's `ENVIRONMENT_INITIALIZER`s, run once it is made ([initialized]), in provider order. */
117
+ private var pendingInitializers = mutableListOf<() -> Any?>()
118
+ /** `StandaloneService`, provided per environment injector: each standalone component's own injector there, or null when its imports give no providers. */
119
+ private val standaloneInjectors = HashMap<Class<*>, Injector?>()
120
+ /**
121
+ * A root view's injector made under component injectors ([enter]): those are asked first, up to the environment
122
+ * injector they sit in, then the standalone injector ([parent]), as Angular asks element injectors first.
123
+ */
124
+ private var viewNodes: Injector? = null
125
+ private var viewEnvironment: Injector? = null
126
+
127
+ init {
128
+ if (providers != null) registerInstance(providers)
129
+ }
130
+
131
+ fun get(token: Any?, notFoundValue: Any? = null, options: Any? = null): Any? = get(token, notFoundValue, options, root = true)
132
+
133
+ /** Without [root], only what this injector and its ancestors provide: the root's answer for a service is the service's `shared`, which itself asks the active injector first. */
134
+ internal fun get(token: Any?, notFoundValue: Any?, options: Any?, root: Boolean, until: Injector? = null): Any? {
135
+ val unwrapped = resolveForwardRef(token)
136
+ val skipSelf = (jsBox(jsGetOptional(options, "skipSelf")) as? Boolean) == true
137
+ val selfOnly = (jsBox(jsGetOptional(options, "self")) as? Boolean) == true
138
+ val key = tokenKey(unwrapped)
139
+ if (!skipSelf && key != null) {
140
+ if (instanceValues.containsKey(key)) return instanceValues[key]
141
+ val multis = instanceMultiFactories[key]
142
+ if (!multis.isNullOrEmpty()) {
143
+ val values = multis.map { fn -> owned { runInContext(this) { try { fn() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)); null } } } }
144
+ val arr = JSArray(values.toMutableList())
145
+ instanceValues[key] = arr
146
+ return arr
147
+ }
148
+ val factory = instanceFactories[key]
149
+ if (factory != null) {
150
+ val v = owned { runInContext(this) { try { factory() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)); null } } }
151
+ instanceValues[key] = v
152
+ return v
153
+ }
154
+ }
155
+ if (selfOnly) return notFoundValue
156
+ val nodes = viewNodes
157
+ if (nodes != null) {
158
+ val found = nodes.get(unwrapped, NOT_FOUND, null, false, viewEnvironment)
159
+ if (found !== NOT_FOUND) return found
160
+ }
161
+ if (parent != null) return if (parent === until) notFoundValue else parent.get(unwrapped, notFoundValue, null, root, until)
162
+ if (skipSelf || !root) return notFoundValue
163
+ return resolveRoot(unwrapped, notFoundValue)
164
+ }
165
+
166
+ private fun initialized(): Injector {
167
+ val initializers = pendingInitializers
168
+ pendingInitializers = mutableListOf()
169
+ for (initFn in initializers) runInContext(this) { try { initFn() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)) } }
170
+ return this
171
+ }
172
+
173
+ private fun registerInstance(providers: Any?) {
174
+ fun walk(item: Any?) {
175
+ val flat = jsBox(item) ?: return
176
+ if (flat is JSArray<*>) {
177
+ for (el in flat.storage) walk(el)
178
+ return
179
+ }
180
+ if (flat is Function0<*>) {
181
+ pendingInitializers.add { flat.invoke() }
182
+ return
183
+ }
184
+ if (flat is JSFunction) {
185
+ pendingInitializers.add { flat.invoke() }
186
+ return
187
+ }
188
+ // A class: its own instance, as `{ provide: X, useClass: X }`.
189
+ if (flat is Class<*>) {
190
+ instanceFactories[flat] = { construct(flat) }
191
+ instanceMultiFactories.remove(flat)
192
+ instanceValues.remove(flat)
193
+ return
194
+ }
195
+ if (flat is JSDynamic) {
196
+ if ("providers" in flat.jsKeys) walk(flat.jsGet("providers"))
197
+ if ("provide" in flat.jsKeys) parseProvider(flat, this)
198
+ }
199
+ }
200
+ walk(providers)
201
+ }
202
+
203
+ fun leave() {
204
+ current = entered
205
+ }
206
+
207
+ private fun <T> owned(body: () -> T): T {
208
+ val owner = owner ?: return body()
209
+ return untrack { owner.run(body) }
210
+ }
211
+
212
+ companion object {
213
+ internal val NOT_FOUND = Any()
214
+ val shared = Injector()
215
+ /** Kept by each effect and template scope as it is made, and current again while they run. */
216
+ internal var current: Injector?
217
+ get() = EffectOrder.ambient as? Injector
218
+ set(value) { EffectOrder.ambient = value }
219
+ val root: Injector get() = current ?: shared
220
+
221
+ private val tokenValues = IdentityHashMap<Any, Any?>()
222
+ private val tokenFactories = IdentityHashMap<Any, () -> Any?>()
223
+ private val multiFactories = IdentityHashMap<Any, MutableList<() -> Any?>>()
224
+
225
+ private fun tokenKey(token: Any?): Any? = jsBox(resolveForwardRef(token))
226
+
227
+ /** The `ErrorHandler` the app provides, which hears what no script code caught, as Angular's zone hands it over. */
228
+ /** `inject(ErrorHandler)`: the one provided, else Angular's own. */
229
+ val errorHandler: ErrorHandler get() = inject(ErrorHandler::class.java) as? ErrorHandler ?: ErrorHandler.shared
230
+
231
+ internal fun providedErrorHandler(): ErrorHandler? {
232
+ val key = tokenKey(ErrorHandler::class.java) ?: return null
233
+ if (!tokenValues.containsKey(key) && !tokenFactories.containsKey(key)) return null
234
+ return resolveRoot(ErrorHandler::class.java) as? ErrorHandler
235
+ }
236
+
237
+ internal fun lookupClassOverride(type: Class<*>): Any? {
238
+ if (tokenValues.containsKey(type)) return tokenValues[type]
239
+ val factory = tokenFactories[type] ?: return null
240
+ val v = try { factory() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)); null }
241
+ tokenValues[type] = v
242
+ return v
243
+ }
244
+
245
+ fun create(options: Any?, parent: Injector? = null): Injector {
246
+ val flat = jsBox(options) ?: return Injector(null, parent)
247
+ if (flat is JSArray<*>) return Injector(flat, parent).initialized()
248
+ val providers = jsGetOptional(flat, "providers") ?: flat
249
+ val resolvedParent = (jsBox(jsGetOptional(flat, "parent")) as? Injector) ?: parent
250
+ return Injector(providers, resolvedParent).initialized()
251
+ }
252
+
253
+ /**
254
+ * `@Component({ providers })`: the component's own injector over the one it is made in, current from the
255
+ * component's first field to the end of its constructor ([leave]), and in its view (`EffectOrder.view`).
256
+ */
257
+ fun enter(providers: Any?): Injector {
258
+ val node = Injector(providers, current)
259
+ node.owner = Owner()
260
+ node.entered = current
261
+ current = node
262
+ return node
263
+ }
264
+
265
+ /**
266
+ * `createRootViewInjector`: a standalone component created as a root view (bootstrap, route, dialog) is made and
267
+ * rendered in its standalone injector, made from its imports the first time it is created over this environment
268
+ * injector, which then runs the initializers that construct its modules.
269
+ */
270
+ fun <T> standalone(type: Class<*>, imports: Any?, make: () -> T): T {
271
+ val active = current ?: shared
272
+ var environment = active
273
+ while (environment.owner != null) environment = environment.parent ?: shared
274
+ val injector = if (environment.standaloneInjectors.containsKey(type)) environment.standaloneInjectors[type] else {
275
+ val out = mutableListOf<Any?>()
276
+ val dedup = mutableSetOf<Class<*>>()
277
+ ngDeepForEach(imports) { walkNgModule(it, out, dedup) }
278
+ val made = if (out.isEmpty()) null else Injector(JSArray(out), environment).initialized()
279
+ environment.standaloneInjectors[type] = made
280
+ made
281
+ } ?: return make()
282
+ if (active === environment) return runInContext(injector, make)
283
+ val view = Injector(null, injector)
284
+ view.viewNodes = active
285
+ view.viewEnvironment = environment
286
+ return runInContext(view, make)
287
+ }
288
+
289
+ /** What a root service makes and injects comes from the root, not from the providers of the component that injected it. */
290
+ internal fun <T> atRoot(body: () -> T): T {
291
+ val active = current
292
+ current = null
293
+ try { return body() } finally { current = active }
294
+ }
295
+
296
+ fun <T> runInContext(injector: Any?, fn: () -> T): T {
297
+ val prev = current
298
+ current = (jsBox(injector) as? Injector) ?: shared
299
+ try { return fn() } finally { current = prev }
300
+ }
301
+
302
+ fun <T> root(make: () -> T): T = atRoot { untrack { AppInjector.owner.run(make) } }
303
+
304
+ fun reset() {
305
+ tokenValues.clear()
306
+ tokenFactories.clear()
307
+ multiFactories.clear()
308
+ current = null
309
+ }
310
+
311
+ fun provide(token: Any?, useValue: Any? = null, useFactory: (() -> Any?)? = null) {
312
+ val key = tokenKey(token) ?: return
313
+ if (useFactory != null) {
314
+ tokenFactories[key] = useFactory
315
+ tokenValues.remove(key)
316
+ } else {
317
+ tokenValues[key] = useValue
318
+ tokenFactories.remove(key)
319
+ }
320
+ }
321
+
322
+ private fun instantiateClass(cls: Class<*>): Any? {
323
+ try {
324
+ val companionField = cls.getDeclaredField("Companion")
325
+ val companion = companionField.get(null)
326
+ // A package's service keeps `shared` as its own static: its root instance is the kit's `jsShared`.
327
+ val methods = companion.javaClass.methods.filter { it.parameterCount == 0 }
328
+ val sharedMethod = methods.firstOrNull { it.name == "getJsShared" } ?: methods.firstOrNull { it.name == "getShared" }
329
+ if (sharedMethod != null) return sharedMethod.invoke(companion)
330
+ } catch (_: Throwable) {}
331
+ return try { construct(cls) } catch (_: Throwable) { null }
332
+ }
333
+
334
+ /** A new instance, as a child injector's `useClass` provider makes one of its own. */
335
+ private fun construct(cls: Class<*>): Any? {
336
+ val ctor = cls.declaredConstructors.firstOrNull { it.parameterCount == 0 } ?: return injectedConstruct(cls)
337
+ ctor.isAccessible = true
338
+ return try { ctor.newInstance() } catch (e: java.lang.reflect.InvocationTargetException) { throw e.targetException }
339
+ }
340
+
341
+ /** A service whose constructor takes what it injects: its companion's `jsConstruct` injects them from the active injector. */
342
+ private fun injectedConstruct(cls: Class<*>): Any? {
343
+ val companion = try { cls.getDeclaredField("Companion").get(null) } catch (_: Throwable) { return null }
344
+ val make = companion.javaClass.methods.firstOrNull { it.name == "jsConstruct" && it.parameterCount == 0 } ?: return null
345
+ return try { make.invoke(companion) } catch (e: java.lang.reflect.InvocationTargetException) { throw e.targetException }
346
+ }
347
+
348
+ private fun parseProvider(dyn: JSDynamic, target: Injector?) {
349
+ val token = resolveForwardRef(dyn.jsGet("provide"))
350
+ val key = tokenKey(token) ?: return
351
+ val isMulti = (jsBox(dyn.jsGet("multi")) as? Boolean) == true
352
+ val hasValue = "useValue" in dyn.jsKeys
353
+ val valProp = dyn.jsGet("useValue")
354
+ val factory = jsBox(dyn.jsGet("useFactory"))
355
+ val existing = jsBox(dyn.jsGet("useExisting"))
356
+ val useClass = jsBox(resolveForwardRef(dyn.jsGet("useClass")))
357
+ val deps = (jsBox(dyn.jsGet("deps")) as? JSArray<*>)?.storage ?: emptyList<Any?>()
358
+ val make: () -> Any? = {
359
+ when {
360
+ hasValue -> valProp
361
+ factory != null -> {
362
+ val resolved = deps.map { dep ->
363
+ val flatDep = jsBox(dep)
364
+ if (flatDep is JSArray<*>) {
365
+ if (flatDep.storage.any { jsBox(it) is SkipSelf }) null
366
+ else flatDep.storage.lastOrNull()?.let { if (target != null) target.get(it) else inject(it) }
367
+ } else {
368
+ if (target != null) target.get(flatDep) else inject(flatDep)
369
+ }
370
+ }
371
+ jsCall(factory, *resolved.toTypedArray())
372
+ }
373
+ existing != null -> if (target != null) target.get(existing) else inject(existing)
374
+ useClass is Class<*> -> if (target != null) construct(useClass) else instantiateClass(useClass)
375
+ useClass != null -> jsCall(useClass)
376
+ key is Class<*> -> instantiateClass(key)
377
+ else -> null
378
+ }
379
+ }
380
+ if (target != null) {
381
+ if (isMulti) {
382
+ target.instanceMultiFactories.getOrPut(key) { mutableListOf() }.add(make)
383
+ target.instanceValues.remove(key)
384
+ } else {
385
+ target.instanceFactories[key] = make
386
+ target.instanceValues.remove(key)
387
+ }
388
+ } else {
389
+ if (isMulti) {
390
+ multiFactories.getOrPut(key) { mutableListOf() }.add(make)
391
+ tokenValues.remove(key)
392
+ } else {
393
+ tokenFactories[key] = make
394
+ tokenValues.remove(key)
395
+ }
396
+ }
397
+ }
398
+
399
+ fun register(providers: Any?) {
400
+ val initializers = mutableListOf<() -> Any?>()
401
+ fun walk(item: Any?) {
402
+ val flat = jsBox(item) ?: return
403
+ if (flat is JSArray<*>) {
404
+ for (el in flat.storage) walk(el)
405
+ return
406
+ }
407
+ if (flat is Function0<*>) {
408
+ initializers.add { flat.invoke() }
409
+ return
410
+ }
411
+ if (flat is JSFunction) {
412
+ initializers.add { flat.invoke() }
413
+ return
414
+ }
415
+ if (flat is JSDynamic) {
416
+ if ("providers" in flat.jsKeys) walk(flat.jsGet("providers"))
417
+ if ("provide" in flat.jsKeys) parseProvider(flat, null)
418
+ }
419
+ }
420
+ walk(providers)
421
+ for (initFn in initializers) {
422
+ try { initFn() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)) }
423
+ }
424
+ }
425
+
426
+ fun inject(token: Any?, options: Any? = null, notFoundValue: Any? = null): Any? {
427
+ val unwrapped = resolveForwardRef(token)
428
+ val active = current
429
+ if (active != null && active !== shared) {
430
+ return active.get(unwrapped, notFoundValue, options)
431
+ }
432
+ if ((jsBox(jsGetOptional(options, "skipSelf")) as? Boolean) == true) {
433
+ return notFoundValue
434
+ }
435
+ return resolveRoot(unwrapped, notFoundValue)
436
+ }
437
+
438
+ internal fun resolveRoot(unwrapped: Any?, notFoundValue: Any? = null): Any? {
439
+ val key = tokenKey(unwrapped) ?: return notFoundValue
440
+ if (tokenValues.containsKey(key)) return tokenValues[key]
441
+ val multis = multiFactories[key]
442
+ if (!multis.isNullOrEmpty()) {
443
+ val values = multis.map { fn -> try { fn() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)); null } }
444
+ val arr = JSArray(values.toMutableList())
445
+ tokenValues[key] = arr
446
+ return arr
447
+ }
448
+ val factory = tokenFactories[key]
449
+ if (factory != null) {
450
+ val v = try { factory() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)); null }
451
+ tokenValues[key] = v
452
+ return v
453
+ }
454
+ if (key is InjectionToken && key.factory != null) {
455
+ val v = try { key.factory.invoke() } catch (t: Throwable) { jsReportUncaught(jsCaught(t)); null }
456
+ tokenValues[key] = v
457
+ return v
458
+ }
459
+ if (key is Class<*>) {
460
+ when (key) {
461
+ ErrorHandler::class.java -> return ErrorHandler.shared
462
+ Injector::class.java -> return current ?: shared
463
+ NgZone::class.java -> return NgZone.shared
464
+ DestroyRef::class.java -> return DestroyRef.current()
465
+ ElementRef::class.java -> return ElementRef.current()
466
+ ApplicationRef::class.java -> return ApplicationRef.shared
467
+ Location::class.java -> return Location.shared
468
+ ViewContainerRef::class.java -> return ViewContainerRef()
469
+ }
470
+ instantiateClass(key)?.let { return it }
471
+ }
472
+ return notFoundValue
473
+ }
474
+ }
475
+ }
476
+
477
+ class InjectionToken(val desc: String = "", options: Any? = null) {
478
+ val factory: (() -> Any?)? = run {
479
+ val fn = jsBox(jsGetOptional(options, "factory")) ?: return@run null
480
+ { jsCall(fn) }
481
+ }
482
+ override fun toString(): String = "InjectionToken $desc"
483
+ }
484
+
485
+ /** Open: an app's class may extend it (`class AppErrorHandler extends ErrorHandler`), provided as `{ provide: ErrorHandler, useClass }`. */
486
+ open class ErrorHandler : JSDynamic {
487
+ open fun handleError(error: Any?) { jsError("ERROR", error) }
488
+ private var added: JSObject? = null
489
+ override fun jsGet(key: String): Any? = added?.get(key)
490
+ override fun jsSet(key: String, value: Any?) { (added ?: JSObject().also { added = it })[key] = value }
491
+ override val jsKeys: List<String> get() = added?.keys ?: emptyList()
492
+ override val jsClassName: String? get() = "ErrorHandler"
493
+ companion object {
494
+ val shared = ErrorHandler()
495
+ }
496
+ }
497
+
498
+ /** Providers are registered once, by the injector they are given to (`bootstrapApplication`'s), as Angular's are. */
499
+ fun makeEnvironmentProviders(providers: Any?): Any? = providers
500
+
501
+ fun provideEnvironmentInitializer(fn: () -> Any?): Any? = fn
502
+ fun provideAppInitializer(fn: () -> Any?): Any? = fn
503
+
504
+ /** An `@NgModule` class's companion: its metadata, evaluated once, and its construction with its constructor's parameters injected. */
505
+ interface JSNgModuleDef {
506
+ val jsNgImports: Any?
507
+ val jsNgProviders: Any?
508
+ fun jsNgConstruct(): Any?
509
+ }
510
+
511
+ private fun ngModuleDef(value: Any?): Pair<Class<*>, JSNgModuleDef>? {
512
+ val cls = jsBox(value) as? Class<*> ?: return null
513
+ val def = try { cls.getDeclaredField("Companion").get(null) as? JSNgModuleDef } catch (_: Throwable) { null } ?: return null
514
+ return cls to def
515
+ }
516
+
517
+ private fun ngDeepForEach(value: Any?, body: (Any?) -> Unit) {
518
+ val flat = jsBox(value) ?: return
519
+ if (flat is JSArray<*>) for (el in flat.storage) ngDeepForEach(el, body) else body(flat)
520
+ }
521
+
522
+ /**
523
+ * Angular's `walkProviderTree`: each module once, its imports first (a `ModuleWithProviders`' providers after all of
524
+ * them), then the module itself, the initializer that makes it when the injector is made, and its own providers.
525
+ * Returns whether [container] is a `ModuleWithProviders`.
526
+ */
527
+ private fun walkNgModule(container: Any?, out: MutableList<Any?>, dedup: MutableSet<Class<*>>): Boolean {
528
+ val flat = jsBox(resolveForwardRef(container)) ?: return false
529
+ val direct = ngModuleDef(flat)
530
+ val (cls, def) = direct ?: ngModuleDef(jsGetOptional(flat, "ngModule")) ?: return false
531
+ if (dedup.add(cls)) {
532
+ val withProviders = mutableListOf<Any?>()
533
+ ngDeepForEach(def.jsNgImports) { if (walkNgModule(it, out, dedup)) withProviders.add(it) }
534
+ for (m in withProviders) ngDeepForEach(jsGetOptional(m, "providers")) { out.add(it) }
535
+ out.add(JSObject(listOf<Pair<String, Any?>>(Pair("provide", cls), Pair("useFactory", { def.jsNgConstruct() }))))
536
+ out.add({ Injector.inject(cls) })
537
+ ngDeepForEach(def.jsNgProviders) { out.add(it) }
538
+ }
539
+ return direct == null && flat is JSDynamic && "providers" in flat.jsKeys
540
+ }
541
+
542
+ /** What is not a compiled NgModule (the kit's own modules) is given to the injector as it is. */
543
+ fun importProvidersFrom(vararg modules: Any?): Any? {
544
+ val out = mutableListOf<Any?>()
545
+ val dedup = HashSet<Class<*>>()
546
+ val withProviders = mutableListOf<Any?>()
547
+ ngDeepForEach(JSArray(modules.toMutableList())) { source ->
548
+ if (walkNgModule(source, out, dedup)) withProviders.add(source)
549
+ else if (ngModuleDef(source) == null && ngModuleDef(jsGetOptional(source, "ngModule")) == null) out.add(source)
550
+ }
551
+ for (m in withProviders) ngDeepForEach(jsGetOptional(m, "providers")) { out.add(it) }
552
+ return JSArray(out)
553
+ }
554
+
555
+ val PLATFORM_ID = InjectionToken("PLATFORM_ID", JSObject("factory" to { "browser" }))
556
+ val APP_INITIALIZER = InjectionToken("APP_INITIALIZER")
557
+ val ENVIRONMENT_INITIALIZER = InjectionToken("ENVIRONMENT_INITIALIZER")
558
+
559
+ fun isPlatformBrowser(platformId: Any?): Boolean = jsToString(platformId) == "browser"
560
+ fun isPlatformServer(platformId: Any?): Boolean = jsToString(platformId) == "server"
561
+
562
+ /** `NgZone` without zone.js: both run their function at once. */
563
+ class NgZone {
564
+ val onStable = Emitter<Any?>()
565
+ val onMicrotaskEmpty = Emitter<Any?>()
566
+ val onUnstable = Emitter<Any?>()
567
+ val onError = Emitter<Any?>()
568
+ val isStable = true
569
+ fun <T> run(fn: () -> T): T = fn()
570
+ fun <T> runOutsideAngular(fn: () -> T): T = fn()
571
+ fun <T> runGuarded(fn: () -> T): T = fn()
572
+ fun <T> runTask(fn: () -> T): T = fn()
573
+
574
+ companion object {
575
+ val shared = NgZone()
576
+ fun isInAngularZone(): Boolean = true
577
+ }
578
+ }
579
+
580
+ class TemplateRef(val elementRef: ElementRef = ElementRef())
581
+
582
+ class EmbeddedViewRef(var context: Any? = null) {
583
+ var rootNodes: JSArray<Any?> = JSArray()
584
+ var destroyed: Boolean = false
585
+ private set
586
+ fun destroy() { destroyed = true }
587
+ fun detectChanges() {}
588
+ fun markForCheck() {}
589
+ }
590
+
591
+ class ComponentRef(
592
+ var instance: Any? = null,
593
+ val location: ElementRef = ElementRef(),
594
+ val injector: Injector = Injector.shared,
595
+ ) {
596
+ val hostView = EmbeddedViewRef(instance)
597
+ fun setInput(name: String, value: Any?) {
598
+ val inst = instance ?: return
599
+ try { jsSet(inst, name, value) } catch (_: Throwable) {}
600
+ }
601
+ fun destroy() { hostView.destroy() }
602
+ }
603
+
604
+ class ViewContainerRef {
605
+ val element = ElementRef()
606
+ val injector = Injector.shared
607
+ private val views = mutableListOf<EmbeddedViewRef>()
608
+ val length: Double get() = views.size.toDouble()
609
+ fun clear() {
610
+ for (v in views) v.destroy()
611
+ views.clear()
612
+ }
613
+ fun createEmbeddedView(@Suppress("UNUSED_PARAMETER") templateRef: Any?, context: Any? = null, @Suppress("UNUSED_PARAMETER") options: Any? = null): EmbeddedViewRef {
614
+ val view = EmbeddedViewRef(context)
615
+ views.add(view)
616
+ return view
617
+ }
618
+ fun createComponent(componentType: Any?, @Suppress("UNUSED_PARAMETER") options: Any? = null): ComponentRef {
619
+ val flat = jsBox(componentType)
620
+ val inst = when (flat) {
621
+ is Class<*> -> try {
622
+ val ctor = flat.declaredConstructors.firstOrNull { it.parameterCount == 0 }
623
+ ctor?.isAccessible = true
624
+ ctor?.newInstance()
625
+ } catch (_: Throwable) { null }
626
+ null -> null
627
+ else -> try { jsCall(flat) } catch (_: Throwable) { null }
628
+ }
629
+ val ref = ComponentRef(inst)
630
+ views.add(ref.hostView)
631
+ return ref
632
+ }
633
+ fun remove(index: Double? = null) {
634
+ if (views.isEmpty()) return
635
+ val idx = index?.toInt() ?: (views.size - 1)
636
+ if (idx in views.indices) {
637
+ views[idx].destroy()
638
+ views.removeAt(idx)
639
+ }
640
+ }
641
+ }
642
+
643
+ class ApplicationRef {
644
+ val isStable = Emitter<Boolean>()
645
+ fun tick() {}
646
+ fun destroy() {}
647
+ companion object {
648
+ val shared = ApplicationRef()
649
+ }
650
+ }
651
+
652
+ class Location {
653
+ private var currentPath = "/"
654
+ fun path(@Suppress("UNUSED_PARAMETER") includeHash: Boolean = false): String = currentPath
655
+ fun go(path: String, query: String = "", @Suppress("UNUSED_PARAMETER") state: Any? = null) {
656
+ currentPath = if (query.isEmpty()) path else "$path?$query"
657
+ }
658
+ fun replaceState(path: String, query: String = "", state: Any? = null) = go(path, query, state)
659
+ fun back() {}
660
+ fun forward() {}
661
+ companion object {
662
+ val shared = Location()
663
+ fun joinWithSlash(start: String, end: String): String {
664
+ if (start.isEmpty()) return end
665
+ if (end.isEmpty()) return start
666
+ val s = if (start.endsWith("/")) start.dropLast(1) else start
667
+ val e = if (end.startsWith("/")) end.drop(1) else end
668
+ return "$s/$e"
669
+ }
670
+ fun stripTrailingSlash(url: String): String =
671
+ if (url.length > 1 && url.endsWith("/")) url.dropLast(1) else url
672
+ }
673
+ }
674
+
675
+ fun bootstrapApplication(@Suppress("UNUSED_PARAMETER") rootComponent: Any?, options: Any? = null): JSPromise<Any?> {
676
+ val providers = jsGetOptional(options, "providers")
677
+ if (!jsIsNullish(providers)) Injector.register(providers)
678
+ return JSPromise.resolve<Any?>(ApplicationRef.shared)
679
+ }
680
+
681
+ fun runNativeScriptAngularApp(options: Any? = null) {
682
+ val fn = jsBox(jsGetOptional(options, "appModuleBootstrap")) ?: return
683
+ jsReport { jsCall(fn) }
684
+ }
685
+