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