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

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