@nstudio/nativescript-compiler 9.2.0-alpha.13 → 9.2.0-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/css/worker.js +2 -2
  2. package/dist/driver/compile.js +4 -3
  3. package/dist/kotlin/arguments.js +7 -3
  4. package/dist/kotlin/assignment.js +3 -0
  5. package/dist/kotlin/builtins.js +15 -4
  6. package/dist/kotlin/class-constructor.js +3 -1
  7. package/dist/kotlin/class-methods.js +9 -2
  8. package/dist/kotlin/components.js +39 -14
  9. package/dist/kotlin/construction.js +4 -5
  10. package/dist/kotlin/conversion.js +19 -3
  11. package/dist/kotlin/core-api.js +31 -7
  12. package/dist/kotlin/declarations.js +8 -3
  13. package/dist/kotlin/expressions.js +10 -5
  14. package/dist/kotlin/library.js +2 -2
  15. package/dist/kotlin/modules.js +9 -4
  16. package/dist/kotlin/names.js +5 -2
  17. package/dist/kotlin/narrowing.js +2 -1
  18. package/dist/kotlin/optional-chains.js +24 -5
  19. package/dist/kotlin/overrides.js +7 -2
  20. package/dist/kotlin/placement.js +5 -4
  21. package/dist/kotlin/static-calls.js +17 -5
  22. package/dist/kotlin/translator.js +15 -39
  23. package/dist/kotlin/type-facts.js +3 -2
  24. package/dist/kotlin/types.js +6 -5
  25. package/dist/kotlin/untyped-values.js +7 -1
  26. package/dist/program/program.js +3 -3
  27. package/dist/semantics/apis/array.js +11 -0
  28. package/dist/semantics/classes.js +24 -0
  29. package/dist/semantics/config.js +2 -0
  30. package/dist/semantics/forms/by-name.js +30 -18
  31. package/dist/semantics/globals.js +8 -2
  32. package/dist/semantics/lang.js +4 -0
  33. package/dist/semantics/ledger.js +0 -24
  34. package/dist/semantics/platform-globals.js +0 -16
  35. package/dist/semantics/refusals.js +1 -1
  36. package/dist/semantics/runtime.js +2 -0
  37. package/dist/semantics/throws.js +7 -0
  38. package/dist/semantics/worker-state.js +41 -1
  39. package/dist/swift/assignment.js +3 -0
  40. package/dist/swift/builtins.js +20 -12
  41. package/dist/swift/class-methods.js +3 -1
  42. package/dist/swift/construction.js +5 -1
  43. package/dist/swift/conversion.js +1 -1
  44. package/dist/swift/expressions.js +2 -4
  45. package/dist/swift/from-any.js +5 -0
  46. package/dist/swift/global-calls.js +8 -1
  47. package/dist/swift/library.js +1 -1
  48. package/dist/swift/modules.js +2 -1
  49. package/dist/swift/object-classes.js +2 -1
  50. package/dist/swift/protocols.js +5 -16
  51. package/dist/swift/type-facts.js +2 -0
  52. package/dist/swift/types.js +7 -6
  53. package/dist/targets/android/build.js +9 -7
  54. package/dist/targets/ios/build.js +23 -8
  55. package/docs/cli/compile-ios.md +1 -1
  56. package/kit-android/generated/kotlin/org/nativescript/kit/file_system_file_system_access.kt +1 -1
  57. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_internal_index.kt +1 -1
  58. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_properties_index.kt +6 -6
  59. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -1
  60. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +2 -2
  61. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_text_base_common.kt +2 -2
  62. package/kit-android/gradlew.bat +2 -2
  63. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Collections.kt +15 -6
  64. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Iterators.kt +1 -0
  65. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Promise.kt +5 -4
  66. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Workers.kt +39 -11
  67. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +13 -2
  68. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +0 -12
  69. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +0 -39
  70. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +0 -44
  71. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +19 -2
  72. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +87 -22
  73. package/kit-apple/Sources/NativeScriptKit/Core/text.text-common.swift +9 -1
  74. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +13 -2
  75. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view-base.index.swift +26 -2
  76. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.liquid-glass-container.index.ios.swift +12 -2
  77. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.root-layout.root-layout-common.swift +46 -6
  78. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +37 -3
  79. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.split-view-common.swift +12 -1
  80. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-selector.swift +50 -6
  81. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.text-base-common.swift +13 -1
  82. package/kit-apple/Sources/NativeScriptKit/Runtime/Collections.swift +5 -1
  83. package/kit-apple/Sources/NativeScriptKit/Runtime/Dynamic.swift +13 -2
  84. package/kit-apple/Sources/NativeScriptKit/Runtime/Errors.swift +10 -2
  85. package/kit-apple/Sources/NativeScriptKit/Runtime/Functions.swift +57 -12
  86. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +12 -3
  87. package/kit-apple/Sources/NativeScriptKit/Runtime/Promise.swift +56 -29
  88. package/kit-apple/Sources/NativeScriptKit/Runtime/Realm.swift +92 -0
  89. package/kit-apple/Sources/NativeScriptKit/Runtime/Record.swift +25 -5
  90. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +13 -4
  91. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExpEngine.swift +14 -5
  92. package/kit-apple/Sources/NativeScriptKit/Runtime/Symbol.swift +28 -6
  93. package/kit-apple/Sources/NativeScriptKit/Runtime/Threads.swift +2 -2
  94. package/kit-apple/Sources/NativeScriptKit/Runtime/Timers.swift +93 -47
  95. package/kit-apple/Sources/NativeScriptKit/Runtime/TypedArrays.swift +37 -9
  96. package/kit-apple/Sources/NativeScriptKit/Runtime/Values.swift +6 -4
  97. package/kit-apple/Sources/NativeScriptKit/Runtime/Views.swift +11 -2
  98. package/kit-apple/Sources/NativeScriptKit/Runtime/Workers.swift +680 -0
  99. package/package.json +1 -1
@@ -988,6 +988,7 @@ enum UnicodeProperties {
988
988
  }()
989
989
 
990
990
  private static var scripts: [String: [Int]] = [:]
991
+ private static let scriptsLock = JSUnfairLock()
991
992
 
992
993
  private static func codePoint(at offset: Int) -> Int {
993
994
  offset < 0xD800 ? offset : offset < 0xF800 ? offset + 0x800 : 0x10000 + (offset - 0xF800) / 2
@@ -1000,15 +1001,23 @@ enum UnicodeProperties {
1000
1001
  let words = name.split(separator: "_", omittingEmptySubsequences: false)
1001
1002
  guard name.count == 4 || words.allSatisfy({ w in w.first.map { ("A"..."Z").contains($0) } == true && w.dropFirst().allSatisfy { ("a"..."z").contains($0) } }) else { return nil }
1002
1003
  let key = (extensions ? "scx=" : "sc=") + name
1003
- if scripts[key] == nil {
1004
+ scriptsLock.lock()
1005
+ let existing = scripts[key]
1006
+ scriptsLock.unlock()
1007
+ let ranges: [Int]
1008
+ if let existing {
1009
+ ranges = existing
1010
+ } else {
1004
1011
  guard let re = try? NSRegularExpression(pattern: "\\p{\(extensions ? "Script_Extensions" : "Script")=\(name)}+") else { return nil }
1005
- var ranges: [Int] = []
1012
+ var built: [Int] = []
1006
1013
  for m in re.matches(in: everyScalar as String, range: NSRange(location: 0, length: everyScalar.length)) {
1007
- ranges += [codePoint(at: m.range.location), codePoint(at: m.range.location + m.range.length - 1)]
1014
+ built += [codePoint(at: m.range.location), codePoint(at: m.range.location + m.range.length - 1)]
1008
1015
  }
1009
- scripts[key] = ranges
1016
+ scriptsLock.lock()
1017
+ scripts[key] = built
1018
+ scriptsLock.unlock()
1019
+ ranges = built
1010
1020
  }
1011
- let ranges = scripts[key]!
1012
1021
  return { inRanges(ranges, $0) }
1013
1022
  }
1014
1023
 
@@ -9,27 +9,45 @@ public final class JSSymbol: Hashable, CustomStringConvertible {
9
9
 
10
10
  public init(_ description: String?) {
11
11
  jsDescription = description
12
+ JSSymbol.lock.lock()
12
13
  JSSymbol.count += 1
13
- key = "\u{0}@@\(JSSymbol.count)"
14
- JSSymbol.byKey[key] = self
14
+ let k = "\u{0}@@\(JSSymbol.count)"
15
+ key = k
16
+ JSSymbol.byKey[k] = self
17
+ JSSymbol.lock.unlock()
15
18
  }
16
19
 
20
+ private nonisolated static let lock = NSLock()
17
21
  private static var count = 0
18
22
  private static var byKey: [String: JSSymbol] = [:]
19
23
  private static var registry: [String: JSSymbol] = [:]
20
24
 
21
25
  /// `Symbol.for(key)`: one symbol per key, program-wide.
22
26
  public static func `for`(_ key: String) -> JSSymbol {
23
- if let s = registry[key] { return s }
27
+ lock.lock()
28
+ if let s = registry[key] {
29
+ lock.unlock()
30
+ return s
31
+ }
32
+ lock.unlock()
24
33
  let s = JSSymbol(key)
34
+ lock.lock()
35
+ if let existing = registry[key] {
36
+ lock.unlock()
37
+ return existing
38
+ }
25
39
  registry[key] = s
40
+ lock.unlock()
26
41
  return s
27
42
  }
28
43
 
29
44
  /// `Symbol.keyFor(symbol)`: the key of a registered symbol.
30
45
  public static func keyFor(_ symbol: JSSymbol) -> String? {
31
- guard let d = symbol.jsDescription, registry[d] === symbol else { return nil }
32
- return d
46
+ guard let d = symbol.jsDescription else { return nil }
47
+ lock.lock()
48
+ let match = registry[d] === symbol
49
+ lock.unlock()
50
+ return match ? d : nil
33
51
  }
34
52
 
35
53
  public static let iterator = JSSymbol("Symbol.iterator")
@@ -42,7 +60,11 @@ public final class JSSymbol: Hashable, CustomStringConvertible {
42
60
 
43
61
  /// The symbol a property key stands for.
44
62
  public static func of(key: String) -> JSSymbol? {
45
- key.utf8.first == 0 ? byKey[key] : nil
63
+ guard key.utf8.first == 0 else { return nil }
64
+ lock.lock()
65
+ let found = byKey[key]
66
+ lock.unlock()
67
+ return found
46
68
  }
47
69
 
48
70
  public func toString() -> String { "Symbol(\(jsDescription ?? ""))" }
@@ -252,7 +252,7 @@ public enum JSPosted {
252
252
  // Read and written only under `lock`.
253
253
  nonisolated(unsafe) private static var jobs: [@MainActor () -> Void] = []
254
254
  private nonisolated static let lock = NSLock()
255
- nonisolated static let arrived = DispatchSemaphore(value: 0)
255
+ public nonisolated static let arrived = DispatchSemaphore(value: 0)
256
256
 
257
257
  @usableFromInline nonisolated static func post(_ job: @escaping @MainActor () -> Void) {
258
258
  lock.lock()
@@ -264,7 +264,7 @@ public enum JSPosted {
264
264
  }
265
265
 
266
266
  /// Runs every posted job, in order; whether there was one.
267
- @discardableResult static func run() -> Bool {
267
+ @discardableResult public static func run() -> Bool {
268
268
  lock.lock()
269
269
  let ready = jobs
270
270
  jobs = []
@@ -55,39 +55,35 @@ final class JSTimerList {
55
55
  var isEmpty: Bool { head >= timers.count }
56
56
  }
57
57
 
58
- /// The event loop for timers: drives them from the main run loop in an app, or from
59
- /// `runUntilIdle()` in a command-line program.
60
- public enum JSEventLoop {
61
- static var lists: [Double: JSTimerList] = [:]
62
- static var timers: [Double: JSTimer] = [:]
63
- static var nextTimerId = 1.0
64
- static var nextSeq = 0
65
- static var processing = false
66
- static var runLoopTimer: CFRunLoopTimer?
67
- static var observer: CFRunLoopObserver?
68
- static let origin = DispatchTime.now().uptimeNanoseconds
69
-
70
- /// libuv's clock: whole milliseconds since the loop started.
71
- static func now() -> Double {
72
- Double(elapsedNanoseconds() / 1_000_000)
73
- }
58
+ /// Per-realm timer queue and run-loop hooks: `JSRealm.main` drives from the main `CFRunLoop`
59
+ /// (or `JSEventLoop.runUntilIdle()`); a worker realm delegates wakeups to its `host` callback.
60
+ final class JSEventLoopState {
61
+ nonisolated deinit {}
62
+ let isMain: Bool
63
+ var host: ((Double?) -> Void)?
64
+ var lists: [Double: JSTimerList] = [:]
65
+ var timers: [Double: JSTimer] = [:]
66
+ var nextTimerId = 1.0
67
+ var nextSeq = 0
68
+ var processing = false
69
+ var runLoopTimer: CFRunLoopTimer?
70
+ var observer: CFRunLoopObserver?
74
71
 
75
- private static func elapsedNanoseconds() -> UInt64 {
76
- let start = origin
77
- return DispatchTime.now().uptimeNanoseconds - start
72
+ init(isMain: Bool) {
73
+ self.isMain = isMain
78
74
  }
79
75
 
80
- static func schedule(_ callback: @escaping () -> Void, _ delay: Double, repeats: Bool) -> Double {
76
+ func schedule(_ callback: @escaping () -> Void, _ delay: Double, repeats: Bool) -> Double {
81
77
  var duration = delay
82
78
  if !(duration >= 1 && duration <= 2_147_483_647) { duration = 1 }
83
79
  let timer = JSTimer(id: nextTimerId, duration: duration, repeatInterval: repeats ? duration : nil, callback: callback)
84
80
  nextTimerId += 1
85
81
  timers[timer.id] = timer
86
- insert(timer, start: now())
82
+ insert(timer, start: JSEventLoop.now())
87
83
  return timer.id
88
84
  }
89
85
 
90
- private static func insert(_ timer: JSTimer, start: Double) {
86
+ private func insert(_ timer: JSTimer, start: Double) {
91
87
  let duration = timer.duration.rounded(.towardZero)
92
88
  timer.start = start
93
89
  timer.seq = nextSeq
@@ -102,7 +98,7 @@ public enum JSEventLoop {
102
98
  arm()
103
99
  }
104
100
 
105
- static func cancel(_ id: Double?) {
101
+ func cancel(_ id: Double?) {
106
102
  guard let id, let timer = timers.removeValue(forKey: id) else { return }
107
103
  timer.active = false
108
104
  let duration = timer.duration.rounded(.towardZero)
@@ -112,7 +108,7 @@ public enum JSEventLoop {
112
108
  arm()
113
109
  }
114
110
 
115
- private static func earliestList() -> JSTimerList? {
111
+ private func earliestList() -> JSTimerList? {
116
112
  var best: JSTimerList?
117
113
  for list in lists.values {
118
114
  guard let current = best else { best = list; continue }
@@ -122,14 +118,14 @@ public enum JSEventLoop {
122
118
  }
123
119
 
124
120
  /// When the next timer is due, on the `now()` clock.
125
- static var nextExpiry: Double? { earliestList()?.expiry }
121
+ var nextExpiry: Double? { earliestList()?.expiry }
126
122
 
127
123
  /// Node's `processTimers`: runs every due timer list in expiry order.
128
- static func processTimers() {
124
+ func processTimers() {
129
125
  guard !processing else { return }
130
126
  processing = true
131
127
  defer { processing = false }
132
- let current = now()
128
+ let current = JSEventLoop.now()
133
129
  while let list = earliestList() {
134
130
  if list.expiry > current { break }
135
131
  listOnTimeout(list, current)
@@ -137,7 +133,7 @@ public enum JSEventLoop {
137
133
  arm()
138
134
  }
139
135
 
140
- private static func listOnTimeout(_ list: JSTimerList, _ current: Double) {
136
+ private func listOnTimeout(_ list: JSTimerList, _ current: Double) {
141
137
  while let timer = list.first {
142
138
  if current - timer.start < list.duration {
143
139
  list.expiry = max(timer.start + list.duration, current + 1)
@@ -145,7 +141,7 @@ public enum JSEventLoop {
145
141
  return
146
142
  }
147
143
  list.removeFirst()
148
- let start = now()
144
+ let start = JSEventLoop.now()
149
145
  timer.callback()
150
146
  Microtasks.taskRan()
151
147
  if let interval = timer.repeatInterval, timer.active {
@@ -160,13 +156,18 @@ public enum JSEventLoop {
160
156
  if lists[list.duration] === list { lists[list.duration] = nil }
161
157
  }
162
158
 
163
- /// Re-arms the run-loop timer for the earliest expiry.
164
- private static func arm() {
159
+ /// Re-arms the run-loop timer (or notifies a worker host) for the earliest expiry.
160
+ private func arm() {
161
+ if let host {
162
+ host(nextExpiry.map { max(0, $0 - JSEventLoop.now()) })
163
+ return
164
+ }
165
+ guard isMain else { return }
165
166
  guard let expiry = nextExpiry else {
166
167
  if let timer = runLoopTimer { CFRunLoopTimerSetNextFireDate(timer, .greatestFiniteMagnitude) }
167
168
  return
168
169
  }
169
- let fireDate = CFAbsoluteTimeGetCurrent() + max(0, expiry - now()) / 1000
170
+ let fireDate = CFAbsoluteTimeGetCurrent() + max(0, expiry - JSEventLoop.now()) / 1000
170
171
  if let timer = runLoopTimer {
171
172
  CFRunLoopTimerSetNextFireDate(timer, fireDate)
172
173
  return
@@ -178,34 +179,79 @@ public enum JSEventLoop {
178
179
  CFRunLoopAddTimer(CFRunLoopGetMain(), timer, .commonModes)
179
180
  }
180
181
 
182
+ func installRunLoopObserver() {
183
+ guard isMain, observer == nil else { return }
184
+ let activities = CFRunLoopActivity.beforeTimers.rawValue | CFRunLoopActivity.beforeWaiting.rawValue
185
+ let created = CFRunLoopObserverCreateWithHandler(nil, activities, true, 0) { _, _ in
186
+ Microtasks.checkpoint()
187
+ }
188
+ observer = created
189
+ CFRunLoopAddObserver(CFRunLoopGetMain(), created, .commonModes)
190
+ }
191
+ }
192
+
193
+ /// The event loop for timers: drives them from the main run loop in an app, or from
194
+ /// `runUntilIdle()` in a command-line program.
195
+ public enum JSEventLoop {
196
+ static let origin = DispatchTime.now().uptimeNanoseconds
197
+
198
+ private static var current: JSEventLoopState { JSRealm.current().loop }
199
+
200
+ /// libuv's clock: whole milliseconds since the loop started.
201
+ static func now() -> Double {
202
+ Double(elapsedNanoseconds() / 1_000_000)
203
+ }
204
+
205
+ private static func elapsedNanoseconds() -> UInt64 {
206
+ let start = origin
207
+ return DispatchTime.now().uptimeNanoseconds - start
208
+ }
209
+
210
+ static func schedule(_ callback: @escaping () -> Void, _ delay: Double, repeats: Bool) -> Double {
211
+ current.schedule(callback, delay, repeats: repeats)
212
+ }
213
+
214
+ static func cancel(_ id: Double?) {
215
+ current.cancel(id)
216
+ }
217
+
218
+ /// When the next timer is due, on the `now()` clock.
219
+ static var nextExpiry: Double? { current.nextExpiry }
220
+
221
+ /// Node's `processTimers`: runs every due timer list in expiry order.
222
+ static func processTimers() {
223
+ current.processTimers()
224
+ }
225
+
181
226
  /// For command-line programs: drains microtasks, then runs timers (sleeping until each is due)
182
- /// until none remain.
227
+ /// and waits for any active workers until none remain.
183
228
  public static func runUntilIdle() {
184
229
  Microtasks.checkpoint()
185
230
  while true {
186
231
  if JSPosted.run() { continue }
187
- guard let expiry = nextExpiry else { break }
188
- let due = UInt64(expiry) * 1_000_000
189
- let elapsed = elapsedNanoseconds()
190
- if due > elapsed {
191
- _ = JSPosted.arrived.wait(timeout: .now() + .nanoseconds(Int(min(due - elapsed, 1_000_000_000)) + 1000))
232
+ if let expiry = nextExpiry {
233
+ let due = UInt64(expiry) * 1_000_000
234
+ let elapsed = elapsedNanoseconds()
235
+ if due > elapsed {
236
+ _ = JSPosted.arrived.wait(timeout: .now() + .nanoseconds(Int(min(due - elapsed, 1_000_000_000)) + 1000))
237
+ continue
238
+ }
239
+ processTimers()
240
+ Microtasks.checkpoint()
192
241
  continue
193
242
  }
194
- processTimers()
195
- Microtasks.checkpoint()
243
+ if JSWorker.hasActiveWorkers {
244
+ _ = JSPosted.arrived.wait(timeout: .now() + .milliseconds(50))
245
+ continue
246
+ }
247
+ break
196
248
  }
197
249
  }
198
250
 
199
251
  /// Adds a main-run-loop observer that performs a microtask checkpoint before timers fire and
200
252
  /// before the loop sleeps, so promise callbacks run after each batch of UIKit work.
201
253
  public static func installRunLoopObserver() {
202
- guard observer == nil else { return }
203
- let activities = CFRunLoopActivity.beforeTimers.rawValue | CFRunLoopActivity.beforeWaiting.rawValue
204
- let created = CFRunLoopObserverCreateWithHandler(nil, activities, true, 0) { _, _ in
205
- Microtasks.checkpoint()
206
- }
207
- observer = created
208
- CFRunLoopAddObserver(CFRunLoopGetMain(), created, .commonModes)
254
+ JSRealm.main.loop.installRunLoopObserver()
209
255
  }
210
256
  }
211
257
 
@@ -59,16 +59,19 @@ public protocol JSTypedArrayProtocol: JSArrayBufferView {
59
59
  var jsLength: Int { get }
60
60
  /// The elements as JavaScript values: numbers, or BigInts.
61
61
  var jsAnyValues: [Any?] { get }
62
+ /// A view of the same typed array kind and layout over another buffer (for structured clone).
63
+ func jsClone(buffer: JSArrayBuffer) -> AnyObject
62
64
  }
63
65
 
64
66
  /// `ArrayBuffer`: a fixed number of bytes, zeroed when made, at an address that stays put for
65
67
  /// as long as the buffer lives (native APIs read and write them in place).
66
68
  public final class JSArrayBuffer: JSDynamic, JSToStringTag, JSBufferSource, JSHostObject {
67
- public let count: Int
68
- let bytes: UnsafeMutableRawPointer
69
+ public private(set) var count: Int
70
+ public private(set) var detached = false
71
+ nonisolated(unsafe) let bytes: UnsafeMutableRawPointer
69
72
  /// Set for memory the buffer does not own: called instead of freeing it.
70
- private let deallocator: (() -> Void)?
71
- private let owned: Bool
73
+ private nonisolated let deallocator: (@Sendable () -> Void)?
74
+ private nonisolated let owned: Bool
72
75
 
73
76
  /// `new ArrayBuffer(length)`.
74
77
  public convenience init(_ length: Double = 0) throws {
@@ -98,12 +101,21 @@ public final class JSArrayBuffer: JSDynamic, JSToStringTag, JSBufferSource, JSHo
98
101
  public init(bytesNoCopy: UnsafeMutableRawPointer, count: Int, deallocator: (() -> Void)?) {
99
102
  self.count = count
100
103
  bytes = bytesNoCopy
101
- self.deallocator = deallocator
104
+ if let deallocator {
105
+ let carried = JSCarried(deallocator)
106
+ self.deallocator = { jsRunInWorker { carried.value() } }
107
+ } else {
108
+ self.deallocator = nil
109
+ }
102
110
  owned = false
103
111
  }
104
112
 
105
- isolated deinit {
106
- if owned { bytes.deallocate() } else { deallocator?() }
113
+ nonisolated deinit {
114
+ if owned {
115
+ bytes.deallocate()
116
+ } else if let deallocator {
117
+ jsLater(deallocator)
118
+ }
107
119
  }
108
120
 
109
121
  public var byteLength: Double { Double(count) }
@@ -119,6 +131,18 @@ public final class JSArrayBuffer: JSDynamic, JSToStringTag, JSBufferSource, JSHo
119
131
  return copy
120
132
  }
121
133
 
134
+ /// Moves this buffer's bytes into a new buffer and detaches this one (for `postMessage` transfer lists).
135
+ func transfer() throws -> JSArrayBuffer {
136
+ if detached {
137
+ throw JSException(JSDOMException("An ArrayBuffer is detached and could not be transferred.", "DataCloneError"))
138
+ }
139
+ let moved = JSArrayBuffer(byteCount: count)
140
+ if count > 0 { moved.bytes.copyMemory(from: bytes, byteCount: count) }
141
+ detached = true
142
+ count = 0
143
+ return moved
144
+ }
145
+
122
146
  /// `ArrayBuffer.prototype`, as far as a program reads it: its tag.
123
147
  public static let jsPrototype: JSArrayBuffer = JSArrayBuffer(byteCount: 0)
124
148
 
@@ -298,6 +322,7 @@ public final class JSTypedArray<Kind: JSTypedArrayElement>: JSTypedArrayProtocol
298
322
 
299
323
  /// `new Float32Array(buffer, byteOffset, length)`.
300
324
  public convenience init(buffer: JSArrayBuffer, _ byteOffset: Double? = nil, _ length: Double? = nil) throws {
325
+ if buffer.detached { throw JSException(JSTypeError("Cannot perform Construct on a detached ArrayBuffer")) }
301
326
  let size = Self.stride
302
327
  let name = Kind.kind.name
303
328
  guard let start = jsIndex(byteOffset ?? 0) else { throw JSException(JSRangeError("Start offset \(jsNumberToString(jsToIntegerOrInfinity(byteOffset ?? 0))) is outside the bounds of the buffer")) }
@@ -376,8 +401,11 @@ public final class JSTypedArray<Kind: JSTypedArrayElement>: JSTypedArrayProtocol
376
401
  public static var BYTES_PER_ELEMENT: Double { Double(Kind.kind.bytesPerElement) }
377
402
  public var BYTES_PER_ELEMENT: Double { Self.BYTES_PER_ELEMENT }
378
403
 
379
- @inlinable public var length: Double { Double(count) }
380
- public var byteLength: Double { Double(count * Self.stride) }
404
+ @inlinable public var length: Double { buffer.detached ? 0 : Double(count) }
405
+ public var byteLength: Double { buffer.detached ? 0 : Double(count * Self.stride) }
406
+ public func jsClone(buffer: JSArrayBuffer) -> AnyObject {
407
+ JSTypedArray(buffer: buffer, offset: offset, count: count)
408
+ }
381
409
  public var byteOffset: Double { Double(offset) }
382
410
  public var jsBytes: UnsafeMutableRawBufferPointer { UnsafeMutableRawBufferPointer(start: base, count: count * Self.stride) }
383
411
  public var jsElementKind: JSTypedArrayKind? { Kind.kind }
@@ -1744,7 +1744,10 @@ public func jsToNumber(_ value: Any?) -> Double {
1744
1744
  }
1745
1745
 
1746
1746
  enum JSJoinGuard {
1747
- static var active: [ObjectIdentifier] = []
1747
+ static var active: [ObjectIdentifier] {
1748
+ get { JSRealm.current().joining }
1749
+ set { JSRealm.current().joining = newValue }
1750
+ }
1748
1751
  }
1749
1752
 
1750
1753
  /// `String(value)`: arrays join with ",", plain objects are "[object Object]", errors "Name: message".
@@ -2006,9 +2009,8 @@ private func jsBuiltinFunction(_ name: String, _ length: Int, _ body: @escaping
2006
2009
  return function
2007
2010
  }
2008
2011
 
2009
- /// `globalThis` read as an object: the runtime's globals (`NativeScriptRuntime`, `com.tns`) are not
2010
- /// in a native app, so reading one gives undefined. `DOMException`, which core's fetch reads from it, is there.
2011
- public let jsGlobalThis = JSObject([("DOMException", jsDOMExceptionConstructor), ("performance", jsDateBuiltin)])
2012
+ /// `globalThis` read as an object: per-realm (a worker's own global on a worker thread, the app's on main).
2013
+ public var jsGlobalThis: JSObject { JSRealm.current().global }
2012
2014
 
2013
2015
  /// `Object` held as a value (`(<any>Object).entries(o)`): its functions over objects, called as script calls them.
2014
2016
  public let jsObjectBuiltin = jsBuiltinFunction("Object", 1, { a in jsIsNullish(jsArg(a, 0)) ? JSObject() : jsArg(a, 0) }, [
@@ -29,6 +29,7 @@ private final class JSWeakView {
29
29
 
30
30
  private var jsViewEntries: [ObjectIdentifier: JSViewEntry] = [:]
31
31
  private var jsViewPruneAt = 64
32
+ private let jsViewLock = JSUnfairLock()
32
33
 
33
34
  /// The object `value` is in JavaScript: what a stand-in stands for, else `value` itself.
34
35
  @inline(__always)
@@ -79,6 +80,8 @@ public func jsViewOf<T: JSViewing>(_ root: JSDynamic, _ type: T.Type, _ make: (J
79
80
  /// The one stand-in of `root` as `T` while both are alive, made by `make` when there is none.
80
81
  func jsStandInOf<T: AnyObject>(_ root: AnyObject, _ type: T.Type, _ make: () -> T) -> T {
81
82
  let id = ObjectIdentifier(root)
83
+ let typeId = ObjectIdentifier(type)
84
+ jsViewLock.lock()
82
85
  let entry: JSViewEntry
83
86
  if let e = jsViewEntries[id], e.root === root {
84
87
  entry = e
@@ -90,8 +93,14 @@ func jsStandInOf<T: AnyObject>(_ root: AnyObject, _ type: T.Type, _ make: () ->
90
93
  entry = JSViewEntry(root)
91
94
  jsViewEntries[id] = entry
92
95
  }
93
- if let v = entry.views[ObjectIdentifier(type)]?.view as? T { return v }
96
+ if let v = entry.views[typeId]?.view as? T {
97
+ jsViewLock.unlock()
98
+ return v
99
+ }
100
+ jsViewLock.unlock()
94
101
  let v = make()
95
- entry.views[ObjectIdentifier(type)] = JSWeakView(v)
102
+ jsViewLock.lock()
103
+ entry.views[typeId] = JSWeakView(v)
104
+ jsViewLock.unlock()
96
105
  return v
97
106
  }