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

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 (132) hide show
  1. package/README.md +1 -1
  2. package/customize.ts +2 -0
  3. package/html.ts +1 -0
  4. package/markdown.ts +1 -0
  5. package/package.json +22 -13
  6. package/patches/dependencies.json +10 -4
  7. package/patches/react-native-enriched-html@1.1.1.patch +854 -0
  8. package/patches/{react-native-enriched-markdown@1.0.2.patch → react-native-enriched-markdown@1.1.1.patch} +2560 -1983
  9. package/schema.json +104 -0
  10. package/skills/spark/SKILL.md +56 -0
  11. package/skills/spark/UPGRADING.md +254 -0
  12. package/vendor/node_modules/@legendapp/spark-ai/package.json +4 -4
  13. package/vendor/node_modules/@legendapp/spark-ai/src/invocation-command.cjs +11 -0
  14. package/vendor/node_modules/@legendapp/spark-ai/src/invocation-command.d.cts +2 -0
  15. package/vendor/node_modules/@legendapp/spark-ai/src/invocations.ts +2 -19
  16. package/vendor/node_modules/@legendapp/spark-audio/package.json +3 -3
  17. package/vendor/node_modules/@legendapp/spark-auth-session/package.json +3 -3
  18. package/vendor/node_modules/@legendapp/spark-cli/dist/add-desktop.js +4 -4
  19. package/vendor/node_modules/@legendapp/spark-cli/dist/build.js +3 -0
  20. package/vendor/node_modules/@legendapp/spark-cli/dist/create.js +31 -11
  21. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-ai.cjs +108 -0
  22. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-artifacts.js +315 -0
  23. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-cli.cjs +75 -0
  24. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-github.cjs +133 -0
  25. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-policy.cjs +102 -0
  26. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-provider.cjs +2 -0
  27. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-worker.cjs +273 -0
  28. package/vendor/node_modules/@legendapp/spark-cli/dist/dependency-pins.js +54 -29
  29. package/vendor/node_modules/@legendapp/spark-cli/dist/dev-command.js +2 -0
  30. package/vendor/node_modules/@legendapp/spark-cli/dist/enriched-html-pins.js +128 -0
  31. package/vendor/node_modules/@legendapp/spark-cli/dist/expo-dev-patch.cjs +30 -1
  32. package/vendor/node_modules/@legendapp/spark-cli/dist/index.js +16 -7
  33. package/vendor/node_modules/@legendapp/spark-cli/dist/init-template.d.cts +1 -0
  34. package/vendor/node_modules/@legendapp/spark-cli/dist/js-runtime.cjs +96 -0
  35. package/vendor/node_modules/@legendapp/spark-cli/dist/migration-helpers.cjs +152 -0
  36. package/vendor/node_modules/@legendapp/spark-cli/dist/migration-helpers.d.cts +15 -0
  37. package/vendor/node_modules/@legendapp/spark-cli/dist/migrations.cjs +184 -0
  38. package/vendor/node_modules/@legendapp/spark-cli/dist/migrations.d.cts +16 -0
  39. package/vendor/node_modules/@legendapp/spark-cli/dist/native-patch-preflight.js +2 -0
  40. package/vendor/node_modules/@legendapp/spark-cli/dist/package-manager-config.js +41 -0
  41. package/vendor/node_modules/@legendapp/spark-cli/dist/package-manager.js +13 -0
  42. package/vendor/node_modules/@legendapp/spark-cli/dist/project-version.js +12 -0
  43. package/vendor/node_modules/@legendapp/spark-cli/dist/project.js +40 -9
  44. package/vendor/node_modules/@legendapp/spark-cli/dist/release.json +19 -19
  45. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-bootstrap.ps1 +87 -0
  46. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-bootstrap.sh +107 -0
  47. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-downloads.tsv +13 -0
  48. package/vendor/node_modules/@legendapp/spark-cli/dist/sdk-install.js +8 -3
  49. package/vendor/node_modules/@legendapp/spark-cli/dist/upgrade.js +102 -0
  50. package/vendor/node_modules/@legendapp/spark-cli/package.json +6 -4
  51. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/.claude/skills/spark/SKILL.md +9 -0
  52. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/AGENTS.md +4 -0
  53. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/CLAUDE.md +4 -0
  54. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/README.md +15 -0
  55. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/package.json +46 -2
  56. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/.claude/skills/spark/SKILL.md +9 -0
  57. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/AGENTS.md +4 -0
  58. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/CLAUDE.md +4 -0
  59. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/README.md +15 -0
  60. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/package.json +45 -2
  61. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/.claude/skills/spark/SKILL.md +9 -0
  62. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/AGENTS.md +4 -0
  63. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/CLAUDE.md +4 -0
  64. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/README.md +15 -0
  65. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/package.json +46 -2
  66. package/vendor/node_modules/@legendapp/spark-clipboard/package.json +3 -3
  67. package/vendor/node_modules/@legendapp/spark-codex/package.json +3 -3
  68. package/vendor/node_modules/@legendapp/spark-commands/package.json +6 -6
  69. package/vendor/node_modules/@legendapp/spark-context-menu/package.json +3 -3
  70. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/RNDesktopApp.mm +14 -1
  71. package/vendor/node_modules/@legendapp/spark-desktop-app/package.json +2 -2
  72. package/vendor/node_modules/@legendapp/spark-desktop-app/src/customize-hooks.ts +17 -0
  73. package/vendor/node_modules/@legendapp/spark-desktop-app/src/customize.ts +117 -0
  74. package/vendor/node_modules/@legendapp/spark-desktop-config/app.plugin.cjs +20 -1
  75. package/vendor/node_modules/@legendapp/spark-desktop-config/config.cjs +3 -2
  76. package/vendor/node_modules/@legendapp/spark-desktop-config/config.d.cts +14 -0
  77. package/vendor/node_modules/@legendapp/spark-desktop-config/customize-provider.cjs +16 -0
  78. package/vendor/node_modules/@legendapp/spark-desktop-config/customize.cjs +16 -0
  79. package/vendor/node_modules/@legendapp/spark-desktop-config/package.json +4 -4
  80. package/vendor/node_modules/@legendapp/spark-desktop-config/schema.json +104 -0
  81. package/vendor/node_modules/@legendapp/spark-desktop-host/SparkCustomize.mm +517 -0
  82. package/vendor/node_modules/@legendapp/spark-desktop-host/package.json +4 -3
  83. package/vendor/node_modules/@legendapp/spark-desktop-links/package.json +3 -3
  84. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/RNDesktopShortcuts.mm +3 -1
  85. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/keyboard-manager/RNKeyboardManager.h +3 -0
  86. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/keyboard-manager/RNKeyboardManager.mm +1 -1
  87. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/package.json +3 -3
  88. package/vendor/node_modules/@legendapp/spark-desktop-windows/macos/window-manager/RNWindowManager.mm +5 -4
  89. package/vendor/node_modules/@legendapp/spark-desktop-windows/package.json +4 -4
  90. package/vendor/node_modules/@legendapp/spark-desktop-windows/src/api.ts +62 -25
  91. package/vendor/node_modules/@legendapp/spark-desktop-windows/src/macos-adapter.ts +7 -5
  92. package/vendor/node_modules/@legendapp/spark-documents/package.json +8 -8
  93. package/vendor/node_modules/@legendapp/spark-drag-drop/package.json +3 -3
  94. package/vendor/node_modules/@legendapp/spark-file-dialog/package.json +3 -3
  95. package/vendor/node_modules/@legendapp/spark-file-system/macos/SparkFileMutations.h +1 -0
  96. package/vendor/node_modules/@legendapp/spark-file-system/macos/SparkFileMutations.mm +11 -10
  97. package/vendor/node_modules/@legendapp/spark-file-system/package.json +3 -3
  98. package/vendor/node_modules/@legendapp/spark-global-shortcuts/package.json +3 -3
  99. package/vendor/node_modules/@legendapp/spark-html/package.json +24 -0
  100. package/vendor/node_modules/@legendapp/spark-html/src/Html.tsx +22 -0
  101. package/vendor/node_modules/@legendapp/spark-html/src/HtmlInput.tsx +102 -0
  102. package/vendor/node_modules/@legendapp/spark-html/src/index.ts +4 -0
  103. package/vendor/node_modules/@legendapp/spark-html/src/types.ts +4 -0
  104. package/vendor/node_modules/@legendapp/spark-markdown/package.json +24 -0
  105. package/vendor/node_modules/@legendapp/spark-markdown/src/Markdown.tsx +24 -0
  106. package/vendor/node_modules/@legendapp/spark-markdown/src/MarkdownInput.tsx +111 -0
  107. package/vendor/node_modules/@legendapp/spark-markdown/src/index.ts +4 -0
  108. package/vendor/node_modules/@legendapp/spark-message-dialog/package.json +3 -3
  109. package/vendor/node_modules/@legendapp/spark-native-menu/package.json +3 -3
  110. package/vendor/node_modules/@legendapp/spark-notifications/package.json +3 -3
  111. package/vendor/node_modules/@legendapp/spark-processes/package.json +3 -3
  112. package/vendor/node_modules/@legendapp/spark-rich-text/package.json +18 -0
  113. package/vendor/node_modules/@legendapp/spark-rich-text/src/components.tsx +52 -0
  114. package/vendor/node_modules/@legendapp/spark-rich-text/src/index.ts +4 -0
  115. package/vendor/node_modules/@legendapp/spark-rich-text/src/types.ts +24 -0
  116. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputShortcuts.macos.ts +55 -0
  117. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputShortcuts.ts +13 -0
  118. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputValue.ts +14 -0
  119. package/vendor/node_modules/@legendapp/spark-rich-text/src/value.ts +16 -0
  120. package/vendor/node_modules/@legendapp/spark-secure-storage/package.json +3 -3
  121. package/vendor/node_modules/@legendapp/spark-settings/package.json +3 -3
  122. package/vendor/node_modules/@legendapp/spark-settings-ui/package.json +5 -5
  123. package/vendor/node_modules/@legendapp/spark-sqlite/package.json +3 -3
  124. package/vendor/node_modules/@legendapp/spark-system/package.json +3 -3
  125. package/vendor/node_modules/@legendapp/spark-tray/package.json +3 -3
  126. package/vendor/node_modules/@legendapp/spark-ui/macos/appkit-split-view/RNSidebarSplitViewComponent.mm +102 -14
  127. package/vendor/node_modules/@legendapp/spark-ui/package.json +3 -3
  128. package/vendor/node_modules/@legendapp/spark-ui/src/appkit-split-view/SidebarSplitViewNativeComponent.ts +5 -0
  129. package/vendor/node_modules/@legendapp/spark-ui/src/appkit-split-view/index.tsx +12 -4
  130. package/vendor/node_modules/@legendapp/spark-updates/package.json +3 -3
  131. package/vendor/node_modules/@legendapp/spark-webview/package.json +2 -2
  132. package/vendor/node_modules/@legendapp/spark-window-options/package.json +1 -1
@@ -0,0 +1,517 @@
1
+ // Included in AppDelegate only for customize releases. Uses OS frameworks, no JS tooling at startup.
2
+ #import <AppKit/AppKit.h>
3
+ #import <Security/Security.h>
4
+ #import <CommonCrypto/CommonDigest.h>
5
+ #import <sys/file.h>
6
+ #import <fcntl.h>
7
+ #import <unistd.h>
8
+
9
+ static NSDictionary *SCRead(NSString *file) {
10
+ NSData *data = [NSData dataWithContentsOfFile:file];
11
+ id value = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
12
+ return [value isKindOfClass:NSDictionary.class] ? value : @{};
13
+ }
14
+ static void SCWrite(NSString *file, NSDictionary *value) {
15
+ [NSFileManager.defaultManager createDirectoryAtPath:file.stringByDeletingLastPathComponent withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions:@0700} error:nil];
16
+ NSError *error;
17
+ NSData *data = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingPrettyPrinted error:&error];
18
+ if (!data || ![data writeToFile:file options:NSDataWritingAtomic error:&error]) @throw [NSException exceptionWithName:@"SparkCustomize" reason:error.localizedDescription userInfo:nil];
19
+ }
20
+ static NSString *SCHash(NSString *file) {
21
+ NSInputStream *stream = [NSInputStream inputStreamWithFileAtPath:file]; [stream open];
22
+ CC_SHA256_CTX context; CC_SHA256_Init(&context);
23
+ uint8_t buffer[65536]; NSInteger count;
24
+ while ((count = [stream read:buffer maxLength:sizeof(buffer)]) > 0) CC_SHA256_Update(&context, buffer, (CC_LONG)count);
25
+ [stream close]; if (count < 0) return @"";
26
+ unsigned char bytes[CC_SHA256_DIGEST_LENGTH]; CC_SHA256_Final(bytes, &context);
27
+ NSMutableString *result = [NSMutableString new]; for (NSUInteger i=0;i<sizeof(bytes);i++) [result appendFormat:@"%02x",bytes[i]]; return result;
28
+ }
29
+ static BOOL SCIdentifier(NSString *value, NSString *pattern) {
30
+ return [value isKindOfClass:NSString.class] && [value rangeOfString:pattern options:NSRegularExpressionSearch].location != NSNotFound;
31
+ }
32
+ static NSMutableSet<NSTask *> *SCTasks;
33
+ static BOOL SCCancelRequested;
34
+ static NSDictionary *SCResult(NSString *output) {
35
+ for (NSString *line in [[output componentsSeparatedByString:@"\n"] reverseObjectEnumerator]) {
36
+ NSData *data=[line dataUsingEncoding:NSUTF8StringEncoding];
37
+ id value=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
38
+ if([value isKindOfClass:NSDictionary.class])return value;
39
+ }
40
+ @throw [NSException exceptionWithName:@"E_INVALID_DATA" reason:@"Customize worker returned invalid data" userInfo:nil];
41
+ }
42
+ static NSString *SCPath(void) {
43
+ NSString *current=NSProcessInfo.processInfo.environment[@"PATH"] ?: @"/usr/bin:/bin:/usr/sbin:/sbin";
44
+ return [NSString stringWithFormat:@"%@/.local/bin:%@/.bun/bin:%@/.claude/local:/opt/homebrew/bin:/usr/local/bin:%@",NSHomeDirectory(),NSHomeDirectory(),NSHomeDirectory(),current];
45
+ }
46
+ static NSDictionary *SCProvider(NSDictionary *value) {
47
+ if(![value isKindOfClass:NSDictionary.class])@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"Invalid customize provider" userInfo:nil];
48
+ NSString *kind=value[@"kind"],*model=value[@"model"];
49
+ if([kind isEqual:@"cli"]) {
50
+ if(![@[@"codex",@"claude"] containsObject:value[@"tool"]] || (model && (![model isKindOfClass:NSString.class] || !model.length)))@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"CLI provider requires codex or claude" userInfo:nil];
51
+ for(NSString *key in value)if(![@[@"kind",@"tool",@"model"] containsObject:key])@throw [NSException exceptionWithName:@"E_UNSUPPORTED_OPTION" reason:@"Unknown CLI provider option" userInfo:nil];
52
+ NSMutableDictionary *result=[@{@"kind":kind,@"tool":value[@"tool"]} mutableCopy];if(model)result[@"model"]=model;return result;
53
+ }
54
+ for(NSString *key in value)if(![@[@"kind",@"endpoint",@"model",@"apiKey"] containsObject:key])@throw [NSException exceptionWithName:@"E_UNSUPPORTED_OPTION" reason:@"Unknown customize provider option" userInfo:nil];
55
+ if(![model isKindOfClass:NSString.class] || !model.length || ![value[@"endpoint"] isKindOfClass:NSString.class])@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"Enter an endpoint and provider model" userInfo:nil];
56
+ NSURLComponents *url=[NSURLComponents componentsWithString:value[@"endpoint"]];
57
+ BOOL local=[kind isEqual:@"local"],remote=[kind isEqual:@"remote"];
58
+ BOOL loopback=[@[@"localhost",@"127.0.0.1",@"::1",@"[::1]"] containsObject:url.host.lowercaseString];
59
+ if((!local && !remote) || !url.host.length || url.user || url.password || url.query || url.fragment || (local ? !loopback || ![@[@"http",@"https"] containsObject:url.scheme.lowercaseString] : ![url.scheme.lowercaseString isEqual:@"https"]))@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"Remote providers require HTTPS; local providers require a loopback HTTP(S) endpoint" userInfo:nil];
60
+ if(local && [url.host.lowercaseString isEqual:@"localhost"])url.host=@"127.0.0.1";
61
+ if(value[@"apiKey"] && (!remote || ![value[@"apiKey"] isKindOfClass:NSString.class]))@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"API keys are only supported for remote providers" userInfo:nil];
62
+ return @{@"kind":kind,@"endpoint":url.string,@"model":model};
63
+ }
64
+ static NSString *SCRun(NSString *executable, NSArray *arguments, NSDictionary *environment) {
65
+ if(SCCancelRequested)@throw [NSException exceptionWithName:@"E_ABORTED" reason:@"Customization canceled; partial changes are retained" userInfo:nil];
66
+ NSTask *task = [NSTask new]; task.executableURL = [NSURL fileURLWithPath:executable]; task.arguments = arguments;
67
+ if (environment) task.environment = environment;
68
+ NSPipe *pipe = [NSPipe pipe]; task.standardOutput = pipe; task.standardError = pipe;
69
+ NSError *error; if (![task launchAndReturnError:&error]) @throw [NSException exceptionWithName:@"SparkCustomize" reason:error.localizedDescription userInfo:nil];
70
+ @synchronized(NSTask.class) { if(!SCTasks)SCTasks=[NSMutableSet new]; [SCTasks addObject:task]; if(SCCancelRequested && task.running)[task terminate]; }
71
+ NSData *data = [pipe.fileHandleForReading readDataToEndOfFile]; [task waitUntilExit];
72
+ @synchronized(NSTask.class) { [SCTasks removeObject:task]; }
73
+ NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"";
74
+ if(SCCancelRequested)@throw [NSException exceptionWithName:@"E_ABORTED" reason:@"Customization canceled; partial changes are retained" userInfo:nil];
75
+ if (task.terminationStatus) @throw [NSException exceptionWithName:@"SparkCustomize" reason:[NSString stringWithFormat:@"%@ failed (%d). %@", executable.lastPathComponent, task.terminationStatus, output] userInfo:@{@"output":output}];
76
+ return output;
77
+ }
78
+ @interface SparkCustomizeController : NSObject
79
+ @property NSDictionary *manifest;
80
+ @property NSDictionary *previewRecord;
81
+ @property NSString *support;
82
+ @property NSString *directory;
83
+ @property NSString *toolkit;
84
+ @property NSPanel *panel;
85
+ @property NSTextView *prompt;
86
+ @property NSTextField *status;
87
+ @property NSTextField *endpoint;
88
+ @property NSTextField *model;
89
+ @property NSPopUpButton *providerChoice;
90
+ @property NSString *phase;
91
+ @property NSString *message;
92
+ @property NSSecureTextField *key;
93
+ @property NSMutableArray<NSButton *> *buttons;
94
+ @property BOOL busy;
95
+ @property BOOL started;
96
+ @property BOOL forceOriginal;
97
+ @property NSWindow *reviewWindow;
98
+ @property NSDictionary *githubSession;
99
+ @end
100
+ static SparkCustomizeController *SCController;
101
+ @implementation SparkCustomizeController
102
+ - (instancetype)init {
103
+ if ((self = [super init])) {
104
+ _manifest = SCRead([NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"spark-customize.json"]);
105
+ NSString *base = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) firstObject];
106
+ _support = [[base stringByAppendingPathComponent:NSBundle.mainBundle.bundleIdentifier] stringByAppendingPathComponent:@"SparkCustomize"];
107
+ _directory = [[_support stringByAppendingPathComponent:@"releases"] stringByAppendingPathComponent:_manifest[@"release"] ?: @"disabled"];
108
+ _phase=@"idle"; _message=@"Ready to customize";
109
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handleCall:) name:@"SparkCustomizeCall" object:nil];
110
+ _forceOriginal = [NSProcessInfo.processInfo.arguments containsObject:@"--spark-original"] || ([NSEvent modifierFlags] & NSEventModifierFlagOption);
111
+ [NSNotificationCenter.defaultCenter addObserverForName:NSApplicationWillTerminateNotification object:nil queue:nil usingBlock:^(NSNotification *note) { @synchronized(NSTask.class) { for(NSTask *task in SCTasks) if(task.running)[task terminate]; } }];
112
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(healthy:) name:@"RCTContentDidAppearNotification" object:nil];
113
+ if(_manifest.count && ![_manifest[@"customize"][@"ui"] isEqual:@"custom"])[NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^NSEvent *(NSEvent *event) {
114
+ if ((event.modifierFlags & (NSEventModifierFlagCommand|NSEventModifierFlagShift)) == (NSEventModifierFlagCommand|NSEventModifierFlagShift) && [event.charactersIgnoringModifiers.lowercaseString isEqual:@"e"]) { [self show:nil]; return nil; }
115
+ return event;
116
+ }];
117
+ } return self;
118
+ }
119
+ - (NSString *)path:(NSString *)name { return [self.directory stringByAppendingPathComponent:name]; }
120
+ - (NSString *)githubCredential:(NSString *)newValue {
121
+ NSDictionary *query=@{(__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword,(__bridge id)kSecAttrService:@"SparkCustomizeGitHub",(__bridge id)kSecAttrAccount:NSBundle.mainBundle.bundleIdentifier};
122
+ if(newValue){
123
+ OSStatus status;
124
+ if(!newValue.length){status=SecItemDelete((__bridge CFDictionaryRef)query);if(status==errSecItemNotFound)status=errSecSuccess;}
125
+ else{
126
+ NSDictionary *update=@{(__bridge id)kSecValueData:[newValue dataUsingEncoding:NSUTF8StringEncoding]};
127
+ status=SecItemUpdate((__bridge CFDictionaryRef)query,(__bridge CFDictionaryRef)update);
128
+ if(status==errSecItemNotFound){NSMutableDictionary *item=[query mutableCopy];[item addEntriesFromDictionary:update];status=SecItemAdd((__bridge CFDictionaryRef)item,NULL);}
129
+ }
130
+ if(status!=errSecSuccess)@throw [NSException exceptionWithName:@"E_PERMISSION_DENIED" reason:@"Could not update the GitHub token in Keychain" userInfo:nil];
131
+ return newValue;
132
+ }
133
+ NSMutableDictionary *lookup=[query mutableCopy];lookup[(__bridge id)kSecReturnData]=@YES;CFTypeRef data=NULL;
134
+ OSStatus status=SecItemCopyMatching((__bridge CFDictionaryRef)lookup,&data);
135
+ if(status==errSecItemNotFound)return @"";
136
+ if(status!=errSecSuccess)@throw [NSException exceptionWithName:@"E_PERMISSION_DENIED" reason:@"Could not read the GitHub token from Keychain" userInfo:nil];
137
+ return [[NSString alloc] initWithData:CFBridgingRelease(data) encoding:NSUTF8StringEncoding] ?: @"";
138
+ }
139
+ - (BOOL)githubAuthenticated {
140
+ NSDictionary *query=@{(__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword,(__bridge id)kSecAttrService:@"SparkCustomizeGitHub",(__bridge id)kSecAttrAccount:NSBundle.mainBundle.bundleIdentifier,(__bridge id)kSecUseAuthenticationUI:(__bridge id)kSecUseAuthenticationUIFail};
141
+ return SecItemCopyMatching((__bridge CFDictionaryRef)query,NULL)==errSecSuccess;
142
+ }
143
+ - (NSString *)credential:(NSString *)newValue {
144
+ NSDictionary *query = @{(__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword, (__bridge id)kSecAttrService:@"SparkCustomizeAI", (__bridge id)kSecAttrAccount:NSBundle.mainBundle.bundleIdentifier};
145
+ if (newValue) {
146
+ SecItemDelete((__bridge CFDictionaryRef)query);
147
+ if (newValue.length) { NSMutableDictionary *item = [query mutableCopy]; item[(__bridge id)kSecValueData] = [newValue dataUsingEncoding:NSUTF8StringEncoding];
148
+ OSStatus status = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
149
+ if (status != errSecSuccess) @throw [NSException exceptionWithName:@"SparkCustomize" reason:@"Could not save the API key in Keychain." userInfo:nil]; }
150
+ return newValue;
151
+ }
152
+ NSMutableDictionary *lookup = [query mutableCopy]; lookup[(__bridge id)kSecReturnData] = @YES; CFTypeRef data = NULL;
153
+ if (SecItemCopyMatching((__bridge CFDictionaryRef)lookup, &data) != errSecSuccess) return @"";
154
+ return [[NSString alloc] initWithData:CFBridgingRelease(data) encoding:NSUTF8StringEncoding] ?: @"";
155
+ }
156
+ - (void)show:(id)sender {
157
+ if (!self.manifest.count) return;
158
+ if (!self.panel) {
159
+ self.panel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0,0,680,570) styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:NO];
160
+ self.panel.title = @"Customize this app"; self.panel.releasedWhenClosed = NO;
161
+ NSView *view = self.panel.contentView;
162
+ NSTextField *intro = [NSTextField wrappingLabelWithString:@"Describe your change. Spark keeps the original app and saves your prompt with the patch. Review generated changes before applying them."];
163
+ intro.frame = NSMakeRect(20,505,640,45); [view addSubview:intro];
164
+ NSScrollView *scroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(20,335,640,155)]; scroll.hasVerticalScroller = YES; scroll.borderType = NSBezelBorder;
165
+ self.prompt = [[NSTextView alloc] initWithFrame:scroll.bounds]; self.prompt.richText = NO; self.prompt.font = [NSFont systemFontOfSize:14]; self.prompt.autoresizingMask = NSViewWidthSizable; self.prompt.textContainer.widthTracksTextView = YES;
166
+ scroll.documentView = self.prompt; [view addSubview:scroll];
167
+ self.providerChoice=[[NSPopUpButton alloc] initWithFrame:NSMakeRect(130,296,530,26)];
168
+ [self.providerChoice addItemsWithTitles:@[@"Codex CLI (existing login)",@"Claude CLI (existing login)",@"Local model server",@"Remote API"]];self.providerChoice.target=self;self.providerChoice.action=@selector(providerChanged:);
169
+ NSDictionary *provider=[self provider];
170
+ [self.providerChoice selectItemAtIndex:[provider[@"kind"] isEqual:@"cli"] ? ([provider[@"tool"] isEqual:@"claude"] ? 1 : 0) : ([provider[@"kind"] isEqual:@"local"] ? 2 : 3)];
171
+ NSArray *labels = @[@"Endpoint", @"Model", @"API key"];
172
+ self.endpoint = [[NSTextField alloc] initWithFrame:NSMakeRect(130,260,530,26)]; self.endpoint.stringValue = provider[@"endpoint"] ?: @"";
173
+ self.model = [[NSTextField alloc] initWithFrame:NSMakeRect(130,224,530,26)]; self.model.stringValue = provider[@"model"] ?: @""; self.model.placeholderString = @"CLI default, or model identifier";
174
+ self.key = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(130,188,530,26)]; self.key.placeholderString = @"Remote API only; stored in Keychain"; self.key.stringValue = [provider[@"kind"] isEqual:@"remote"] ? [self credential:nil] : @"";
175
+ NSTextField *providerLabel=[NSTextField labelWithString:@"Provider"];providerLabel.frame=NSMakeRect(20,300,105,20);[view addSubview:providerLabel];[view addSubview:self.providerChoice];
176
+ NSArray *fields = @[self.endpoint,self.model,self.key];
177
+ for (NSUInteger i=0;i<3;i++) { NSTextField *label=[NSTextField labelWithString:labels[i]]; label.frame=NSMakeRect(20,264-36*i,105,20); [view addSubview:label]; [view addSubview:fields[i]]; }
178
+ [self syncProviderFields];
179
+ self.buttons = [NSMutableArray new];
180
+ NSArray *titles = @[@"Generate",@"Migrate edits",@"Review",@"Preview",@"Apply",@"Original"];
181
+ NSArray *selectors = @[@"generate:",@"migrate:",@"review:",@"preview:",@"apply:",@"original:"];
182
+ for (NSUInteger i=0;i<titles.count;i++) {
183
+ NSButton *button = [NSButton buttonWithTitle:titles[i] target:self action:NSSelectorFromString(selectors[i])]; button.frame=NSMakeRect(20+(i%3)*215,145-(i/3)*40,205,32); [view addSubview:button]; [self.buttons addObject:button];
184
+ }
185
+ if(self.manifest[@"customize"][@"githubClientId"]){NSButton *button=[NSButton buttonWithTitle:@"Submit as PR" target:self action:@selector(submitPR:)];button.frame=NSMakeRect(20,66,205,30);[view addSubview:button];[self.buttons addObject:button];}
186
+ self.status = [NSTextField wrappingLabelWithString:@"Tools download on first use. AI requests send relevant source to your chosen provider and may incur charges. Hold Option at launch to use the original app."];
187
+ long long bytes=[self.manifest[@"source"][@"size"] longLongValue]+[self.manifest[@"toolkit"][@"size"] longLongValue];
188
+ if(bytes>0)self.status.stringValue=[NSString stringWithFormat:@"First-use source and tools: %@, plus Bun if needed. AI sends relevant source to your chosen provider. Hold Option at launch for the original app.",[NSByteCountFormatter stringFromByteCount:bytes countStyle:NSByteCountFormatterCountStyleFile]];
189
+ self.status.frame=NSMakeRect(20,10,640,self.manifest[@"customize"][@"githubClientId"] ? 50 : 85); [view addSubview:self.status]; [self.panel center];
190
+ }
191
+ [self.panel makeKeyAndOrderFront:nil]; [NSApp activateIgnoringOtherApps:YES];
192
+ if(self.busy){for(NSButton *button in self.buttons)button.enabled=NO;self.buttons.firstObject.title=@"Cancel";self.buttons.firstObject.enabled=YES;self.providerChoice.enabled=NO;self.endpoint.enabled=NO;self.model.enabled=NO;self.key.enabled=NO;}
193
+ }
194
+ - (NSDictionary *)provider {
195
+ NSUserDefaults *defaults=NSUserDefaults.standardUserDefaults;
196
+ NSDictionary *launch=[defaults volatileDomainForName:NSArgumentDomain];
197
+ if(launch[@"SparkCustomizeEndpoint"])return @{@"kind":@"remote",@"endpoint":launch[@"SparkCustomizeEndpoint"],@"model":launch[@"SparkCustomizeModel"] ?: @""};
198
+ return [defaults dictionaryForKey:@"SparkCustomizeProvider"] ?: self.manifest[@"customize"][@"provider"] ?: @{@"kind":@"remote",@"endpoint":[defaults stringForKey:@"SparkCustomizeEndpoint"] ?: @"https://api.openai.com/v1/chat/completions",@"model":[defaults stringForKey:@"SparkCustomizeModel"] ?: @""};
199
+ }
200
+ - (void)syncProviderFields {
201
+ self.endpoint.enabled=self.providerChoice.indexOfSelectedItem>=2;self.key.enabled=self.providerChoice.indexOfSelectedItem==3;
202
+ }
203
+ - (void)providerChanged:(id)sender {
204
+ [self syncProviderFields];self.model.stringValue=@"";
205
+ self.endpoint.stringValue=self.providerChoice.indexOfSelectedItem==2 ? @"http://127.0.0.1:11434/v1/chat/completions" : @"https://api.openai.com/v1/chat/completions";
206
+ self.message=self.providerChoice.indexOfSelectedItem<2 ? @"Uses the installed CLI and its existing login. No API key needed." : @"Choose a model supported by this endpoint.";self.status.stringValue=self.message;
207
+ }
208
+ - (NSDictionary *)panelProvider {
209
+ NSInteger index=self.providerChoice.indexOfSelectedItem;
210
+ NSMutableDictionary *provider=[NSMutableDictionary new];
211
+ if(index<2){provider[@"kind"]=@"cli";provider[@"tool"]=index==0 ? @"codex" : @"claude";if(self.model.stringValue.length)provider[@"model"]=self.model.stringValue;}
212
+ else{provider[@"kind"]=index==2 ? @"local" : @"remote";provider[@"endpoint"]=self.endpoint.stringValue;provider[@"model"]=self.model.stringValue;if(index==3)provider[@"apiKey"]=self.key.stringValue;}
213
+ return provider;
214
+ }
215
+ - (void)configure:(NSDictionary *)value {
216
+ NSDictionary *provider=SCProvider(value);
217
+ if(value[@"apiKey"])[self credential:value[@"apiKey"]];
218
+ [NSUserDefaults.standardUserDefaults setObject:provider forKey:@"SparkCustomizeProvider"];
219
+ if(self.panel){[self.providerChoice selectItemAtIndex:[provider[@"kind"] isEqual:@"cli"] ? ([provider[@"tool"] isEqual:@"claude"] ? 1 : 0) : ([provider[@"kind"] isEqual:@"local"] ? 2 : 3)];self.endpoint.stringValue=provider[@"endpoint"] ?: @"";self.model.stringValue=provider[@"model"] ?: @"";self.key.stringValue=[provider[@"kind"] isEqual:@"remote"] ? [self credential:nil] : @"";[self syncProviderFields];}
220
+ }
221
+ - (NSString *)previousRelease {
222
+ NSString *previous=nil;NSDate *newest=NSDate.distantPast;
223
+ for(NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:[self.support stringByAppendingPathComponent:@"releases"] error:nil]) {
224
+ if([name isEqual:self.manifest[@"release"]])continue;
225
+ NSString *folder=[[self.support stringByAppendingPathComponent:@"releases"] stringByAppendingPathComponent:name];
226
+ if(![SCRead([folder stringByAppendingPathComponent:@"state.json"])[@"status"] isEqual:@"customized"])continue;
227
+ NSDate *date=[[NSFileManager.defaultManager attributesOfItemAtPath:[folder stringByAppendingPathComponent:@"state.json"] error:nil] fileModificationDate];
228
+ if(date && [date compare:newest]==NSOrderedDescending){newest=date;previous=folder;}
229
+ }return previous;
230
+ }
231
+ - (NSDictionary *)state {
232
+ return @{@"enabled":@(self.manifest.count>0),@"busy":@(self.busy),@"phase":self.phase ?: @"idle",@"message":self.message ?: @"",@"ready":@(SCRead([self path:@"ready.json"]).count>0),@"customized":@(!self.forceOriginal && SCRead([self path:@"active.json"]).count>0),@"previewing":@(self.previewRecord!=nil),@"migrationAvailable":@([self previousRelease]!=nil),@"provider":[self provider],@"githubAuthenticated":@([self githubAuthenticated]),@"repository":self.manifest[@"repository"] ?: @""};
233
+ }
234
+ - (void)emitState {
235
+ self.status.stringValue=self.message;
236
+ [NSNotificationCenter.defaultCenter postNotificationName:@"SparkDesktopEvent" object:nil userInfo:@{@"type":@"customizeState",@"state":[self state]}];
237
+ }
238
+ - (void)perform:(NSString *)phase message:(NSString *)message block:(id (^)(void))block completion:(void (^)(id,NSException *))completion {
239
+ if(self.busy){if(completion)completion(nil,[NSException exceptionWithName:@"E_BUSY" reason:@"A customization operation is already running" userInfo:nil]);return;}
240
+ self.busy=YES;SCCancelRequested=NO;self.phase=phase;self.message=message;[self emitState];
241
+ for(NSButton *button in self.buttons)button.enabled=NO;self.buttons.firstObject.title=@"Cancel";self.buttons.firstObject.enabled=YES;
242
+ self.providerChoice.enabled=NO;self.endpoint.enabled=NO;self.model.enabled=NO;self.key.enabled=NO;
243
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0), ^{
244
+ id result;NSException *failure;
245
+ @try { result=block(); } @catch(NSException *exception){failure=exception;}
246
+ dispatch_async(dispatch_get_main_queue(), ^{
247
+ self.busy=NO;self.phase=failure ? @"error" : @"idle";self.message=failure ? failure.reason : ([result isKindOfClass:NSString.class] ? result : @"Done. Review the candidate before applying it.");
248
+ self.buttons.firstObject.title=@"Generate";for(NSButton *button in self.buttons)button.enabled=YES;self.providerChoice.enabled=YES;self.model.enabled=YES;[self syncProviderFields];[self emitState];
249
+ if(completion)completion(result,failure);
250
+ });
251
+ });
252
+ }
253
+ - (void)operation:(NSString *)message block:(NSString *(^)(void))block {
254
+ [self perform:@"preparing" message:message block:block completion:nil];
255
+ }
256
+ - (void)cancel {
257
+ if(!self.busy)return;
258
+ @synchronized(NSTask.class){SCCancelRequested=YES;for(NSTask *task in SCTasks)if(task.running)[task terminate];}
259
+ self.message=@"Canceling; any generated candidate and prompt will be retained.";[self emitState];
260
+ }
261
+ - (NSString *)download:(NSDictionary *)asset kind:(NSString *)kind {
262
+ if (!SCIdentifier(asset[@"sha256"], @"^[a-f0-9]{64}$") || !SCIdentifier(asset[@"url"], @"^https://github[.]com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/releases/download/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") || [asset[@"size"] longLongValue]<=0) @throw [NSException exceptionWithName:@"SparkCustomize" reason:@"Invalid pinned download." userInfo:nil];
263
+ NSString *cache=[[[self.support stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Legend Spark/CustomizeToolkits"];
264
+ [NSFileManager.defaultManager createDirectoryAtPath:cache withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions:@0700} error:nil];
265
+ NSString *target=[cache stringByAppendingPathComponent:asset[@"sha256"]];
266
+ int fd=open([[target stringByAppendingString:@".lock"] fileSystemRepresentation], O_CREAT|O_RDWR,0600);
267
+ if (fd<0 || flock(fd,LOCK_EX)) { if(fd>=0)close(fd); @throw [NSException exceptionWithName:@"SparkCustomize" reason:@"Could not lock download cache." userInfo:nil]; }
268
+ NSString *stage=[target stringByAppendingFormat:@".pending-%@",NSUUID.UUID.UUIDString];
269
+ @try {
270
+ if ([SCRead([target stringByAppendingPathComponent:@"complete.json"])[@"sha256"] isEqual:asset[@"sha256"]]) return [target stringByAppendingPathComponent:kind];
271
+ [NSFileManager.defaultManager createDirectoryAtPath:stage withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions:@0700} error:nil];
272
+ NSString *archive=[stage stringByAppendingPathComponent:@"download.tgz"];
273
+ SCRun(@"/usr/bin/curl",@[@"--fail",@"--location",@"--proto",@"=https",@"--proto-redir",@"=https",@"--connect-timeout",@"30",@"--max-time",@"1800",@"--max-filesize",[asset[@"size"] stringValue],@"--output",archive,asset[@"url"]],nil);
274
+ NSDictionary *attributes=[NSFileManager.defaultManager attributesOfItemAtPath:archive error:nil];
275
+ if (![SCHash(archive) isEqual:asset[@"sha256"]] || [attributes fileSize] != [asset[@"size"] unsignedLongLongValue]) @throw [NSException exceptionWithName:@"SparkCustomize" reason:@"Download checksum or size mismatch." userInfo:nil];
276
+ SCRun(@"/usr/bin/tar",@[@"-xzf",archive,@"-C",stage],nil);
277
+ if (![NSFileManager.defaultManager fileExistsAtPath:[stage stringByAppendingPathComponent:kind]]) @throw [NSException exceptionWithName:@"SparkCustomize" reason:@"Incomplete customize archive." userInfo:nil];
278
+ [NSFileManager.defaultManager removeItemAtPath:archive error:nil]; SCWrite([stage stringByAppendingPathComponent:@"complete.json"],@{@"sha256":asset[@"sha256"]});
279
+ [NSFileManager.defaultManager removeItemAtPath:target error:nil]; NSError *error;
280
+ if (![NSFileManager.defaultManager moveItemAtPath:stage toPath:target error:&error]) @throw [NSException exceptionWithName:@"SparkCustomize" reason:error.localizedDescription userInfo:nil];
281
+ return [target stringByAppendingPathComponent:kind];
282
+ } @finally { [NSFileManager.defaultManager removeItemAtPath:stage error:nil]; flock(fd,LOCK_UN);close(fd); }
283
+ }
284
+ - (NSString *)worker:(NSArray *)arguments key:(NSString *)key {
285
+ NSMutableDictionary *env=[NSProcessInfo.processInfo.environment mutableCopy];
286
+ env[@"PATH"]=SCPath();
287
+ [env removeObjectForKey:@"SPARK_CUSTOMIZE_AI_KEY"];
288
+ [env removeObjectForKey:@"SPARK_CUSTOMIZE_GITHUB_TOKEN"];[env removeObjectForKey:@"SPARK_CUSTOMIZE_GITHUB_REQUEST"];
289
+ env[@"SPARK_HOME"]=[[self.support stringByDeletingLastPathComponent].stringByDeletingLastPathComponent stringByAppendingPathComponent:@"Legend Spark"];
290
+ if(key.length)env[@"SPARK_CUSTOMIZE_AI_KEY"]=key;
291
+ NSArray *args=[@[[self.toolkit stringByAppendingPathComponent:@"runtime-bootstrap.sh"],[self.toolkit stringByAppendingPathComponent:@"customize-worker.cjs"]] arrayByAddingObjectsFromArray:arguments];
292
+ return SCRun(@"/bin/sh",args,env);
293
+ }
294
+ - (NSDictionary *)github:(NSString *)command request:(NSDictionary *)request {
295
+ // GitHub credentials go only to the trusted submission process, never to the AI worker.
296
+ NSMutableDictionary *env=[NSProcessInfo.processInfo.environment mutableCopy];env[@"PATH"]=SCPath();
297
+ env[@"SPARK_HOME"]=[[self.support stringByDeletingLastPathComponent].stringByDeletingLastPathComponent stringByAppendingPathComponent:@"Legend Spark"];
298
+ [env removeObjectForKey:@"SPARK_CUSTOMIZE_AI_KEY"];[env removeObjectForKey:@"SPARK_CUSTOMIZE_GITHUB_TOKEN"];
299
+ env[@"SPARK_CUSTOMIZE_GITHUB_REQUEST"]=[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:request options:0 error:nil] encoding:NSUTF8StringEncoding];
300
+ if([command isEqual:@"submit"])env[@"SPARK_CUSTOMIZE_GITHUB_TOKEN"]=[self githubCredential:nil];
301
+ self.toolkit=[self download:self.manifest[@"toolkit"] kind:@"toolkit"];
302
+ NSArray *args=@[[self.toolkit stringByAppendingPathComponent:@"runtime-bootstrap.sh"],[self.toolkit stringByAppendingPathComponent:@"customize-github.cjs"],command,self.directory];
303
+ @try{return SCResult(SCRun(@"/bin/sh",args,env));}
304
+ @catch(NSException *error){
305
+ if([error.name hasPrefix:@"E_"])@throw;
306
+ NSDictionary *failure;
307
+ @try{failure=SCResult(error.userInfo[@"output"] ?: @"");} @catch(NSException *ignored){}
308
+ if([@[@"E_INVALID_ARGUMENT",@"E_UNSUPPORTED_OPTION",@"E_INVALID_DATA",@"E_PERMISSION_DENIED",@"E_TIMEOUT",@"E_NATIVE"] containsObject:failure[@"error"]] && [failure[@"message"] isKindOfClass:NSString.class])@throw [NSException exceptionWithName:failure[@"error"] reason:failure[@"message"] userInfo:nil];
309
+ // Do not propagate unknown process output to UI: a credential response must stay native.
310
+ @throw [NSException exceptionWithName:@"E_NATIVE" reason:@"GitHub operation failed. Check authorization and whether the source matches the repository." userInfo:nil];
311
+ }
312
+ }
313
+ - (NSDictionary *)beginGitHub {
314
+ NSString *client=self.manifest[@"customize"][@"githubClientId"];
315
+ if(![client isKindOfClass:NSString.class] || !client.length)@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"The developer must configure customize.githubClientId for GitHub device authorization" userInfo:nil];
316
+ self.githubSession=[self github:@"begin" request:@{@"clientId":client}];
317
+ return @{@"userCode":self.githubSession[@"userCode"],@"verificationUri":self.githubSession[@"verificationUri"],@"expiresIn":self.githubSession[@"expiresIn"]};
318
+ }
319
+ - (void)completeGitHub {
320
+ if(!self.githubSession)@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"Start GitHub authorization first" userInfo:nil];
321
+ NSDictionary *result=[self github:@"complete" request:self.githubSession];
322
+ if(![result[@"token"] isKindOfClass:NSString.class] || ![result[@"token"] length])@throw [NSException exceptionWithName:@"E_INVALID_DATA" reason:@"GitHub returned no authorization token" userInfo:nil];
323
+ [self githubCredential:result[@"token"]];self.githubSession=nil;
324
+ }
325
+ - (void)submitPR:(id)sender {
326
+ if(self.busy)return;
327
+ if(![self githubAuthenticated]){
328
+ [self perform:@"authenticating" message:@"Starting GitHub authorization…" block:^id{return [self beginGitHub];} completion:^(id result,NSException *error){
329
+ if(error)return;
330
+ NSAlert *alert=[NSAlert new];alert.messageText=@"Authorize with GitHub";alert.informativeText=[NSString stringWithFormat:@"Open %@ and enter %@. GitHub will ask permission to create a fork, branch and pull request in a public repository.",result[@"verificationUri"],result[@"userCode"]];[alert addButtonWithTitle:@"Open GitHub and wait"];[alert addButtonWithTitle:@"Cancel"];
331
+ if([alert runModal]!=NSAlertFirstButtonReturn){self.githubSession=nil;return;}
332
+ [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:result[@"verificationUri"]]];
333
+ [self perform:@"authenticating" message:@"Waiting for GitHub authorization…" block:^id{[self completeGitHub];return @"GitHub connected. Choose Submit as PR to review and submit.";} completion:nil];
334
+ }];return;
335
+ }
336
+ NSAlert *alert=[NSAlert new];alert.messageText=@"Submit this customization as a pull request?";alert.informativeText=[NSString stringWithFormat:@"Your saved prompts and reviewed patch will be public in %@. Spark creates a branch in your repository or fork. The app developer decides whether to accept it.",self.manifest[@"repository"] ?: @""];
337
+ NSTextField *title=[[NSTextField alloc] initWithFrame:NSMakeRect(0,0,400,24)];title.stringValue=@"Customize app";alert.accessoryView=title;[alert addButtonWithTitle:@"Submit as PR"];[alert addButtonWithTitle:@"Cancel"];
338
+ if([alert runModal]!=NSAlertFirstButtonReturn)return;
339
+ NSDictionary *request=@{@"title":title.stringValue};
340
+ [self perform:@"submitting" message:@"Submitting customization to GitHub…" block:^id{return [self github:@"submit" request:request];} completion:^(id result,NSException *error){if(!error){self.message=[@"Pull request submitted: " stringByAppendingString:result[@"url"]];[self emitState];}}];
341
+ }
342
+ - (void)prepare {
343
+ self.toolkit=[self download:self.manifest[@"toolkit"] kind:@"toolkit"];
344
+ {
345
+ NSString *source=[NSFileManager.defaultManager fileExistsAtPath:[self path:@"state.json"]] ? [self path:@"base"] : [self download:self.manifest[@"source"] kind:@"source"];
346
+ [self worker:@[@"prepare",[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"spark-customize.json"],source,self.toolkit,self.support] key:nil];
347
+ }
348
+ }
349
+ - (BOOL)confirmAI:(NSDictionary *)provider {
350
+ if([provider[@"kind"] isEqual:@"local"])return YES;
351
+ NSString *identity=[provider[@"kind"] isEqual:@"cli"] ? [@"cli:" stringByAppendingString:provider[@"tool"]] : provider[@"endpoint"];
352
+ if([[NSUserDefaults.standardUserDefaults stringForKey:@"SparkCustomizeConsentEndpoint"] isEqual:identity])return YES;
353
+ NSAlert *alert=[NSAlert new];alert.messageText=@"Send this request to your AI provider?";
354
+ alert.informativeText=@"The prompt, relevant app source, build diagnostics and, for migrations, previous prompts and patches are passed to the selected provider. Installed CLI tools use their existing login and may send this context to their cloud service. Changes remain separate until you apply them.";
355
+ [alert addButtonWithTitle:@"Send request"];[alert addButtonWithTitle:@"Cancel"];
356
+ if([alert runModal]!=NSAlertFirstButtonReturn)return NO;
357
+ [NSUserDefaults.standardUserDefaults setObject:identity forKey:@"SparkCustomizeConsentEndpoint"];return YES;
358
+ }
359
+ - (NSDictionary *)generateRequest:(NSDictionary *)args {
360
+ NSString *prompt=args[@"prompt"];
361
+ if(![prompt isKindOfClass:NSString.class] || ![prompt stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length || prompt.length>32000)@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"Enter a prompt of at most 32000 characters" userInfo:nil];
362
+ NSDictionary *raw=args[@"provider"] ?: [self provider],*provider=SCProvider(raw);
363
+ if(![provider[@"kind"] isEqual:@"local"] && ![args[@"allowSourceSharing"] isEqual:@YES])@throw [NSException exceptionWithName:@"E_PERMISSION_DENIED" reason:@"Explain source sharing and obtain consent before generating edits" userInfo:nil];
364
+ if([args[@"migration"] boolValue] && !SCRead([self path:@"state.json"])[@"migration"])@throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"Prepare an edit migration first" userInfo:nil];
365
+ [self configure:raw];
366
+ NSMutableDictionary *request=[provider mutableCopy];request[@"provider"]=request[@"kind"];[request removeObjectForKey:@"kind"];request[@"prompt"]=prompt;request[@"allowSourceSharing"]=@YES;request[@"migration"]=@([args[@"migration"] boolValue]);return request;
367
+ }
368
+ - (NSDictionary *)runPrompt:(NSDictionary *)request key:(NSString *)key {
369
+ [self prepare];NSString *file=[self path:@"request.json"];SCWrite(file,request);
370
+ @try { return SCResult([self worker:@[@"prompt",self.directory,file] key:key]); }
371
+ @finally { [NSFileManager.defaultManager removeItemAtPath:file error:nil]; }
372
+ }
373
+ - (void)generate:(id)sender { if(self.busy){[self cancel];return;}[self generateMigration:NO]; }
374
+ - (void)generateMigration:(BOOL)migration {
375
+ @try {
376
+ NSDictionary *provider=[self panelProvider];if(![self confirmAI:provider])return;
377
+ NSDictionary *request=[self generateRequest:@{@"prompt":self.prompt.string,@"provider":provider,@"allowSourceSharing":@YES,@"migration":@(migration)}];
378
+ NSString *key=[provider[@"kind"] isEqual:@"remote"] ? [self credential:nil] : nil;
379
+ [self perform:@"generating" message:@"Preparing tools and generating a separate candidate…" block:^id{[self runPrompt:request key:key];return @"Candidate compiled successfully. Review its prompt and changes before applying.";} completion:nil];
380
+ } @catch(NSException *e){self.message=e.reason;[self emitState];}
381
+ }
382
+ - (NSDictionary *)prepareMigration {
383
+ [self prepare];NSDictionary *migration=SCRead([self path:@"state.json"])[@"migration"];
384
+ if(!migration){NSString *previous=[self previousRelease];if(!previous)return @{@"status":@"none",@"conflicts":@[]};[self worker:@[@"migrate",previous,self.directory] key:nil];migration=SCRead([self path:@"state.json"])[@"migration"];}
385
+ if(![migration[@"conflicts"] count])[self worker:@[@"build",self.directory,migration[@"candidate"]] key:nil];return migration;
386
+ }
387
+ - (void)migrate:(id)sender {
388
+ if(SCRead([self path:@"state.json"])[@"migration"]) {
389
+ if(!self.prompt.string.length)self.prompt.string=@"Preserve my previous customizations on this updated app. Use the saved prompts to understand their intent and resolve incompatibilities.";
390
+ [self generateMigration:YES];return;
391
+ }
392
+ [self perform:@"migrating" message:@"Preparing migration from the previous customized release…" block:^id{
393
+ NSDictionary *migration=[self prepareMigration];
394
+ if([migration[@"status"] isEqual:@"none"])return @"No previous customized release was found.";
395
+ if([migration[@"conflicts"] count])return @"Migration has conflicts. Enter a prompt and choose Migrate edits again to resolve them.";
396
+ return @"Migration compiled. Review it and Apply, or enter a migration prompt for AI assistance.";
397
+ } completion:nil];
398
+ }
399
+ - (NSDictionary *)editReview {
400
+ NSString *text=[NSString stringWithContentsOfFile:[self path:@"review.txt"] encoding:NSUTF8StringEncoding error:nil] ?: @"";
401
+ NSDictionary *state=SCRead([self path:@"state.json"]);NSMutableArray *history=[NSMutableArray arrayWithArray:state[@"inheritedPrompts"] ?: @[]];[history addObjectsFromArray:state[@"history"] ?: @[]];
402
+ // The full diff is already in text; avoid sending stored file contents twice over the bridge.
403
+ NSMutableArray *prompts=[NSMutableArray new];
404
+ for(NSDictionary *item in history){NSMutableDictionary *metadata=[NSMutableDictionary new];for(NSString *key in @[@"id",@"prompt",@"baseRelease",@"created",@"model",@"provider",@"providerKind",@"status",@"summary",@"error"])if(item[key])metadata[key]=item[key];[prompts addObject:metadata];}
405
+ NSMutableDictionary *review=[@{@"text":text,@"prompts":prompts} mutableCopy];
406
+ NSString *candidate=SCRead([self path:@"ready.json"])[@"candidate"];if(candidate)review[@"candidate"]=candidate;return review;
407
+ }
408
+ - (void)review:(id)sender {
409
+ NSString *content=[NSString stringWithContentsOfFile:[self path:@"review.txt"] encoding:NSUTF8StringEncoding error:nil];
410
+ if(!content.length){self.status.stringValue=@"Generate or migrate a candidate to review changes.";return;}
411
+ NSMutableString *history=[content mutableCopy];[history appendString:@"\n\nSaved prompts\n"];
412
+ for(NSDictionary *item in SCRead([self path:@"state.json"])[@"history"]){[history appendFormat:@"\n%@ — %@\n%@\n",item[@"created"] ?: @"",item[@"status"] ?: @"",item[@"prompt"] ?: @""];}
413
+ content=history;
414
+ if(!self.reviewWindow){self.reviewWindow=[[NSWindow alloc] initWithContentRect:NSMakeRect(0,0,800,600) styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO];self.reviewWindow.releasedWhenClosed=NO;self.reviewWindow.title=@"Review customization";[self.reviewWindow center];}
415
+ NSScrollView *scroll=[[NSScrollView alloc] initWithFrame:self.reviewWindow.contentView.bounds];scroll.autoresizingMask=NSViewWidthSizable|NSViewHeightSizable;scroll.hasVerticalScroller=YES;
416
+ NSTextView *text=[[NSTextView alloc] initWithFrame:scroll.bounds];text.editable=NO;text.font=[NSFont monospacedSystemFontOfSize:12 weight:NSFontWeightRegular];text.string=content;text.autoresizingMask=NSViewWidthSizable;text.textContainer.widthTracksTextView=YES;scroll.documentView=text;
417
+ self.reviewWindow.contentView=scroll;[self.reviewWindow makeKeyAndOrderFront:nil];
418
+ }
419
+ - (void)activateCandidate:(BOOL)preview {
420
+ [self prepare];[self worker:@[preview ? @"verify" : @"accept",self.directory] key:nil];NSDictionary *ready=SCRead([self path:@"ready.json"]);
421
+ SCWrite([self path:@"pending.json"],@{@"previous":SCRead([self path:@"active.json"]),@"launched":@NO,@"activation":NSUUID.UUID.UUIDString});
422
+ if(!preview)SCWrite([self path:@"active.json"],ready);
423
+ dispatch_async(dispatch_get_main_queue(),^{self.previewRecord=preview ? ready : nil;self.forceOriginal=NO;self.started=NO;[self emitState];});
424
+ }
425
+ - (void)reload {
426
+ // Let the bridge deliver completion before replacing the JS runtime.
427
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,100*NSEC_PER_MSEC),dispatch_get_main_queue(),^{[[NSNotificationCenter defaultCenter] postNotificationName:@"SparkCustomizeReload" object:nil];});
428
+ }
429
+ - (void)activate:(BOOL)preview {
430
+ NSAlert *alert=[NSAlert new];alert.messageText=preview ? @"Preview this customization?" : @"Apply the reviewed customization?";alert.informativeText=@"The app will reload using your current data. Save your work first. Code changes can affect app data; reverting code does not undo data changes.";[alert addButtonWithTitle:preview ? @"Preview" : @"Apply and reload"];[alert addButtonWithTitle:@"Cancel"];
431
+ if([alert runModal]!=NSAlertFirstButtonReturn)return;
432
+ [self perform:preview ? @"previewing" : @"applying" message:@"Activating customization…" block:^id{[self activateCandidate:preview];return preview ? @"Previewing for this session. Apply to keep it, or choose Original." : @"Customization activated. The original remains available.";} completion:^(id result,NSException *error){if(!error)[self reload];}];
433
+ }
434
+ - (void)preview:(id)sender { [self activate:YES]; }
435
+ - (void)apply:(id)sender { [self activate:NO]; }
436
+ - (void)original:(id)sender {
437
+ self.previewRecord=nil;self.forceOriginal=YES;[NSFileManager.defaultManager removeItemAtPath:[self path:@"active.json"] error:nil];[NSFileManager.defaultManager removeItemAtPath:[self path:@"pending.json"] error:nil];
438
+ self.phase=@"idle";self.message=@"Using the original app. Your source, prompts and patches are preserved.";[self emitState];[self reload];
439
+ }
440
+ - (void)handleCall:(NSNotification *)note {
441
+ if(!self.manifest.count)return;
442
+ void (^claim)(void)=note.userInfo[@"claim"];claim();
443
+ void (^reply)(NSString *,NSString *,NSString *)=note.userInfo[@"reply"];
444
+ void (^done)(id,NSException *)=^(id result,NSException *error){
445
+ if(error){reply(nil,[error.name hasPrefix:@"E_"] ? error.name : @"E_NATIVE",error.reason);return;}
446
+ NSData *data=[NSJSONSerialization dataWithJSONObject:result ?: NSNull.null options:NSJSONWritingFragmentsAllowed error:nil];reply([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding],nil,nil);
447
+ };
448
+ NSString *method=note.userInfo[@"method"];NSDictionary *args=note.userInfo[@"args"];
449
+ @try {
450
+ NSArray *allowed=[method isEqual:@"prompt"] ? @[@"prompt",@"provider",@"allowSourceSharing",@"migration"] : ([method isEqual:@"configure"] ? @[@"provider"] : ([method isEqual:@"submitPR"] ? @[@"title"] : @[]));
451
+ for(NSString *key in args)if(![allowed containsObject:key])@throw [NSException exceptionWithName:@"E_UNSUPPORTED_OPTION" reason:@"Unknown customize option" userInfo:nil];
452
+ if([method isEqual:@"state"]){done([self state],nil);return;}
453
+ if([method isEqual:@"cancel"]){[self cancel];done(nil,nil);return;}
454
+ if([method isEqual:@"show"]){[self show:nil];done(nil,nil);return;}
455
+ if(self.busy)@throw [NSException exceptionWithName:@"E_BUSY" reason:@"A customization operation is already running" userInfo:nil];
456
+ if([method isEqual:@"configure"]){[self configure:args[@"provider"]];[self emitState];done(nil,nil);}
457
+ else if([method isEqual:@"review"])done([self editReview],nil);
458
+ else if([method isEqual:@"githubBegin"])[self perform:@"authenticating" message:@"Starting GitHub authorization…" block:^id{return [self beginGitHub];} completion:done];
459
+ else if([method isEqual:@"githubComplete"])[self perform:@"authenticating" message:@"Waiting for GitHub authorization…" block:^id{[self completeGitHub];return nil;} completion:done];
460
+ else if([method isEqual:@"githubSignOut"]){self.githubSession=nil;[self githubCredential:@""];[self emitState];done(nil,nil);}
461
+ else if([method isEqual:@"submitPR"])[self perform:@"submitting" message:@"Submitting customization to GitHub…" block:^id{return [self github:@"submit" request:args];} completion:done];
462
+ else if([method isEqual:@"prompt"]){NSDictionary *request=[self generateRequest:args];NSString *key=[request[@"provider"] isEqual:@"remote"] ? [self credential:nil] : nil;[self perform:@"generating" message:@"Generating customization…" block:^id{return [self runPrompt:request key:key];} completion:done];}
463
+ else if([method isEqual:@"migrate"])[self perform:@"migrating" message:@"Preparing migration…" block:^id{return [self prepareMigration];} completion:done];
464
+ else if([method isEqual:@"preview"] || [method isEqual:@"apply"]){BOOL preview=[method isEqual:@"preview"];[self perform:preview ? @"previewing" : @"applying" message:@"Activating customization…" block:^id{[self activateCandidate:preview];return nil;} completion:^(id result,NSException *error){done(result,error);if(!error)[self reload];}];}
465
+ else if([method isEqual:@"original"]){[self original:nil];done(nil,nil);}
466
+ else @throw [NSException exceptionWithName:@"E_INVALID_ARGUMENT" reason:@"Unknown customize operation" userInfo:nil];
467
+ } @catch(NSException *error){done(nil,error);}
468
+ }
469
+ - (void)recoverActivation:(NSString *)activation {
470
+ if([SCRead([self path:@"pending.json"])[@"activation"] isEqual:activation]) { [self show:nil];[self original:nil];self.status.stringValue=@"The customization did not render within 30 seconds. Restored the original; your changes are preserved."; }
471
+ }
472
+ - (void)healthy:(NSNotification *)notification {
473
+ if([notification.object isKindOfClass:NSView.class] && ![(NSView *)notification.object window])return;
474
+ if(self.started && !self.forceOriginal) [NSFileManager.defaultManager removeItemAtPath:[self path:@"pending.json"] error:nil];
475
+ }
476
+ - (NSURL *)bundleURL {
477
+ NSURL *original=[NSBundle.mainBundle URLForResource:@"main" withExtension:@"jsbundle"];
478
+ if(self.forceOriginal)return original;
479
+ if(!self.started) {
480
+ NSDictionary *pending=SCRead([self path:@"pending.json"]);
481
+ if([pending[@"launched"] boolValue]) {SCWrite([self path:@"active.json"],pending[@"previous"] ?: @{});[NSFileManager.defaultManager removeItemAtPath:[self path:@"pending.json"] error:nil];}
482
+ else if(pending.count) {
483
+ NSString *activation=pending[@"activation"] ?: NSUUID.UUID.UUIDString;
484
+ SCWrite([self path:@"pending.json"],@{@"previous":pending[@"previous"] ?: @{},@"launched":@YES,@"activation":activation});
485
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,30*NSEC_PER_SEC),dispatch_get_main_queue(),^{ [self recoverActivation:activation]; });
486
+ }
487
+ self.started=YES;
488
+ }
489
+ NSDictionary *active=self.previewRecord ?: SCRead([self path:@"active.json"]);
490
+ if(![active[@"release"] isEqual:self.manifest[@"release"]] || ![active[@"fingerprint"] isEqual:self.manifest[@"runtime"][@"fingerprint"]] || !SCIdentifier(active[@"build"],@"^[A-Fa-f0-9-]{36}$"))return original;
491
+ NSString *file=[[[self path:@"builds"] stringByAppendingPathComponent:active[@"build"]] stringByAppendingPathComponent:@"main.jsbundle"];
492
+ if(![SCHash(file) isEqual:active[@"bundleHash"]])return original;
493
+ return [NSURL fileURLWithPath:file];
494
+ }
495
+ @end
496
+ static void SparkCustomizeStart(void) {
497
+ if(SCController)return;SCController=[SparkCustomizeController new];
498
+ if(!SCController.manifest.count)return;
499
+ NSString *notice=[@"SparkCustomizeSeen-" stringByAppendingString:SCController.manifest[@"release"]];
500
+ if(![SCController.manifest[@"customize"][@"ui"] isEqual:@"custom"] && ![NSUserDefaults.standardUserDefaults boolForKey:notice] && !SCRead([SCController path:@"state.json"]).count) {
501
+ for(NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:[SCController.support stringByAppendingPathComponent:@"releases"] error:nil]) {
502
+ NSDictionary *state=SCRead([[[SCController.support stringByAppendingPathComponent:@"releases"] stringByAppendingPathComponent:name] stringByAppendingPathComponent:@"state.json"]);
503
+ if([state[@"status"] isEqual:@"customized"]) {
504
+ dispatch_async(dispatch_get_main_queue(),^{[SCController show:nil];SCController.status.stringValue=@"This update is running the original app. Your previous changes and prompts are preserved. Choose Migrate edits to bring them forward.";});break;
505
+ }
506
+ }
507
+ [NSUserDefaults.standardUserDefaults setBool:YES forKey:notice];
508
+ }
509
+ }
510
+ static NSURL *SparkCustomizeBundleURL(void) { @try { SparkCustomizeStart();return [SCController bundleURL]; } @catch(NSException *exception) { return [NSBundle.mainBundle URLForResource:@"main" withExtension:@"jsbundle"]; } }
511
+ static NSMenu *SparkCustomizeDockMenu(NSMenu *existing) {
512
+ SparkCustomizeStart();
513
+ if(!SCController.manifest.count || [SCController.manifest[@"customize"][@"ui"] isEqual:@"custom"])return existing;
514
+ NSMenu *menu=existing ? [existing copy] : [NSMenu new];
515
+ NSMenuItem *item=[[NSMenuItem alloc] initWithTitle:@"Customize app…" action:@selector(show:) keyEquivalent:@""];
516
+ item.target=SCController;[menu addItem:item];return menu;
517
+ }
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@legendapp/spark-desktop-host",
3
- "version": "0.0.1-next.4",
3
+ "version": "0.0.1-next.6",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "AppDelegate.mm",
7
- "windows"
7
+ "windows",
8
+ "SparkCustomize.mm"
8
9
  ],
9
10
  "dependencies": {
10
- "@legendapp/spark-desktop-app": "0.0.1-next.4"
11
+ "@legendapp/spark-desktop-app": "0.0.1-next.6"
11
12
  },
12
13
  "private": true
13
14
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@legendapp/spark-desktop-links",
3
- "version": "0.0.1-next.4",
3
+ "version": "0.0.1-next.6",
4
4
  "license": "MIT",
5
5
  "main": "src/index",
6
6
  "react-native": "src/index",
@@ -13,7 +13,7 @@
13
13
  "common"
14
14
  ],
15
15
  "peerDependencies": {
16
- "react": "19.1.4",
16
+ "react": "^19.1.0",
17
17
  "react-native": "0.81.6",
18
18
  "expo-linking": "~8.0.12"
19
19
  },
@@ -42,7 +42,7 @@
42
42
  ]
43
43
  },
44
44
  "dependencies": {
45
- "@legendapp/spark-desktop-app": "0.0.1-next.4"
45
+ "@legendapp/spark-desktop-app": "0.0.1-next.6"
46
46
  },
47
47
  "peerDependenciesMeta": {
48
48
  "expo-linking": {
@@ -1,4 +1,5 @@
1
1
  #import "RNDesktopShortcuts.h"
2
+ #import "keyboard-manager/RNKeyboardManager.h"
2
3
  #import <RNDesktopApp/SparkDesktop.h>
3
4
  @interface RNDesktopShortcuts ()
4
5
  @property NSMutableDictionary *shortcuts;
@@ -25,10 +26,11 @@ RCT_EXPORT_MODULE(NativeDesktopShortcuts)
25
26
  self.monitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^NSEvent *(NSEvent *event) {
26
27
  RNDesktopShortcuts *strongSelf = weakSelf;
27
28
  NSUInteger flags = event.modifierFlags & (NSEventModifierFlagCommand | NSEventModifierFlagControl | NSEventModifierFlagOption | NSEventModifierFlagShift);
29
+ NSString *key = SparkKeyboardKeyString(event);
28
30
  NSString *windowID = [event.window.identifier hasPrefix:@"spark."] ? [event.window.identifier substringFromIndex:6] : nil;
29
31
  NSDictionary *match;
30
32
  for (NSDictionary *shortcut in strongSelf.shortcuts.allValues) {
31
- if ([shortcut[@"key"] isEqual:event.charactersIgnoringModifiers.lowercaseString] && flags == [shortcut[@"modifiers"] unsignedIntegerValue] &&
33
+ if ([shortcut[@"key"] isEqual:key] && flags == [shortcut[@"modifiers"] unsignedIntegerValue] &&
32
34
  (!shortcut[@"windowId"] || [shortcut[@"windowId"] isEqual:windowID])) {
33
35
  // A window-specific binding overrides the app-wide binding.
34
36
  if (!match || shortcut[@"windowId"]) match = shortcut;
@@ -3,6 +3,9 @@
3
3
 
4
4
  NS_ASSUME_NONNULL_BEGIN
5
5
 
6
+ @class NSEvent;
7
+ FOUNDATION_EXPORT NSString *SparkKeyboardKeyString(NSEvent *event);
8
+
6
9
  @interface RNKeyboardManager : RCTEventEmitter <NativeKeyboardManagerSpec>
7
10
  @end
8
11
 
@@ -33,7 +33,7 @@ static BOOL SparkKeyboardBoolean(id value) { return [value isKindOfClass:NSNumbe
33
33
  // U+001D, Backspace U+0008), which no accelerator can name; accelerators parse AppKit's
34
34
  // private-use code and U+007F instead. Tab and Return are also C0 but already spell their
35
35
  // accelerators, so only keys whose unmodified character identifies them are substituted.
36
- static NSString *SparkKeyboardKeyString(NSEvent *event) {
36
+ NSString *SparkKeyboardKeyString(NSEvent *event) {
37
37
  NSString *key = [event charactersByApplyingModifiers:0] ?: @"";
38
38
  if (key.length == 1 && [key characterAtIndex:0] < 0x20) {
39
39
  NSString *unmodified = event.charactersIgnoringModifiers;