@legendapp/spark 0.0.1-next.6 → 0.0.1-next.8

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 (128) hide show
  1. package/package.json +8 -8
  2. package/schema.json +9 -0
  3. package/skills/spark/SKILL.md +1 -1
  4. package/skills/spark/UPGRADING.md +37 -0
  5. package/vendor/node_modules/@legendapp/spark-ai/package.json +3 -3
  6. package/vendor/node_modules/@legendapp/spark-audio/package.json +2 -2
  7. package/vendor/node_modules/@legendapp/spark-auth-session/package.json +3 -3
  8. package/vendor/node_modules/@legendapp/spark-cli/dist/add-desktop.js +1 -1
  9. package/vendor/node_modules/@legendapp/spark-cli/dist/build.js +16 -4
  10. package/vendor/node_modules/@legendapp/spark-cli/dist/create.js +16 -4
  11. package/vendor/node_modules/@legendapp/spark-cli/dist/credentials.js +2 -2
  12. package/vendor/node_modules/@legendapp/spark-cli/dist/init-template.cjs +2 -1
  13. package/vendor/node_modules/@legendapp/spark-cli/dist/macos-release.js +4 -0
  14. package/vendor/node_modules/@legendapp/spark-cli/dist/project.js +10 -4
  15. package/vendor/node_modules/@legendapp/spark-cli/dist/release-driver.js +35 -0
  16. package/vendor/node_modules/@legendapp/spark-cli/dist/release.json +18 -18
  17. package/vendor/node_modules/@legendapp/spark-cli/dist/updates.js +18 -8
  18. package/vendor/node_modules/@legendapp/spark-cli/dist/windows.js +1 -1
  19. package/vendor/node_modules/@legendapp/spark-cli/package.json +4 -4
  20. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/app.json +5 -1
  21. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/gitignore +2 -1
  22. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/package.json +7 -7
  23. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/app.json +5 -1
  24. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/gitignore +2 -1
  25. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/package.json +8 -8
  26. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/app.json +5 -1
  27. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/gitignore +2 -1
  28. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/package.json +8 -8
  29. package/vendor/node_modules/@legendapp/spark-clipboard/package.json +2 -2
  30. package/vendor/node_modules/@legendapp/spark-codex/cpp/HybridCodexAppServer.mm +88 -76
  31. package/vendor/node_modules/@legendapp/spark-codex/package.json +2 -2
  32. package/vendor/node_modules/@legendapp/spark-commands/package.json +5 -5
  33. package/vendor/node_modules/@legendapp/spark-context-menu/package.json +2 -2
  34. package/vendor/node_modules/@legendapp/spark-desktop-app/RNDesktopApp.podspec +12 -1
  35. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/RNDesktopApp.mm +8 -1
  36. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkDesktop.h +8 -0
  37. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkDesktop.mm +84 -21
  38. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkInstance.h +27 -0
  39. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkInstance.mm +207 -0
  40. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkTestDriver.h +44 -0
  41. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkTestDriver.mm +349 -0
  42. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkWindow.mm +3 -1
  43. package/vendor/node_modules/@legendapp/spark-desktop-app/package.json +1 -1
  44. package/vendor/node_modules/@legendapp/spark-desktop-app/src/api.ts +39 -6
  45. package/vendor/node_modules/@legendapp/spark-desktop-app/src/contracts/menu.ts +21 -7
  46. package/vendor/node_modules/@legendapp/spark-desktop-config/accessibility-state.cjs +50 -0
  47. package/vendor/node_modules/@legendapp/spark-desktop-config/app.plugin.cjs +9 -1
  48. package/vendor/node_modules/@legendapp/spark-desktop-config/autolinking.cjs +8 -1
  49. package/vendor/node_modules/@legendapp/spark-desktop-config/config.cjs +1 -1
  50. package/vendor/node_modules/@legendapp/spark-desktop-config/config.d.cts +7 -1
  51. package/vendor/node_modules/@legendapp/spark-desktop-config/package.json +4 -4
  52. package/vendor/node_modules/@legendapp/spark-desktop-config/rtl-scroll-view.cjs +144 -0
  53. package/vendor/node_modules/@legendapp/spark-desktop-config/rtl-text-alignment.cjs +60 -0
  54. package/vendor/node_modules/@legendapp/spark-desktop-config/rtl-text-input-alignment.cjs +112 -0
  55. package/vendor/node_modules/@legendapp/spark-desktop-config/schema.json +9 -0
  56. package/vendor/node_modules/@legendapp/spark-desktop-config/test-driver.cjs +11 -0
  57. package/vendor/node_modules/@legendapp/spark-desktop-config/test-driver.d.cts +2 -0
  58. package/vendor/node_modules/@legendapp/spark-desktop-config/text-input-accessibility.cjs +47 -0
  59. package/vendor/node_modules/@legendapp/spark-desktop-config/updates.cjs +4 -2
  60. package/vendor/node_modules/@legendapp/spark-desktop-config/validation.cjs +2 -1
  61. package/vendor/node_modules/@legendapp/spark-desktop-config/windows.plugin.cjs +1 -1
  62. package/vendor/node_modules/@legendapp/spark-desktop-host/AppDelegate.mm +18 -6
  63. package/vendor/node_modules/@legendapp/spark-desktop-host/package.json +2 -2
  64. package/vendor/node_modules/@legendapp/spark-desktop-host/windows/application.inc +61 -15
  65. package/vendor/node_modules/@legendapp/spark-desktop-host/windows/launch.inc +67 -0
  66. package/vendor/node_modules/@legendapp/spark-desktop-links/package.json +2 -2
  67. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/package.json +2 -2
  68. package/vendor/node_modules/@legendapp/spark-desktop-windows/RNDesktopWindows.podspec +3 -0
  69. package/vendor/node_modules/@legendapp/spark-desktop-windows/macos/RNDesktopWindows.mm +5 -2
  70. package/vendor/node_modules/@legendapp/spark-desktop-windows/macos/window-manager/RNWindowManager.mm +22 -3
  71. package/vendor/node_modules/@legendapp/spark-desktop-windows/package.json +3 -3
  72. package/vendor/node_modules/@legendapp/spark-documents/package.json +7 -7
  73. package/vendor/node_modules/@legendapp/spark-drag-drop/package.json +2 -2
  74. package/vendor/node_modules/@legendapp/spark-file-dialog/RNFileDialog.podspec +1 -0
  75. package/vendor/node_modules/@legendapp/spark-file-dialog/ios/RNFileDialog.mm +153 -64
  76. package/vendor/node_modules/@legendapp/spark-file-dialog/package.json +2 -2
  77. package/vendor/node_modules/@legendapp/spark-file-dialog/src/index.ts +19 -7
  78. package/vendor/node_modules/@legendapp/spark-file-dialog/src/native.ts +5 -1
  79. package/vendor/node_modules/@legendapp/spark-file-dialog/src/options.ts +42 -4
  80. package/vendor/node_modules/@legendapp/spark-file-dialog/src/types.ts +18 -2
  81. package/vendor/node_modules/@legendapp/spark-file-system/package.json +2 -2
  82. package/vendor/node_modules/@legendapp/spark-global-shortcuts/package.json +2 -2
  83. package/vendor/node_modules/@legendapp/spark-html/package.json +2 -2
  84. package/vendor/node_modules/@legendapp/spark-markdown/package.json +2 -2
  85. package/vendor/node_modules/@legendapp/spark-markdown/src/Markdown.tsx +2 -1
  86. package/vendor/node_modules/@legendapp/spark-message-dialog/macos/RNDesktopMessageDialog.mm +113 -12
  87. package/vendor/node_modules/@legendapp/spark-message-dialog/package.json +2 -2
  88. package/vendor/node_modules/@legendapp/spark-message-dialog/src/index.ts +110 -14
  89. package/vendor/node_modules/@legendapp/spark-native-menu/ios/RNNativeMenu.mm +116 -8
  90. package/vendor/node_modules/@legendapp/spark-native-menu/package.json +2 -2
  91. package/vendor/node_modules/@legendapp/spark-native-menu/src/api.ts +63 -18
  92. package/vendor/node_modules/@legendapp/spark-native-menu/src/hooks.ts +9 -3
  93. package/vendor/node_modules/@legendapp/spark-notifications/package.json +2 -2
  94. package/vendor/node_modules/@legendapp/spark-processes/package.json +2 -2
  95. package/vendor/node_modules/@legendapp/spark-rich-text/package.json +2 -2
  96. package/vendor/node_modules/@legendapp/spark-secure-storage/package.json +2 -2
  97. package/vendor/node_modules/@legendapp/spark-settings/package.json +3 -3
  98. package/vendor/node_modules/@legendapp/spark-settings-ui/package.json +4 -4
  99. package/vendor/node_modules/@legendapp/spark-settings-ui/src/index.tsx +5 -2
  100. package/vendor/node_modules/@legendapp/spark-sqlite/package.json +3 -3
  101. package/vendor/node_modules/@legendapp/spark-system/macos/RNDesktopSystem.mm +13 -3
  102. package/vendor/node_modules/@legendapp/spark-system/macos/SparkAppearancePreferences.h +9 -0
  103. package/vendor/node_modules/@legendapp/spark-system/macos/SparkAppearancePreferences.mm +31 -0
  104. package/vendor/node_modules/@legendapp/spark-system/macos/SparkDockTile.h +24 -0
  105. package/vendor/node_modules/@legendapp/spark-system/macos/SparkDockTile.mm +101 -0
  106. package/vendor/node_modules/@legendapp/spark-system/package.json +2 -2
  107. package/vendor/node_modules/@legendapp/spark-system/src/index.ts +73 -7
  108. package/vendor/node_modules/@legendapp/spark-tray/package.json +2 -2
  109. package/vendor/node_modules/@legendapp/spark-ui/macos/RNSparkButton.mm +2 -0
  110. package/vendor/node_modules/@legendapp/spark-ui/macos/RNSparkLayoutDirection.h +17 -0
  111. package/vendor/node_modules/@legendapp/spark-ui/macos/RNSparkTextInput.mm +6 -1
  112. package/vendor/node_modules/@legendapp/spark-ui/macos/appkit-split-view/RNSidebarSplitViewComponent.mm +55 -8
  113. package/vendor/node_modules/@legendapp/spark-ui/macos/glass-effect-view/RNGlassEffectView.mm +11 -7
  114. package/vendor/node_modules/@legendapp/spark-ui/macos/native-select/RNNativeSegmentedControl.mm +4 -0
  115. package/vendor/node_modules/@legendapp/spark-ui/macos/native-select/RNNativeSelect.mm +4 -0
  116. package/vendor/node_modules/@legendapp/spark-ui/macos/sf-symbol/RNSFSymbol.mm +4 -0
  117. package/vendor/node_modules/@legendapp/spark-ui/macos/sidebar/RNSidebar.mm +77 -14
  118. package/vendor/node_modules/@legendapp/spark-ui/macos/swipe-actions/RNSwipeActions.mm +31 -7
  119. package/vendor/node_modules/@legendapp/spark-ui/macos/text-input-search/RNTextInputSearch.mm +25 -1
  120. package/vendor/node_modules/@legendapp/spark-ui/package.json +2 -2
  121. package/vendor/node_modules/@legendapp/spark-ui/src/sidebar/SidebarNativeComponent.ts +5 -0
  122. package/vendor/node_modules/@legendapp/spark-ui/src/sidebar/index.tsx +19 -8
  123. package/vendor/node_modules/@legendapp/spark-updates/macos/RNDesktopUpdates.mm +25 -13
  124. package/vendor/node_modules/@legendapp/spark-updates/macos/SparkUpdateState.h +39 -0
  125. package/vendor/node_modules/@legendapp/spark-updates/package.json +2 -2
  126. package/vendor/node_modules/@legendapp/spark-updates/src/index.ts +45 -9
  127. package/vendor/node_modules/@legendapp/spark-webview/package.json +2 -2
  128. package/vendor/node_modules/@legendapp/spark-window-options/package.json +1 -1
@@ -0,0 +1,349 @@
1
+ #import "SparkTestDriver.h"
2
+ #import <QuartzCore/QuartzCore.h>
3
+ #include <atomic>
4
+ #include <fcntl.h>
5
+ #include <string.h>
6
+ #include <sys/socket.h>
7
+ #include <sys/stat.h>
8
+ #include <sys/un.h>
9
+ #include <unistd.h>
10
+
11
+ // Protocol: newline-delimited JSON over a Unix socket in the run directory. The
12
+ // first message is {"token": "..."}; then one request at a time, each answered
13
+ // with {"id", "ok", ...} or {"id", "ok": false, "error": {"code", "message"}}.
14
+ typedef void (^SparkDriverReply)(NSDictionary *reply);
15
+ static BOOL active = NO, ending = NO;
16
+ static int directoryFD = -1, listenFD = -1;
17
+ static NSString *socketPath;
18
+ static NSData *token;
19
+ static id activity;
20
+ static std::atomic<bool> authenticated{false};
21
+ static CFTimeInterval lastMount = 0;
22
+ static const CFTimeInterval SparkSettleInterval = 0.1;
23
+ static const NSUInteger SparkMaxMessage = 1 << 20;
24
+
25
+ static void SparkDriverRefuse(NSString *message) {
26
+ NSLog(@"Spark test driver: %@", message);
27
+ exit(78); // EX_CONFIG: the runner's launch contract was violated.
28
+ }
29
+ static void SparkDriverTerminate(void) { ending = YES; [NSApp terminate:nil]; }
30
+ BOOL SparkTestDriverActive(void) { return active; }
31
+ BOOL SparkTestDriverEnding(void) { return ending; }
32
+ void SparkTestDriverDidMount(void) { lastMount = CACurrentMediaTime(); }
33
+ static NSArray<NSString *> *const SparkBuiltInCommands = @[@"ping", @"navigate", @"openFile", @"waitFor", @"setAppAppearance", @"capture", @"quit"];
34
+ static NSMutableDictionary<NSString *, SparkTestDriverHandler> *SparkModuleCommands(void) {
35
+ static NSMutableDictionary *commands;
36
+ static dispatch_once_t once;
37
+ dispatch_once(&once, ^{ commands = [NSMutableDictionary new]; });
38
+ return commands;
39
+ }
40
+ void SparkTestDriverRegisterCommand(NSString *name, SparkTestDriverHandler handler) {
41
+ NSCAssert(NSThread.isMainThread, @"Driver commands are registered on the main thread");
42
+ if ([SparkBuiltInCommands containsObject:name] || SparkModuleCommands()[name]) [NSException raise:NSInvalidArgumentException format:@"Driver command %@ is already defined", name];
43
+ SparkModuleCommands()[name] = [handler copy];
44
+ }
45
+
46
+ static BOOL SparkPrivate(int fd, mode_t type, mode_t mode) {
47
+ struct stat info;
48
+ return fstat(fd, &info) == 0 && (info.st_mode & S_IFMT) == type && info.st_uid == getuid() && (info.st_mode & 0777) == mode;
49
+ }
50
+ static NSData *SparkConsumeToken(void) {
51
+ int fd = openat(directoryFD, "token", O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
52
+ if (fd < 0) return nil;
53
+ struct stat info;
54
+ NSMutableData *data = nil;
55
+ if (SparkPrivate(fd, S_IFREG, 0600) && fstat(fd, &info) == 0 && info.st_size >= 32 && info.st_size <= 256) {
56
+ data = [NSMutableData dataWithLength:(NSUInteger)info.st_size];
57
+ if (read(fd, data.mutableBytes, data.length) != (ssize_t)data.length) data = nil;
58
+ }
59
+ close(fd);
60
+ // One-time: nothing else can read the token after launch.
61
+ return data && unlinkat(directoryFD, "token", 0) == 0 ? data : nil;
62
+ }
63
+ static int SparkListen(NSString *path) {
64
+ struct sockaddr_un address = {};
65
+ address.sun_family = AF_UNIX;
66
+ if (strlcpy(address.sun_path, path.fileSystemRepresentation, sizeof address.sun_path) >= sizeof address.sun_path) return -1;
67
+ int fd = socket(AF_UNIX, SOCK_STREAM, 0);
68
+ if (fd < 0) return -1;
69
+ // Nothing can connect before listen(), so tightening the mode after bind() is race-free.
70
+ if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0 || bind(fd, (struct sockaddr *)&address, sizeof address) != 0 ||
71
+ chmod(address.sun_path, 0600) != 0 || listen(fd, 1) != 0) { close(fd); return -1; }
72
+ return fd;
73
+ }
74
+
75
+ static NSData *SparkReadLine(int fd, NSMutableData *buffer) {
76
+ for (;;) {
77
+ const char *bytes = (const char *)buffer.bytes;
78
+ const char *newline = (const char *)memchr(bytes, '\n', buffer.length);
79
+ if (newline) {
80
+ NSUInteger length = (NSUInteger)(newline - bytes);
81
+ NSData *line = [buffer subdataWithRange:NSMakeRange(0, length)];
82
+ [buffer replaceBytesInRange:NSMakeRange(0, length + 1) withBytes:NULL length:0];
83
+ return line;
84
+ }
85
+ if (buffer.length > SparkMaxMessage) return nil;
86
+ char chunk[4096];
87
+ ssize_t count = recv(fd, chunk, sizeof chunk, 0);
88
+ if (count < 0 && errno == EINTR) continue;
89
+ if (count <= 0) return nil; // EOF, error, or the authentication timeout.
90
+ [buffer appendBytes:chunk length:(NSUInteger)count];
91
+ }
92
+ }
93
+ static BOOL SparkSend(int fd, NSDictionary *message) {
94
+ NSMutableData *data = [[NSJSONSerialization dataWithJSONObject:message options:0 error:nil] mutableCopy];
95
+ [data appendBytes:"\n" length:1];
96
+ const char *bytes = (const char *)data.bytes;
97
+ size_t remaining = data.length;
98
+ while (remaining) {
99
+ ssize_t count = send(fd, bytes, remaining, 0);
100
+ if (count < 0 && errno == EINTR) continue;
101
+ if (count <= 0) return NO;
102
+ bytes += count; remaining -= (size_t)count;
103
+ }
104
+ return YES;
105
+ }
106
+ static NSDictionary *SparkFailure(NSString *code, NSString *message) {
107
+ return @{ @"ok": @NO, @"error": @{ @"code": code, @"message": message } };
108
+ }
109
+
110
+ static void SparkWaitUntil(NSTimeInterval timeout, BOOL (^ready)(void), void (^done)(BOOL ready)) {
111
+ if (ready()) { done(YES); return; }
112
+ NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:timeout];
113
+ NSTimer *timer = [NSTimer timerWithTimeInterval:0.02 repeats:YES block:^(NSTimer *timer) {
114
+ BOOL now = ready();
115
+ if (!now && deadline.timeIntervalSinceNow > 0) return;
116
+ [timer invalidate]; done(now);
117
+ }];
118
+ [NSRunLoop.mainRunLoop addTimer:timer forMode:NSRunLoopCommonModes];
119
+ }
120
+ static BOOL SparkSettled(void) { return CACurrentMediaTime() - lastMount >= SparkSettleInterval; }
121
+ static NSTimeInterval SparkTimeout(id value, NSTimeInterval fallback) {
122
+ return [value isKindOfClass:NSNumber.class] ? MIN(MAX([value doubleValue], 0), 120000) / 1000 : fallback;
123
+ }
124
+ static NSView *SparkFrameView(NSWindow *window) { return window.contentView.superview ?: window.contentView; }
125
+ static NSView *SparkFindTestID(NSView *view, NSString *testID) {
126
+ if (view.isHidden) return nil;
127
+ if ([view.accessibilityIdentifier isEqualToString:testID]) return view;
128
+ for (NSView *child in view.subviews) {
129
+ NSView *match = SparkFindTestID(child, testID);
130
+ if (match) return match;
131
+ }
132
+ return nil;
133
+ }
134
+ static NSWindow *SparkResolveWindow(id target, NSString **failure) {
135
+ if (![target isKindOfClass:NSString.class]) { *failure = @"Expected window: main, key, id:<identifier> or title:<title>"; return nil; }
136
+ if ([target isEqual:@"key"]) {
137
+ if (!NSApp.keyWindow) *failure = @"No key window. Driver-mode apps never activate; use main, id:<identifier> or title:<title>";
138
+ return NSApp.keyWindow;
139
+ }
140
+ NSString *identifier = [target isEqual:@"main"] ? @"spark.main" : [target hasPrefix:@"id:"] ? [target substringFromIndex:3] : nil;
141
+ NSString *title = [target hasPrefix:@"title:"] ? [target substringFromIndex:6] : nil;
142
+ if (!identifier && !title) { *failure = @"Expected window: main, key, id:<identifier> or title:<title>"; return nil; }
143
+ NSMutableArray<NSWindow *> *matches = [NSMutableArray new];
144
+ for (NSWindow *window in NSApp.windows)
145
+ if (identifier ? [window.identifier isEqualToString:identifier] : [window.title isEqualToString:title]) [matches addObject:window];
146
+ if (matches.count != 1) { *failure = [NSString stringWithFormat:@"%lu windows match %@", (unsigned long)matches.count, target]; return nil; }
147
+ return matches.firstObject;
148
+ }
149
+ static BOOL SparkCaptureName(id name) {
150
+ if (![name isKindOfClass:NSString.class] || [name length] < 1 || [name length] > 100) return NO;
151
+ NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"];
152
+ return [name rangeOfCharacterFromSet:allowed.invertedSet].location == NSNotFound && [name characterAtIndex:0] != '-';
153
+ }
154
+ // cacheDisplayInRect: draws the view tree, so it works for windows never shown on
155
+ // screen. CALayer rendering does not (docs/test-driver.md has the measurements).
156
+ static NSBitmapImageRep *SparkRender(NSView *view) {
157
+ NSBitmapImageRep *rep = [view bitmapImageRepForCachingDisplayInRect:view.bounds];
158
+ [view cacheDisplayInRect:view.bounds toBitmapImageRep:rep];
159
+ return rep;
160
+ }
161
+ // Captures are created only inside the runner's private run directory.
162
+ static int SparkWriteCapture(NSString *file, NSData *data) {
163
+ int fd = openat(directoryFD, file.fileSystemRepresentation, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
164
+ if (fd < 0) return errno;
165
+ const char *bytes = (const char *)data.bytes;
166
+ size_t remaining = data.length;
167
+ int failure = 0;
168
+ while (remaining && !failure) {
169
+ ssize_t count = write(fd, bytes, remaining);
170
+ if (count < 0 && errno == EINTR) continue;
171
+ if (count < 0) failure = errno;
172
+ else { bytes += count; remaining -= (size_t)count; }
173
+ }
174
+ if (close(fd) != 0 && !failure) failure = errno;
175
+ if (failure) unlinkat(directoryFD, file.fileSystemRepresentation, 0);
176
+ return failure;
177
+ }
178
+
179
+ static void SparkCapture(NSDictionary *request, SparkDriverReply reply) {
180
+ NSString *failure = nil;
181
+ NSWindow *window = SparkResolveWindow(request[@"window"], &failure);
182
+ if (!window) { reply(SparkFailure(@"E_NO_WINDOW", failure)); return; }
183
+ NSString *name = request[@"name"];
184
+ if (!SparkCaptureName(name)) { reply(SparkFailure(@"E_INVALID_ARGUMENT", @"Capture names use 1-100 of [A-Za-z0-9_-] and do not start with -")); return; }
185
+ SparkWaitUntil(SparkTimeout(request[@"timeoutMs"], 5), ^{ return SparkSettled(); }, ^(BOOL settled) {
186
+ if (!settled) { reply(SparkFailure(@"E_NOT_SETTLED", @"The UI kept mounting changes until the timeout")); return; }
187
+ NSView *view = SparkFrameView(window);
188
+ [window layoutIfNeeded];
189
+ [view displayIfNeeded];
190
+ NSBitmapImageRep *rep = SparkRender(view);
191
+ NSData *png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
192
+ if (!png) { reply(SparkFailure(@"E_RENDER", @"Rendering produced no image")); return; }
193
+ NSString *file = [name stringByAppendingPathExtension:@"png"];
194
+ int error = SparkWriteCapture(file, png);
195
+ if (error) { reply(SparkFailure(@"E_IO", [NSString stringWithFormat:@"%@: %s", file, strerror(error)])); return; }
196
+ reply(@{ @"ok": @YES, @"file": file, @"width": @(rep.pixelsWide), @"height": @(rep.pixelsHigh), @"scale": @(window.backingScaleFactor) });
197
+ });
198
+ }
199
+ static void SparkSetAppearance(NSDictionary *request, SparkDriverReply reply) {
200
+ NSString *value = request[@"appearance"];
201
+ NSAppearanceName name = [value isEqual:@"dark"] ? NSAppearanceNameDarkAqua : [value isEqual:@"light"] ? NSAppearanceNameAqua : nil;
202
+ if (!name) { reply(SparkFailure(@"E_INVALID_ARGUMENT", @"Appearance is light or dark")); return; }
203
+ NSTimeInterval timeout = SparkTimeout(request[@"timeoutMs"], 10);
204
+ // An override set while the app is still launching did not last (its first render came out in the OS
205
+ // appearance), so it is applied once the first rendered UI has settled, as navigate waits too.
206
+ SparkWaitUntil(timeout, ^{ return (BOOL)(lastMount > 0 && SparkSettled()); }, ^(BOOL launched) {
207
+ if (!launched) { reply(SparkFailure(@"E_TIMEOUT", @"The app has not rendered")); return; }
208
+ NSArray *names = @[NSAppearanceNameAqua, NSAppearanceNameDarkAqua];
209
+ BOOL changed = ![[NSApp.effectiveAppearance bestMatchFromAppearancesWithNames:names] isEqualToString:name];
210
+ // The app-level override, independent of the OS setting; per-window overrides still win.
211
+ NSApp.appearance = [NSAppearance appearanceNamed:name];
212
+ if (!changed) { reply(@{ @"ok": @YES, @"changed": @NO }); return; }
213
+ CFTimeInterval changedAt = CACurrentMediaTime();
214
+ SparkWaitUntil(timeout, ^{ return (BOOL)(lastMount > changedAt && SparkSettled()); }, ^(BOOL rendered) {
215
+ reply(rendered ? @{ @"ok": @YES, @"changed": @YES } : SparkFailure(@"E_TIMEOUT", @"No UI update followed the appearance change"));
216
+ });
217
+ });
218
+ }
219
+ // Deep links and files arrive through application:openURLs:, the path the OS uses for a
220
+ // clicked link or a file opened from Finder, once the first render has settled so the
221
+ // app's link and open-file listeners are subscribed.
222
+ static void SparkOpenURL(NSURL *url, NSDictionary *request, SparkDriverReply reply) {
223
+ id<NSApplicationDelegate> delegate = NSApp.delegate;
224
+ if (![delegate respondsToSelector:@selector(application:openURLs:)]) { reply(SparkFailure(@"E_UNSUPPORTED", @"The application delegate does not open URLs")); return; }
225
+ SparkWaitUntil(SparkTimeout(request[@"timeoutMs"], 30), ^{ return (BOOL)(lastMount > 0 && SparkSettled()); }, ^(BOOL rendered) {
226
+ if (!rendered) { reply(SparkFailure(@"E_TIMEOUT", @"The app has not rendered")); return; }
227
+ [delegate application:NSApp openURLs:@[url]];
228
+ reply(@{ @"ok": @YES });
229
+ });
230
+ }
231
+ static void SparkExecute(NSDictionary *request, SparkDriverReply reply) {
232
+ NSString *command = request[@"command"];
233
+ if ([command isEqual:@"ping"]) reply(@{ @"ok": @YES });
234
+ else if ([command isEqual:@"navigate"]) {
235
+ NSURL *url = [request[@"url"] isKindOfClass:NSString.class] ? [NSURL URLWithString:request[@"url"]] : nil;
236
+ if (!url.scheme.length || url.isFileURL) { reply(SparkFailure(@"E_INVALID_ARGUMENT", @"navigate expects a non-file URL; open files with openFile")); return; }
237
+ SparkOpenURL(url, request, reply);
238
+ }
239
+ else if ([command isEqual:@"openFile"]) {
240
+ NSString *path = request[@"path"];
241
+ if (![path isKindOfClass:NSString.class] || !path.isAbsolutePath) { reply(SparkFailure(@"E_INVALID_ARGUMENT", @"openFile expects an absolute path")); return; }
242
+ BOOL directory = NO;
243
+ if (![NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&directory]) { reply(SparkFailure(@"E_NOT_FOUND", [NSString stringWithFormat:@"No file at %@", path])); return; }
244
+ SparkOpenURL([NSURL fileURLWithPath:path isDirectory:directory], request, reply);
245
+ }
246
+ else if ([command isEqual:@"waitFor"]) {
247
+ NSString *testID = request[@"testID"];
248
+ if (![testID isKindOfClass:NSString.class] || !testID.length) { reply(SparkFailure(@"E_INVALID_ARGUMENT", @"waitFor expects testID")); return; }
249
+ __block NSView *match = nil;
250
+ SparkWaitUntil(SparkTimeout(request[@"timeoutMs"], 10), ^{
251
+ for (NSWindow *window in NSApp.windows) if ((match = SparkFindTestID(SparkFrameView(window), testID))) return YES;
252
+ return NO;
253
+ }, ^(BOOL found) {
254
+ if (!found) { reply(SparkFailure(@"E_TIMEOUT", [NSString stringWithFormat:@"No view with testID %@", testID])); return; }
255
+ // Points from the top-left of the frame view, the area `capture` renders, so frames map onto capture pixels.
256
+ NSView *root = SparkFrameView(match.window);
257
+ NSRect frame = [match convertRect:match.bounds toView:root];
258
+ if (!root.isFlipped) frame.origin.y = NSHeight(root.bounds) - NSMaxY(frame);
259
+ reply(@{ @"ok": @YES, @"window": match.window.identifier ?: @"", @"frame": @{ @"x": @(frame.origin.x), @"y": @(frame.origin.y), @"width": @(frame.size.width), @"height": @(frame.size.height) } });
260
+ });
261
+ }
262
+ else if ([command isEqual:@"setAppAppearance"]) SparkSetAppearance(request, reply);
263
+ else if ([command isEqual:@"capture"]) SparkCapture(request, reply);
264
+ else if ([command isKindOfClass:NSString.class] && SparkModuleCommands()[command]) SparkModuleCommands()[command](request, reply);
265
+ else reply(SparkFailure(@"E_UNKNOWN_COMMAND", [NSString stringWithFormat:@"Unknown command %@", command]));
266
+ }
267
+
268
+ static NSDictionary *SparkParse(NSData *line) {
269
+ id value = line ? [NSJSONSerialization JSONObjectWithData:line options:0 error:nil] : nil;
270
+ return [value isKindOfClass:NSDictionary.class] ? value : nil;
271
+ }
272
+ static void SparkSession(int fd) {
273
+ NSMutableData *buffer = [NSMutableData new];
274
+ struct timeval limit = { 10, 0 }, unlimited = { 0, 0 };
275
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &limit, sizeof limit);
276
+ NSString *presented = SparkParse(SparkReadLine(fd, buffer))[@"token"];
277
+ NSData *candidate = [presented isKindOfClass:NSString.class] ? [presented dataUsingEncoding:NSUTF8StringEncoding] : nil;
278
+ if (candidate.length != token.length || timingsafe_bcmp(candidate.bytes, token.bytes, token.length) != 0) {
279
+ NSLog(@"Spark test driver: authentication failed");
280
+ SparkSend(fd, SparkFailure(@"E_AUTH", @"Authentication failed"));
281
+ return;
282
+ }
283
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &unlimited, sizeof unlimited);
284
+ authenticated = true;
285
+ if (!SparkSend(fd, @{ @"ok": @YES, @"protocol": @1 })) return;
286
+ for (;;) {
287
+ NSData *line = SparkReadLine(fd, buffer);
288
+ if (!line) return;
289
+ NSDictionary *request = SparkParse(line);
290
+ id identifier = request[@"id"] ?: NSNull.null;
291
+ if ([request[@"command"] isEqual:@"quit"]) { SparkSend(fd, @{ @"id": identifier, @"ok": @YES }); return; }
292
+ __block NSDictionary *reply = nil;
293
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
294
+ if (!request) reply = SparkFailure(@"E_INVALID_ARGUMENT", @"Expected a JSON object");
295
+ else dispatch_async(dispatch_get_main_queue(), ^{
296
+ SparkExecute(request, ^(NSDictionary *result) { reply = result; dispatch_semaphore_signal(done); });
297
+ });
298
+ if (request) dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
299
+ NSMutableDictionary *message = [reply mutableCopy];
300
+ message[@"id"] = identifier;
301
+ if (!SparkSend(fd, message)) return;
302
+ }
303
+ }
304
+ // One session per launch. When it ends (quit, disconnect or failed
305
+ // authentication) the driver closes and the app quits: it belongs to the runner.
306
+ static void SparkServe(void) {
307
+ int fd;
308
+ do fd = accept(listenFD, NULL, NULL); while (fd < 0 && errno == EINTR);
309
+ if (fd >= 0) {
310
+ uid_t uid; gid_t gid;
311
+ int one = 1, flags = fcntl(fd, F_GETFL);
312
+ // Accepted sockets inherit the listener's flags; replies rely on blocking I/O.
313
+ if (getpeereid(fd, &uid, &gid) == 0 && uid == getuid() && flags >= 0 && fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) == 0 &&
314
+ fcntl(fd, F_SETFD, FD_CLOEXEC) == 0 && setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one) == 0)
315
+ SparkSession(fd);
316
+ else NSLog(@"Spark test driver: rejected a client");
317
+ close(fd);
318
+ }
319
+ close(listenFD);
320
+ unlink(socketPath.fileSystemRepresentation);
321
+ dispatch_async(dispatch_get_main_queue(), ^{ SparkDriverTerminate(); });
322
+ }
323
+
324
+ BOOL SparkTestDriverStart(void) {
325
+ NSCAssert(NSThread.isMainThread, @"The test driver starts on the main thread");
326
+ const char *directory = getenv("SPARK_TEST_DRIVER_DIR");
327
+ if (!directory) return NO;
328
+ NSString *path = @(directory);
329
+ unsetenv("SPARK_TEST_DRIVER_DIR"); // Child processes never inherit driver mode. Invalidates `directory`.
330
+ if (!path.isAbsolutePath) SparkDriverRefuse(@"SPARK_TEST_DRIVER_DIR must be absolute");
331
+ directoryFD = open(path.fileSystemRepresentation, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
332
+ if (directoryFD < 0 || !SparkPrivate(directoryFD, S_IFDIR, 0700)) SparkDriverRefuse(@"The run directory must be a 0700 directory owned by this user");
333
+ token = SparkConsumeToken();
334
+ if (!token) SparkDriverRefuse(@"The run directory needs a 0600 token file of 32-256 bytes");
335
+ socketPath = [path stringByAppendingPathComponent:@"driver.sock"];
336
+ listenFD = SparkListen(socketPath);
337
+ if (listenFD < 0) SparkDriverRefuse([NSString stringWithFormat:@"Unable to listen on %@: %s", socketPath, strerror(errno)]);
338
+ active = YES;
339
+ // Never take focus from the person using this Mac, and avoid App Nap timer throttling.
340
+ [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];
341
+ activity = [NSProcessInfo.processInfo beginActivityWithOptions:NSActivityUserInitiatedAllowingIdleSystemSleep reason:@"Spark test driver"];
342
+ [NSThread detachNewThreadWithBlock:^{ SparkServe(); }];
343
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
344
+ if (authenticated) return;
345
+ NSLog(@"Spark test driver: no authenticated client within 30 seconds");
346
+ SparkDriverTerminate();
347
+ });
348
+ return YES;
349
+ }
@@ -1,4 +1,5 @@
1
1
  #import "SparkDesktop.h"
2
+ #import "SparkTestDriver.h"
2
3
  #import <objc/runtime.h>
3
4
  static char optionsKey;
4
5
  NSDictionary *SparkWindowConfiguration(void) {
@@ -74,7 +75,8 @@ void SparkApplyWindowOptions(NSWindow *window, NSDictionary *patch) {
74
75
  }
75
76
  void SparkRestoreWindow(NSWindow *window, NSString *key, NSDictionary *options) {
76
77
  [window center];
77
- if ([options[@"restoreFrame"] boolValue]) {
78
+ // Safe and driver-mode launches neither read nor save the frame: the saved one survives for the next normal launch, and every driven launch starts at the configured size.
79
+ if ([options[@"restoreFrame"] boolValue] && !SparkSafeMode() && !SparkTestDriverActive()) {
78
80
  NSString *name = [NSString stringWithFormat:@"%@.%@", SparkNamespace(), key];
79
81
  [window setFrameUsingName:name]; [window setFrameAutosaveName:name];
80
82
  // Restored dimensions respect current constraints, rather than overriding them.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@legendapp/spark-desktop-app",
3
- "version": "0.0.1-next.6",
3
+ "version": "0.0.1-next.8",
4
4
  "license": "MIT",
5
5
  "main": "src/index",
6
6
  "react-native": "src/index",
@@ -4,7 +4,20 @@ import { callAppNative } from "./transport";
4
4
  import { SparkError, asyncRegistration, nativeError, type Availability, type AsyncRegistration, type Subscription } from "./contracts";
5
5
  export type { AsyncRegistration, Subscription } from "./contracts";
6
6
  export interface AppRuntime { mode: "go" | "dev" | "preview" | "release"; modules: Readonly<Record<string, string>> }
7
- export interface AppContext { projectId: string; name: string; version: string; runtime: AppRuntime; launchArguments: readonly string[] }
7
+ /** What started this process. Safe mode is latched at launch and skips Spark's native restoration. */
8
+ export interface AppLaunch {
9
+ /** `flag`: launched with `--spark-safe-mode`. `modifier`: Shift was held at launch. `null`: a normal launch. */
10
+ safeMode: "flag" | "modifier" | null;
11
+ /** Started by `relaunch()`. */
12
+ relaunched: boolean;
13
+ /** `primary`: this process owns the project's single-instance lock. `test-driver`: a test-driver session, which never takes it. */
14
+ instance: "primary" | "test-driver";
15
+ }
16
+ export interface AppContext { projectId: string; name: string; version: string; runtime: AppRuntime; launchArguments: readonly string[]; launch: AppLaunch }
17
+ export interface RelaunchOptions {
18
+ /** Arguments after the executable for the new instance. Default: this launch's arguments except --spark-safe-mode. */
19
+ arguments?: readonly string[];
20
+ }
8
21
  export type QuitResult = { quitRequested: true } | { quitRequested: false; reason: "vetoed" };
9
22
  export type AppEventMap = {
10
23
  windowOpened: { type: "windowOpened"; windowId: string };
@@ -12,7 +25,8 @@ export type AppEventMap = {
12
25
  activate: { type: "activate" };
13
26
  deactivate: { type: "deactivate" };
14
27
  reopen: { type: "reopen"; hasVisibleWindows: boolean; mainWindowWasVisible: boolean };
15
- secondInstance: { type: "secondInstance"; arguments: readonly string[] };
28
+ /** A later launch of this project, forwarded before that process exits. `files` are absolute paths and `urls` non-file URLs it was asked to open. */
29
+ secondInstance: { type: "secondInstance"; arguments: readonly string[]; workingDirectory: string; files: readonly string[]; urls: readonly string[] };
16
30
  willQuit: { type: "willQuit" };
17
31
  };
18
32
  export type AppEvent = AppEventMap[keyof AppEventMap];
@@ -23,23 +37,42 @@ export function getAppAvailability(): Availability {
23
37
  }
24
38
  function record(value: unknown): value is Record<string, unknown> { return !!value && typeof value === "object" && !Array.isArray(value); }
25
39
  function strings(value: unknown): value is string[] { return Array.isArray(value) && value.every(item => typeof item === "string"); }
40
+ function launch(value: unknown): value is AppLaunch {
41
+ return record(value) && [null, "flag", "modifier"].includes(value.safeMode as string) && typeof value.relaunched === "boolean" && (value.instance === "primary" || value.instance === "test-driver");
42
+ }
26
43
  function context(value: unknown): value is AppContext {
27
- if (!record(value) || ![value.projectId, value.name, value.version].every(item => typeof item === "string" && item.length > 0) || !strings(value.launchArguments) || !record(value.runtime)) return false;
44
+ if (!record(value) || ![value.projectId, value.name, value.version].every(item => typeof item === "string" && item.length > 0) || !strings(value.launchArguments) || !record(value.runtime) || !launch(value.launch)) return false;
28
45
  return ["go", "dev", "preview", "release"].includes(value.runtime.mode as string) && record(value.runtime.modules) && Object.values(value.runtime.modules).every(item => typeof item === "string");
29
46
  }
30
47
  export async function getAppContext(): Promise<AppContext> {
31
48
  const value = await callAppNative("context", context);
32
- return { projectId: value.projectId, name: value.name, version: value.version, launchArguments: [...value.launchArguments], runtime: { mode: value.runtime.mode, modules: { ...value.runtime.modules } } };
49
+ const { safeMode, relaunched, instance } = value.launch;
50
+ return { projectId: value.projectId, name: value.name, version: value.version, launchArguments: [...value.launchArguments], runtime: { mode: value.runtime.mode, modules: { ...value.runtime.modules } }, launch: { safeMode, relaunched, instance } };
33
51
  }
34
52
  const command = (method: string, args: object = {}) => callAppNative(method, (value): value is null => value === null, args).then(() => {});
35
53
  const orphanGuards = new Set<AsyncRegistration>();
36
54
  async function cleanOrphanGuards(): Promise<void> {
37
55
  await Promise.all([...orphanGuards].map(async guard => { await guard.remove(); orphanGuards.delete(guard); }));
38
56
  }
57
+ const quitResult = (value: unknown): value is QuitResult => record(value) && (value.quitRequested === true || (value.quitRequested === false && value.reason === "vetoed"));
39
58
  let quitting: Promise<QuitResult> | undefined;
40
59
  /** Joins an existing quit decision. Success permits shutdown; it is not an after-exit hook. */
41
60
  export function quit(): Promise<QuitResult> {
42
- return quitting ??= cleanOrphanGuards().then(() => callAppNative("quit", (value): value is QuitResult => record(value) && (value.quitRequested === true || (value.quitRequested === false && value.reason === "vetoed")))).finally(() => { quitting = undefined; });
61
+ return quitting ??= cleanOrphanGuards().then(() => callAppNative("quit", quitResult)).finally(() => { quitting = undefined; });
62
+ }
63
+ /**
64
+ * Starts a new instance, then runs the same quit decision as `quit()` (joining one already pending).
65
+ * Approval hands the project's instance lock to the new process when this one exits; a veto stops it.
66
+ */
67
+ export async function relaunch(options: RelaunchOptions = {}): Promise<QuitResult> {
68
+ if (!record(options)) throw new SparkError("E_INVALID_ARGUMENT", "Expected relaunch options");
69
+ for (const key of Object.keys(options)) if (key !== "arguments") throw new SparkError("E_UNSUPPORTED_OPTION", `Unknown relaunch option: ${key}`);
70
+ const input = options.arguments;
71
+ if (input !== undefined && !Array.isArray(input)) throw new SparkError("E_INVALID_ARGUMENT", "Relaunch arguments must be an array");
72
+ const args = input === undefined ? undefined : [...input];
73
+ if (args !== undefined && (!strings(args) || args.some(item => item.includes("\0")))) throw new SparkError("E_INVALID_ARGUMENT", "Relaunch arguments must be strings without NUL characters");
74
+ await cleanOrphanGuards();
75
+ return callAppNative("relaunch", quitResult, args === undefined ? {} : { arguments: args });
43
76
  }
44
77
  export const hide = (): Promise<void> => command("hide");
45
78
  export const activate = (): Promise<void> => command("activate");
@@ -48,7 +81,7 @@ function appEvent(value: DesktopEvent): AppEvent | undefined {
48
81
  case "opened": case "closed": if (typeof value.windowId === "string" && value.windowId) return { type: value.type === "opened" ? "windowOpened" : "windowClosed", windowId: value.windowId }; break;
49
82
  case "activate": case "deactivate": case "willQuit": return { type: value.type };
50
83
  case "reopen": if (typeof value.hasVisibleWindows === "boolean" && typeof value.mainWindowWasVisible === "boolean") return { type: "reopen", hasVisibleWindows: value.hasVisibleWindows, mainWindowWasVisible: value.mainWindowWasVisible }; break;
51
- case "secondInstance": if (strings(value.arguments)) return { type: "secondInstance", arguments: [...value.arguments] }; break;
84
+ case "secondInstance": if (strings(value.arguments) && typeof value.workingDirectory === "string" && strings(value.files) && strings(value.urls)) return { type: "secondInstance", arguments: [...value.arguments], workingDirectory: value.workingDirectory, files: [...value.files], urls: [...value.urls] }; break;
52
85
  }
53
86
  }
54
87
  /** Live events only. Initial identity is getAppContext; file/URL replay belongs to documents. */
@@ -16,24 +16,30 @@ export type MenuItem =
16
16
  | (Omit<MenuEntry, "label"> & { type: "role"; role: MenuRole; label?: string; shortcut?: string })
17
17
  | (MenuEntry & { type: "slider"; min: number; max: number; value: number; suffix?: string });
18
18
  export type MenuAction = { type: "action"; itemId: string } | { type: "valueChanged"; itemId: string; value: number };
19
+ /** Validator input: the shared model plus application-menu fields that MenuSupport gates (`alternate`, checkbox `"mixed"`). */
20
+ export type MenuInputItem =
21
+ | Exclude<MenuItem, { type: "action" | "checkbox" | "role" | "submenu" }>
22
+ | (Extract<MenuItem, { type: "action" | "role" }> & { alternate?: boolean })
23
+ | (Omit<Extract<MenuItem, { type: "checkbox" }>, "checked"> & { checked: boolean | "mixed"; alternate?: boolean })
24
+ | (Omit<Extract<MenuItem, { type: "submenu" }>, "items"> & { items: readonly MenuInputItem[] });
19
25
  /** Internal recursive subset helper for feature surfaces that support fewer menu item arms. */
20
26
  export type MenuItemTree<Leaf extends Exclude<MenuItem, { type: "submenu" }>> = Leaf | (Omit<Extract<MenuItem, { type: "submenu" }>, "items"> & { items: readonly MenuItemTree<Leaf>[] });
21
27
  /** Internal transport shape; never reexported from feature entry points. */
22
28
  export interface MenuWireItem {
23
29
  id?: string; title?: string; target?: MenuTarget; placement?: MenuPlacement; _sparkOwner?: string; _sparkIdentity?: string; enabled?: boolean; hidden?: boolean; checked?: boolean; separator?: boolean;
24
- shortcut?: Accelerator; items?: MenuWireItem[]; role?: MenuRole; radio?: boolean;
30
+ shortcut?: Accelerator; items?: MenuWireItem[]; role?: MenuRole; radio?: boolean; alternate?: boolean; mixed?: boolean; _sparkLifecycle?: boolean;
25
31
  systemImageName?: string; imagePath?: string; slider?: { min: number; max: number; value: number; suffix?: string };
26
32
  }
27
- export interface MenuSupport { types: readonly MenuItem["type"][]; shortcuts?: boolean; icons?: readonly MenuIcon["type"][]; targeting?: boolean }
33
+ export interface MenuSupport { types: readonly MenuItem["type"][]; shortcuts?: boolean; icons?: readonly MenuIcon["type"][]; targeting?: boolean; alternates?: boolean; mixedState?: boolean }
28
34
  const roles: readonly string[] = ["new", "open", "save", "saveAs", "clearRecentDocuments", "about", "settings", "services", "hide", "hideOthers", "showAll", "quit", "undo", "redo", "cut", "copy", "paste", "selectAll", "minimize", "zoom", "close", "toggleFullscreen"];
29
35
  function keys(value: object, allowed: readonly string[]) {
30
36
  for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new SparkError("E_UNSUPPORTED_OPTION", `Unsupported menu property: ${key}`);
31
37
  }
32
38
  /** Validate and snapshot the complete tree before a native side effect. */
33
- export function menuItems(input: readonly MenuItem[], support: MenuSupport, platform: "macos" | "windows"): MenuWireItem[] {
39
+ export function menuItems(input: readonly MenuInputItem[], support: MenuSupport, platform: "macos" | "windows"): MenuWireItem[] {
34
40
  const ids = new Set<string>();
35
41
  const active = new Set<object>();
36
- function visit(items: readonly MenuItem[], depth: number): MenuWireItem[] {
42
+ function visit(items: readonly MenuInputItem[], depth: number): MenuWireItem[] {
37
43
  if (!Array.isArray(items) || depth > 5 || active.has(items)) throw new SparkError("E_INVALID_ARGUMENT", "Menus must be acyclic arrays with at most five levels");
38
44
  active.add(items);
39
45
  try {
@@ -44,7 +50,7 @@ export function menuItems(input: readonly MenuItem[], support: MenuSupport, plat
44
50
  if (typeof item.id !== "string" || !item.id.length || item.id.length > 200 || item.id.includes("\0") || ids.has(item.id)) throw new SparkError("E_INVALID_ARGUMENT", "Menu item ids must be nonempty and unique");
45
51
  ids.add(item.id);
46
52
  const common = ["type", "id", "label", "disabled", "hidden", "icon", "target", "placement"];
47
- keys(item, [...common, ...(item.type === "submenu" ? ["items"] : item.type === "slider" ? ["min", "max", "value", "suffix"] : item.type === "role" ? ["role", "shortcut"] : item.type === "checkbox" || item.type === "radio" ? ["checked", "shortcut"] : ["shortcut"])]);
53
+ keys(item, [...common, ...(item.type === "submenu" ? ["items"] : item.type === "slider" ? ["min", "max", "value", "suffix"] : item.type === "role" ? ["role", "shortcut", "alternate"] : item.type === "checkbox" ? ["checked", "shortcut", "alternate"] : item.type === "radio" ? ["checked", "shortcut"] : ["shortcut", "alternate"])]);
48
54
  if ((item.type !== "role" || item.label !== undefined) && (typeof item.label !== "string" || !item.label.trim())) throw new SparkError("E_INVALID_ARGUMENT", "Menu items need a label");
49
55
  if ([item.disabled, item.hidden].some(value => value !== undefined && typeof value !== "boolean")) throw new SparkError("E_INVALID_ARGUMENT", "Menu flags must be boolean");
50
56
  const result: MenuWireItem = { id: item.id, title: item.label, enabled: !item.disabled };
@@ -58,9 +64,17 @@ export function menuItems(input: readonly MenuItem[], support: MenuSupport, plat
58
64
  result.placement = item.placement.before !== undefined ? { before: menuTarget(item.placement.before) } : { after: menuTarget(item.placement.after!) };
59
65
  }
60
66
  }
67
+ if ("alternate" in item && item.alternate !== undefined) {
68
+ if (!support.alternates) throw new SparkError("E_UNSUPPORTED_OPTION", "This menu surface does not support alternate items");
69
+ if (typeof item.alternate !== "boolean") throw new SparkError("E_INVALID_ARGUMENT", "Menu alternate must be boolean");
70
+ result.alternate = item.alternate;
71
+ }
61
72
  if (item.type === "checkbox" || item.type === "radio") {
62
- if (typeof item.checked !== "boolean") throw new SparkError("E_INVALID_ARGUMENT", "Checkbox and radio menus require checked state");
63
- result.checked = item.checked;
73
+ if (item.type === "checkbox" && item.checked === "mixed") {
74
+ if (!support.mixedState) throw new SparkError("E_UNSUPPORTED_OPTION", "This menu surface does not support mixed checkbox state");
75
+ result.mixed = true;
76
+ } else if (typeof item.checked !== "boolean") throw new SparkError("E_INVALID_ARGUMENT", "Checkbox and radio menus require checked state");
77
+ result.checked = item.checked === true;
64
78
  if (item.type === "radio") result.radio = true;
65
79
  }
66
80
  if (item.type === "submenu") result.items = visit(item.items, depth + 1);
@@ -0,0 +1,50 @@
1
+ // RN macOS 0.81.7 Fabric applies accessibilityState only on iOS: RCTViewComponentView's accessibilityState block is
2
+ // inside #if !TARGET_OS_OSX, so a disabled Pressable with an accessibilityRole reports itself enabled to VoiceOver and a
3
+ // selected one unselected. A view whose accessibility traits never changed (no accessibilityRole) reported
4
+ // isAccessibilityEnabled NO, as a plain NSView does, enabled or not. The patch answers both from the view's current
5
+ // props, which covers the first mount, recycled views and every update: enabled unless accessibilityState.disabled or
6
+ // the not-enabled trait, selected when accessibilityState.selected.
7
+ const fs = require("node:fs");
8
+ const path = require("node:path");
9
+ const file = "React/Fabric/Mounting/ComponentViews/View/RCTViewComponentView.mm";
10
+ const methods = `#if TARGET_OS_OSX // [Spark] accessibilityState, which upstream applies only on iOS, read from the current props.
11
+ - (BOOL)isAccessibilityEnabled
12
+ {
13
+ return !_props->accessibilityState.value_or(AccessibilityState{}).disabled &&
14
+ (_props->accessibilityTraits & AccessibilityTraits::NotEnabled) == AccessibilityTraits::None;
15
+ }
16
+
17
+ - (BOOL)isAccessibilitySelected
18
+ {
19
+ return _props->accessibilityState.value_or(AccessibilityState{}).selected;
20
+ }
21
+ #endif // [Spark]
22
+ `;
23
+ const before = `#else // [macOS
24
+ - (NSView *)accessibilityElement // macOS]
25
+ #endif // macOS]
26
+ {
27
+ return self;
28
+ }
29
+ `;
30
+ const after = `${before}
31
+ ${methods}`;
32
+ function patchAccessibilityStateSource(source) {
33
+ if (source.includes(after)) return source;
34
+ if (source.split(before).length !== 2)
35
+ throw new Error(`React Native macOS View source changed (${file}); review the accessibility state patch before building.`);
36
+ return source.replace(before, after);
37
+ }
38
+ function installAccessibilityStatePatch(root) {
39
+ const manifest = require.resolve("react-native-macos/package.json", { paths: [root] });
40
+ const version = JSON.parse(fs.readFileSync(manifest, "utf8")).version;
41
+ if (version !== "0.81.7") throw new Error(`spark's accessibility state patch requires react-native-macos@0.81.7; found ${version}.`);
42
+ const target = path.join(path.dirname(manifest), file);
43
+ const source = fs.readFileSync(target, "utf8"), patched = patchAccessibilityStateSource(source);
44
+ if (source !== patched) {
45
+ const temporary = `${target}.spark-${process.pid}.tmp`;
46
+ fs.writeFileSync(temporary, patched);
47
+ fs.renameSync(temporary, target); // Preserve package-manager cache hardlinks.
48
+ }
49
+ }
50
+ module.exports = { file, methods, before, after, patchAccessibilityStateSource, installAccessibilityStatePatch };
@@ -63,6 +63,11 @@ module.exports = function withSparkDesktop(config) {
63
63
  require("./autolinking.cjs").installAutolinkingPatch(mod.modRequest.projectRoot);
64
64
  require("./fabric-lifecycle.cjs").installSurfaceLifecyclePatch(mod.modRequest.projectRoot);
65
65
  require("./keyboard-events.cjs").installKeyboardEventsPatch(mod.modRequest.projectRoot);
66
+ require("./rtl-scroll-view.cjs").installRTLScrollViewPatch(mod.modRequest.projectRoot);
67
+ require("./rtl-text-alignment.cjs").installRTLTextAlignmentPatch(mod.modRequest.projectRoot);
68
+ require("./rtl-text-input-alignment.cjs").installRTLTextInputAlignmentPatch(mod.modRequest.projectRoot);
69
+ require("./text-input-accessibility.cjs").installTextInputAccessibilityPatch(mod.modRequest.projectRoot);
70
+ require("./accessibility-state.cjs").installAccessibilityStatePatch(mod.modRequest.projectRoot);
66
71
  // The beta template passes the resolved package to use_react_native!, but
67
72
  // post_install otherwise resets Xcode script paths to ../node_modules.
68
73
  mod.modResults.contents = mod.modResults.contents.replace(
@@ -76,7 +81,8 @@ module.exports = function withSparkDesktop(config) {
76
81
  })))).replace(/#\{/g, "\\#{");
77
82
  mod.modResults.contents = mod.modResults.contents.replaceAll('"#{config[:reactNativePath]}-macos"', macOSPath);
78
83
  const selectionFile = statePath(mod.modRequest.projectRoot, "native-selection.json", "macos");
79
- const included = fs.existsSync(selectionFile) ? JSON.parse(fs.readFileSync(selectionFile, "utf8")).included : [];
84
+ const { included, excluded } = fs.existsSync(selectionFile) ? JSON.parse(fs.readFileSync(selectionFile, "utf8")) : { included: [], excluded: [] };
85
+ mod.modResults.contents = require("./autolinking.cjs").excludeNativeModules(mod.modResults.contents, excluded);
80
86
  const updatePackage = included.find(pkg => pkg.name === "@legendapp/spark-updates");
81
87
  // Pin the spec and archive with the SDK, avoiding a mutable CocoaPods index.
82
88
  const sparkleMarker = "# spark: Sparkle pod";
@@ -90,6 +96,8 @@ module.exports = function withSparkDesktop(config) {
90
96
  if (!mod.modResults.contents.includes(autolinkMarker)) {
91
97
  mod.modResults.contents = `${autolinkMarker}\nENV['SPARK_DESKTOP_AUTOLINK'] = 'macos'\n${mod.modResults.contents}`;
92
98
  }
99
+ // The test driver compiles into release builds, and its private event functions anywhere, only on request (docs/test-driver.md#builds).
100
+ mod.modResults.contents = require("./test-driver.cjs").testDriverPodfile(mod.modResults.contents, config.macos);
93
101
  const marker = "# spark: Fabric enabled";
94
102
  if (!mod.modResults.contents.includes(marker)) {
95
103
  mod.modResults.contents = `${marker}\nENV['RCT_NEW_ARCH_ENABLED'] = '1'\n${mod.modResults.contents}`;
@@ -32,4 +32,11 @@ function installAutolinkingPatch(root) {
32
32
  fs.renameSync(temporary, file); // Do not modify package-cache hardlinks.
33
33
  }
34
34
  }
35
- module.exports = { patchAutolinkingSource, installAutolinkingPatch };
35
+ // Expo autolinking ignores an app-level `ios: null` override when the package's own
36
+ // react-native.config.js declares iOS, so pass the native selection's exclusions to its CLI.
37
+ function excludeNativeModules(podfile, excluded) {
38
+ const call = /use_native_modules!\(config_command(?: \+ \[[^\]]*\])?\)/;
39
+ if (!call.test(podfile)) throw new Error("The macOS Podfile no longer calls use_native_modules!(config_command); review spark's native selection.");
40
+ return podfile.replace(call, `use_native_modules!(config_command + ${JSON.stringify(excluded.flatMap(name => ["--exclude", name]))})`);
41
+ }
42
+ module.exports = { patchAutolinkingSource, installAutolinkingPatch, excludeNativeModules };