orvyn-lang 0.2.0 → 0.4.0

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 (63) hide show
  1. package/GUIDE.md +198 -0
  2. package/LANGUAGE.md +818 -30
  3. package/README.md +211 -250
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +207 -16
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +152 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +615 -58
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +69 -8
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +65 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +176 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +970 -50
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/assets.js +39 -0
  27. package/src/lang/native/build.js +140 -63
  28. package/src/lang/native/compatibility.js +57 -0
  29. package/src/lang/native/config.js +108 -0
  30. package/src/lang/native/ios/OrvynApp.swift +6 -0
  31. package/src/lang/native/ios/OrvynEngine.swift +291 -4
  32. package/src/lang/native/ios/OrvynViews.swift +769 -41
  33. package/src/lang/native/ios.js +81 -2
  34. package/src/lang/native-runtime.js +541 -55
  35. package/src/lang/native-size.js +53 -0
  36. package/src/lang/page-files.js +71 -0
  37. package/src/lang/page.js +63 -0
  38. package/src/lang/parser.js +278 -15
  39. package/src/lang/prerender.js +300 -0
  40. package/src/lang/read-import.js +12 -0
  41. package/src/lang/router.js +266 -0
  42. package/src/lang/runtime-shared.js +796 -10
  43. package/src/lang/runtime.js +399 -51
  44. package/src/lang/select.js +13 -0
  45. package/src/lang/server-code.js +233 -0
  46. package/src/lang/server-export.js +78 -0
  47. package/src/lang/server-libs.js +53 -0
  48. package/src/lang/server.js +409 -0
  49. package/src/lang/style-check.js +60 -0
  50. package/src/lang/test-runner.js +134 -0
  51. package/src/lang/types.js +317 -0
  52. package/src/lang/vite-plugin.js +108 -6
  53. package/src/lang/web-overlay.js +578 -0
  54. package/src/lang/widgets.js +94 -0
  55. package/src/lang/words.js +38 -0
  56. package/src/runtime/animations.js +24 -0
  57. package/src/runtime/appear.js +73 -0
  58. package/src/runtime/marquee.js +57 -0
  59. package/src/runtime/mount.js +120 -27
  60. package/src/runtime/patch.js +90 -11
  61. package/src/runtime/style.js +50 -9
  62. package/src/styling/fluid.js +129 -6
  63. package/src/styling/spec.js +319 -0
@@ -3,9 +3,14 @@
3
3
  // Runs the compiled Orvyn app (app.js) in JavaScriptCore and publishes the
4
4
  // UI tree it renders. Taps and typing are sent back to JS as events.
5
5
 
6
+ import CoreLocation
6
7
  import Foundation
7
8
  import JavaScriptCore
9
+ import PhotosUI
10
+ import UniformTypeIdentifiers
11
+ import Security
8
12
  import SwiftUI
13
+ import UIKit
9
14
 
10
15
  struct ONode: Identifiable {
11
16
  let id: String
@@ -17,9 +22,15 @@ struct ONode: Identifiable {
17
22
  let v: String?
18
23
  let src: String?
19
24
  let href: String?
25
+ let a: String?
26
+ let rh: Double?
27
+ let o: [String]
20
28
  let tap: Int?
21
29
  let change: Int?
30
+ let visible: Int?
22
31
  let c: [ONode]
32
+ let theme: [String: Any]?
33
+ let canGoBack: Bool
23
34
 
24
35
  init(_ d: [String: Any]) {
25
36
  id = d["id"] as? String ?? UUID().uuidString
@@ -31,26 +42,39 @@ struct ONode: Identifiable {
31
42
  v = d["v"] as? String
32
43
  src = d["src"] as? String
33
44
  href = d["href"] as? String
45
+ a = d["a"] as? String
46
+ rh = (d["rh"] as? NSNumber)?.doubleValue
47
+ o = d["o"] as? [String] ?? []
34
48
  let e = d["e"] as? [String: Any] ?? [:]
35
49
  tap = (e["tap"] as? NSNumber)?.intValue
36
50
  change = (e["change"] as? NSNumber)?.intValue
51
+ visible = (e["visible"] as? NSNumber)?.intValue
37
52
  c = (d["c"] as? [[String: Any]] ?? []).map(ONode.init)
53
+ theme = d["theme"] as? [String: Any]
54
+ canGoBack = d["canGoBack"] as? Bool ?? false
38
55
  }
39
56
  }
40
57
 
41
58
  final class OrvynEngine: ObservableObject {
42
59
  @Published var root: ONode?
43
60
  @Published var error: String?
61
+ /// scrollTo("section-about") asks the page to scroll to that label;
62
+ /// `scrollTick` makes the same label work twice in a row
63
+ @Published var scrollTarget: String?
64
+ @Published var scrollTick = 0
44
65
 
45
66
  /// Set by `orvyn dev ios` (e.g. http://127.0.0.1:8790). When present the app
46
67
  /// loads its code from your Mac and reloads when you save a .orv file.
47
68
  let devServer = ProcessInfo.processInfo.environment["ORVYN_DEV_SERVER"]
48
69
 
49
70
  private var context: JSContext!
71
+ private let device = ODevice()
50
72
  // bumps on every reload so callbacks from the old app are ignored
51
73
  private var generation = 0
52
74
  private var devVersion: String?
53
75
  private var testScriptStarted = false
76
+ private var initialURL: String?
77
+ private var fetchTasks: [Int: URLSessionDataTask] = [:]
54
78
 
55
79
  init() {
56
80
  if devServer != nil {
@@ -129,6 +153,14 @@ final class OrvynEngine: ObservableObject {
129
153
  self.context = context
130
154
 
131
155
  installHost(context, generation)
156
+ context.setObject("ios", forKeyedSubscript: "__orvynPlatform" as NSString)
157
+ context.setObject([
158
+ "width": UIScreen.main.bounds.width,
159
+ "height": UIScreen.main.bounds.height
160
+ ], forKeyedSubscript: "__orvynViewport" as NSString)
161
+ if let initialURL {
162
+ context.setObject(initialURL, forKeyedSubscript: "__orvynInitialUrl" as NSString)
163
+ }
132
164
  context.evaluateScript(code, withSourceURL: url)
133
165
 
134
166
  if !testScriptStarted {
@@ -139,6 +171,15 @@ final class OrvynEngine: ObservableObject {
139
171
 
140
172
  // MARK: - Native → JS
141
173
 
174
+ func openURL(_ url: String) {
175
+ initialURL = url
176
+ context?.objectForKeyedSubscript("__orvynDeepLink")?.call(withArguments: [url])
177
+ }
178
+
179
+ func goBack() {
180
+ _ = context?.objectForKeyedSubscript("__orvynBack")?.call(withArguments: [])
181
+ }
182
+
142
183
  func fire(_ handler: Int?, _ value: String? = nil) {
143
184
  guard let handler else { return }
144
185
  let event = context.objectForKeyedSubscript("__orvynEvent")
@@ -168,16 +209,52 @@ final class OrvynEngine: ObservableObject {
168
209
  }
169
210
  context.setObject(render, forKeyedSubscript: "__orvynRender" as NSString)
170
211
 
212
+ let openExternal: @convention(block) (String) -> Void = { address in
213
+ guard let url = URL(string: address) else { return }
214
+ DispatchQueue.main.async { UIApplication.shared.open(url) }
215
+ }
216
+ context.setObject(openExternal, forKeyedSubscript: "__orvynOpenExternal" as NSString)
217
+
218
+ let scrollTo: @convention(block) (String) -> Void = { [weak self] label in
219
+ DispatchQueue.main.async {
220
+ self?.scrollTarget = label
221
+ self?.scrollTick += 1
222
+ }
223
+ }
224
+ context.setObject(scrollTo, forKeyedSubscript: "__orvynScrollTo" as NSString)
225
+
226
+ let device: @convention(block) (Int, String) -> Void = { [weak self] id, kind in
227
+ DispatchQueue.main.async {
228
+ self?.device.ask(kind) { json, error in
229
+ guard self?.generation == generation else { return }
230
+ self?.context.objectForKeyedSubscript("__orvynDeviceDone")?
231
+ .call(withArguments: [id, json, error])
232
+ }
233
+ }
234
+ }
235
+ context.setObject(device, forKeyedSubscript: "__orvynDevice" as NSString)
236
+
237
+ // JavaScriptCore has no timers of its own
238
+ var nextTimer = 0
239
+ var timers = Set<Int>()
171
240
  let setTimeout: @convention(block) (JSValue, JSValue) -> Int = { [weak self] callback, ms in
172
241
  let delay = ms.isNumber ? ms.toDouble() : 0
242
+ nextTimer += 1
243
+ let id = nextTimer
244
+ timers.insert(id)
173
245
  DispatchQueue.main.asyncAfter(deadline: .now() + delay / 1000) { [weak self] in
174
- guard self?.generation == generation else { return }
246
+ guard self?.generation == generation, timers.remove(id) != nil else { return }
175
247
  callback.call(withArguments: [])
176
248
  }
177
- return 0
249
+ return id
178
250
  }
179
251
  context.setObject(setTimeout, forKeyedSubscript: "setTimeout" as NSString)
180
252
 
253
+ let clearTimeout: @convention(block) (JSValue) -> Void = { id in
254
+ if id.isNumber { timers.remove(Int(id.toInt32())) }
255
+ }
256
+ context.setObject(clearTimeout, forKeyedSubscript: "clearTimeout" as NSString)
257
+
181
258
  let fetch: @convention(block) (Int, String, String, JSValue, String) -> Void = { [weak self] id, url, method, body, headersJson in
182
259
  guard let target = URL(string: url) else {
183
260
  self?.fetchDone(id, 0, "Invalid URL", "", generation)
@@ -196,7 +273,7 @@ final class OrvynEngine: ObservableObject {
196
273
  request.setValue(value, forHTTPHeaderField: key)
197
274
  }
198
275
  }
199
- URLSession.shared.dataTask(with: request) { data, response, error in
276
+ let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
200
277
  let http = response as? HTTPURLResponse
201
278
  let status = error == nil ? (http?.statusCode ?? 0) : 0
202
279
  let contentType = http?.value(forHTTPHeaderField: "Content-Type") ?? ""
@@ -204,12 +281,20 @@ final class OrvynEngine: ObservableObject {
204
281
  ?? String(data: data ?? Data(), encoding: .utf8)
205
282
  ?? ""
206
283
  DispatchQueue.main.async {
284
+ self?.fetchTasks.removeValue(forKey: id)
207
285
  self?.fetchDone(id, status, text, contentType, generation)
208
286
  }
209
- }.resume()
287
+ }
288
+ self?.fetchTasks[id] = task
289
+ task.resume()
210
290
  }
211
291
  context.setObject(fetch, forKeyedSubscript: "__orvynFetch" as NSString)
212
292
 
293
+ let abortFetch: @convention(block) (Int) -> Void = { [weak self] id in
294
+ self?.fetchTasks.removeValue(forKey: id)?.cancel()
295
+ }
296
+ context.setObject(abortFetch, forKeyedSubscript: "__orvynAbortFetch" as NSString)
297
+
213
298
  // saved state → UserDefaults (kept after the app closes)
214
299
  let storageGet: @convention(block) (String) -> Any = { key in
215
300
  UserDefaults.standard.string(forKey: key) ?? NSNull()
@@ -221,6 +306,75 @@ final class OrvynEngine: ObservableObject {
221
306
  }
222
307
  context.setObject(storageSet, forKeyedSubscript: "__orvynStorageSet" as NSString)
223
308
 
309
+ let storageRemove: @convention(block) (String) -> Void = { key in
310
+ UserDefaults.standard.removeObject(forKey: key)
311
+ }
312
+ context.setObject(storageRemove, forKeyedSubscript: "__orvynStorageRemove" as NSString)
313
+
314
+ // secure credentials → iOS Keychain (strictly separate from saved state)
315
+ let keychainService = (Bundle.main.bundleIdentifier ?? "dev.orvyn.app") + ".secure"
316
+
317
+ let secureGet: @convention(block) (String) -> Any = { key in
318
+ let query: [String: Any] = [
319
+ kSecClass as String: kSecClassGenericPassword,
320
+ kSecAttrService as String: keychainService,
321
+ kSecAttrAccount as String: key,
322
+ kSecReturnData as String: true,
323
+ kSecMatchLimit as String: kSecMatchLimitOne
324
+ ]
325
+ var item: CFTypeRef?
326
+ let status = SecItemCopyMatching(query as CFDictionary, &item)
327
+ if status == errSecSuccess, let data = item as? Data, let text = String(data: data, encoding: .utf8) {
328
+ return text
329
+ }
330
+ return NSNull()
331
+ }
332
+ context.setObject(secureGet, forKeyedSubscript: "__orvynSecureGet" as NSString)
333
+
334
+ let secureSet: @convention(block) (String, String) -> Any = { key, value in
335
+ let data = value.data(using: .utf8) ?? Data()
336
+ let query: [String: Any] = [
337
+ kSecClass as String: kSecClassGenericPassword,
338
+ kSecAttrService as String: keychainService,
339
+ kSecAttrAccount as String: key
340
+ ]
341
+ let updateStatus = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary)
342
+ if updateStatus == errSecSuccess {
343
+ return NSNull()
344
+ }
345
+ var addQuery = query
346
+ addQuery[kSecValueData as String] = data
347
+ addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
348
+ let addStatus = SecItemAdd(addQuery as CFDictionary, nil)
349
+ return addStatus == errSecSuccess ? NSNull() : "Keychain write failed (\(addStatus))"
350
+ }
351
+ context.setObject(secureSet, forKeyedSubscript: "__orvynSecureSet" as NSString)
352
+
353
+ let secureRemove: @convention(block) (String) -> Any = { key in
354
+ let query: [String: Any] = [
355
+ kSecClass as String: kSecClassGenericPassword,
356
+ kSecAttrService as String: keychainService,
357
+ kSecAttrAccount as String: key
358
+ ]
359
+ let status = SecItemDelete(query as CFDictionary)
360
+ return (status == errSecSuccess || status == errSecItemNotFound)
361
+ ? NSNull()
362
+ : "Keychain delete failed (\(status))"
363
+ }
364
+ context.setObject(secureRemove, forKeyedSubscript: "__orvynSecureRemove" as NSString)
365
+
366
+ let secureClear: @convention(block) () -> Any = {
367
+ let query: [String: Any] = [
368
+ kSecClass as String: kSecClassGenericPassword,
369
+ kSecAttrService as String: keychainService
370
+ ]
371
+ let status = SecItemDelete(query as CFDictionary)
372
+ return (status == errSecSuccess || status == errSecItemNotFound)
373
+ ? NSNull()
374
+ : "Keychain clear failed (\(status))"
375
+ }
376
+ context.setObject(secureClear, forKeyedSubscript: "__orvynSecureClear" as NSString)
377
+
224
378
  let console = JSValue(newObjectIn: context)!
225
379
  for level in ["log", "warn", "error", "info"] {
226
380
  let log: @convention(block) () -> Void = {
@@ -267,3 +421,136 @@ final class OrvynEngine: ObservableObject {
267
421
  return nil
268
422
  }
269
423
  }
424
+
425
+ // Camera, photo library, files and location. One request at a time.
426
+ final class ODevice: NSObject, PHPickerViewControllerDelegate, UIImagePickerControllerDelegate,
427
+ UINavigationControllerDelegate, UIDocumentPickerDelegate, CLLocationManagerDelegate {
428
+ typealias Done = (_ json: String, _ error: String) -> Void
429
+
430
+ private var done: Done?
431
+ private var locations: CLLocationManager?
432
+
433
+ func ask(_ kind: String, _ done: @escaping Done) {
434
+ if self.done != nil { return done("", "Already waiting for another choice") }
435
+ self.done = done
436
+ switch kind {
437
+ case "photo":
438
+ var setup = PHPickerConfiguration()
439
+ setup.filter = .images
440
+ let picker = PHPickerViewController(configuration: setup)
441
+ picker.delegate = self
442
+ present(picker)
443
+ case "camera":
444
+ guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
445
+ return finish(error: "This device has no camera")
446
+ }
447
+ let picker = UIImagePickerController()
448
+ picker.sourceType = .camera
449
+ picker.delegate = self
450
+ present(picker)
451
+ case "file":
452
+ let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: true)
453
+ picker.delegate = self
454
+ present(picker)
455
+ case "location":
456
+ let manager = CLLocationManager()
457
+ locations = manager
458
+ manager.delegate = self
459
+ if manager.authorizationStatus == .notDetermined {
460
+ manager.requestWhenInUseAuthorization()
461
+ } else {
462
+ locationManagerDidChangeAuthorization(manager)
463
+ }
464
+ default:
465
+ finish(error: "Unknown request: \(kind)")
466
+ }
467
+ }
468
+
469
+ private func present(_ controller: UIViewController) {
470
+ // a swipe down would otherwise leave the app waiting forever
471
+ controller.isModalInPresentation = true
472
+ let window = UIApplication.shared.connectedScenes
473
+ .compactMap { $0 as? UIWindowScene }
474
+ .flatMap(\.windows)
475
+ .first { $0.isKeyWindow }
476
+ var top = window?.rootViewController
477
+ while let next = top?.presentedViewController { top = next }
478
+ guard let top else { return finish(error: "Could not open the picker") }
479
+ top.present(controller, animated: true)
480
+ }
481
+
482
+ private func finish(_ value: [String: Any]? = nil, error: String = "") {
483
+ let done = self.done
484
+ self.done = nil
485
+ let json = value.flatMap { try? JSONSerialization.data(withJSONObject: $0) }
486
+ .flatMap { String(data: $0, encoding: .utf8) } ?? ""
487
+ DispatchQueue.main.async { done?(json, error) }
488
+ }
489
+
490
+ private func file(_ name: String, _ type: String, _ data: Data) -> [String: Any] {
491
+ ["name": name, "type": type, "size": data.count, "dataUrl": "data:\(type);base64,\(data.base64EncodedString())"]
492
+ }
493
+
494
+ // large photos are scaled down so the app stays quick
495
+ private func photo(_ image: UIImage) -> [String: Any]? {
496
+ let scale = min(1, 1600 / max(image.size.width, image.size.height))
497
+ let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
498
+ let format = UIGraphicsImageRendererFormat()
499
+ format.scale = 1
500
+ let small = UIGraphicsImageRenderer(size: size, format: format).image { _ in
501
+ image.draw(in: CGRect(origin: .zero, size: size))
502
+ }
503
+ return small.jpegData(compressionQuality: 0.85).map { file("photo.jpg", "image/jpeg", $0) }
504
+ }
505
+
506
+ func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
507
+ picker.dismiss(animated: true)
508
+ guard let provider = results.first?.itemProvider, provider.canLoadObject(ofClass: UIImage.self) else {
509
+ return finish()
510
+ }
511
+ provider.loadObject(ofClass: UIImage.self) { [weak self] object, _ in
512
+ DispatchQueue.main.async {
513
+ self?.finish((object as? UIImage).flatMap { self?.photo($0) })
514
+ }
515
+ }
516
+ }
517
+
518
+ func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
519
+ picker.dismiss(animated: true)
520
+ finish((info[.originalImage] as? UIImage).flatMap { photo($0) })
521
+ }
522
+
523
+ func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
524
+ picker.dismiss(animated: true)
525
+ finish()
526
+ }
527
+
528
+ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
529
+ guard let url = urls.first, let data = try? Data(contentsOf: url) else {
530
+ return finish(error: "Could not read the file")
531
+ }
532
+ let type = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "application/octet-stream"
533
+ finish(file(url.lastPathComponent, type, data))
534
+ }
535
+
536
+ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
537
+ finish()
538
+ }
539
+
540
+ func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
541
+ switch manager.authorizationStatus {
542
+ case .authorizedWhenInUse, .authorizedAlways: manager.requestLocation()
543
+ case .denied, .restricted: finish(error: "Location was not allowed")
544
+ default: break
545
+ }
546
+ }
547
+
548
+ func locationManager(_ manager: CLLocationManager, didUpdateLocations found: [CLLocation]) {
549
+ guard let place = found.last, done != nil else { return }
550
+ finish(["latitude": place.coordinate.latitude, "longitude": place.coordinate.longitude, "accuracy": place.horizontalAccuracy])
551
+ }
552
+
553
+ func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
554
+ if done != nil { finish(error: "Could not get the location") }
555
+ }
556
+ }