rvlib-shipkit 2.18.0 → 2.20.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 (186) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/package.json +1 -1
  3. package/src/annex/annex.ts +227 -0
  4. package/src/annex/offload.ts +279 -0
  5. package/src/asks/asks-queue.ts +63 -10
  6. package/src/checks/SK040-release-words.check.ts +43 -0
  7. package/src/checks/SK041-annex-links.check.ts +28 -0
  8. package/src/checks/SK042-post-kinds.check.ts +73 -0
  9. package/src/cli/cmd_Annex.ts +179 -0
  10. package/src/cli/cmd_Asks.ts +3 -1
  11. package/src/cli/cmd_Commands.ts +4 -1
  12. package/src/cli/cmd_GlobalProcesses.ts +34 -11
  13. package/src/cli/cmd_Home.ts +41 -4
  14. package/src/cli/cmd_Messages.ts +155 -0
  15. package/src/cli/cmd_Releases.ts +48 -0
  16. package/src/cli/cmd_Review.ts +161 -6
  17. package/src/cli/cmd_Secret.ts +4 -30
  18. package/src/cli/cmd_Shot.ts +4 -4
  19. package/src/cli/cmd_Social.ts +179 -3
  20. package/src/cli/cmd_Trailer.ts +15 -3
  21. package/src/cli/family-pages.ts +2 -0
  22. package/src/cli/kit/index.ts +1 -1
  23. package/src/cli/kit/verb.ts +11 -3
  24. package/src/cli/registry.ts +8 -2
  25. package/src/collections/actions.ts +29 -1
  26. package/src/collections/collection-types.ts +10 -1
  27. package/src/collections/providers.ts +5 -2
  28. package/src/commands/model.ts +36 -0
  29. package/src/commands/registry.ts +49 -0
  30. package/src/commands/routes.ts +59 -0
  31. package/src/commands/runner.ts +35 -0
  32. package/src/commands/runs.ts +112 -0
  33. package/src/core/app-icon.ts +4 -3
  34. package/src/core/icon-type.ts +8 -0
  35. package/src/core/jobs.ts +4 -3
  36. package/src/core/layout.ts +5 -2
  37. package/src/core/squircle.ts +95 -0
  38. package/src/home/daemon-jobs.ts +26 -2
  39. package/src/home/global-units.ts +3 -0
  40. package/src/home/gui-app/ShipkitGui.swift +302 -5
  41. package/src/home/gui-app.ts +63 -33
  42. package/src/home/hmr-keep.ts +134 -0
  43. package/src/home/home-paths.ts +5 -1
  44. package/src/home/home-start.ts +14 -14
  45. package/src/home/lib-watch.ts +21 -11
  46. package/src/home/pm.ts +1 -1
  47. package/src/home/process-apps.ts +181 -0
  48. package/src/home/resources.ts +3 -3
  49. package/src/home/run-daemon.ts +11 -2
  50. package/src/home/run-pm.ts +9 -1
  51. package/src/home/run-web.ts +7 -4
  52. package/src/home/serve-web.ts +64 -14
  53. package/src/home/supervise.ts +3 -1
  54. package/src/identities/collection.ts +49 -0
  55. package/src/identities/identities.ts +130 -11
  56. package/src/identities/machine.ts +4 -3
  57. package/src/identities/rating.ts +33 -0
  58. package/src/identities/shown.ts +170 -0
  59. package/src/identities/steps.ts +5 -0
  60. package/src/media-store/purge.ts +15 -1
  61. package/src/media-store/remote.ts +22 -6
  62. package/src/messages/brief.ts +117 -0
  63. package/src/messages/collection.ts +40 -0
  64. package/src/messages/model.ts +171 -0
  65. package/src/messages/routes.ts +15 -0
  66. package/src/messages/score.ts +180 -0
  67. package/src/messages/tabs.ts +13 -0
  68. package/src/release/notes.ts +130 -0
  69. package/src/release/run-bump.ts +41 -18
  70. package/src/release/run-release.ts +22 -4
  71. package/src/release/run-releases.ts +17 -15
  72. package/src/release/unit-resolve.ts +9 -0
  73. package/src/releases/add.ts +66 -0
  74. package/src/releases/collection.ts +36 -0
  75. package/src/releases/from-card.ts +66 -0
  76. package/src/releases/model.ts +267 -0
  77. package/src/releases/pictures.ts +89 -0
  78. package/src/releases/routes.ts +36 -0
  79. package/src/releases/store.ts +71 -0
  80. package/src/repo-config.ts +5 -0
  81. package/src/review/cells.ts +0 -11
  82. package/src/review/format.ts +10 -6
  83. package/src/review/http.ts +7 -2
  84. package/src/review/model.ts +92 -3
  85. package/src/review/notes.ts +2 -48
  86. package/src/review/routes.ts +28 -10
  87. package/src/review/stage-card.ts +197 -0
  88. package/src/review/stage-routes.ts +123 -0
  89. package/src/review/store.ts +117 -19
  90. package/src/review/trailer-card.ts +99 -0
  91. package/src/review/trailer-desk.ts +57 -4
  92. package/src/review/trailer-model.ts +41 -7
  93. package/src/review/trailer-notes.ts +45 -0
  94. package/src/review/trailer-routes.ts +22 -13
  95. package/src/secrets/manager.ts +59 -0
  96. package/src/secrets/name.ts +2 -0
  97. package/src/serve/hub-app/app-bridge.ts +71 -0
  98. package/src/serve/hub-app/col-card.tsx +10 -0
  99. package/src/serve/hub-app/cols-svc.ts +37 -6
  100. package/src/serve/hub-app/commands/commands-page.tsx +122 -0
  101. package/src/serve/hub-app/commands/commands-st.ts +177 -0
  102. package/src/serve/hub-app/commands.css +24 -0
  103. package/src/serve/hub-app/hash-route.ts +40 -1
  104. package/src/serve/hub-app/home-st.ts +11 -2
  105. package/src/serve/hub-app/home.html +3 -0
  106. package/src/serve/hub-app/hub-app.tsx +6 -0
  107. package/src/serve/hub-app/hub.css +1 -0
  108. package/src/serve/hub-app/icons.tsx +5 -0
  109. package/src/serve/hub-app/identities-view.tsx +4 -1
  110. package/src/serve/hub-app/identities.css +1 -0
  111. package/src/serve/hub-app/index.html +3 -0
  112. package/src/serve/hub-app/keys.ts +2 -2
  113. package/src/serve/hub-app/machine-st.ts +41 -10
  114. package/src/serve/hub-app/messages/messages-page.tsx +354 -0
  115. package/src/serve/hub-app/messages/messages-st.ts +74 -0
  116. package/src/serve/hub-app/messages.css +35 -0
  117. package/src/serve/hub-app/releases/releases-page.tsx +94 -0
  118. package/src/serve/hub-app/releases/releases-st.ts +69 -0
  119. package/src/serve/hub-app/releases.css +25 -0
  120. package/src/serve/hub-app/repo-sections.ts +15 -1
  121. package/src/serve/hub-app/repo-st.ts +56 -5
  122. package/src/serve/hub-app/review/clip-st.ts +31 -3
  123. package/src/serve/hub-app/review/note-place.ts +31 -0
  124. package/src/serve/hub-app/review/review-cells.tsx +27 -3
  125. package/src/serve/hub-app/review/review-st.ts +77 -2
  126. package/src/serve/hub-app/review/review-thread.tsx +9 -31
  127. package/src/serve/hub-app/review/review-views.tsx +164 -58
  128. package/src/serve/hub-app/review/thread-st.ts +108 -41
  129. package/src/serve/hub-app/review/trailer-card.tsx +187 -0
  130. package/src/serve/hub-app/review/trailer-page.tsx +62 -31
  131. package/src/serve/hub-app/review/trailer-st.ts +138 -26
  132. package/src/serve/hub-app/review/trailer-timeline.tsx +39 -26
  133. package/src/serve/hub-app/review.css +49 -6
  134. package/src/serve/hub-app/social/comms-page.tsx +55 -23
  135. package/src/serve/hub-app/social/identity-pictures.ts +112 -0
  136. package/src/serve/hub-app/social/kit.tsx +9 -6
  137. package/src/serve/hub-app/social/post-card.tsx +10 -2
  138. package/src/serve/hub-app/social/social-model.ts +37 -3
  139. package/src/serve/hub-app/social/social-page.tsx +236 -82
  140. package/src/serve/hub-app/social/social-st.ts +79 -26
  141. package/src/serve/hub-app/social/stage-popup.tsx +268 -0
  142. package/src/serve/hub-app/social/stage-st.ts +310 -0
  143. package/src/serve/hub-app/social/step-layout.ts +42 -0
  144. package/src/serve/hub-app/social.css +68 -4
  145. package/src/serve/hub-app/tree-build.ts +38 -1
  146. package/src/serve/hub-app/tree-svc.ts +10 -3
  147. package/src/serve/project-gutter-route.ts +4 -2
  148. package/src/serve/same-origin.ts +24 -1
  149. package/src/serve/serve-hub.ts +27 -3
  150. package/src/shipkit-files.ts +9 -7
  151. package/src/shot/shooter.ts +3 -3
  152. package/src/shot/shot-ask.ts +14 -3
  153. package/src/shot/shot.shipkit.ts +1 -1
  154. package/src/social/discord-layout.ts +282 -0
  155. package/src/social/fit.ts +84 -0
  156. package/src/social/identity-words.ts +74 -0
  157. package/src/social/kind-pages.ts +41 -0
  158. package/src/social/kinds.ts +92 -0
  159. package/src/social/load.ts +105 -9
  160. package/src/social/md.ts +14 -6
  161. package/src/social/media-limit.ts +63 -2
  162. package/src/social/presence.ts +1 -1
  163. package/src/social/publish/bluesky.ts +58 -19
  164. package/src/social/publish/discord.ts +3 -2
  165. package/src/social/publish/index.ts +31 -5
  166. package/src/social/reach.ts +49 -0
  167. package/src/social/release-stage.ts +173 -0
  168. package/src/social/routes.ts +44 -9
  169. package/src/social/stage.ts +227 -0
  170. package/src/social/strip.ts +85 -0
  171. package/src/social/text.ts +6 -2
  172. package/src/social/unit.ts +57 -1
  173. package/src/social/writes.ts +11 -0
  174. package/src/stores/routes.ts +2 -2
  175. package/src/suite/judge-suites.ts +1 -1
  176. package/src/suite/suite-cli.ts +5 -5
  177. package/src/trailer/build.ts +90 -52
  178. package/src/trailer/draft.ts +28 -0
  179. package/src/trailer/footage.ts +4 -2
  180. package/src/trailer/grammar.ts +25 -13
  181. package/src/trailer/graph.ts +32 -9
  182. package/src/trailer/profile.ts +35 -0
  183. package/src/trailer/prune.ts +15 -10
  184. package/src/trailer/public-words.ts +41 -0
  185. package/src/trailer/stitch.ts +22 -10
  186. package/src/trailer/titles.ts +47 -2
@@ -5,12 +5,50 @@
5
5
  // a bare launch opens (ShipkitStartURL). One WKWebView per window; every
6
6
  // `open -a <app> <url>` opens one more window, cmd-n too. A link to another
7
7
  // site opens in the default browser, and a download lands in ~/Downloads.
8
+ // The shipkit app alone wears the Dock badge of the review cards waiting for
9
+ // the owner and notifies each new one, as its page posts them (`shipkit`
10
+ // message handler, serve/hub-app/app-bridge.ts).
8
11
  import AppKit
12
+ import UserNotifications
9
13
  import WebKit
10
14
 
11
15
  let info = Bundle.main.infoDictionary ?? [:]
12
16
  let appName = (info["CFBundleName"] as? String) ?? "shipkit"
13
17
  let startURL = URL(string: (info["ShipkitStartURL"] as? String) ?? "") ?? URL(string: "http://127.0.0.1:4799/")!
18
+ /** the shipkit app itself (home/gui-app.ts BUNDLE_ID), never a process app */
19
+ let isShipkit = Bundle.main.bundleIdentifier == "dev.shipkit.gui"
20
+
21
+ /** a card that started waiting, as the page posts it */
22
+ struct Card {
23
+ let id: String, title: String, repo: String, url: String
24
+ var key: String { "\(repo)/\(id)" }
25
+ }
26
+
27
+ /** one notification: a card, or the line for the rest of a burst, which opens the inbox of the home they came from */
28
+ enum Note {
29
+ case card(Card)
30
+ case more([Card], inbox: URL?)
31
+ }
32
+
33
+ /** what a burst of new cards shows: each card up to `cap`, then one line for the rest */
34
+ func notesOf(_ cards: [Card], cap: Int = 3) -> [Note] {
35
+ if cards.count <= cap { return cards.map { .card($0) } }
36
+ let inbox = URL(string: cards[cap].url).flatMap { URL(string: "/inbox", relativeTo: $0)?.absoluteURL }
37
+ return cards.prefix(cap).map { .card($0) } + [.more(Array(cards.dropFirst(cap)), inbox: inbox)]
38
+ }
39
+
40
+ /** a notification's identifier: its card's key, so the banner can be taken back once the card stops waiting */
41
+ func idOf(_ note: Note) -> String {
42
+ switch note {
43
+ case .card(let c): return c.key
44
+ case .more(let cards, _): return "more:" + cards.map(\.key).joined(separator: ",")
45
+ }
46
+ }
47
+
48
+ /** the banners to take back: a card's once it no longer waits, a burst line's once none of its cards does */
49
+ func staleOf(_ delivered: [(id: String, cards: [String])], waiting: Set<String>) -> [String] {
50
+ delivered.filter { $0.cards.allSatisfy { !waiting.contains($0) } }.map(\.id)
51
+ }
14
52
 
15
53
  /** a url that stays in the app: the machine itself, or the host the app is for */
16
54
  func stays(_ url: URL) -> Bool {
@@ -124,15 +162,32 @@ final class Pane: NSView, NSSearchFieldDelegate {
124
162
  }
125
163
  }
126
164
 
127
- final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate, NSWindowDelegate, NSMenuItemValidation {
165
+ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate, NSWindowDelegate, NSMenuItemValidation, WKScriptMessageHandler, UNUserNotificationCenterDelegate {
128
166
  var windows: [NSWindow] = []
129
167
  var opened = false
130
168
 
169
+ // a click on a notification can launch the app: its delegate is set before launch ends
170
+ func applicationWillFinishLaunching(_ note: Notification) {
171
+ if isShipkit && !CommandLine.arguments.contains(where: { $0.hasPrefix("--self-test") }) { UNUserNotificationCenter.current().delegate = self }
172
+ }
173
+
131
174
  func applicationDidFinishLaunching(_ note: Notification) {
132
175
  if CommandLine.arguments.contains("--self-test-find") { return selfTestFind() }
133
176
  if CommandLine.arguments.contains("--self-test-panels") { return selfTestPanels() }
134
177
  if CommandLine.arguments.contains("--self-test-download") { return selfTestDownload() }
178
+ if CommandLine.arguments.contains("--self-test-badge") { return selfTestBadge() }
135
179
  buildMenu()
180
+ // the system asks the owner once; refused, the badge still counts and each notification says why it did not show
181
+ if isShipkit {
182
+ UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { ok, err in
183
+ if !ok { NSLog("shipkit: notifications are off for this app (System Settings, Notifications, shipkit)\(err.map { ": \($0.localizedDescription)" } ?? "")") }
184
+ }
185
+ // `--background`: running with no window from the start, the badge live, as after the last window closed
186
+ if CommandLine.arguments.contains("--background") {
187
+ opened = true
188
+ keep(home: startURL)
189
+ }
190
+ }
136
191
  // esc closes the find bar of the key window, and reaches the page otherwise
137
192
  NSEvent.addLocalMonitorForEvents(matching: .keyDown) { e in
138
193
  if e.keyCode == 53, let pane = self.keyPane(), pane.isFindBarVisible {
@@ -154,7 +209,8 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
154
209
  for u in urls { open(u) }
155
210
  }
156
211
 
157
- func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool { true }
212
+ // the shipkit app stays running with no window, as a mail or chat app does, so its badge stays live; Quit ends it
213
+ func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool { !isShipkit }
158
214
 
159
215
  func applicationShouldHandleReopen(_ app: NSApplication, hasVisibleWindows: Bool) -> Bool {
160
216
  if !hasVisibleWindows { open(startURL) }
@@ -214,11 +270,31 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
214
270
  return true
215
271
  }
216
272
 
217
- func open(_ url: URL) {
218
- opened = true
273
+ func webConfig() -> WKWebViewConfiguration {
219
274
  let config = WKWebViewConfiguration()
220
275
  config.preferences.setValue(true, forKey: "developerExtrasEnabled")
221
- let web = WKWebView(frame: .zero, configuration: config)
276
+ if isShipkit {
277
+ config.userContentController.add(self, name: "shipkit")
278
+ // the badge's poll keeps its pace while the window is hidden or covered
279
+ if #available(macOS 14.0, *) { config.preferences.inactiveSchedulingPolicy = .none }
280
+ }
281
+ return config
282
+ }
283
+
284
+ /** the page of the home the app keeps loaded while no window is open: it alone keeps the badge and the
285
+ * notifications live, and leaves once a window's page posts again */
286
+ var keeper: WKWebView?
287
+
288
+ func keep(home: URL) {
289
+ let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 1400, height: 900), configuration: webConfig())
290
+ web.navigationDelegate = self
291
+ web.load(URLRequest(url: home))
292
+ keeper = web
293
+ }
294
+
295
+ func open(_ url: URL) {
296
+ opened = true
297
+ let web = WKWebView(frame: .zero, configuration: webConfig())
222
298
  if #available(macOS 13.3, *) { web.isInspectable = true }
223
299
  web.navigationDelegate = self
224
300
  web.uiDelegate = self
@@ -325,7 +401,16 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
325
401
  }
326
402
 
327
403
  func windowWillClose(_ note: Notification) {
404
+ let pane = (note.object as? NSWindow)?.contentView as? Pane
328
405
  windows.removeAll { $0 === note.object as? NSWindow }
406
+ guard let pane else { return }
407
+ // the last window leaves the home loaded with no window, on the home that window was on; its count holds
408
+ // until that page posts its own
409
+ if isShipkit && windows.isEmpty && keeper == nil {
410
+ keep(home: pane.web.url.flatMap { stays($0) ? URL(string: "/", relativeTo: $0)?.absoluteURL : nil } ?? startURL)
411
+ return
412
+ }
413
+ dropCount(pane.web)
329
414
  }
330
415
 
331
416
  // the page title names the window, so cmd-tab and the window menu tell pages apart
@@ -430,6 +515,218 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
430
515
  web.loadHTMLString("<body data-page=here><a id=a href='data:text/plain,hello' download='hello.txt'>save</a></body>", baseURL: nil)
431
516
  }
432
517
 
518
+ // the Dock badge and the notifications: every window's page posts the same house count, the cards waiting at its
519
+ // first answer (the seed) and those it saw start waiting after; the app owns the one set of cards notified, so a
520
+ // card notifies once whatever the number of windows or reloads, a burst gathered for half a second
521
+
522
+ /** the cards already notified or already waiting at start, for the life of the app */
523
+ var notified = Set<String>()
524
+ /** the first seed of the app's life is the backlog: it never notifies */
525
+ var seeded = false
526
+ var burst: [Card] = []
527
+ /** each web view's last count: a page that leaves the home, or a closed window, drops out of the badge */
528
+ var counts: [ObjectIdentifier: Int] = [:]
529
+ /** hears every notification instead of the system: the self test reads it */
530
+ var deliver: ((Note) -> Void)?
531
+
532
+ func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
533
+ guard message.frameInfo.isMainFrame, let body = message.body as? [String: Any] else { return }
534
+ if let n = body["waiting"] as? Int, let web = message.webView {
535
+ // a window's page posts again: the page kept with no window leaves
536
+ if let k = keeper, k !== web {
537
+ keeper = nil
538
+ k.stopLoading()
539
+ }
540
+ let live = Set((windows.compactMap { ($0.contentView as? Pane)?.web } + [web]).map(ObjectIdentifier.init))
541
+ counts = counts.filter { live.contains($0.key) }
542
+ counts[ObjectIdentifier(web)] = n
543
+ drawBadge()
544
+ if let keys = body["keys"] as? [String] { takeBack(waiting: Set(keys)) }
545
+ }
546
+ if let seed = body["seed"] as? [[String: Any]] {
547
+ let cards = seed.compactMap(cardOf)
548
+ if !seeded {
549
+ seeded = true
550
+ for c in cards { notified.insert("\(c.repo)/\(c.id)") }
551
+ } else {
552
+ // a reloaded page or a later window: what waits that the app never saw arrived in between
553
+ cards.forEach(arrived)
554
+ }
555
+ }
556
+ if let c = (body["card"] as? [String: Any]).flatMap(cardOf) { arrived(c) }
557
+ }
558
+
559
+ func cardOf(_ c: [String: Any]) -> Card? {
560
+ guard let id = c["id"] as? String, let repo = c["repo"] as? String else { return nil }
561
+ return Card(id: id, title: (c["title"] as? String) ?? id, repo: repo, url: (c["url"] as? String) ?? "")
562
+ }
563
+
564
+ func arrived(_ c: Card) {
565
+ if !notified.insert("\(c.repo)/\(c.id)").inserted { return }
566
+ burst.append(c)
567
+ if burst.count == 1 { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.flush() } }
568
+ }
569
+
570
+ func drawBadge() {
571
+ let n = counts.values.max() ?? 0
572
+ NSApp.dockTile.badgeLabel = n > 0 ? String(n) : nil
573
+ }
574
+
575
+ func dropCount(_ web: WKWebView) {
576
+ if counts.removeValue(forKey: ObjectIdentifier(web)) != nil { drawBadge() }
577
+ }
578
+
579
+ // a new page in a window: its count is gone until the page posts one
580
+ func webView(_ web: WKWebView, didCommit nav: WKNavigation!) { dropCount(web) }
581
+
582
+ /** the banners of the cards that no longer wait leave Notification Center */
583
+ func takeBack(waiting: Set<String>) {
584
+ guard isShipkit, deliver == nil else { return }
585
+ let center = UNUserNotificationCenter.current()
586
+ center.getDeliveredNotifications { delivered in
587
+ let ids = staleOf(delivered.map { ($0.request.identifier, ($0.request.content.userInfo["cards"] as? [String]) ?? [$0.request.identifier]) }, waiting: waiting)
588
+ if !ids.isEmpty { center.removeDeliveredNotifications(withIdentifiers: ids) }
589
+ }
590
+ }
591
+
592
+ func flush() {
593
+ let notes = notesOf(burst)
594
+ burst = []
595
+ for n in notes { (deliver ?? notify)(n) }
596
+ }
597
+
598
+ func notify(_ note: Note) {
599
+ let content = UNMutableNotificationContent()
600
+ switch note {
601
+ case .card(let c):
602
+ content.title = c.title
603
+ content.body = c.repo
604
+ content.threadIdentifier = c.repo
605
+ content.userInfo = ["repo": c.repo, "id": c.id, "url": c.url, "cards": [c.key]]
606
+ case .more(let cards, let inbox):
607
+ content.title = "\(cards.count) more card\(cards.count == 1 ? "" : "s") wait for you"
608
+ content.body = "open the inbox"
609
+ content.userInfo = ["inbox": true, "url": inbox?.absoluteString ?? "", "cards": cards.map(\.key)]
610
+ }
611
+ content.sound = .default
612
+ UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: idOf(note), content: content, trigger: nil)) { err in
613
+ if let err { NSLog("shipkit: a notification did not show: \(err.localizedDescription)") }
614
+ }
615
+ }
616
+
617
+ // the app in front shows its banners too
618
+ func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler done: @escaping (UNNotificationPresentationOptions) -> Void) {
619
+ done([.banner, .list, .sound])
620
+ }
621
+
622
+ func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler done: @escaping () -> Void) {
623
+ route(response.notification.request.content.userInfo)
624
+ done()
625
+ }
626
+
627
+ /** a click: a window forward on the card (or the inbox), in place through the page's hooks; a page without them,
628
+ * or no window at all, loads the address */
629
+ func route(_ info: [AnyHashable: Any]) {
630
+ let win = (NSApp.keyWindow?.contentView is Pane ? NSApp.keyWindow : nil) ?? windows.first
631
+ guard let win, let pane = win.contentView as? Pane else {
632
+ if let url = fallbackOf(info) { open(url) }
633
+ return
634
+ }
635
+ if win.isMiniaturized { win.deminiaturize(nil) }
636
+ win.makeKeyAndOrderFront(nil)
637
+ NSApp.activate(ignoringOtherApps: true)
638
+ openIn(pane.web, info)
639
+ }
640
+
641
+ /** the address a click loads where the page has no hooks: the card's review page, or the inbox of the home the
642
+ * cards came from */
643
+ func fallbackOf(_ info: [AnyHashable: Any]) -> URL? {
644
+ let url = URL(string: (info["url"] as? String) ?? "")
645
+ return (info["inbox"] as? Bool) == true && url == nil ? URL(string: "/inbox", relativeTo: startURL)?.absoluteURL : url
646
+ }
647
+
648
+ /** the page's own hooks open the card in place; `done` hears whether they did */
649
+ func openIn(_ web: WKWebView, _ info: [AnyHashable: Any], done: ((Bool) -> Void)? = nil) {
650
+ let inbox = (info["inbox"] as? Bool) == true
651
+ let js = inbox ? "if (!window.shipkitApp) return false; shipkitApp.openInbox(); return true" : "if (!window.shipkitApp) return false; shipkitApp.openCard(repo, id); return true"
652
+ web.callAsyncJavaScript(js, arguments: ["repo": (info["repo"] as? String) ?? "", "id": (info["id"] as? String) ?? ""], in: nil, in: .page) { r in
653
+ if case .success(let v) = r, (v as? Bool) == true {
654
+ done?(true)
655
+ return
656
+ }
657
+ if let url = self.fallbackOf(info) { web.load(URLRequest(url: url)) }
658
+ done?(false)
659
+ }
660
+ }
661
+
662
+ // `--self-test-badge`: an offscreen page posts as the hub does: the seed and a count, cards (one twice), the seed
663
+ // of a reload, a burst of five, the count back to zero, then a notification's click opens a card through the
664
+ // page's hook; the badge, the planned
665
+ // notifications and the card opened printed, exit 0 only when each one is as the owner would see it. Nothing
666
+ // reaches the system's notification center, and the test never takes the focus
667
+ func selfTestBadge() {
668
+ let config = WKWebViewConfiguration()
669
+ config.userContentController.add(self, name: "shipkit")
670
+ let web = WKWebView(frame: .zero, configuration: config)
671
+ web.navigationDelegate = self
672
+ let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
673
+ win.contentView = Pane(web: web)
674
+ win.orderFrontRegardless()
675
+ windows.append(win)
676
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); exit(1) }
677
+ var notes: [String] = []
678
+ deliver = { n in
679
+ switch n {
680
+ case .card(let c): notes.append("\(c.repo)/\(c.id):\(c.title)")
681
+ case .more(let cards, let inbox): notes.append("more:\(cards.count):\(inbox?.absoluteString ?? "none")")
682
+ }
683
+ notes[notes.count - 1] += "@" + idOf(n)
684
+ }
685
+ let post = { (js: String, then: @escaping () -> Void) in
686
+ web.evaluateJavaScript("(() => { const p = (m) => webkit.messageHandlers.shipkit.postMessage(m); \(js) })(); 0") { _, _ in
687
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: then)
688
+ }
689
+ }
690
+ let row = { (repo: String, id: String) in "{id: '\(id)', title: 't\(id)', repo: '\(repo)', url: 'http://127.0.0.1:9/r/\(repo)/'}" }
691
+ let card = { (repo: String, id: String) in "p({card: \(row(repo, id))})" }
692
+ // the second seed is a reloaded page: a/0 waited at start, a/1 was notified, d/1 arrived during the reload
693
+ let reload = "p({seed: [\(row("a", "0")), \(row("a", "1")), \(row("d", "1"))]})"
694
+ var started = false
695
+ onLoad = { _ in
696
+ if started { return }
697
+ started = true
698
+ post("p({seed: [\(row("a", "0"))]}); p({waiting: 2})") {
699
+ let two = NSApp.dockTile.badgeLabel ?? "none"
700
+ post([card("a", "1"), card("a", "1"), card("b", "1"), reload].joined(separator: "; ")) {
701
+ let few = notes
702
+ notes = []
703
+ post((1...5).map { card("c", "\($0)") }.joined(separator: "; ") + "; " + card("a", "1")) {
704
+ let many = notes
705
+ post("p({waiting: 0})") {
706
+ let zero = NSApp.dockTile.badgeLabel ?? "none"
707
+ // a click on the notification of card b/1: the page's hook opens it in place
708
+ self.openIn(web, ["repo": "b", "id": "1", "url": "http://127.0.0.1:9/"]) { ok in
709
+ web.evaluateJavaScript("document.body.dataset.opened") { opened, _ in
710
+ let o = (opened as? String) ?? "none"
711
+ // the banners taken back once a/1 and c/5 alone still wait: b/1's, and one left by an older build
712
+ let stale = staleOf([("a/1", ["a/1"]), ("b/1", ["b/1"]), ("more:c/4,c/5", ["c/4", "c/5"]), ("F09E-0F96", ["F09E-0F96"])], waiting: ["a/1", "c/5"])
713
+ print("badge-two=\(two)")
714
+ print("few=\(few.joined(separator: ","))")
715
+ print("burst=\(many.joined(separator: ","))")
716
+ print("badge-zero=\(zero)")
717
+ print("click-opened=\(ok ? o : "fallback")")
718
+ print("stale=\(stale.joined(separator: ","))")
719
+ exit(two == "2" && few == ["a/1:t1@a/1", "b/1:t1@b/1", "d/1:t1@d/1"] && many == ["c/1:t1@c/1", "c/2:t2@c/2", "c/3:t3@c/3", "more:2:http://127.0.0.1:9/inbox@more:c/4,c/5"] && zero == "none" && ok && o == "b/1" && stale == ["b/1", "F09E-0F96"] ? 0 : 1)
720
+ }
721
+ }
722
+ }
723
+ }
724
+ }
725
+ }
726
+ }
727
+ web.loadHTMLString("<body><script>window.shipkitApp = { openCard: (r, i) => { document.body.dataset.opened = r + '/' + i }, openInbox: () => { document.body.dataset.opened = 'inbox' } }</script><p>badge</p></body>", baseURL: nil)
728
+ }
729
+
433
730
  // window.open and target=_blank: one more window of this app for its own pages
434
731
  func webView(_ web: WKWebView, createWebViewWith config: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
435
732
  if let url = action.request.url {
@@ -1,24 +1,24 @@
1
1
  // the macOS apps shipkit opens web pages in: ONE source, ShipkitGui.swift,
2
2
  // built with swiftc into a bundle per page it serves. `shipkit gui` is that
3
3
  // app pointed at the home; each global process with a url gets its own, named
4
- // and iconed after it, in its repo's `.shipkit/wrapper/`. The bundle's
5
- // Info.plist carries what differs (name, bundle id, start url), so a fix to
6
- // the window (find, the inspector, zoom) lands in every app at its next
7
- // build. The icon is core/app-icon.ts: the repo's mark, its margin cut, on
8
- // a plate in the repo's colour. Rebuilt only when the source, the icon, the
9
- // colours or the start url changed (a stamp in the bundle). No compiler, or not macOS: the caller falls back.
10
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
11
- import { homedir } from 'os'
4
+ // and iconed after it, in ~/Applications, where Spotlight and Launchpad find
5
+ // it (home/process-apps.ts builds them all and removes the stale ones). The
6
+ // bundle's Info.plist carries what differs (name, bundle id, start url), so a
7
+ // fix to the window (find, the inspector, zoom) lands in every app at its next
8
+ // build. The binary is compiled once per source and copied into each bundle.
9
+ // The icon is core/app-icon.ts: the repo's mark, its margin cut, on a plate in
10
+ // the repo's colour. Rebuilt only when the source, the icon, the colours or the
11
+ // start url changed (a stamp in the bundle). No compiler, or not macOS: the caller falls back.
12
+ import { createHash } from 'crypto'
13
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'
12
14
  import { dirname, join } from 'path'
13
- import { fileURLToPath } from 'url'
14
15
  import { appIconOf, appIconPngs, identityOfRoot } from '../core/app-icon.ts'
15
16
  import { identityOfName, type Identity } from '../core/identity-color.ts'
16
- import { LAYOUT } from '../core/layout.ts'
17
-
18
- const SOURCE = fileURLToPath(new URL('./gui-app/ShipkitGui.swift', import.meta.url))
17
+ import { homeDir } from './home-paths.ts'
18
+ import { appNameOf, appsDir, GUI_SOURCE as SOURCE, shipkitBundleOf, wrapperBundleId, wrapperPath, type AppOf } from './process-apps.ts'
19
19
 
20
20
  export const BUNDLE_ID = 'dev.shipkit.gui'
21
- export const guiAppPath = (): string => process.env.SHIPKIT_GUI_APP ?? join(homedir(), 'Applications', 'Shipkit.app')
21
+ export const guiAppPath = (): string => process.env.SHIPKIT_GUI_APP ?? join(appsDir(), 'Shipkit.app')
22
22
 
23
23
  /** what one app bundle is: the rest comes from the shared source */
24
24
  export type AppSpec = {
@@ -86,15 +86,33 @@ export function stampOf(source: string, icon: string | null, identity = ''): str
86
86
  return h.digest('hex').slice(0, 16)
87
87
  }
88
88
 
89
+ /** the window's binary, compiled once per source text into `bins`: swiftc
90
+ * takes about a minute, and every bundle runs the same binary */
91
+ function compiledGui(source: string, text: string, run: Run, bins: string): string {
92
+ const bin = join(bins, `shipkit-gui-${createHash('sha256').update(text).digest('hex').slice(0, 16)}`)
93
+ if (existsSync(bin)) return bin
94
+ mkdirSync(bins, { recursive: true })
95
+ const tmp = `${bin}.building-${process.pid}`
96
+ const built = run(['swiftc', '-O', '-o', tmp, source])
97
+ if (built.code !== 0 || !existsSync(tmp)) {
98
+ rmSync(tmp, { force: true })
99
+ throw new Error(`swiftc could not build the window: ${built.err.slice(0, 400)}`)
100
+ }
101
+ renameSync(tmp, bin)
102
+ return bin
103
+ }
104
+
89
105
  /** one app, built or rebuilt when stale. Throws with the step that failed.
90
106
  * `rebuilt` tells the caller a running copy is now the old one */
91
- export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string } = {}): Promise<{ app: string; rebuilt: boolean }> {
107
+ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string; bins?: string } = {}): Promise<{ app: string; rebuilt: boolean }> {
92
108
  const { app, icon } = spec
93
109
  const run = o.run ?? runSync
94
110
  const source = o.source ?? SOURCE
95
- const stamp = stampOf(readFileSync(source, 'utf8'), icon, JSON.stringify([spec.name, spec.bundleId, spec.url, spec.identity, ICON_DRAWING]))
111
+ const text = readFileSync(source, 'utf8')
112
+ const stamp = stampOf(text, icon, JSON.stringify([spec.name, spec.bundleId, spec.url, spec.identity, ICON_DRAWING]))
96
113
  const stampFile = join(app, 'Contents', 'Resources', 'stamp')
97
114
  if (existsSync(stampFile) && readFileSync(stampFile, 'utf8') === stamp) return { app, rebuilt: false }
115
+ const bin = compiledGui(source, text, run, o.bins ?? join(homeDir(), 'gui-bin'))
98
116
  const tmp = `${app}.building-${process.pid}`
99
117
  const fail = (msg: string): never => { rmSync(tmp, { recursive: true, force: true }); throw new Error(msg) }
100
118
  rmSync(tmp, { recursive: true, force: true })
@@ -102,8 +120,9 @@ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string }
102
120
  mkdirSync(join(tmp, 'Contents', 'MacOS'), { recursive: true })
103
121
  mkdirSync(res, { recursive: true })
104
122
  writeFileSync(join(tmp, 'Contents', 'Info.plist'), infoPlist(spec))
105
- const built = run(['swiftc', '-O', '-o', join(tmp, 'Contents', 'MacOS', 'shipkit-gui'), source])
106
- if (built.code !== 0) fail(`swiftc could not build ${spec.name}.app: ${built.err.slice(0, 400)}`)
123
+ const exe = join(tmp, 'Contents', 'MacOS', 'shipkit-gui')
124
+ copyFileSync(bin, exe)
125
+ chmodSync(exe, 0o755)
107
126
  if (icon != null) {
108
127
  const set = join(res, 'AppIcon.iconset')
109
128
  mkdirSync(set, { recursive: true })
@@ -116,9 +135,20 @@ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string }
116
135
  if (r.code !== 0) fail(`iconutil could not build the icon: ${r.err.slice(0, 200)}`)
117
136
  }
118
137
  writeFileSync(join(res, 'stamp'), stamp)
138
+ // signed as the bundle it is, never as the bare binary: macOS refuses notifications to a bundle its signature does not name
139
+ const signed = run(['codesign', '--force', '--sign', '-', tmp])
140
+ if (signed.code !== 0) fail(`codesign could not sign the bundle: ${signed.err.slice(0, 200)}`)
119
141
  mkdirSync(dirname(app), { recursive: true })
120
- rmSync(app, { recursive: true, force: true })
121
- run(['mv', tmp, app])
142
+ // a rename, never `mv`: a build that lands in between would get this one nested inside it
143
+ for (let tries = 0; ; tries++) {
144
+ rmSync(app, { recursive: true, force: true })
145
+ try {
146
+ renameSync(tmp, app)
147
+ break
148
+ } catch (e) {
149
+ if (tries >= 2) fail(`could not move the built bundle to ${app}: ${(e as Error).message}`)
150
+ }
151
+ }
122
152
  // launch services caches icons by bundle: tell it this one changed
123
153
  run(['/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister', '-f', app])
124
154
  return { app, rebuilt: true }
@@ -129,31 +159,31 @@ export function ensureGuiApp(o: { root: string | null; version: string; app?: st
129
159
  return ensureApp({ name: 'shipkit', bundleId: BUNDLE_ID, url: null, icon: o.root == null ? null : appIconOf(o.root), identity: o.root == null ? identityOfName('shipkit') : identityOfRoot(o.root), app: o.app ?? guiAppPath(), version: o.version }, { run: o.run })
130
160
  }
131
161
 
132
- /** what a global process gives its app */
133
- export type WrapperOf = { id: string; label: string; url: string | null; icon: string | null; root: string }
162
+ /** what a global process gives its app. `app`: its declared app name, else the label */
163
+ export type WrapperOf = AppOf
134
164
 
135
165
  /** the images the icon renderer reads; an emoji or an svg leaves the repo's mark */
136
166
  const RASTER = /\.(png|jpe?g|gif|webp)$/i
137
167
 
138
- export const wrapperBundleId = (id: string): string => `dev.shipkit.app.${id.replace(/[^A-Za-z0-9-]+/g, '-')}`
139
- export const wrapperPath = (root: string, id: string): string => join(root, LAYOUT.wrapper, `${id.replace(/[^A-Za-z0-9._-]+/g, '-')}.app`)
140
-
141
- /** the spec of a process's own app: its label, its declared image icon or
142
- * else its repo's mark, in its repo's `.shipkit/wrapper/`. Throws for a
143
- * process with no url: there is no page to wrap */
144
- export function wrapperSpec(d: WrapperOf, version: string): AppSpec {
168
+ /** the spec of a process's own app: its app name, its declared image icon
169
+ * or else its repo's mark, in ~/Applications. Throws for a process with no
170
+ * url: there is no page to wrap */
171
+ export function wrapperSpec(d: WrapperOf, version: string, dir = appsDir()): AppSpec {
145
172
  if (d.url == null) throw new Error(`${d.id} declares no url: there is no page to open as an app`)
146
173
  const declared = d.icon != null && RASTER.test(d.icon) && existsSync(join(d.root, d.icon)) ? join(d.root, d.icon) : null
147
- return { name: d.label, bundleId: wrapperBundleId(d.id), url: d.url, icon: declared ?? appIconOf(d.root), identity: identityOfRoot(d.root), app: wrapperPath(d.root, d.id), version }
174
+ return { name: appNameOf(d), bundleId: wrapperBundleId(d.id), url: d.url, icon: declared ?? appIconOf(d.root), identity: identityOfRoot(d.root), app: wrapperPath(d, dir), version }
148
175
  }
149
176
 
150
- export const ensureWrapperApp = async (d: WrapperOf, o: { version: string; run?: Run }): Promise<{ app: string; rebuilt: boolean; bundleId: string }> => {
151
- const spec = wrapperSpec(d, o.version)
152
- return { ...(await ensureApp(spec, { run: o.run })), bundleId: spec.bundleId }
177
+ /** builds a process's app when it is missing or stale. Refuses to replace
178
+ * an app at its path that shipkit did not build */
179
+ export const ensureWrapperApp = async (d: WrapperOf, o: { version: string; run?: Run; dir?: string; bins?: string }): Promise<{ app: string; rebuilt: boolean; bundleId: string }> => {
180
+ const spec = wrapperSpec(d, o.version, o.dir)
181
+ if (existsSync(spec.app) && shipkitBundleOf(spec.app) == null) throw new Error(`${spec.app} is an app shipkit did not build: give ${d.id} another app name (app: in its unit file)`)
182
+ return { ...(await ensureApp(spec, { run: o.run, bins: o.bins })), bundleId: spec.bundleId }
153
183
  }
154
184
 
155
185
  /** quits a running copy of an app, and launches nothing when none runs */
156
186
  export const quitCmd = (bundleId: string): string[] => ['osascript', '-e', `if application id "${bundleId}" is running then quit application id "${bundleId}"`]
157
187
 
158
188
  /** true when this machine can build the app */
159
- export const canBuildGui = (platform = process.platform): boolean => platform === 'darwin' && Bun.which('swiftc') != null && Bun.which('iconutil') != null
189
+ export const canBuildGui = (platform = process.platform): boolean => platform === 'darwin' && ['swiftc', 'iconutil', 'codesign'].every((t) => Bun.which(t) != null)